CWL spec -> CWL standards
[arvados.git] / services / api / test / unit / collection_test.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'test_helper'
6 require 'sweep_trashed_objects'
7
8 class CollectionTest < ActiveSupport::TestCase
9   include DbCurrentTime
10
11   def create_collection name, enc=nil
12     txt = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:#{name}.txt\n"
13     txt.force_encoding(enc) if enc
14     return Collection.create(manifest_text: txt, name: name)
15   end
16
17   test 'accept ASCII manifest_text' do
18     act_as_system_user do
19       c = create_collection 'foo', Encoding::US_ASCII
20       assert c.valid?
21     end
22   end
23
24   test 'accept UTF-8 manifest_text' do
25     act_as_system_user do
26       c = create_collection "f\xc3\x98\xc3\x98", Encoding::UTF_8
27       assert c.valid?
28     end
29   end
30
31   test 'refuse manifest_text with invalid UTF-8 byte sequence' do
32     act_as_system_user do
33       c = create_collection "f\xc8o", Encoding::UTF_8
34       assert !c.valid?
35       assert_equal [:manifest_text], c.errors.messages.keys
36       assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
37     end
38   end
39
40   test 'refuse manifest_text with non-UTF-8 encoding' do
41     act_as_system_user do
42       c = create_collection "f\xc8o", Encoding::ASCII_8BIT
43       assert !c.valid?
44       assert_equal [:manifest_text], c.errors.messages.keys
45       assert_match(/UTF-8/, c.errors.messages[:manifest_text].first)
46     end
47   end
48
49   [
50     ". 0:0:foo.txt",
51     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
52     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
53     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
54   ].each do |manifest_text|
55     test "create collection with invalid manifest text #{manifest_text} and expect error" do
56       act_as_system_user do
57         c = Collection.create(manifest_text: manifest_text)
58         assert !c.valid?
59       end
60     end
61   end
62
63   [
64     [". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", 1, 34],
65     [". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:30:foo.txt 0:30:foo1.txt 0:30:foo2.txt 0:30:foo3.txt 0:30:foo4.txt\n", 5, 184],
66     [". d41d8cd98f00b204e9800998ecf8427e 0:0:.\n", 0, 0]
67   ].each do |manifest, count, size|
68     test "file stats on create collection with #{manifest}" do
69       act_as_system_user do
70         c = Collection.create(manifest_text: manifest)
71         assert_equal count, c.file_count
72         assert_equal size, c.file_size_total
73       end
74     end
75   end
76
77   test "file stats cannot be changed unless through manifest change" do
78     act_as_system_user do
79       # Direct changes to file stats should be ignored
80       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n")
81       c.file_count = 6
82       c.file_size_total = 30
83       assert c.valid?
84       assert_equal 1, c.file_count
85       assert_equal 34, c.file_size_total
86
87       # File stats specified on create should be ignored and overwritten
88       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count: 10, file_size_total: 10)
89       assert c.valid?
90       assert_equal 1, c.file_count
91       assert_equal 34, c.file_size_total
92
93       # Updating the manifest should change file stats
94       c.update_attributes(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:34:foo2.txt\n")
95       assert c.valid?
96       assert_equal 2, c.file_count
97       assert_equal 68, c.file_size_total
98
99       # Updating file stats and the manifest should use manifest values
100       c.update_attributes(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count:10, file_size_total: 10)
101       assert c.valid?
102       assert_equal 1, c.file_count
103       assert_equal 34, c.file_size_total
104
105       # Updating just the file stats should be ignored
106       c.update_attributes(file_count: 10, file_size_total: 10)
107       assert c.valid?
108       assert_equal 1, c.file_count
109       assert_equal 34, c.file_size_total
110     end
111   end
112
113   [
114     nil,
115     "",
116     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
117   ].each do |manifest_text|
118     test "create collection with valid manifest text #{manifest_text.inspect} and expect success" do
119       act_as_system_user do
120         c = Collection.create(manifest_text: manifest_text)
121         assert c.valid?
122       end
123     end
124   end
125
126   [
127     ". 0:0:foo.txt",
128     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
129     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
130     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
131   ].each do |manifest_text|
132     test "update collection with invalid manifest text #{manifest_text} and expect error" do
133       act_as_system_user do
134         c = create_collection 'foo', Encoding::US_ASCII
135         assert c.valid?
136
137         c.update_attribute 'manifest_text', manifest_text
138         assert !c.valid?
139       end
140     end
141   end
142
143   [
144     nil,
145     "",
146     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
147   ].each do |manifest_text|
148     test "update collection with valid manifest text #{manifest_text.inspect} and expect success" do
149       act_as_system_user do
150         c = create_collection 'foo', Encoding::US_ASCII
151         assert c.valid?
152
153         c.update_attribute 'manifest_text', manifest_text
154         assert c.valid?
155       end
156     end
157   end
158
159   test "auto-create version after idle setting" do
160     Rails.configuration.Collections.CollectionVersioning = true
161     Rails.configuration.Collections.PreserveVersionIfIdle = 600 # 10 minutes
162     act_as_user users(:active) do
163       # Set up initial collection
164       c = create_collection 'foo', Encoding::US_ASCII
165       assert c.valid?
166       assert_equal 1, c.version
167       assert_equal false, c.preserve_version
168       # Make a versionable update, it shouldn't create a new version yet
169       c.update_attributes!({'name' => 'bar'})
170       c.reload
171       assert_equal 'bar', c.name
172       assert_equal 1, c.version
173       # Update modified_at to trigger a version auto-creation
174       fifteen_min_ago = Time.now - 15.minutes
175       c.update_column('modified_at', fifteen_min_ago) # Update without validations/callbacks
176       c.reload
177       assert_equal fifteen_min_ago.to_i, c.modified_at.to_i
178       c.update_attributes!({'name' => 'baz'})
179       c.reload
180       assert_equal 'baz', c.name
181       assert_equal 2, c.version
182       # Make another update, no new version should be created
183       c.update_attributes!({'name' => 'foobar'})
184       c.reload
185       assert_equal 'foobar', c.name
186       assert_equal 2, c.version
187     end
188   end
189
190   test "preserve_version=false assignment is ignored while being true and not producing a new version" do
191     Rails.configuration.Collections.CollectionVersioning = true
192     Rails.configuration.Collections.PreserveVersionIfIdle = 3600
193     act_as_user users(:active) do
194       # Set up initial collection
195       c = create_collection 'foo', Encoding::US_ASCII
196       assert c.valid?
197       assert_equal 1, c.version
198       assert_equal false, c.preserve_version
199       # This update shouldn't produce a new version, as the idle time is not up
200       c.update_attributes!({
201         'name' => 'bar',
202         'preserve_version' => true
203       })
204       c.reload
205       assert_equal 1, c.version
206       assert_equal 'bar', c.name
207       assert_equal true, c.preserve_version
208       # Make sure preserve_version is not disabled after being enabled, unless
209       # a new version is created.
210       c.update_attributes!({
211         'preserve_version' => false,
212         'replication_desired' => 2
213       })
214       c.reload
215       assert_equal 1, c.version
216       assert_equal 2, c.replication_desired
217       assert_equal true, c.preserve_version
218       c.update_attributes!({'name' => 'foobar'})
219       c.reload
220       assert_equal 2, c.version
221       assert_equal false, c.preserve_version
222       assert_equal 'foobar', c.name
223     end
224   end
225
226   [
227     ['version', 10],
228     ['current_version_uuid', 'zzzzz-4zz18-bv31uwvy3neko21'],
229   ].each do |name, new_value|
230     test "'#{name}' updates on current version collections are not allowed" do
231       act_as_user users(:active) do
232         # Set up initial collection
233         c = create_collection 'foo', Encoding::US_ASCII
234         assert c.valid?
235         assert_equal 1, c.version
236
237         assert_raises(ActiveRecord::RecordInvalid) do
238           c.update_attributes!({
239             name => new_value
240           })
241         end
242       end
243     end
244   end
245
246   test "uuid updates on current version make older versions update their pointers" do
247     Rails.configuration.Collections.CollectionVersioning = true
248     Rails.configuration.Collections.PreserveVersionIfIdle = 0
249     act_as_system_user do
250       # Set up initial collection
251       c = create_collection 'foo', Encoding::US_ASCII
252       assert c.valid?
253       assert_equal 1, c.version
254       # Make changes so that a new version is created
255       c.update_attributes!({'name' => 'bar'})
256       c.reload
257       assert_equal 2, c.version
258       assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
259       new_uuid = 'zzzzz-4zz18-somefakeuuidnow'
260       assert_empty Collection.where(uuid: new_uuid)
261       # Update UUID on current version, check that both collections point to it
262       c.update_attributes!({'uuid' => new_uuid})
263       c.reload
264       assert_equal new_uuid, c.uuid
265       assert_equal 2, Collection.where(current_version_uuid: new_uuid).count
266     end
267   end
268
269   # This test exposes a bug related to JSONB attributes, see #15725.
270   test "recently loaded collection shouldn't list changed attributes" do
271     col = Collection.where("properties != '{}'::jsonb").limit(1).first
272     refute col.properties_changed?, 'Properties field should not be seen as changed'
273   end
274
275   [
276     [
277       true,
278       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
279       {:foo=>:bar, :lst=>[1, 3, 5, 7], :hsh=>{'baz'=>'qux', :foobar=>true, 'hsh'=>{:nested=>true}}, :delete_at=>nil},
280     ],
281     [
282       true,
283       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
284       {'delete_at'=>nil, 'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}},
285     ],
286     [
287       true,
288       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
289       {'delete_at'=>nil, 'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'foobar'=>true, 'hsh'=>{'nested'=>true}, 'baz'=>'qux'}},
290     ],
291     [
292       false,
293       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
294       {'foo'=>'bar', 'lst'=>[1, 3, 5, 42], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
295     ],
296     [
297       false,
298       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
299       {'foo'=>'bar', 'lst'=>[1, 3, 7, 5], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
300     ],
301     [
302       false,
303       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
304       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>false}}, 'delete_at'=>nil},
305     ],
306     [
307       false,
308       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>nil},
309       {'foo'=>'bar', 'lst'=>[1, 3, 5, 7], 'hsh'=>{'baz'=>'qux', 'foobar'=>true, 'hsh'=>{'nested'=>true}}, 'delete_at'=>1234567890},
310     ],
311   ].each do |should_be_equal, value_1, value_2|
312     test "JSONB properties #{value_1} is#{should_be_equal ? '' : ' not'} equal to #{value_2}" do
313       act_as_user users(:active) do
314         # Set up initial collection
315         c = create_collection 'foo', Encoding::US_ASCII
316         assert c.valid?
317         c.update_attributes!({'properties' => value_1})
318         c.reload
319         assert c.changes.keys.empty?
320         c.properties = value_2
321         if should_be_equal
322           assert c.changes.keys.empty?, "Properties #{value_1.inspect} should be equal to #{value_2.inspect}"
323         else
324           refute c.changes.keys.empty?, "Properties #{value_1.inspect} should not be equal to #{value_2.inspect}"
325         end
326       end
327     end
328   end
329
330   test "older versions' modified_at indicate when they're created" do
331     Rails.configuration.Collections.CollectionVersioning = true
332     Rails.configuration.Collections.PreserveVersionIfIdle = 0
333     act_as_user users(:active) do
334       # Set up initial collection
335       c = create_collection 'foo', Encoding::US_ASCII
336       assert c.valid?
337       # Make changes so that a new version is created
338       c.update_attributes!({'name' => 'bar'})
339       c.reload
340       assert_equal 2, c.version
341       # Get the old version
342       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
343       assert_not_nil c_old
344
345       version_creation_datetime = c_old.modified_at.to_f
346       assert_equal c.created_at.to_f, c_old.created_at.to_f
347       # Current version is updated just a few milliseconds before the version is
348       # saved on the database.
349       assert_operator c.modified_at.to_f, :<, version_creation_datetime
350
351       # Make update on current version so old version get the attribute synced;
352       # its modified_at should not change.
353       new_replication = 3
354       c.update_attributes!({'replication_desired' => new_replication})
355       c.reload
356       assert_equal new_replication, c.replication_desired
357       c_old.reload
358       assert_equal new_replication, c_old.replication_desired
359       assert_equal version_creation_datetime, c_old.modified_at.to_f
360       assert_operator c.modified_at.to_f, :>, c_old.modified_at.to_f
361     end
362   end
363
364   test "past versions should not be directly updatable" do
365     Rails.configuration.Collections.CollectionVersioning = true
366     Rails.configuration.Collections.PreserveVersionIfIdle = 0
367     act_as_system_user do
368       # Set up initial collection
369       c = create_collection 'foo', Encoding::US_ASCII
370       assert c.valid?
371       # Make changes so that a new version is created
372       c.update_attributes!({'name' => 'bar'})
373       c.reload
374       assert_equal 2, c.version
375       # Get the old version
376       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
377       assert_not_nil c_old
378       # With collection versioning still being enabled, try to update
379       c_old.name = 'this was foo'
380       assert c_old.invalid?
381       c_old.reload
382       # Try to fool the validator attempting to make c_old to look like a
383       # current version, it should also fail.
384       c_old.current_version_uuid = c_old.uuid
385       assert c_old.invalid?
386       c_old.reload
387       # Now disable collection versioning, it should behave the same way
388       Rails.configuration.Collections.CollectionVersioning = false
389       c_old.name = 'this was foo'
390       assert c_old.invalid?
391     end
392   end
393
394   [
395     ['owner_uuid', 'zzzzz-tpzed-d9tiejq69daie8f', 'zzzzz-tpzed-xurymjxw79nv3jz'],
396     ['replication_desired', 2, 3],
397     ['storage_classes_desired', ['hot'], ['archive']],
398   ].each do |attr, first_val, second_val|
399     test "sync #{attr} with older versions" do
400       Rails.configuration.Collections.CollectionVersioning = true
401       Rails.configuration.Collections.PreserveVersionIfIdle = 0
402       act_as_system_user do
403         # Set up initial collection
404         c = create_collection 'foo', Encoding::US_ASCII
405         assert c.valid?
406         assert_equal 1, c.version
407         assert_not_equal first_val, c.attributes[attr]
408         # Make changes so that a new version is created and a synced field is
409         # updated on both
410         c.update_attributes!({'name' => 'bar', attr => first_val})
411         c.reload
412         assert_equal 2, c.version
413         assert_equal first_val, c.attributes[attr]
414         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
415         assert_equal first_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
416         # Only make an update on the same synced field & check that the previously
417         # created version also gets it.
418         c.update_attributes!({attr => second_val})
419         c.reload
420         assert_equal 2, c.version
421         assert_equal second_val, c.attributes[attr]
422         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
423         assert_equal second_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
424       end
425     end
426   end
427
428   [
429     [false, 'name', 'bar', false],
430     [false, 'description', 'The quick brown fox jumps over the lazy dog', false],
431     [false, 'properties', {'new_version' => true}, false],
432     [false, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", false],
433     [true, 'name', 'bar', true],
434     [true, 'description', 'The quick brown fox jumps over the lazy dog', true],
435     [true, 'properties', {'new_version' => true}, true],
436     [true, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", true],
437     # Non-versionable attribute updates shouldn't create new versions
438     [true, 'replication_desired', 5, false],
439     [false, 'replication_desired', 5, false],
440   ].each do |versioning, attr, val, new_version_expected|
441     test "update #{attr} with versioning #{versioning ? '' : 'not '}enabled should #{new_version_expected ? '' : 'not '}create a new version" do
442       Rails.configuration.Collections.CollectionVersioning = versioning
443       Rails.configuration.Collections.PreserveVersionIfIdle = 0
444       act_as_user users(:active) do
445         # Create initial collection
446         c = create_collection 'foo', Encoding::US_ASCII
447         assert c.valid?
448         assert_equal 'foo', c.name
449
450         # Check current version attributes
451         assert_equal 1, c.version
452         assert_equal c.uuid, c.current_version_uuid
453
454         # Update attribute and check if version number should be incremented
455         old_value = c.attributes[attr]
456         c.update_attributes!({attr => val})
457         assert_equal new_version_expected, c.version == 2
458         assert_equal val, c.attributes[attr]
459
460         if versioning && new_version_expected
461           # Search for the snapshot & previous value
462           assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
463           s = Collection.where(current_version_uuid: c.uuid, version: 1).first
464           assert_not_nil s
465           assert_equal old_value, s.attributes[attr]
466         else
467           # If versioning is disabled or no versionable attribute was updated,
468           # only the current version should exist
469           assert_equal 1, Collection.where(current_version_uuid: c.uuid).count
470           assert_equal c, Collection.where(current_version_uuid: c.uuid).first
471         end
472       end
473     end
474   end
475
476   test 'current_version_uuid is ignored during update' do
477     Rails.configuration.Collections.CollectionVersioning = true
478     Rails.configuration.Collections.PreserveVersionIfIdle = 0
479     act_as_user users(:active) do
480       # Create 1st collection
481       col1 = create_collection 'foo', Encoding::US_ASCII
482       assert col1.valid?
483       assert_equal 1, col1.version
484
485       # Create 2nd collection, update it so it becomes version:2
486       # (to avoid unique index violation)
487       col2 = create_collection 'bar', Encoding::US_ASCII
488       assert col2.valid?
489       assert_equal 1, col2.version
490       col2.update_attributes({name: 'baz'})
491       assert_equal 2, col2.version
492
493       # Try to make col2 a past version of col1. It shouldn't be possible
494       col2.update_attributes({current_version_uuid: col1.uuid})
495       assert col2.invalid?
496       col2.reload
497       assert_not_equal col1.uuid, col2.current_version_uuid
498     end
499   end
500
501   test 'with versioning enabled, simultaneous updates increment version correctly' do
502     Rails.configuration.Collections.CollectionVersioning = true
503     Rails.configuration.Collections.PreserveVersionIfIdle = 0
504     act_as_user users(:active) do
505       # Create initial collection
506       col = create_collection 'foo', Encoding::US_ASCII
507       assert col.valid?
508       assert_equal 1, col.version
509
510       # Simulate simultaneous updates
511       c1 = Collection.where(uuid: col.uuid).first
512       assert_equal 1, c1.version
513       c1.name = 'bar'
514       c2 = Collection.where(uuid: col.uuid).first
515       c2.description = 'foo collection'
516       c1.save!
517       assert_equal 1, c2.version
518       # with_lock forces a reload, so this shouldn't produce an unique violation error
519       c2.save!
520       assert_equal 3, c2.version
521       assert_equal 'foo collection', c2.description
522     end
523   end
524
525   test 'create and update collection and verify file_names' do
526     act_as_system_user do
527       c = create_collection 'foo', Encoding::US_ASCII
528       assert c.valid?
529       created_file_names = c.file_names
530       assert created_file_names
531       assert_match(/foo.txt/, c.file_names)
532
533       c.update_attribute 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo2.txt\n"
534       assert_not_equal created_file_names, c.file_names
535       assert_match(/foo2.txt/, c.file_names)
536     end
537   end
538
539   [
540     [2**8, false],
541     [2**18, true],
542   ].each do |manifest_size, allow_truncate|
543     test "create collection with manifest size #{manifest_size} with allow_truncate=#{allow_truncate},
544           and not expect exceptions even on very large manifest texts" do
545       # file_names has a max size, hence there will be no errors even on large manifests
546       act_as_system_user do
547         manifest_text = ''
548         index = 0
549         while manifest_text.length < manifest_size
550           manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
551           index += 1
552         end
553         manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
554         c = Collection.create(manifest_text: manifest_text)
555
556         assert c.valid?
557         assert c.file_names
558         assert_match(/veryverylongfilename0000000000001.txt/, c.file_names)
559         assert_match(/veryverylongfilename0000000000002.txt/, c.file_names)
560         if not allow_truncate
561           assert_match(/veryverylastfilename/, c.file_names)
562           assert_match(/laststreamname/, c.file_names)
563         end
564       end
565     end
566   end
567
568   test "full text search for collections" do
569     # file_names column does not get populated when fixtures are loaded, hence setup test data
570     act_as_system_user do
571       Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n")
572       Collection.create(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
573       Collection.create(manifest_text: ". 85877ca2d7e05498dd3d109baf2df106+95+A3a4e26a366ee7e4ed3e476ccf05354761be2e4ae@545a9920 0:95:file_in_subdir1\n./subdir2/subdir3 2bbc341c702df4d8f42ec31f16c10120+64+A315d7e7bad2ce937e711fc454fae2d1194d14d64@545a9920 0:32:file1.txt 32:32:file2.txt\n./subdir2/subdir3/subdir4 2bbc341c702df4d8f42ec31f16c10120+64+A315d7e7bad2ce937e711fc454fae2d1194d14d64@545a9920 0:32:file3.txt 32:32:file4.txt\n")
574     end
575
576     [
577       ['foo', true],
578       ['foo bar', false],                     # no collection matching both
579       ['foo&bar', false],                     # no collection matching both
580       ['foo|bar', true],                      # works only no spaces between the words
581       ['Gnu public', true],                   # both prefixes found, though not consecutively
582       ['Gnu&public', true],                   # both prefixes found, though not consecutively
583       ['file4', true],                        # prefix match
584       ['file4.txt', true],                    # whole string match
585       ['filex', false],                       # no such prefix
586       ['subdir', true],                       # prefix matches
587       ['subdir2', true],
588       ['subdir2/', true],
589       ['subdir2/subdir3', true],
590       ['subdir2/subdir3/subdir4', true],
591       ['subdir2 file4', true],                # look for both prefixes
592       ['subdir4', false],                     # not a prefix match
593     ].each do |search_filter, expect_results|
594       search_filters = search_filter.split.each {|s| s.concat(':*')}.join('&')
595       results = Collection.where("#{Collection.full_text_tsvector} @@ to_tsquery(?)",
596                                  "#{search_filters}")
597       if expect_results
598         refute_empty results
599       else
600         assert_empty results
601       end
602     end
603   end
604
605   test 'portable data hash with missing size hints' do
606     [[". d41d8cd98f00b204e9800998ecf8427e+0+Bar 0:0:x\n",
607       ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"],
608      [". d41d8cd98f00b204e9800998ecf8427e+Foo 0:0:x\n",
609       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
610      [". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n",
611       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
612     ].each do |unportable, portable|
613       c = Collection.new(manifest_text: unportable)
614       assert c.valid?
615       assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
616                    c.portable_data_hash)
617     end
618   end
619
620   pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
621   pdhmd5 = Digest::MD5.hexdigest pdhmanifest
622   [[true, nil],
623    [true, pdhmd5],
624    [true, pdhmd5+'+12345'],
625    [true, pdhmd5+'+'+pdhmanifest.length.to_s],
626    [true, pdhmd5+'+12345+Foo'],
627    [true, pdhmd5+'+Foo'],
628    [false, Digest::MD5.hexdigest(pdhmanifest.strip)],
629    [false, Digest::MD5.hexdigest(pdhmanifest.strip)+'+'+pdhmanifest.length.to_s],
630    [false, pdhmd5[0..30]],
631    [false, pdhmd5[0..30]+'z'],
632    [false, pdhmd5[0..24]+'000000000'],
633    [false, pdhmd5[0..24]+'000000000+0']].each do |isvalid, pdh|
634     test "portable_data_hash #{pdh.inspect} valid? == #{isvalid}" do
635       c = Collection.new manifest_text: pdhmanifest, portable_data_hash: pdh
636       assert_equal isvalid, c.valid?, c.errors.full_messages.to_s
637     end
638   end
639
640   test "storage_classes_desired cannot be empty" do
641     act_as_user users(:active) do
642       c = collections(:collection_owned_by_active)
643       c.update_attributes storage_classes_desired: ["hot"]
644       assert_equal ["hot"], c.storage_classes_desired
645       assert_raise ArvadosModel::InvalidStateTransitionError do
646         c.update_attributes storage_classes_desired: []
647       end
648     end
649   end
650
651   test "storage classes lists should only contain non-empty strings" do
652     c = collections(:storage_classes_desired_default_unconfirmed)
653     act_as_user users(:admin) do
654       assert c.update_attributes(storage_classes_desired: ["default", "a_string"],
655                                  storage_classes_confirmed: ["another_string"])
656       [
657         ["storage_classes_desired", ["default", 42]],
658         ["storage_classes_confirmed", [{the_answer: 42}]],
659         ["storage_classes_desired", ["default", ""]],
660         ["storage_classes_confirmed", [""]],
661       ].each do |attr, val|
662         assert_raise ArvadosModel::InvalidStateTransitionError do
663           assert c.update_attributes({attr => val})
664         end
665       end
666     end
667   end
668
669   test "storage_classes_confirmed* can be set by admin user" do
670     c = collections(:storage_classes_desired_default_unconfirmed)
671     act_as_user users(:admin) do
672       assert c.update_attributes(storage_classes_confirmed: ["default"],
673                                  storage_classes_confirmed_at: Time.now)
674     end
675   end
676
677   test "storage_classes_confirmed* cannot be set by non-admin user" do
678     act_as_user users(:active) do
679       c = collections(:storage_classes_desired_default_unconfirmed)
680       # Cannot set just one at a time.
681       assert_raise ArvadosModel::PermissionDeniedError do
682         c.update_attributes storage_classes_confirmed: ["default"]
683       end
684       c.reload
685       assert_raise ArvadosModel::PermissionDeniedError do
686         c.update_attributes storage_classes_confirmed_at: Time.now
687       end
688       # Cannot set bot at once, either.
689       c.reload
690       assert_raise ArvadosModel::PermissionDeniedError do
691         assert c.update_attributes(storage_classes_confirmed: ["default"],
692                                    storage_classes_confirmed_at: Time.now)
693       end
694     end
695   end
696
697   test "storage_classes_confirmed* can be cleared (but only together) by non-admin user" do
698     act_as_user users(:active) do
699       c = collections(:storage_classes_desired_default_confirmed_default)
700       # Cannot clear just one at a time.
701       assert_raise ArvadosModel::PermissionDeniedError do
702         c.update_attributes storage_classes_confirmed: []
703       end
704       c.reload
705       assert_raise ArvadosModel::PermissionDeniedError do
706         c.update_attributes storage_classes_confirmed_at: nil
707       end
708       # Can clear both at once.
709       c.reload
710       assert c.update_attributes(storage_classes_confirmed: [],
711                                  storage_classes_confirmed_at: nil)
712     end
713   end
714
715   [0, 2, 4, nil].each do |ask|
716     test "set replication_desired to #{ask.inspect}" do
717       Rails.configuration.Collections.DefaultReplication = 2
718       act_as_user users(:active) do
719         c = collections(:replication_undesired_unconfirmed)
720         c.update_attributes replication_desired: ask
721         assert_equal ask, c.replication_desired
722       end
723     end
724   end
725
726   test "replication_confirmed* can be set by admin user" do
727     c = collections(:replication_desired_2_unconfirmed)
728     act_as_user users(:admin) do
729       assert c.update_attributes(replication_confirmed: 2,
730                                  replication_confirmed_at: Time.now)
731     end
732   end
733
734   test "replication_confirmed* cannot be set by non-admin user" do
735     act_as_user users(:active) do
736       c = collections(:replication_desired_2_unconfirmed)
737       # Cannot set just one at a time.
738       assert_raise ArvadosModel::PermissionDeniedError do
739         c.update_attributes replication_confirmed: 1
740       end
741       assert_raise ArvadosModel::PermissionDeniedError do
742         c.update_attributes replication_confirmed_at: Time.now
743       end
744       # Cannot set both at once, either.
745       assert_raise ArvadosModel::PermissionDeniedError do
746         c.update_attributes(replication_confirmed: 1,
747                             replication_confirmed_at: Time.now)
748       end
749     end
750   end
751
752   test "replication_confirmed* can be cleared (but only together) by non-admin user" do
753     act_as_user users(:active) do
754       c = collections(:replication_desired_2_confirmed_2)
755       # Cannot clear just one at a time.
756       assert_raise ArvadosModel::PermissionDeniedError do
757         c.update_attributes replication_confirmed: nil
758       end
759       c.reload
760       assert_raise ArvadosModel::PermissionDeniedError do
761         c.update_attributes replication_confirmed_at: nil
762       end
763       # Can clear both at once.
764       c.reload
765       assert c.update_attributes(replication_confirmed: nil,
766                                  replication_confirmed_at: nil)
767     end
768   end
769
770   test "clear replication_confirmed* when introducing a new block in manifest" do
771     c = collections(:replication_desired_2_confirmed_2)
772     act_as_user users(:active) do
773       assert c.update_attributes(manifest_text: collections(:user_agreement).signed_manifest_text)
774       assert_nil c.replication_confirmed
775       assert_nil c.replication_confirmed_at
776     end
777   end
778
779   test "don't clear replication_confirmed* when just renaming a file" do
780     c = collections(:replication_desired_2_confirmed_2)
781     act_as_user users(:active) do
782       new_manifest = c.signed_manifest_text.sub(':bar', ':foo')
783       assert c.update_attributes(manifest_text: new_manifest)
784       assert_equal 2, c.replication_confirmed
785       assert_not_nil c.replication_confirmed_at
786     end
787   end
788
789   test "don't clear replication_confirmed* when just deleting a data block" do
790     c = collections(:replication_desired_2_confirmed_2)
791     act_as_user users(:active) do
792       new_manifest = c.signed_manifest_text
793       new_manifest.sub!(/ \S+:bar/, '')
794       new_manifest.sub!(/ acbd\S+/, '')
795
796       # Confirm that we did just remove a block from the manifest (if
797       # not, this test would pass without testing the relevant case):
798       assert_operator new_manifest.length+40, :<, c.signed_manifest_text.length
799
800       assert c.update_attributes(manifest_text: new_manifest)
801       assert_equal 2, c.replication_confirmed
802       assert_not_nil c.replication_confirmed_at
803     end
804   end
805
806   test 'signature expiry does not exceed trash_at' do
807     act_as_user users(:active) do
808       t0 = db_current_time
809       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
810       c.update_attributes! trash_at: (t0 + 1.hours)
811       c.reload
812       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
813       assert_operator sig_exp.to_i, :<=, (t0 + 1.hours).to_i
814     end
815   end
816
817   test 'far-future expiry date cannot be used to circumvent configured permission ttl' do
818     act_as_user users(:active) do
819       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n",
820                              name: 'foo',
821                              trash_at: db_current_time + 1.years)
822       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
823       expect_max_sig_exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
824       assert_operator c.trash_at.to_i, :>, expect_max_sig_exp
825       assert_operator sig_exp.to_i, :<=, expect_max_sig_exp
826     end
827   end
828
829   test "create collection with properties" do
830     act_as_system_user do
831       c = Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n",
832                             properties: {'property_1' => 'value_1'})
833       assert c.valid?
834       assert_equal 'value_1', c.properties['property_1']
835     end
836   end
837
838   test 'create, delete, recreate collection with same name and owner' do
839     act_as_user users(:active) do
840       # create collection with name
841       c = Collection.create(manifest_text: '',
842                             name: "test collection name")
843       assert c.valid?
844       uuid = c.uuid
845
846       c = Collection.readable_by(current_user).where(uuid: uuid)
847       assert_not_empty c, 'Should be able to find live collection'
848
849       # mark collection as expired
850       c.first.update_attributes!(trash_at: Time.new.strftime("%Y-%m-%d"))
851       c = Collection.readable_by(current_user).where(uuid: uuid)
852       assert_empty c, 'Should not be able to find expired collection'
853
854       # recreate collection with the same name
855       c = Collection.create(manifest_text: '',
856                             name: "test collection name")
857       assert c.valid?
858     end
859   end
860
861   test 'trash_at cannot be set too far in the past' do
862     act_as_user users(:active) do
863       t0 = db_current_time
864       c = Collection.create!(manifest_text: '', name: 'foo')
865       c.update_attributes! trash_at: (t0 - 2.weeks)
866       c.reload
867       assert_operator c.trash_at, :>, t0
868     end
869   end
870
871   now = Time.now
872   [['trash-to-delete interval negative',
873     :collection_owned_by_active,
874     {trash_at: now+2.weeks, delete_at: now},
875     {state: :invalid}],
876    ['now-to-delete interval short',
877     :collection_owned_by_active,
878     {trash_at: now+3.days, delete_at: now+7.days},
879     {state: :trash_future}],
880    ['now-to-delete interval short, trash=delete',
881     :collection_owned_by_active,
882     {trash_at: now+3.days, delete_at: now+3.days},
883     {state: :trash_future}],
884    ['trash-to-delete interval ok',
885     :collection_owned_by_active,
886     {trash_at: now, delete_at: now+15.days},
887     {state: :trash_now}],
888    ['trash-to-delete interval short, but far enough in future',
889     :collection_owned_by_active,
890     {trash_at: now+13.days, delete_at: now+15.days},
891     {state: :trash_future}],
892    ['trash by setting is_trashed bool',
893     :collection_owned_by_active,
894     {is_trashed: true},
895     {state: :trash_now}],
896    ['trash in future by setting just trash_at',
897     :collection_owned_by_active,
898     {trash_at: now+1.week},
899     {state: :trash_future}],
900    ['trash in future by setting trash_at and delete_at',
901     :collection_owned_by_active,
902     {trash_at: now+1.week, delete_at: now+4.weeks},
903     {state: :trash_future}],
904    ['untrash by clearing is_trashed bool',
905     :expired_collection,
906     {is_trashed: false},
907     {state: :not_trash}],
908   ].each do |test_name, fixture_name, updates, expect|
909     test test_name do
910       act_as_user users(:active) do
911         min_exp = (db_current_time +
912                    Rails.configuration.Collections.BlobSigningTTL)
913         if fixture_name == :expired_collection
914           # Fixture-finder shorthand doesn't find trashed collections
915           # because they're not in the default scope.
916           c = Collection.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
917         else
918           c = collections(fixture_name)
919         end
920         updates_ok = c.update_attributes(updates)
921         expect_valid = expect[:state] != :invalid
922         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
923         case expect[:state]
924         when :invalid
925           refute c.valid?
926         when :trash_now
927           assert c.is_trashed
928           assert_not_nil c.trash_at
929           assert_operator c.trash_at, :<=, db_current_time
930           assert_not_nil c.delete_at
931           assert_operator c.delete_at, :>=, min_exp
932         when :trash_future
933           refute c.is_trashed
934           assert_not_nil c.trash_at
935           assert_operator c.trash_at, :>, db_current_time
936           assert_not_nil c.delete_at
937           assert_operator c.delete_at, :>=, c.trash_at
938           # Currently this minimum interval is needed to prevent early
939           # garbage collection:
940           assert_operator c.delete_at, :>=, min_exp
941         when :not_trash
942           refute c.is_trashed
943           assert_nil c.trash_at
944           assert_nil c.delete_at
945         else
946           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
947         end
948       end
949     end
950   end
951
952   test 'default trash interval > blob signature ttl' do
953     Rails.configuration.Collections.DefaultTrashLifetime = 86400 * 21 # 3 weeks
954     start = db_current_time
955     act_as_user users(:active) do
956       c = Collection.create!(manifest_text: '', name: 'foo')
957       c.update_attributes!(trash_at: start + 86400.seconds)
958       assert_operator c.delete_at, :>=, start + (86400*22).seconds
959       assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
960       c.destroy
961
962       c = Collection.create!(manifest_text: '', name: 'foo')
963       c.update_attributes!(is_trashed: true)
964       assert_operator c.delete_at, :>=, start + (86400*21).seconds
965     end
966   end
967
968   test "find_all_for_docker_image resolves names that look like hashes" do
969     coll_list = Collection.
970       find_all_for_docker_image('a' * 64, nil, [users(:active)])
971     coll_uuids = coll_list.map(&:uuid)
972     assert_includes(coll_uuids, collections(:docker_image).uuid)
973   end
974
975   test "move collections to trash in SweepTrashedObjects" do
976     c = collections(:trashed_on_next_sweep)
977     refute_empty Collection.where('uuid=? and is_trashed=false', c.uuid)
978     assert_raises(ActiveRecord::RecordNotUnique) do
979       act_as_user users(:active) do
980         Collection.create!(owner_uuid: c.owner_uuid,
981                            name: c.name)
982       end
983     end
984     SweepTrashedObjects.sweep_now
985     c = Collection.where('uuid=? and is_trashed=true', c.uuid).first
986     assert c
987     act_as_user users(:active) do
988       assert Collection.create!(owner_uuid: c.owner_uuid,
989                                 name: c.name)
990     end
991   end
992
993   test "delete collections in SweepTrashedObjects" do
994     uuid = 'zzzzz-4zz18-3u1p5umicfpqszp' # deleted_on_next_sweep
995     assert_not_empty Collection.where(uuid: uuid)
996     SweepTrashedObjects.sweep_now
997     assert_empty Collection.where(uuid: uuid)
998   end
999
1000   test "delete referring links in SweepTrashedObjects" do
1001     uuid = collections(:trashed_on_next_sweep).uuid
1002     act_as_system_user do
1003       Link.create!(head_uuid: uuid,
1004                    tail_uuid: system_user_uuid,
1005                    link_class: 'whatever',
1006                    name: 'something')
1007     end
1008     past = db_current_time
1009     Collection.where(uuid: uuid).
1010       update_all(is_trashed: true, trash_at: past, delete_at: past)
1011     assert_not_empty Collection.where(uuid: uuid)
1012     SweepTrashedObjects.sweep_now
1013     assert_empty Collection.where(uuid: uuid)
1014   end
1015
1016   test "empty names are exempt from name uniqueness" do
1017     act_as_user users(:active) do
1018       c1 = Collection.new(name: nil, manifest_text: '', owner_uuid: groups(:aproject).uuid)
1019       assert c1.save
1020       c2 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1021       assert c2.save
1022       c3 = Collection.new(name: '', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1023       assert c3.save
1024       c4 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1025       assert c4.save
1026       c5 = Collection.new(name: 'c4', manifest_text: '', owner_uuid: groups(:aproject).uuid)
1027       assert_raises(ActiveRecord::RecordNotUnique) do
1028         c5.save
1029       end
1030     end
1031   end
1032
1033   test "create collections with managed properties" do
1034     Rails.configuration.Collections.ManagedProperties = {
1035       'default_prop1' => {'Value' => 'prop1_value'},
1036       'responsible_person_uuid' => {'Function' => 'original_owner'}
1037     }
1038     # Test collection without initial properties
1039     act_as_user users(:active) do
1040       c = create_collection 'foo', Encoding::US_ASCII
1041       assert c.valid?
1042       assert_not_empty c.properties
1043       assert_equal 'prop1_value', c.properties['default_prop1']
1044       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1045     end
1046     # Test collection with default_prop1 property already set
1047     act_as_user users(:active) do
1048       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n",
1049                             properties: {'default_prop1' => 'custom_value'})
1050       assert c.valid?
1051       assert_not_empty c.properties
1052       assert_equal 'custom_value', c.properties['default_prop1']
1053       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1054     end
1055     # Test collection inside a sub project
1056     act_as_user users(:active) do
1057       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n",
1058                             owner_uuid: groups(:asubproject).uuid)
1059       assert c.valid?
1060       assert_not_empty c.properties
1061       assert_equal users(:active).uuid, c.properties['responsible_person_uuid']
1062     end
1063   end
1064
1065   test "update collection with protected managed properties" do
1066     Rails.configuration.Collections.ManagedProperties = {
1067       'default_prop1' => {'Value' => 'prop1_value', 'Protected' => true},
1068     }
1069     act_as_user users(:active) do
1070       c = create_collection 'foo', Encoding::US_ASCII
1071       assert c.valid?
1072       assert_not_empty c.properties
1073       assert_equal 'prop1_value', c.properties['default_prop1']
1074       # Add new property
1075       c.properties['prop2'] = 'value2'
1076       c.save!
1077       c.reload
1078       assert_equal 'value2', c.properties['prop2']
1079       # Try to change protected property's value
1080       c.properties['default_prop1'] = 'new_value'
1081       assert_raises(ArvadosModel::PermissionDeniedError) do
1082         c.save!
1083       end
1084       # Admins are allowed to change protected properties
1085       act_as_system_user do
1086         c.properties['default_prop1'] = 'new_value'
1087         c.save!
1088         c.reload
1089         assert_equal 'new_value', c.properties['default_prop1']
1090       end
1091     end
1092   end
1093
1094   test "collection names must be displayable in a filesystem" do
1095     set_user_from_auth :active
1096     ["", "{SOLIDUS}"].each do |subst|
1097       Rails.configuration.Collections.ForwardSlashNameSubstitution = subst
1098       c = Collection.create
1099       [[nil, true],
1100        ["", true],
1101        [".", false],
1102        ["..", false],
1103        ["...", true],
1104        ["..z..", true],
1105        ["foo/bar", subst != ""],
1106        ["../..", subst != ""],
1107        ["/", subst != ""],
1108       ].each do |name, valid|
1109         c.name = name
1110         assert_equal valid, c.valid?, "#{name.inspect} should be #{valid ? "valid" : "invalid"}"
1111       end
1112     end
1113   end
1114 end