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