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