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