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