62e3755a3fb8793d3b05c2766fbc5c5705245315
[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_collections'
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)
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 'create and update collection and verify file_names' do
110     act_as_system_user do
111       c = create_collection 'foo', Encoding::US_ASCII
112       assert c.valid?
113       created_file_names = c.file_names
114       assert created_file_names
115       assert_match(/foo.txt/, c.file_names)
116
117       c.update_attribute 'manifest_text', ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo2.txt\n"
118       assert_not_equal created_file_names, c.file_names
119       assert_match(/foo2.txt/, c.file_names)
120     end
121   end
122
123   [
124     [2**8, false],
125     [2**18, true],
126   ].each do |manifest_size, allow_truncate|
127     test "create collection with manifest size #{manifest_size} with allow_truncate=#{allow_truncate},
128           and not expect exceptions even on very large manifest texts" do
129       # file_names has a max size, hence there will be no errors even on large manifests
130       act_as_system_user do
131         manifest_text = ''
132         index = 0
133         while manifest_text.length < manifest_size
134           manifest_text += "./blurfl d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylongfilename000000000000#{index}.txt\n"
135           index += 1
136         end
137         manifest_text += "./laststreamname d41d8cd98f00b204e9800998ecf8427e+0 0:0:veryverylastfilename.txt\n"
138         c = Collection.create(manifest_text: manifest_text)
139
140         assert c.valid?
141         assert c.file_names
142         assert_match(/veryverylongfilename0000000000001.txt/, c.file_names)
143         assert_match(/veryverylongfilename0000000000002.txt/, c.file_names)
144         if not allow_truncate
145           assert_match(/veryverylastfilename/, c.file_names)
146           assert_match(/laststreamname/, c.file_names)
147         end
148       end
149     end
150   end
151
152   test "full text search for collections" do
153     # file_names column does not get populated when fixtures are loaded, hence setup test data
154     act_as_system_user do
155       Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n")
156       Collection.create(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
157       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")
158     end
159
160     [
161       ['foo', true],
162       ['foo bar', false],                     # no collection matching both
163       ['foo&bar', false],                     # no collection matching both
164       ['foo|bar', true],                      # works only no spaces between the words
165       ['Gnu public', true],                   # both prefixes found, though not consecutively
166       ['Gnu&public', true],                   # both prefixes found, though not consecutively
167       ['file4', true],                        # prefix match
168       ['file4.txt', true],                    # whole string match
169       ['filex', false],                       # no such prefix
170       ['subdir', true],                       # prefix matches
171       ['subdir2', true],
172       ['subdir2/', true],
173       ['subdir2/subdir3', true],
174       ['subdir2/subdir3/subdir4', true],
175       ['subdir2 file4', true],                # look for both prefixes
176       ['subdir4', false],                     # not a prefix match
177     ].each do |search_filter, expect_results|
178       search_filters = search_filter.split.each {|s| s.concat(':*')}.join('&')
179       results = Collection.where("#{Collection.full_text_tsvector} @@ to_tsquery(?)",
180                                  "#{search_filters}")
181       if expect_results
182         refute_empty results
183       else
184         assert_empty results
185       end
186     end
187   end
188
189   test 'portable data hash with missing size hints' do
190     [[". d41d8cd98f00b204e9800998ecf8427e+0+Bar 0:0:x\n",
191       ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"],
192      [". d41d8cd98f00b204e9800998ecf8427e+Foo 0:0:x\n",
193       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
194      [". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n",
195       ". d41d8cd98f00b204e9800998ecf8427e 0:0:x\n"],
196     ].each do |unportable, portable|
197       c = Collection.new(manifest_text: unportable)
198       assert c.valid?
199       assert_equal(Digest::MD5.hexdigest(portable)+"+#{portable.length}",
200                    c.portable_data_hash)
201     end
202   end
203
204   pdhmanifest = ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n"
205   pdhmd5 = Digest::MD5.hexdigest pdhmanifest
206   [[true, nil],
207    [true, pdhmd5],
208    [true, pdhmd5+'+12345'],
209    [true, pdhmd5+'+'+pdhmanifest.length.to_s],
210    [true, pdhmd5+'+12345+Foo'],
211    [true, pdhmd5+'+Foo'],
212    [false, Digest::MD5.hexdigest(pdhmanifest.strip)],
213    [false, Digest::MD5.hexdigest(pdhmanifest.strip)+'+'+pdhmanifest.length.to_s],
214    [false, pdhmd5[0..30]],
215    [false, pdhmd5[0..30]+'z'],
216    [false, pdhmd5[0..24]+'000000000'],
217    [false, pdhmd5[0..24]+'000000000+0']].each do |isvalid, pdh|
218     test "portable_data_hash #{pdh.inspect} valid? == #{isvalid}" do
219       c = Collection.new manifest_text: pdhmanifest, portable_data_hash: pdh
220       assert_equal isvalid, c.valid?, c.errors.full_messages.to_s
221     end
222   end
223
224   [0, 2, 4, nil].each do |ask|
225     test "set replication_desired to #{ask.inspect}" do
226       Rails.configuration.default_collection_replication = 2
227       act_as_user users(:active) do
228         c = collections(:replication_undesired_unconfirmed)
229         c.update_attributes replication_desired: ask
230         assert_equal ask, c.replication_desired
231       end
232     end
233   end
234
235   test "replication_confirmed* can be set by admin user" do
236     c = collections(:replication_desired_2_unconfirmed)
237     act_as_user users(:admin) do
238       assert c.update_attributes(replication_confirmed: 2,
239                                  replication_confirmed_at: Time.now)
240     end
241   end
242
243   test "replication_confirmed* cannot be set by non-admin user" do
244     act_as_user users(:active) do
245       c = collections(:replication_desired_2_unconfirmed)
246       # Cannot set just one at a time.
247       assert_raise ArvadosModel::PermissionDeniedError do
248         c.update_attributes replication_confirmed: 1
249       end
250       assert_raise ArvadosModel::PermissionDeniedError do
251         c.update_attributes replication_confirmed_at: Time.now
252       end
253       # Cannot set both at once, either.
254       assert_raise ArvadosModel::PermissionDeniedError do
255         c.update_attributes(replication_confirmed: 1,
256                             replication_confirmed_at: Time.now)
257       end
258     end
259   end
260
261   test "replication_confirmed* can be cleared (but only together) by non-admin user" do
262     act_as_user users(:active) do
263       c = collections(:replication_desired_2_confirmed_2)
264       # Cannot clear just one at a time.
265       assert_raise ArvadosModel::PermissionDeniedError do
266         c.update_attributes replication_confirmed: nil
267       end
268       c.reload
269       assert_raise ArvadosModel::PermissionDeniedError do
270         c.update_attributes replication_confirmed_at: nil
271       end
272       # Can clear both at once.
273       c.reload
274       assert c.update_attributes(replication_confirmed: nil,
275                                  replication_confirmed_at: nil)
276     end
277   end
278
279   test "clear replication_confirmed* when introducing a new block in manifest" do
280     c = collections(:replication_desired_2_confirmed_2)
281     act_as_user users(:active) do
282       assert c.update_attributes(manifest_text: collections(:user_agreement).signed_manifest_text)
283       assert_nil c.replication_confirmed
284       assert_nil c.replication_confirmed_at
285     end
286   end
287
288   test "don't clear replication_confirmed* when just renaming a file" do
289     c = collections(:replication_desired_2_confirmed_2)
290     act_as_user users(:active) do
291       new_manifest = c.signed_manifest_text.sub(':bar', ':foo')
292       assert c.update_attributes(manifest_text: new_manifest)
293       assert_equal 2, c.replication_confirmed
294       assert_not_nil c.replication_confirmed_at
295     end
296   end
297
298   test "don't clear replication_confirmed* when just deleting a data block" do
299     c = collections(:replication_desired_2_confirmed_2)
300     act_as_user users(:active) do
301       new_manifest = c.signed_manifest_text
302       new_manifest.sub!(/ \S+:bar/, '')
303       new_manifest.sub!(/ acbd\S+/, '')
304
305       # Confirm that we did just remove a block from the manifest (if
306       # not, this test would pass without testing the relevant case):
307       assert_operator new_manifest.length+40, :<, c.signed_manifest_text.length
308
309       assert c.update_attributes(manifest_text: new_manifest)
310       assert_equal 2, c.replication_confirmed
311       assert_not_nil c.replication_confirmed_at
312     end
313   end
314
315   test 'signature expiry does not exceed trash_at' do
316     act_as_user users(:active) do
317       t0 = db_current_time
318       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n", name: 'foo')
319       c.update_attributes! trash_at: (t0 + 1.hours)
320       c.reload
321       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
322       assert_operator sig_exp.to_i, :<=, (t0 + 1.hours).to_i
323     end
324   end
325
326   test 'far-future expiry date cannot be used to circumvent configured permission ttl' do
327     act_as_user users(:active) do
328       c = Collection.create!(manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:x\n",
329                              name: 'foo',
330                              trash_at: db_current_time + 1.years)
331       sig_exp = /\+A[0-9a-f]{40}\@([0-9]+)/.match(c.signed_manifest_text)[1].to_i
332       expect_max_sig_exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
333       assert_operator c.trash_at.to_i, :>, expect_max_sig_exp
334       assert_operator sig_exp.to_i, :<=, expect_max_sig_exp
335     end
336   end
337
338   test "create collection with properties" do
339     act_as_system_user do
340       c = Collection.create(manifest_text: ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n",
341                             properties: {'property_1' => 'value_1'})
342       assert c.valid?
343       assert_equal 'value_1', c.properties['property_1']
344     end
345   end
346
347   test 'create, delete, recreate collection with same name and owner' do
348     act_as_user users(:active) do
349       # create collection with name
350       c = Collection.create(manifest_text: '',
351                             name: "test collection name")
352       assert c.valid?
353       uuid = c.uuid
354
355       c = Collection.readable_by(current_user).where(uuid: uuid)
356       assert_not_empty c, 'Should be able to find live collection'
357
358       # mark collection as expired
359       c.first.update_attributes!(trash_at: Time.new.strftime("%Y-%m-%d"))
360       c = Collection.readable_by(current_user).where(uuid: uuid)
361       assert_empty c, 'Should not be able to find expired collection'
362
363       # recreate collection with the same name
364       c = Collection.create(manifest_text: '',
365                             name: "test collection name")
366       assert c.valid?
367     end
368   end
369
370   test 'trash_at cannot be set too far in the past' do
371     act_as_user users(:active) do
372       t0 = db_current_time
373       c = Collection.create!(manifest_text: '', name: 'foo')
374       c.update_attributes! trash_at: (t0 - 2.weeks)
375       c.reload
376       assert_operator c.trash_at, :>, t0
377     end
378   end
379
380   now = Time.now
381   [['trash-to-delete interval negative',
382     :collection_owned_by_active,
383     {trash_at: now+2.weeks, delete_at: now},
384     {state: :invalid}],
385    ['now-to-delete interval short',
386     :collection_owned_by_active,
387     {trash_at: now+3.days, delete_at: now+7.days},
388     {state: :trash_future}],
389    ['now-to-delete interval short, trash=delete',
390     :collection_owned_by_active,
391     {trash_at: now+3.days, delete_at: now+3.days},
392     {state: :trash_future}],
393    ['trash-to-delete interval ok',
394     :collection_owned_by_active,
395     {trash_at: now, delete_at: now+15.days},
396     {state: :trash_now}],
397    ['trash-to-delete interval short, but far enough in future',
398     :collection_owned_by_active,
399     {trash_at: now+13.days, delete_at: now+15.days},
400     {state: :trash_future}],
401    ['trash by setting is_trashed bool',
402     :collection_owned_by_active,
403     {is_trashed: true},
404     {state: :trash_now}],
405    ['trash in future by setting just trash_at',
406     :collection_owned_by_active,
407     {trash_at: now+1.week},
408     {state: :trash_future}],
409    ['trash in future by setting trash_at and delete_at',
410     :collection_owned_by_active,
411     {trash_at: now+1.week, delete_at: now+4.weeks},
412     {state: :trash_future}],
413    ['untrash by clearing is_trashed bool',
414     :expired_collection,
415     {is_trashed: false},
416     {state: :not_trash}],
417   ].each do |test_name, fixture_name, updates, expect|
418     test test_name do
419       act_as_user users(:active) do
420         min_exp = (db_current_time +
421                    Rails.configuration.blob_signature_ttl.seconds)
422         if fixture_name == :expired_collection
423           # Fixture-finder shorthand doesn't find trashed collections
424           # because they're not in the default scope.
425           c = Collection.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
426         else
427           c = collections(fixture_name)
428         end
429         updates_ok = c.update_attributes(updates)
430         expect_valid = expect[:state] != :invalid
431         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
432         case expect[:state]
433         when :invalid
434           refute c.valid?
435         when :trash_now
436           assert c.is_trashed
437           assert_not_nil c.trash_at
438           assert_operator c.trash_at, :<=, db_current_time
439           assert_not_nil c.delete_at
440           assert_operator c.delete_at, :>=, min_exp
441         when :trash_future
442           refute c.is_trashed
443           assert_not_nil c.trash_at
444           assert_operator c.trash_at, :>, db_current_time
445           assert_not_nil c.delete_at
446           assert_operator c.delete_at, :>=, c.trash_at
447           # Currently this minimum interval is needed to prevent early
448           # garbage collection:
449           assert_operator c.delete_at, :>=, min_exp
450         when :not_trash
451           refute c.is_trashed
452           assert_nil c.trash_at
453           assert_nil c.delete_at
454         else
455           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
456         end
457       end
458     end
459   end
460
461   test 'default trash interval > blob signature ttl' do
462     Rails.configuration.default_trash_lifetime = 86400 * 21 # 3 weeks
463     start = db_current_time
464     act_as_user users(:active) do
465       c = Collection.create!(manifest_text: '', name: 'foo')
466       c.update_attributes!(trash_at: start + 86400.seconds)
467       assert_operator c.delete_at, :>=, start + (86400*22).seconds
468       assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
469       c.destroy
470
471       c = Collection.create!(manifest_text: '', name: 'foo')
472       c.update_attributes!(is_trashed: true)
473       assert_operator c.delete_at, :>=, start + (86400*21).seconds
474     end
475   end
476
477   test "find_all_for_docker_image resolves names that look like hashes" do
478     coll_list = Collection.
479       find_all_for_docker_image('a' * 64, nil, [users(:active)])
480     coll_uuids = coll_list.map(&:uuid)
481     assert_includes(coll_uuids, collections(:docker_image).uuid)
482   end
483
484   test "move to trash in SweepTrashedCollections" do
485     c = collections(:trashed_on_next_sweep)
486     refute_empty Collection.where('uuid=? and is_trashed=false', c.uuid)
487     assert_raises(ActiveRecord::RecordNotUnique) do
488       act_as_user users(:active) do
489         Collection.create!(owner_uuid: c.owner_uuid,
490                            name: c.name)
491       end
492     end
493     SweepTrashedCollections.sweep_now
494     c = Collection.where('uuid=? and is_trashed=true', c.uuid).first
495     assert c
496     act_as_user users(:active) do
497       assert Collection.create!(owner_uuid: c.owner_uuid,
498                                 name: c.name)
499     end
500   end
501
502   test "delete in SweepTrashedCollections" do
503     uuid = 'zzzzz-4zz18-3u1p5umicfpqszp' # deleted_on_next_sweep
504     assert_not_empty Collection.where(uuid: uuid)
505     SweepTrashedCollections.sweep_now
506     assert_empty Collection.where(uuid: uuid)
507   end
508
509   test "delete referring links in SweepTrashedCollections" do
510     uuid = collections(:trashed_on_next_sweep).uuid
511     act_as_system_user do
512       Link.create!(head_uuid: uuid,
513                    tail_uuid: system_user_uuid,
514                    link_class: 'whatever',
515                    name: 'something')
516     end
517     past = db_current_time
518     Collection.where(uuid: uuid).
519       update_all(is_trashed: true, trash_at: past, delete_at: past)
520     assert_not_empty Collection.where(uuid: uuid)
521     SweepTrashedCollections.sweep_now
522     assert_empty Collection.where(uuid: uuid)
523   end
524 end