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