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