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