8538b35b35c7ba20738144b166326ee7257e4df9
[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       # Changing file stats via an update should fail validation
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       c.reload
85       assert_equal 1, c.file_count
86       assert_equal 34, c.file_size_total
87
88       # Changing the file stats via manifest change validates
89       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt 0:34:foo2.txt\n")
90       c.reload
91       assert c.valid?
92       assert_equal 2, c.file_count
93       assert_equal 68, c.file_size_total
94
95       # Changing file stats at create, will silently overwrite
96       c = Collection.create(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:34:foo.txt\n", file_count: 10, file_size_total: 10)
97       c.reload
98       assert c.valid?
99       assert_equal 1, c.file_count
100       assert_equal 34, c.file_size_total
101     end
102   end
103
104   [
105     nil,
106     "",
107     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
108   ].each do |manifest_text|
109     test "create collection with valid manifest text #{manifest_text.inspect} and expect success" do
110       act_as_system_user do
111         c = Collection.create(manifest_text: manifest_text)
112         assert c.valid?
113       end
114     end
115   end
116
117   [
118     ". 0:0:foo.txt",
119     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
120     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
121     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
122   ].each do |manifest_text|
123     test "update collection with invalid manifest text #{manifest_text} and expect error" do
124       act_as_system_user do
125         c = create_collection 'foo', Encoding::US_ASCII
126         assert c.valid?
127
128         c.update_attribute 'manifest_text', manifest_text
129         assert !c.valid?
130       end
131     end
132   end
133
134   [
135     nil,
136     "",
137     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
138   ].each do |manifest_text|
139     test "update collection with valid manifest text #{manifest_text.inspect} and expect success" do
140       act_as_system_user do
141         c = create_collection 'foo', Encoding::US_ASCII
142         assert c.valid?
143
144         c.update_attribute 'manifest_text', manifest_text
145         assert c.valid?
146       end
147     end
148   end
149
150   test "auto-create version after idle setting" do
151     Rails.configuration.collection_versioning = true
152     Rails.configuration.preserve_version_if_idle = 600 # 10 minutes
153     act_as_user users(:active) do
154       # Set up initial collection
155       c = create_collection 'foo', Encoding::US_ASCII
156       assert c.valid?
157       assert_equal 1, c.version
158       assert_equal false, c.preserve_version
159       # Make a versionable update, it shouldn't create a new version yet
160       c.update_attributes!({'name' => 'bar'})
161       c.reload
162       assert_equal 'bar', c.name
163       assert_equal 1, c.version
164       # Update modified_at to trigger a version auto-creation
165       fifteen_min_ago = Time.now - 15.minutes
166       c.update_column('modified_at', fifteen_min_ago) # Update without validations/callbacks
167       c.reload
168       assert_equal fifteen_min_ago.to_i, c.modified_at.to_i
169       c.update_attributes!({'name' => 'baz'})
170       c.reload
171       assert_equal 'baz', c.name
172       assert_equal 2, c.version
173       # Make another update, no new version should be created
174       c.update_attributes!({'name' => 'foobar'})
175       c.reload
176       assert_equal 'foobar', c.name
177       assert_equal 2, c.version
178     end
179   end
180
181   test "preserve_version=false assignment is ignored while being true and not producing a new version" do
182     Rails.configuration.collection_versioning = true
183     Rails.configuration.preserve_version_if_idle = 3600
184     act_as_user users(:active) do
185       # Set up initial collection
186       c = create_collection 'foo', Encoding::US_ASCII
187       assert c.valid?
188       assert_equal 1, c.version
189       assert_equal false, c.preserve_version
190       # This update shouldn't produce a new version, as the idle time is not up
191       c.update_attributes!({
192         'name' => 'bar',
193         'preserve_version' => true
194       })
195       c.reload
196       assert_equal 1, c.version
197       assert_equal 'bar', c.name
198       assert_equal true, c.preserve_version
199       # Make sure preserve_version is not disabled after being enabled, unless
200       # a new version is created.
201       c.update_attributes!({
202         'preserve_version' => false,
203         'replication_desired' => 2
204       })
205       c.reload
206       assert_equal 1, c.version
207       assert_equal 2, c.replication_desired
208       assert_equal true, c.preserve_version
209       c.update_attributes!({'name' => 'foobar'})
210       c.reload
211       assert_equal 2, c.version
212       assert_equal false, c.preserve_version
213       assert_equal 'foobar', c.name
214     end
215   end
216
217   [
218     ['version', 10],
219     ['current_version_uuid', 'zzzzz-4zz18-bv31uwvy3neko21'],
220   ].each do |name, new_value|
221     test "'#{name}' updates on current version collections are not allowed" do
222       act_as_user users(:active) do
223         # Set up initial collection
224         c = create_collection 'foo', Encoding::US_ASCII
225         assert c.valid?
226         assert_equal 1, c.version
227
228         assert_raises(ActiveRecord::RecordInvalid) do
229           c.update_attributes!({
230             name => new_value
231           })
232         end
233       end
234     end
235   end
236
237   test "uuid updates on current version make older versions update their pointers" do
238     Rails.configuration.collection_versioning = true
239     Rails.configuration.preserve_version_if_idle = 0
240     act_as_system_user do
241       # Set up initial collection
242       c = create_collection 'foo', Encoding::US_ASCII
243       assert c.valid?
244       assert_equal 1, c.version
245       # Make changes so that a new version is created
246       c.update_attributes!({'name' => 'bar'})
247       c.reload
248       assert_equal 2, c.version
249       assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
250       new_uuid = 'zzzzz-4zz18-somefakeuuidnow'
251       assert_empty Collection.where(uuid: new_uuid)
252       # Update UUID on current version, check that both collections point to it
253       c.update_attributes!({'uuid' => new_uuid})
254       c.reload
255       assert_equal new_uuid, c.uuid
256       assert_equal 2, Collection.where(current_version_uuid: new_uuid).count
257     end
258   end
259
260   test "older versions' modified_at indicate when they're created" do
261     Rails.configuration.collection_versioning = true
262     Rails.configuration.preserve_version_if_idle = 0
263     act_as_user users(:active) do
264       # Set up initial collection
265       c = create_collection 'foo', Encoding::US_ASCII
266       assert c.valid?
267       # Make changes so that a new version is created
268       c.update_attributes!({'name' => 'bar'})
269       c.reload
270       assert_equal 2, c.version
271       # Get the old version
272       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
273       assert_not_nil c_old
274
275       version_creation_datetime = c_old.modified_at.to_f
276       assert_equal c.created_at.to_f, c_old.created_at.to_f
277       # Current version is updated just a few milliseconds before the version is
278       # saved on the database.
279       assert_operator c.modified_at.to_f, :<, version_creation_datetime
280
281       # Make update on current version so old version get the attribute synced;
282       # its modified_at should not change.
283       new_replication = 3
284       c.update_attributes!({'replication_desired' => new_replication})
285       c.reload
286       assert_equal new_replication, c.replication_desired
287       c_old.reload
288       assert_equal new_replication, c_old.replication_desired
289       assert_equal version_creation_datetime, c_old.modified_at.to_f
290       assert_operator c.modified_at.to_f, :>, c_old.modified_at.to_f
291     end
292   end
293
294   test "past versions should not be directly updatable" do
295     Rails.configuration.collection_versioning = true
296     Rails.configuration.preserve_version_if_idle = 0
297     act_as_system_user do
298       # Set up initial collection
299       c = create_collection 'foo', Encoding::US_ASCII
300       assert c.valid?
301       # Make changes so that a new version is created
302       c.update_attributes!({'name' => 'bar'})
303       c.reload
304       assert_equal 2, c.version
305       # Get the old version
306       c_old = Collection.where(current_version_uuid: c.uuid, version: 1).first
307       assert_not_nil c_old
308       # With collection versioning still being enabled, try to update
309       c_old.name = 'this was foo'
310       assert c_old.invalid?
311       c_old.reload
312       # Try to fool the validator attempting to make c_old to look like a
313       # current version, it should also fail.
314       c_old.current_version_uuid = c_old.uuid
315       assert c_old.invalid?
316       c_old.reload
317       # Now disable collection versioning, it should behave the same way
318       Rails.configuration.collection_versioning = false
319       c_old.name = 'this was foo'
320       assert c_old.invalid?
321     end
322   end
323
324   [
325     ['owner_uuid', 'zzzzz-tpzed-d9tiejq69daie8f', 'zzzzz-tpzed-xurymjxw79nv3jz'],
326     ['replication_desired', 2, 3],
327     ['storage_classes_desired', ['hot'], ['archive']],
328     ['is_trashed', true, false],
329   ].each do |attr, first_val, second_val|
330     test "sync #{attr} with older versions" do
331       Rails.configuration.collection_versioning = true
332       Rails.configuration.preserve_version_if_idle = 0
333       act_as_system_user do
334         # Set up initial collection
335         c = create_collection 'foo', Encoding::US_ASCII
336         assert c.valid?
337         assert_equal 1, c.version
338         assert_not_equal first_val, c.attributes[attr]
339         # Make changes so that a new version is created and a synced field is
340         # updated on both
341         c.update_attributes!({'name' => 'bar', attr => first_val})
342         c.reload
343         assert_equal 2, c.version
344         assert_equal first_val, c.attributes[attr]
345         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
346         assert_equal first_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
347         # Only make an update on the same synced field & check that the previously
348         # created version also gets it.
349         c.update_attributes!({attr => second_val})
350         c.reload
351         assert_equal 2, c.version
352         assert_equal second_val, c.attributes[attr]
353         assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
354         assert_equal second_val, Collection.where(current_version_uuid: c.uuid, version: 1).first.attributes[attr]
355       end
356     end
357   end
358
359   [
360     [false, 'name', 'bar', false],
361     [false, 'description', 'The quick brown fox jumps over the lazy dog', false],
362     [false, 'properties', {'new_version' => true}, false],
363     [false, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", false],
364     [true, 'name', 'bar', true],
365     [true, 'description', 'The quick brown fox jumps over the lazy dog', true],
366     [true, 'properties', {'new_version' => true}, true],
367     [true, 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", true],
368     # Non-versionable attribute updates shouldn't create new versions
369     [true, 'replication_desired', 5, false],
370     [false, 'replication_desired', 5, false],
371   ].each do |versioning, attr, val, new_version_expected|
372     test "update #{attr} with versioning #{versioning ? '' : 'not '}enabled should #{new_version_expected ? '' : 'not '}create a new version" do
373       Rails.configuration.collection_versioning = versioning
374       Rails.configuration.preserve_version_if_idle = 0
375       act_as_user users(:active) do
376         # Create initial collection
377         c = create_collection 'foo', Encoding::US_ASCII
378         assert c.valid?
379         assert_equal 'foo', c.name
380
381         # Check current version attributes
382         assert_equal 1, c.version
383         assert_equal c.uuid, c.current_version_uuid
384
385         # Update attribute and check if version number should be incremented
386         old_value = c.attributes[attr]
387         c.update_attributes!({attr => val})
388         assert_equal new_version_expected, c.version == 2
389         assert_equal val, c.attributes[attr]
390
391         if versioning && new_version_expected
392           # Search for the snapshot & previous value
393           assert_equal 2, Collection.where(current_version_uuid: c.uuid).count
394           s = Collection.where(current_version_uuid: c.uuid, version: 1).first
395           assert_not_nil s
396           assert_equal old_value, s.attributes[attr]
397         else
398           # If versioning is disabled or no versionable attribute was updated,
399           # only the current version should exist
400           assert_equal 1, Collection.where(current_version_uuid: c.uuid).count
401           assert_equal c, Collection.where(current_version_uuid: c.uuid).first
402         end
403       end
404     end
405   end
406
407   test 'current_version_uuid is ignored during update' do
408     Rails.configuration.collection_versioning = true
409     Rails.configuration.preserve_version_if_idle = 0
410     act_as_user users(:active) do
411       # Create 1st collection
412       col1 = create_collection 'foo', Encoding::US_ASCII
413       assert col1.valid?
414       assert_equal 1, col1.version
415
416       # Create 2nd collection, update it so it becomes version:2
417       # (to avoid unique index violation)
418       col2 = create_collection 'bar', Encoding::US_ASCII
419       assert col2.valid?
420       assert_equal 1, col2.version
421       col2.update_attributes({name: 'baz'})
422       assert_equal 2, col2.version
423
424       # Try to make col2 a past version of col1. It shouldn't be possible
425       col2.update_attributes({current_version_uuid: col1.uuid})
426       assert col2.invalid?
427       col2.reload
428       assert_not_equal col1.uuid, col2.current_version_uuid
429     end
430   end
431
432   test 'with versioning enabled, simultaneous updates increment version correctly' do
433     Rails.configuration.collection_versioning = true
434     Rails.configuration.preserve_version_if_idle = 0
435     act_as_user users(:active) do
436       # Create initial collection
437       col = create_collection 'foo', Encoding::US_ASCII
438       assert col.valid?
439       assert_equal 1, col.version
440
441       # Simulate simultaneous updates
442       c1 = Collection.where(uuid: col.uuid).first
443       assert_equal 1, c1.version
444       c1.name = 'bar'
445       c2 = Collection.where(uuid: col.uuid).first
446       c2.description = 'foo collection'
447       c1.save!
448       assert_equal 1, c2.version
449       # with_lock forces a reload, so this shouldn't produce an unique violation error
450       c2.save!
451       assert_equal 3, c2.version
452       assert_equal 'foo collection', c2.description
453     end
454   end
455
456   test 'create and update collection and verify file_names' do
457     act_as_system_user do
458       c = create_collection 'foo', Encoding::US_ASCII
459       assert c.valid?
460       created_file_names = c.file_names
461       assert created_file_names
462       assert_match(/foo.txt/, c.file_names)
463
464       c.update_attribute 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo2.txt\n"
465       assert_not_equal created_file_names, c.file_names
466       assert_match(/foo2.txt/, c.file_names)
467     end
468   end
469
470   [
471     [2**8, false],
472     [2**18, true],
473   ].each do |manifest_size, allow_truncate|
474     test "create collection with manifest size #{manifest_size} with allow_truncate=#{allow_truncate},
475           and not expect exceptions even on very large manifest texts" do
476       # file_names has a max size, hence there will be no errors even on large manifests
477       act_as_system_user do
478         manifest_text = ''
479         index = 0
480         while manifest_text.length < manifest_size
481           manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
482           index += 1
483         end
484         manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
485         c = Collection.create(manifest_text: manifest_text)
486
487         assert c.valid?
488         assert c.file_names
489         assert_match(/veryverylongfilename0000000000001.txt/, c.file_names)
490         assert_match(/veryverylongfilename0000000000002.txt/, c.file_names)
491         if not allow_truncate
492           assert_match(/veryverylastfilename/, c.file_names)
493           assert_match(/laststreamname/, c.file_names)
494         end
495       end
496     end
497   end
498
499   test "full text search for collections" do
500     # file_names column does not get populated when fixtures are loaded, hence setup test data
501     act_as_system_user do
502       Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n")
503       Collection.create(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
504       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")
505     end
506
507     [
508       ['foo', true],
509       ['foo bar', false],                     # no collection matching both
510       ['foo&bar', false],                     # no collection matching both
511       ['foo|bar', true],                      # works only no spaces between the words
512       ['Gnu public', true],                   # both prefixes found, though not consecutively
513       ['Gnu&public', true],                   # both prefixes found, though not consecutively
514       ['file4', true],                        # prefix match
515       ['file4.txt', true],                    # whole string match
516       ['filex', false],                       # no such prefix
517       ['subdir', true],                       # prefix matches
518       ['subdir2', true],
519       ['subdir2/', true],
520       ['subdir2/subdir3', true],
521       ['subdir2/subdir3/subdir4', true],
522       ['subdir2 file4', true],                # look for both prefixes
523       ['subdir4', false],                     # not a prefix match
524     ].each do |search_filter, expect_results|
525       search_filters = search_filter.split.each {|s| s.concat(':*')}.join('&')
526       results = Collection.where("#{Collection.full_text_tsvector} @@ to_tsquery(?)",
527                                  "#{search_filters}")
528       if expect_results
529         refute_empty results
530       else
531         assert_empty results
532       end
533     end
534   end
535
536   test 'portable data hash with missing size hints' do
537     [[". d41d8cd98f00b204e9800998ecf8427e+0+Bar 0:0:x\n",
538       ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"],
539      [". d41d8cd98f00b204e9800998ecf8427e+Foo 0:0:x\n",
540       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
541      [". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n",
542       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
543     ].each do |unportable, portable|
544       c = Collection.new(manifest_text: unportable)
545       assert c.valid?
546       assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
547                    c.portable_data_hash)
548     end
549   end
550
551   pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
552   pdhmd5 = Digest::MD5.hexdigest pdhmanifest
553   [[true, nil],
554    [true, pdhmd5],
555    [true, pdhmd5+'+12345'],
556    [true, pdhmd5+'+'+pdhmanifest.length.to_s],
557    [true, pdhmd5+'+12345+Foo'],
558    [true, pdhmd5+'+Foo'],
559    [false, Digest::MD5.hexdigest(pdhmanifest.strip)],
560    [false, Digest::MD5.hexdigest(pdhmanifest.strip)+'+'+pdhmanifest.length.to_s],
561    [false, pdhmd5[0..30]],
562    [false, pdhmd5[0..30]+'z'],
563    [false, pdhmd5[0..24]+'000000000'],
564    [false, pdhmd5[0..24]+'000000000+0']].each do |isvalid, pdh|
565     test "portable_data_hash #{pdh.inspect} valid? == #{isvalid}" do
566       c = Collection.new manifest_text: pdhmanifest, portable_data_hash: pdh
567       assert_equal isvalid, c.valid?, c.errors.full_messages.to_s
568     end
569   end
570
571   test "storage_classes_desired cannot be empty" do
572     act_as_user users(:active) do
573       c = collections(:collection_owned_by_active)
574       c.update_attributes storage_classes_desired: ["hot"]
575       assert_equal ["hot"], c.storage_classes_desired
576       assert_raise ArvadosModel::InvalidStateTransitionError do
577         c.update_attributes storage_classes_desired: []
578       end
579     end
580   end
581
582   test "storage classes lists should only contain non-empty strings" do
583     c = collections(:storage_classes_desired_default_unconfirmed)
584     act_as_user users(:admin) do
585       assert c.update_attributes(storage_classes_desired: ["default", "a_string"],
586                                  storage_classes_confirmed: ["another_string"])
587       [
588         ["storage_classes_desired", ["default", 42]],
589         ["storage_classes_confirmed", [{the_answer: 42}]],
590         ["storage_classes_desired", ["default", ""]],
591         ["storage_classes_confirmed", [""]],
592       ].each do |attr, val|
593         assert_raise ArvadosModel::InvalidStateTransitionError do
594           assert c.update_attributes({attr => val})
595         end
596       end
597     end
598   end
599
600   test "storage_classes_confirmed* can be set by admin user" do
601     c = collections(:storage_classes_desired_default_unconfirmed)
602     act_as_user users(:admin) do
603       assert c.update_attributes(storage_classes_confirmed: ["default"],
604                                  storage_classes_confirmed_at: Time.now)
605     end
606   end
607
608   test "storage_classes_confirmed* cannot be set by non-admin user" do
609     act_as_user users(:active) do
610       c = collections(:storage_classes_desired_default_unconfirmed)
611       # Cannot set just one at a time.
612       assert_raise ArvadosModel::PermissionDeniedError do
613         c.update_attributes storage_classes_confirmed: ["default"]
614       end
615       c.reload
616       assert_raise ArvadosModel::PermissionDeniedError do
617         c.update_attributes storage_classes_confirmed_at: Time.now
618       end
619       # Cannot set bot at once, either.
620       c.reload
621       assert_raise ArvadosModel::PermissionDeniedError do
622         assert c.update_attributes(storage_classes_confirmed: ["default"],
623                                    storage_classes_confirmed_at: Time.now)
624       end
625     end
626   end
627
628   test "storage_classes_confirmed* can be cleared (but only together) by non-admin user" do
629     act_as_user users(:active) do
630       c = collections(:storage_classes_desired_default_confirmed_default)
631       # Cannot clear just one at a time.
632       assert_raise ArvadosModel::PermissionDeniedError do
633         c.update_attributes storage_classes_confirmed: []
634       end
635       c.reload
636       assert_raise ArvadosModel::PermissionDeniedError do
637         c.update_attributes storage_classes_confirmed_at: nil
638       end
639       # Can clear both at once.
640       c.reload
641       assert c.update_attributes(storage_classes_confirmed: [],
642                                  storage_classes_confirmed_at: nil)
643     end
644   end
645
646   [0, 2, 4, nil].each do |ask|
647     test "set replication_desired to #{ask.inspect}" do
648       Rails.configuration.default_collection_replication = 2
649       act_as_user users(:active) do
650         c = collections(:replication_undesired_unconfirmed)
651         c.update_attributes replication_desired: ask
652         assert_equal ask, c.replication_desired
653       end
654     end
655   end
656
657   test "replication_confirmed* can be set by admin user" do
658     c = collections(:replication_desired_2_unconfirmed)
659     act_as_user users(:admin) do
660       assert c.update_attributes(replication_confirmed: 2,
661                                  replication_confirmed_at: Time.now)
662     end
663   end
664
665   test "replication_confirmed* cannot be set by non-admin user" do
666     act_as_user users(:active) do
667       c = collections(:replication_desired_2_unconfirmed)
668       # Cannot set just one at a time.
669       assert_raise ArvadosModel::PermissionDeniedError do
670         c.update_attributes replication_confirmed: 1
671       end
672       assert_raise ArvadosModel::PermissionDeniedError do
673         c.update_attributes replication_confirmed_at: Time.now
674       end
675       # Cannot set both at once, either.
676       assert_raise ArvadosModel::PermissionDeniedError do
677         c.update_attributes(replication_confirmed: 1,
678                             replication_confirmed_at: Time.now)
679       end
680     end
681   end
682
683   test "replication_confirmed* can be cleared (but only together) by non-admin user" do
684     act_as_user users(:active) do
685       c = collections(:replication_desired_2_confirmed_2)
686       # Cannot clear just one at a time.
687       assert_raise ArvadosModel::PermissionDeniedError do
688         c.update_attributes replication_confirmed: nil
689       end
690       c.reload
691       assert_raise ArvadosModel::PermissionDeniedError do
692         c.update_attributes replication_confirmed_at: nil
693       end
694       # Can clear both at once.
695       c.reload
696       assert c.update_attributes(replication_confirmed: nil,
697                                  replication_confirmed_at: nil)
698     end
699   end
700
701   test "clear replication_confirmed* when introducing a new block in manifest" do
702     c = collections(:replication_desired_2_confirmed_2)
703     act_as_user users(:active) do
704       assert c.update_attributes(manifest_text: collections(:user_agreement).signed_manifest_text)
705       assert_nil c.replication_confirmed
706       assert_nil c.replication_confirmed_at
707     end
708   end
709
710   test "don't clear replication_confirmed* when just renaming a file" do
711     c = collections(:replication_desired_2_confirmed_2)
712     act_as_user users(:active) do
713       new_manifest = c.signed_manifest_text.sub(':bar', ':foo')
714       assert c.update_attributes(manifest_text: new_manifest)
715       assert_equal 2, c.replication_confirmed
716       assert_not_nil c.replication_confirmed_at
717     end
718   end
719
720   test "don't clear replication_confirmed* when just deleting a data block" do
721     c = collections(:replication_desired_2_confirmed_2)
722     act_as_user users(:active) do
723       new_manifest = c.signed_manifest_text
724       new_manifest.sub!(/ \S+:bar/, '')
725       new_manifest.sub!(/ acbd\S+/, '')
726
727       # Confirm that we did just remove a block from the manifest (if
728       # not, this test would pass without testing the relevant case):
729       assert_operator new_manifest.length+40, :<, c.signed_manifest_text.length
730
731       assert c.update_attributes(manifest_text: new_manifest)
732       assert_equal 2, c.replication_confirmed
733       assert_not_nil c.replication_confirmed_at
734     end
735   end
736
737   test 'signature expiry does not exceed trash_at' do
738     act_as_user users(:active) do
739       t0 = db_current_time
740       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
741       c.update_attributes! trash_at: (t0 + 1.hours)
742       c.reload
743       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
744       assert_operator sig_exp.to_i, :<=, (t0 + 1.hours).to_i
745     end
746   end
747
748   test 'far-future expiry date cannot be used to circumvent configured permission ttl' do
749     act_as_user users(:active) do
750       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n",
751                              name: 'foo',
752                              trash_at: db_current_time + 1.years)
753       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
754       expect_max_sig_exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
755       assert_operator c.trash_at.to_i, :>, expect_max_sig_exp
756       assert_operator sig_exp.to_i, :<=, expect_max_sig_exp
757     end
758   end
759
760   test "create collection with properties" do
761     act_as_system_user do
762       c = Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n",
763                             properties: {'property_1' => 'value_1'})
764       assert c.valid?
765       assert_equal 'value_1', c.properties['property_1']
766     end
767   end
768
769   test 'create, delete, recreate collection with same name and owner' do
770     act_as_user users(:active) do
771       # create collection with name
772       c = Collection.create(manifest_text: '',
773                             name: "test collection name")
774       assert c.valid?
775       uuid = c.uuid
776
777       c = Collection.readable_by(current_user).where(uuid: uuid)
778       assert_not_empty c, 'Should be able to find live collection'
779
780       # mark collection as expired
781       c.first.update_attributes!(trash_at: Time.new.strftime("%Y-%m-%d"))
782       c = Collection.readable_by(current_user).where(uuid: uuid)
783       assert_empty c, 'Should not be able to find expired collection'
784
785       # recreate collection with the same name
786       c = Collection.create(manifest_text: '',
787                             name: "test collection name")
788       assert c.valid?
789     end
790   end
791
792   test 'trash_at cannot be set too far in the past' do
793     act_as_user users(:active) do
794       t0 = db_current_time
795       c = Collection.create!(manifest_text: '', name: 'foo')
796       c.update_attributes! trash_at: (t0 - 2.weeks)
797       c.reload
798       assert_operator c.trash_at, :>, t0
799     end
800   end
801
802   now = Time.now
803   [['trash-to-delete interval negative',
804     :collection_owned_by_active,
805     {trash_at: now+2.weeks, delete_at: now},
806     {state: :invalid}],
807    ['now-to-delete interval short',
808     :collection_owned_by_active,
809     {trash_at: now+3.days, delete_at: now+7.days},
810     {state: :trash_future}],
811    ['now-to-delete interval short, trash=delete',
812     :collection_owned_by_active,
813     {trash_at: now+3.days, delete_at: now+3.days},
814     {state: :trash_future}],
815    ['trash-to-delete interval ok',
816     :collection_owned_by_active,
817     {trash_at: now, delete_at: now+15.days},
818     {state: :trash_now}],
819    ['trash-to-delete interval short, but far enough in future',
820     :collection_owned_by_active,
821     {trash_at: now+13.days, delete_at: now+15.days},
822     {state: :trash_future}],
823    ['trash by setting is_trashed bool',
824     :collection_owned_by_active,
825     {is_trashed: true},
826     {state: :trash_now}],
827    ['trash in future by setting just trash_at',
828     :collection_owned_by_active,
829     {trash_at: now+1.week},
830     {state: :trash_future}],
831    ['trash in future by setting trash_at and delete_at',
832     :collection_owned_by_active,
833     {trash_at: now+1.week, delete_at: now+4.weeks},
834     {state: :trash_future}],
835    ['untrash by clearing is_trashed bool',
836     :expired_collection,
837     {is_trashed: false},
838     {state: :not_trash}],
839   ].each do |test_name, fixture_name, updates, expect|
840     test test_name do
841       act_as_user users(:active) do
842         min_exp = (db_current_time +
843                    Rails.configuration.blob_signature_ttl.seconds)
844         if fixture_name == :expired_collection
845           # Fixture-finder shorthand doesn't find trashed collections
846           # because they're not in the default scope.
847           c = Collection.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
848         else
849           c = collections(fixture_name)
850         end
851         updates_ok = c.update_attributes(updates)
852         expect_valid = expect[:state] != :invalid
853         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
854         case expect[:state]
855         when :invalid
856           refute c.valid?
857         when :trash_now
858           assert c.is_trashed
859           assert_not_nil c.trash_at
860           assert_operator c.trash_at, :<=, db_current_time
861           assert_not_nil c.delete_at
862           assert_operator c.delete_at, :>=, min_exp
863         when :trash_future
864           refute c.is_trashed
865           assert_not_nil c.trash_at
866           assert_operator c.trash_at, :>, db_current_time
867           assert_not_nil c.delete_at
868           assert_operator c.delete_at, :>=, c.trash_at
869           # Currently this minimum interval is needed to prevent early
870           # garbage collection:
871           assert_operator c.delete_at, :>=, min_exp
872         when :not_trash
873           refute c.is_trashed
874           assert_nil c.trash_at
875           assert_nil c.delete_at
876         else
877           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
878         end
879       end
880     end
881   end
882
883   test 'default trash interval > blob signature ttl' do
884     Rails.configuration.default_trash_lifetime = 86400 * 21 # 3 weeks
885     start = db_current_time
886     act_as_user users(:active) do
887       c = Collection.create!(manifest_text: '', name: 'foo')
888       c.update_attributes!(trash_at: start + 86400.seconds)
889       assert_operator c.delete_at, :>=, start + (86400*22).seconds
890       assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
891       c.destroy
892
893       c = Collection.create!(manifest_text: '', name: 'foo')
894       c.update_attributes!(is_trashed: true)
895       assert_operator c.delete_at, :>=, start + (86400*21).seconds
896     end
897   end
898
899   test "find_all_for_docker_image resolves names that look like hashes" do
900     coll_list = Collection.
901       find_all_for_docker_image('a' * 64, nil, [users(:active)])
902     coll_uuids = coll_list.map(&:uuid)
903     assert_includes(coll_uuids, collections(:docker_image).uuid)
904   end
905
906   test "move collections to trash in SweepTrashedObjects" do
907     c = collections(:trashed_on_next_sweep)
908     refute_empty Collection.where('uuid=? and is_trashed=false', c.uuid)
909     assert_raises(ActiveRecord::RecordNotUnique) do
910       act_as_user users(:active) do
911         Collection.create!(owner_uuid: c.owner_uuid,
912                            name: c.name)
913       end
914     end
915     SweepTrashedObjects.sweep_now
916     c = Collection.where('uuid=? and is_trashed=true', c.uuid).first
917     assert c
918     act_as_user users(:active) do
919       assert Collection.create!(owner_uuid: c.owner_uuid,
920                                 name: c.name)
921     end
922   end
923
924   test "delete collections in SweepTrashedObjects" do
925     uuid = 'zzzzz-4zz18-3u1p5umicfpqszp' # deleted_on_next_sweep
926     assert_not_empty Collection.where(uuid: uuid)
927     SweepTrashedObjects.sweep_now
928     assert_empty Collection.where(uuid: uuid)
929   end
930
931   test "delete referring links in SweepTrashedObjects" do
932     uuid = collections(:trashed_on_next_sweep).uuid
933     act_as_system_user do
934       Link.create!(head_uuid: uuid,
935                    tail_uuid: system_user_uuid,
936                    link_class: 'whatever',
937                    name: 'something')
938     end
939     past = db_current_time
940     Collection.where(uuid: uuid).
941       update_all(is_trashed: true, trash_at: past, delete_at: past)
942     assert_not_empty Collection.where(uuid: uuid)
943     SweepTrashedObjects.sweep_now
944     assert_empty Collection.where(uuid: uuid)
945   end
946 end