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