e5b17dd965c534ac536d88af87610d95ad424fcf
[arvados.git] / services / api / test / functional / arvados / v1 / collections_controller_test.rb
1 require 'test_helper'
2
3 class Arvados::V1::CollectionsControllerTest < ActionController::TestCase
4
5   setup do
6     # Unless otherwise specified in the test, we want normal/secure behavior.
7     permit_unsigned_manifests false
8   end
9
10   teardown do
11     # Reset to secure behavior after each test.
12     permit_unsigned_manifests false
13   end
14
15   def permit_unsigned_manifests isok=true
16     # Set security model for the life of a test.
17     Rails.configuration.permit_create_collection_with_unsigned_manifest = isok
18   end
19
20   test "should get index" do
21     authorize_with :active
22     get :index
23     assert_response :success
24     assert(assigns(:objects).andand.any?, "no Collections returned in index")
25     refute(json_response["items"].any? { |c| c.has_key?("manifest_text") },
26            "basic Collections index included manifest_text")
27   end
28
29   test "index with manifest_text selected returns signed locators" do
30     columns = %w(uuid owner_uuid manifest_text)
31     authorize_with :active
32     get :index, select: columns
33     assert_response :success
34     assert(assigns(:objects).andand.any?,
35            "no Collections returned for index with columns selected")
36     json_response["items"].each do |coll|
37       assert_equal(columns, columns & coll.keys,
38                    "Collections index did not respect selected columns")
39       loc_regexp = / [[:xdigit:]]{32}\+\d+\S+/
40       pos = 0
41       while match = loc_regexp.match(coll["manifest_text"], pos)
42         assert_match(/\+A[[:xdigit:]]+@[[:xdigit:]]{8}\b/, match.to_s,
43                      "Locator in manifest_text was not signed")
44         pos = match.end(0)
45       end
46     end
47   end
48
49   [0,1,2].each do |limit|
50     test "get index with limit=#{limit}" do
51       authorize_with :active
52       get :index, limit: limit
53       assert_response :success
54       assert_equal limit, assigns(:objects).count
55       resp = JSON.parse(@response.body)
56       assert_equal limit, resp['limit']
57     end
58   end
59
60   test "items.count == items_available" do
61     authorize_with :active
62     get :index, limit: 100000
63     assert_response :success
64     resp = JSON.parse(@response.body)
65     assert_equal resp['items_available'], assigns(:objects).length
66     assert_equal resp['items_available'], resp['items'].count
67     unique_uuids = resp['items'].collect { |i| i['uuid'] }.compact.uniq
68     assert_equal unique_uuids.count, resp['items'].count
69   end
70
71   test "get index with limit=2 offset=99999" do
72     # Assume there are not that many test fixtures.
73     authorize_with :active
74     get :index, limit: 2, offset: 99999
75     assert_response :success
76     assert_equal 0, assigns(:objects).count
77     resp = JSON.parse(@response.body)
78     assert_equal 2, resp['limit']
79     assert_equal 99999, resp['offset']
80   end
81
82   test "admin can create collection with unsigned manifest" do
83     authorize_with :admin
84     test_collection = {
85       manifest_text: <<-EOS
86 . d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo.txt
87 . acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar.txt
88 . acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar.txt
89 ./baz acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar.txt
90 EOS
91     }
92     test_collection[:portable_data_hash] =
93       Digest::MD5.hexdigest(test_collection[:manifest_text]) +
94       '+' +
95       test_collection[:manifest_text].length.to_s
96
97     # post :create will modify test_collection in place, so we save a copy first.
98     # Hash.deep_dup is not sufficient as it preserves references of strings (??!?)
99     post_collection = Marshal.load(Marshal.dump(test_collection))
100     post :create, {
101       collection: post_collection
102     }
103
104     assert_response :success
105     assert_nil assigns(:objects)
106
107     response_collection = assigns(:object)
108
109     stored_collection = Collection.select([:uuid, :portable_data_hash, :manifest_text]).
110       where(portable_data_hash: response_collection['portable_data_hash']).first
111
112     assert_equal test_collection[:portable_data_hash], stored_collection['portable_data_hash']
113
114     # The manifest in the response will have had permission hints added.
115     # Remove any permission hints in the response before comparing it to the source.
116     stripped_manifest = stored_collection['manifest_text'].gsub(/\+A[A-Za-z0-9@_-]+/, '')
117     assert_equal test_collection[:manifest_text], stripped_manifest
118
119     # TBD: create action should add permission signatures to manifest_text in the response,
120     # and we need to check those permission signatures here.
121   end
122
123   [:admin, :active].each do |user|
124     test "#{user} can get collection using portable data hash" do
125       authorize_with user
126
127       foo_collection = collections(:foo_file)
128
129       # Get foo_file using it's portable data has
130       get :show, {
131         id: foo_collection[:portable_data_hash]
132       }
133       assert_response :success
134       assert_not_nil assigns(:object)
135       resp = assigns(:object)
136       assert_equal foo_collection[:portable_data_hash], resp['portable_data_hash']
137
138       # The manifest in the response will have had permission hints added.
139       # Remove any permission hints in the response before comparing it to the source.
140       stripped_manifest = resp['manifest_text'].gsub(/\+A[A-Za-z0-9@_-]+/, '')
141       assert_equal foo_collection[:manifest_text], stripped_manifest
142     end
143   end
144
145   test "create with owner_uuid set to owned group" do
146     permit_unsigned_manifests
147     authorize_with :active
148     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
149     post :create, {
150       collection: {
151         owner_uuid: 'zzzzz-j7d0g-rew6elm53kancon',
152         manifest_text: manifest_text,
153         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
154       }
155     }
156     assert_response :success
157     resp = JSON.parse(@response.body)
158     assert_equal 'zzzzz-j7d0g-rew6elm53kancon', resp['owner_uuid']
159   end
160
161   test "create fails with duplicate name" do
162     permit_unsigned_manifests
163     authorize_with :admin
164     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
165     post :create, {
166       collection: {
167         owner_uuid: 'zzzzz-tpzed-000000000000000',
168         manifest_text: manifest_text,
169         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47",
170         name: "foo_file"
171       }
172     }
173     assert_response 422
174     response_errors = json_response['errors']
175     assert_not_nil response_errors, 'Expected error in response'
176     assert(response_errors.first.include?('duplicate key'),
177            "Expected 'duplicate key' error in #{response_errors.first}")
178   end
179
180   test "create succeeds with duplicate name with ensure_unique_name" do
181     permit_unsigned_manifests
182     authorize_with :active
183     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
184     post :create, {
185       collection: {
186         owner_uuid: users(:active).uuid,
187         manifest_text: manifest_text,
188         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47",
189         name: "owned_by_active"
190       },
191       ensure_unique_name: true
192     }
193     assert_response :success
194     assert_equal 'owned_by_active (2)', json_response['name']
195   end
196
197   test "create with owner_uuid set to group i can_manage" do
198     permit_unsigned_manifests
199     authorize_with :active
200     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
201     post :create, {
202       collection: {
203         owner_uuid: groups(:active_user_has_can_manage).uuid,
204         manifest_text: manifest_text,
205         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
206       }
207     }
208     assert_response :success
209     resp = JSON.parse(@response.body)
210     assert_equal groups(:active_user_has_can_manage).uuid, resp['owner_uuid']
211   end
212
213   test "create with owner_uuid fails on group with only can_read permission" do
214     permit_unsigned_manifests
215     authorize_with :active
216     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
217     post :create, {
218       collection: {
219         owner_uuid: groups(:all_users).uuid,
220         manifest_text: manifest_text,
221         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
222       }
223     }
224     assert_response 403
225   end
226
227   test "create with owner_uuid fails on group with no permission" do
228     permit_unsigned_manifests
229     authorize_with :active
230     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
231     post :create, {
232       collection: {
233         owner_uuid: groups(:public).uuid,
234         manifest_text: manifest_text,
235         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
236       }
237     }
238     assert_response 422
239   end
240
241   test "admin create with owner_uuid set to group with no permission" do
242     permit_unsigned_manifests
243     authorize_with :admin
244     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
245     post :create, {
246       collection: {
247         owner_uuid: 'zzzzz-j7d0g-it30l961gq3t0oi',
248         manifest_text: manifest_text,
249         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
250       }
251     }
252     assert_response :success
253   end
254
255   test "should create with collection passed as json" do
256     permit_unsigned_manifests
257     authorize_with :active
258     post :create, {
259       collection: <<-EOS
260       {
261         "manifest_text":". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",\
262         "portable_data_hash":"d30fe8ae534397864cb96c544f4cf102+47"\
263       }
264       EOS
265     }
266     assert_response :success
267   end
268
269   test "should fail to create with checksum mismatch" do
270     permit_unsigned_manifests
271     authorize_with :active
272     post :create, {
273       collection: <<-EOS
274       {
275         "manifest_text":". d41d8cd98f00b204e9800998ecf8427e 0:0:bar.txt\n",\
276         "portable_data_hash":"d30fe8ae534397864cb96c544f4cf102+47"\
277       }
278       EOS
279     }
280     assert_response 422
281   end
282
283   test "collection UUID is normalized when created" do
284     permit_unsigned_manifests
285     authorize_with :active
286     post :create, {
287       collection: {
288         manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
289         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47+Khint+Xhint+Zhint"
290       }
291     }
292     assert_response :success
293     assert_not_nil assigns(:object)
294     resp = JSON.parse(@response.body)
295     assert_equal "d30fe8ae534397864cb96c544f4cf102+47", resp['portable_data_hash']
296   end
297
298   test "get full provenance for baz file" do
299     authorize_with :active
300     get :provenance, id: 'ea10d51bcf88862dbcc36eb292017dfd+45'
301     assert_response :success
302     resp = JSON.parse(@response.body)
303     assert_not_nil resp['ea10d51bcf88862dbcc36eb292017dfd+45'] # baz
304     assert_not_nil resp['fa7aeb5140e2848d39b416daeef4ffc5+45'] # bar
305     assert_not_nil resp['1f4b0bc7583c2a7f9102c395f4ffc5e3+45'] # foo
306     assert_not_nil resp['zzzzz-8i9sb-cjs4pklxxjykyuq'] # bar->baz
307     assert_not_nil resp['zzzzz-8i9sb-aceg2bnq7jt7kon'] # foo->bar
308   end
309
310   test "get no provenance for foo file" do
311     # spectator user cannot even see baz collection
312     authorize_with :spectator
313     get :provenance, id: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
314     assert_response 404
315   end
316
317   test "get partial provenance for baz file" do
318     # spectator user can see bar->baz job, but not foo->bar job
319     authorize_with :spectator
320     get :provenance, id: 'ea10d51bcf88862dbcc36eb292017dfd+45'
321     assert_response :success
322     resp = JSON.parse(@response.body)
323     assert_not_nil resp['ea10d51bcf88862dbcc36eb292017dfd+45'] # baz
324     assert_not_nil resp['fa7aeb5140e2848d39b416daeef4ffc5+45'] # bar
325     assert_not_nil resp['zzzzz-8i9sb-cjs4pklxxjykyuq']     # bar->baz
326     assert_nil resp['zzzzz-8i9sb-aceg2bnq7jt7kon']         # foo->bar
327     assert_nil resp['1f4b0bc7583c2a7f9102c395f4ffc5e3+45'] # foo
328   end
329
330   test "search collections with 'any' operator" do
331     authorize_with :active
332     get :index, {
333       where: { any: ['contains', '7f9102c395f4ffc5e3'] }
334     }
335     assert_response :success
336     found = assigns(:objects).collect(&:portable_data_hash)
337     assert_equal 2, found.count
338     assert_equal true, !!found.index('1f4b0bc7583c2a7f9102c395f4ffc5e3+45')
339   end
340
341   [false, true].each do |permit_unsigned|
342     test "create collection with signed manifest, permit_unsigned=#{permit_unsigned}" do
343       permit_unsigned_manifests permit_unsigned
344       authorize_with :active
345       locators = %w(
346       d41d8cd98f00b204e9800998ecf8427e+0
347       acbd18db4cc2f85cedef654fccc4a4d8+3
348       ea10d51bcf88862dbcc36eb292017dfd+45)
349
350       unsigned_manifest = locators.map { |loc|
351         ". " + loc + " 0:0:foo.txt\n"
352       }.join()
353       manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
354         '+' +
355         unsigned_manifest.length.to_s
356
357       # Build a manifest with both signed and unsigned locators.
358       signing_opts = {
359         key: Rails.configuration.blob_signing_key,
360         api_token: api_token(:active),
361       }
362       signed_locators = locators.collect do |x|
363         Blob.sign_locator x, signing_opts
364       end
365       if permit_unsigned
366         # Leave a non-empty blob unsigned.
367         signed_locators[1] = locators[1]
368       else
369         # Leave the empty blob unsigned. This should still be allowed.
370         signed_locators[0] = locators[0]
371       end
372       signed_manifest =
373         ". " + signed_locators[0] + " 0:0:foo.txt\n" +
374         ". " + signed_locators[1] + " 0:0:foo.txt\n" +
375         ". " + signed_locators[2] + " 0:0:foo.txt\n"
376
377       post :create, {
378         collection: {
379           manifest_text: signed_manifest,
380           portable_data_hash: manifest_uuid,
381         }
382       }
383       assert_response :success
384       assert_not_nil assigns(:object)
385       resp = JSON.parse(@response.body)
386       assert_equal manifest_uuid, resp['portable_data_hash']
387       # All of the locators in the output must be signed.
388       resp['manifest_text'].lines.each do |entry|
389         m = /([[:xdigit:]]{32}\+\S+)/.match(entry)
390         if m
391           assert Blob.verify_signature m[0], signing_opts
392         end
393       end
394     end
395   end
396
397   test "create collection with signed manifest and explicit TTL" do
398     authorize_with :active
399     locators = %w(
400       d41d8cd98f00b204e9800998ecf8427e+0
401       acbd18db4cc2f85cedef654fccc4a4d8+3
402       ea10d51bcf88862dbcc36eb292017dfd+45)
403
404     unsigned_manifest = locators.map { |loc|
405       ". " + loc + " 0:0:foo.txt\n"
406     }.join()
407     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
408       '+' +
409       unsigned_manifest.length.to_s
410
411     # build a manifest with both signed and unsigned locators.
412     # TODO(twp): in phase 4, all locators will need to be signed, so
413     # this test should break and will need to be rewritten. Issue #2755.
414     signing_opts = {
415       key: Rails.configuration.blob_signing_key,
416       api_token: api_token(:active),
417       ttl: 3600   # 1 hour
418     }
419     signed_manifest =
420       ". " + locators[0] + " 0:0:foo.txt\n" +
421       ". " + Blob.sign_locator(locators[1], signing_opts) + " 0:0:foo.txt\n" +
422       ". " + Blob.sign_locator(locators[2], signing_opts) + " 0:0:foo.txt\n"
423
424     post :create, {
425       collection: {
426         manifest_text: signed_manifest,
427         portable_data_hash: manifest_uuid,
428       }
429     }
430     assert_response :success
431     assert_not_nil assigns(:object)
432     resp = JSON.parse(@response.body)
433     assert_equal manifest_uuid, resp['portable_data_hash']
434     # All of the locators in the output must be signed.
435     resp['manifest_text'].lines.each do |entry|
436       m = /([[:xdigit:]]{32}\+\S+)/.match(entry)
437       if m
438         assert Blob.verify_signature m[0], signing_opts
439       end
440     end
441   end
442
443   test "create fails with invalid signature" do
444     authorize_with :active
445     signing_opts = {
446       key: Rails.configuration.blob_signing_key,
447       api_token: api_token(:active),
448     }
449
450     # Generate a locator with a bad signature.
451     unsigned_locator = "d41d8cd98f00b204e9800998ecf8427e+0"
452     bad_locator = unsigned_locator + "+Affffffff@ffffffff"
453     assert !Blob.verify_signature(bad_locator, signing_opts)
454
455     # Creating a collection with this locator should
456     # produce 403 Permission denied.
457     unsigned_manifest = ". #{unsigned_locator} 0:0:foo.txt\n"
458     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
459       '+' +
460       unsigned_manifest.length.to_s
461
462     bad_manifest = ". #{bad_locator} 0:0:foo.txt\n"
463     post :create, {
464       collection: {
465         manifest_text: bad_manifest,
466         portable_data_hash: manifest_uuid
467       }
468     }
469
470     assert_response 403
471   end
472
473   test "create fails with uuid of signed manifest" do
474     authorize_with :active
475     signing_opts = {
476       key: Rails.configuration.blob_signing_key,
477       api_token: api_token(:active),
478     }
479
480     unsigned_locator = "d41d8cd98f00b204e9800998ecf8427e+0"
481     signed_locator = Blob.sign_locator(unsigned_locator, signing_opts)
482     signed_manifest = ". #{signed_locator} 0:0:foo.txt\n"
483     manifest_uuid = Digest::MD5.hexdigest(signed_manifest) +
484       '+' +
485       signed_manifest.length.to_s
486
487     post :create, {
488       collection: {
489         manifest_text: signed_manifest,
490         portable_data_hash: manifest_uuid
491       }
492     }
493
494     assert_response 422
495   end
496
497   test "multiple locators per line" do
498     permit_unsigned_manifests
499     authorize_with :active
500     locators = %w(
501       d41d8cd98f00b204e9800998ecf8427e+0
502       acbd18db4cc2f85cedef654fccc4a4d8+3
503       ea10d51bcf88862dbcc36eb292017dfd+45)
504
505     manifest_text = [".", *locators, "0:0:foo.txt\n"].join(" ")
506     manifest_uuid = Digest::MD5.hexdigest(manifest_text) +
507       '+' +
508       manifest_text.length.to_s
509
510     test_collection = {
511       manifest_text: manifest_text,
512       portable_data_hash: manifest_uuid,
513     }
514     post_collection = Marshal.load(Marshal.dump(test_collection))
515     post :create, {
516       collection: post_collection
517     }
518     assert_response :success
519     assert_not_nil assigns(:object)
520     resp = JSON.parse(@response.body)
521     assert_equal manifest_uuid, resp['portable_data_hash']
522
523     # The manifest in the response will have had permission hints added.
524     # Remove any permission hints in the response before comparing it to the source.
525     stripped_manifest = resp['manifest_text'].gsub(/\+A[A-Za-z0-9@_-]+/, '')
526     assert_equal manifest_text, stripped_manifest
527   end
528
529   test "multiple signed locators per line" do
530     permit_unsigned_manifests
531     authorize_with :active
532     locators = %w(
533       d41d8cd98f00b204e9800998ecf8427e+0
534       acbd18db4cc2f85cedef654fccc4a4d8+3
535       ea10d51bcf88862dbcc36eb292017dfd+45)
536
537     signing_opts = {
538       key: Rails.configuration.blob_signing_key,
539       api_token: api_token(:active),
540     }
541
542     unsigned_manifest = [".", *locators, "0:0:foo.txt\n"].join(" ")
543     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
544       '+' +
545       unsigned_manifest.length.to_s
546
547     signed_locators = locators.map { |loc| Blob.sign_locator loc, signing_opts }
548     signed_manifest = [".", *signed_locators, "0:0:foo.txt\n"].join(" ")
549
550     post :create, {
551       collection: {
552         manifest_text: signed_manifest,
553         portable_data_hash: manifest_uuid,
554       }
555     }
556     assert_response :success
557     assert_not_nil assigns(:object)
558     resp = JSON.parse(@response.body)
559     assert_equal manifest_uuid, resp['portable_data_hash']
560     # All of the locators in the output must be signed.
561     # Each line is of the form "path locator locator ... 0:0:file.txt"
562     # entry.split[1..-2] will yield just the tokens in the middle of the line
563     returned_locator_count = 0
564     resp['manifest_text'].lines.each do |entry|
565       entry.split[1..-2].each do |tok|
566         returned_locator_count += 1
567         assert Blob.verify_signature tok, signing_opts
568       end
569     end
570     assert_equal locators.count, returned_locator_count
571   end
572
573   test 'Reject manifest with unsigned blob' do
574     authorize_with :active
575     unsigned_manifest = ". 0cc175b9c0f1b6a831c399e269772661+1 0:1:a.txt\n"
576     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest)
577     post :create, {
578       collection: {
579         manifest_text: unsigned_manifest,
580         portable_data_hash: manifest_uuid,
581       }
582     }
583     assert_response 403,
584     "Creating a collection with unsigned blobs should respond 403"
585     assert_empty Collection.where('uuid like ?', manifest_uuid+'%'),
586     "Collection should not exist in database after failed create"
587   end
588
589   test 'List expired collection returns empty list' do
590     authorize_with :active
591     get :index, {
592       where: {name: 'expired_collection'},
593     }
594     assert_response :success
595     found = assigns(:objects)
596     assert_equal 0, found.count
597   end
598
599   test 'Show expired collection returns 404' do
600     authorize_with :active
601     get :show, {
602       id: 'zzzzz-4zz18-mto52zx1s7sn3ih',
603     }
604     assert_response 404
605   end
606
607   test 'Update expired collection returns 404' do
608     authorize_with :active
609     post :update, {
610       id: 'zzzzz-4zz18-mto52zx1s7sn3ih',
611       collection: {
612         name: "still expired"
613       }
614     }
615     assert_response 404
616   end
617
618   test 'List collection with future expiration time succeeds' do
619     authorize_with :active
620     get :index, {
621       where: {name: 'collection_expires_in_future'},
622     }
623     found = assigns(:objects)
624     assert_equal 1, found.count
625   end
626
627
628   test 'Show collection with future expiration time succeeds' do
629     authorize_with :active
630     get :show, {
631       id: 'zzzzz-4zz18-padkqo7yb8d9i3j',
632     }
633     assert_response :success
634   end
635
636   test 'Update collection with future expiration time succeeds' do
637     authorize_with :active
638     post :update, {
639       id: 'zzzzz-4zz18-padkqo7yb8d9i3j',
640       collection: {
641         name: "still not expired"
642       }
643     }
644     assert_response :success
645   end
646 end