12216: Allow Content-Type header via CORS.
[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       # mark collection as expired
356       c.update_attributes!(trash_at: Time.new.strftime("%Y-%m-%d"))
357       c = Collection.where(uuid: uuid)
358       assert_empty c, 'Should not be able to find expired collection'
359
360       # recreate collection with the same name
361       c = Collection.create(manifest_text: '',
362                             name: "test collection name")
363       assert c.valid?
364     end
365   end
366
367   test 'trash_at cannot be set too far in the past' do
368     act_as_user users(:active) do
369       t0 = db_current_time
370       c = Collection.create!(manifest_text: '', name: 'foo')
371       c.update_attributes! trash_at: (t0 - 2.weeks)
372       c.reload
373       assert_operator c.trash_at, :>, t0
374     end
375   end
376
377   now = Time.now
378   [['trash-to-delete interval negative',
379     :collection_owned_by_active,
380     {trash_at: now+2.weeks, delete_at: now},
381     {state: :invalid}],
382    ['now-to-delete interval short',
383     :collection_owned_by_active,
384     {trash_at: now+3.days, delete_at: now+7.days},
385     {state: :trash_future}],
386    ['now-to-delete interval short, trash=delete',
387     :collection_owned_by_active,
388     {trash_at: now+3.days, delete_at: now+3.days},
389     {state: :trash_future}],
390    ['trash-to-delete interval ok',
391     :collection_owned_by_active,
392     {trash_at: now, delete_at: now+15.days},
393     {state: :trash_now}],
394    ['trash-to-delete interval short, but far enough in future',
395     :collection_owned_by_active,
396     {trash_at: now+13.days, delete_at: now+15.days},
397     {state: :trash_future}],
398    ['trash by setting is_trashed bool',
399     :collection_owned_by_active,
400     {is_trashed: true},
401     {state: :trash_now}],
402    ['trash in future by setting just trash_at',
403     :collection_owned_by_active,
404     {trash_at: now+1.week},
405     {state: :trash_future}],
406    ['trash in future by setting trash_at and delete_at',
407     :collection_owned_by_active,
408     {trash_at: now+1.week, delete_at: now+4.weeks},
409     {state: :trash_future}],
410    ['untrash by clearing is_trashed bool',
411     :expired_collection,
412     {is_trashed: false},
413     {state: :not_trash}],
414   ].each do |test_name, fixture_name, updates, expect|
415     test test_name do
416       act_as_user users(:active) do
417         min_exp = (db_current_time +
418                    Rails.configuration.blob_signature_ttl.seconds)
419         if fixture_name == :expired_collection
420           # Fixture-finder shorthand doesn't find trashed collections
421           # because they're not in the default scope.
422           c = Collection.unscoped.find_by_uuid('zzzzz-4zz18-mto52zx1s7sn3ih')
423         else
424           c = collections(fixture_name)
425         end
426         updates_ok = c.update_attributes(updates)
427         expect_valid = expect[:state] != :invalid
428         assert_equal expect_valid, updates_ok, c.errors.full_messages.to_s
429         case expect[:state]
430         when :invalid
431           refute c.valid?
432         when :trash_now
433           assert c.is_trashed
434           assert_not_nil c.trash_at
435           assert_operator c.trash_at, :<=, db_current_time
436           assert_not_nil c.delete_at
437           assert_operator c.delete_at, :>=, min_exp
438         when :trash_future
439           refute c.is_trashed
440           assert_not_nil c.trash_at
441           assert_operator c.trash_at, :>, db_current_time
442           assert_not_nil c.delete_at
443           assert_operator c.delete_at, :>=, c.trash_at
444           # Currently this minimum interval is needed to prevent early
445           # garbage collection:
446           assert_operator c.delete_at, :>=, min_exp
447         when :not_trash
448           refute c.is_trashed
449           assert_nil c.trash_at
450           assert_nil c.delete_at
451         else
452           raise "bad expect[:state]==#{expect[:state].inspect} in test case"
453         end
454       end
455     end
456   end
457
458   test 'default trash interval > blob signature ttl' do
459     Rails.configuration.default_trash_lifetime = 86400 * 21 # 3 weeks
460     start = db_current_time
461     act_as_user users(:active) do
462       c = Collection.create!(manifest_text: '', name: 'foo')
463       c.update_attributes!(trash_at: start + 86400.seconds)
464       assert_operator c.delete_at, :>=, start + (86400*22).seconds
465       assert_operator c.delete_at, :<, start + (86400*22 + 30).seconds
466       c.destroy
467
468       c = Collection.create!(manifest_text: '', name: 'foo')
469       c.update_attributes!(is_trashed: true)
470       assert_operator c.delete_at, :>=, start + (86400*21).seconds
471     end
472   end
473
474   test "find_all_for_docker_image resolves names that look like hashes" do
475     coll_list = Collection.
476       find_all_for_docker_image('a' * 64, nil, [users(:active)])
477     coll_uuids = coll_list.map(&:uuid)
478     assert_includes(coll_uuids, collections(:docker_image).uuid)
479   end
480
481   test "move to trash in SweepTrashedCollections" do
482     c = collections(:trashed_on_next_sweep)
483     refute_empty Collection.where('uuid=? and is_trashed=false', c.uuid)
484     assert_raises(ActiveRecord::RecordNotUnique) do
485       act_as_user users(:active) do
486         Collection.create!(owner_uuid: c.owner_uuid,
487                            name: c.name)
488       end
489     end
490     SweepTrashedCollections.sweep_now
491     c = Collection.unscoped.where('uuid=? and is_trashed=true', c.uuid).first
492     assert c
493     act_as_user users(:active) do
494       assert Collection.create!(owner_uuid: c.owner_uuid,
495                                 name: c.name)
496     end
497   end
498
499   test "delete in SweepTrashedCollections" do
500     uuid = 'zzzzz-4zz18-3u1p5umicfpqszp' # deleted_on_next_sweep
501     assert_not_empty Collection.unscoped.where(uuid: uuid)
502     SweepTrashedCollections.sweep_now
503     assert_empty Collection.unscoped.where(uuid: uuid)
504   end
505
506   test "delete referring links in SweepTrashedCollections" do
507     uuid = collections(:trashed_on_next_sweep).uuid
508     act_as_system_user do
509       Link.create!(head_uuid: uuid,
510                    tail_uuid: system_user_uuid,
511                    link_class: 'whatever',
512                    name: 'something')
513     end
514     past = db_current_time
515     Collection.unscoped.where(uuid: uuid).
516       update_all(is_trashed: true, trash_at: past, delete_at: past)
517     assert_not_empty Collection.unscoped.where(uuid: uuid)
518     SweepTrashedCollections.sweep_now
519     assert_empty Collection.unscoped.where(uuid: uuid)
520   end
521 end