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