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