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