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