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