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