Merge branch '9897-log-block-prefetch-worker-exceptions' closes #9897
[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   test 'index without select returns everything except manifest' do
50     authorize_with :active
51     get :index
52     assert_response :success
53     assert json_response['items'].any?
54     json_response['items'].each do |coll|
55       assert_includes(coll.keys, 'uuid')
56       assert_includes(coll.keys, 'name')
57       assert_includes(coll.keys, 'created_at')
58       refute_includes(coll.keys, 'manifest_text')
59     end
60   end
61
62   ['', nil, false, 'null'].each do |select|
63     test "index with select=#{select.inspect} returns everything except manifest" do
64       authorize_with :active
65       get :index, select: select
66       assert_response :success
67       assert json_response['items'].any?
68       json_response['items'].each do |coll|
69         assert_includes(coll.keys, 'uuid')
70         assert_includes(coll.keys, 'name')
71         assert_includes(coll.keys, 'created_at')
72         refute_includes(coll.keys, 'manifest_text')
73       end
74     end
75   end
76
77   [["uuid"],
78    ["uuid", "manifest_text"],
79    '["uuid"]',
80    '["uuid", "manifest_text"]'].each do |select|
81     test "index with select=#{select.inspect} returns no name" do
82       authorize_with :active
83       get :index, select: select
84       assert_response :success
85       assert json_response['items'].any?
86       json_response['items'].each do |coll|
87         refute_includes(coll.keys, 'name')
88       end
89     end
90   end
91
92   [0,1,2].each do |limit|
93     test "get index with limit=#{limit}" do
94       authorize_with :active
95       get :index, limit: limit
96       assert_response :success
97       assert_equal limit, assigns(:objects).count
98       resp = JSON.parse(@response.body)
99       assert_equal limit, resp['limit']
100     end
101   end
102
103   test "items.count == items_available" do
104     authorize_with :active
105     get :index, limit: 100000
106     assert_response :success
107     resp = JSON.parse(@response.body)
108     assert_equal resp['items_available'], assigns(:objects).length
109     assert_equal resp['items_available'], resp['items'].count
110     unique_uuids = resp['items'].collect { |i| i['uuid'] }.compact.uniq
111     assert_equal unique_uuids.count, resp['items'].count
112   end
113
114   test "items.count == items_available with filters" do
115     authorize_with :active
116     get :index, {
117       limit: 100,
118       filters: [['uuid','=',collections(:foo_file).uuid]]
119     }
120     assert_response :success
121     assert_equal 1, assigns(:objects).length
122     assert_equal 1, json_response['items_available']
123     assert_equal 1, json_response['items'].count
124   end
125
126   test "get index with limit=2 offset=99999" do
127     # Assume there are not that many test fixtures.
128     authorize_with :active
129     get :index, limit: 2, offset: 99999
130     assert_response :success
131     assert_equal 0, assigns(:objects).count
132     resp = JSON.parse(@response.body)
133     assert_equal 2, resp['limit']
134     assert_equal 99999, resp['offset']
135   end
136
137   def request_capped_index(params={})
138     authorize_with :user1_with_load
139     coll1 = collections(:collection_1_of_201)
140     Rails.configuration.max_index_database_read =
141       yield(coll1.manifest_text.size)
142     get :index, {
143       select: %w(uuid manifest_text),
144       filters: [["owner_uuid", "=", coll1.owner_uuid]],
145       limit: 300,
146     }.merge(params)
147   end
148
149   test "index with manifest_text limited by max_index_database_read returns non-empty" do
150     request_capped_index() { |_| 1 }
151     assert_response :success
152     assert_equal(1, json_response["items"].size)
153     assert_equal(1, json_response["limit"])
154     assert_equal(201, json_response["items_available"])
155   end
156
157   test "max_index_database_read size check follows same order as real query" do
158     authorize_with :user1_with_load
159     txt = '.' + ' d41d8cd98f00b204e9800998ecf8427e+0'*1000 + " 0:0:empty.txt\n"
160     c = Collection.create! manifest_text: txt, name: '0000000000000000000'
161     request_capped_index(select: %w(uuid manifest_text name),
162                          order: ['name asc'],
163                          filters: [['name','>=',c.name]]) do |_|
164       txt.length - 1
165     end
166     assert_response :success
167     assert_equal(1, json_response["items"].size)
168     assert_equal(1, json_response["limit"])
169     assert_equal(c.uuid, json_response["items"][0]["uuid"])
170     # The effectiveness of the test depends on >1 item matching the filters.
171     assert_operator(1, :<, json_response["items_available"])
172   end
173
174   test "index with manifest_text limited by max_index_database_read" do
175     request_capped_index() { |size| (size * 3) + 1 }
176     assert_response :success
177     assert_equal(3, json_response["items"].size)
178     assert_equal(3, json_response["limit"])
179     assert_equal(201, json_response["items_available"])
180   end
181
182   test "max_index_database_read does not interfere with limit" do
183     request_capped_index(limit: 5) { |size| size * 20 }
184     assert_response :success
185     assert_equal(5, json_response["items"].size)
186     assert_equal(5, json_response["limit"])
187     assert_equal(201, json_response["items_available"])
188   end
189
190   test "max_index_database_read does not interfere with order" do
191     request_capped_index(select: %w(uuid manifest_text name),
192                          order: "name DESC") { |size| (size * 11) + 1 }
193     assert_response :success
194     assert_equal(11, json_response["items"].size)
195     assert_empty(json_response["items"].reject do |coll|
196                    coll["name"] =~ /^Collection_9/
197                  end)
198     assert_equal(11, json_response["limit"])
199     assert_equal(201, json_response["items_available"])
200   end
201
202   test "admin can create collection with unsigned manifest" do
203     authorize_with :admin
204     test_collection = {
205       manifest_text: <<-EOS
206 . d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo.txt
207 . acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar.txt
208 . acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar.txt
209 ./baz acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar.txt
210 EOS
211     }
212     test_collection[:portable_data_hash] =
213       Digest::MD5.hexdigest(test_collection[:manifest_text]) +
214       '+' +
215       test_collection[:manifest_text].length.to_s
216
217     # post :create will modify test_collection in place, so we save a copy first.
218     # Hash.deep_dup is not sufficient as it preserves references of strings (??!?)
219     post_collection = Marshal.load(Marshal.dump(test_collection))
220     post :create, {
221       collection: post_collection
222     }
223
224     assert_response :success
225     assert_nil assigns(:objects)
226
227     response_collection = assigns(:object)
228
229     stored_collection = Collection.select([:uuid, :portable_data_hash, :manifest_text]).
230       where(portable_data_hash: response_collection['portable_data_hash']).first
231
232     assert_equal test_collection[:portable_data_hash], stored_collection['portable_data_hash']
233
234     # The manifest in the response will have had permission hints added.
235     # Remove any permission hints in the response before comparing it to the source.
236     stripped_manifest = stored_collection['manifest_text'].gsub(/\+A[A-Za-z0-9@_-]+/, '')
237     assert_equal test_collection[:manifest_text], stripped_manifest
238
239     # TBD: create action should add permission signatures to manifest_text in the response,
240     # and we need to check those permission signatures here.
241   end
242
243   [:admin, :active].each do |user|
244     test "#{user} can get collection using portable data hash" do
245       authorize_with user
246
247       foo_collection = collections(:foo_file)
248
249       # Get foo_file using its portable data hash
250       get :show, {
251         id: foo_collection[:portable_data_hash]
252       }
253       assert_response :success
254       assert_not_nil assigns(:object)
255       resp = assigns(:object)
256       assert_equal foo_collection[:portable_data_hash], resp['portable_data_hash']
257       assert_signed_manifest resp['manifest_text']
258
259       # The manifest in the response will have had permission hints added.
260       # Remove any permission hints in the response before comparing it to the source.
261       stripped_manifest = resp['manifest_text'].gsub(/\+A[A-Za-z0-9@_-]+/, '')
262       assert_equal foo_collection[:manifest_text], stripped_manifest
263     end
264   end
265
266   test "create with owner_uuid set to owned group" do
267     permit_unsigned_manifests
268     authorize_with :active
269     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
270     post :create, {
271       collection: {
272         owner_uuid: 'zzzzz-j7d0g-rew6elm53kancon',
273         manifest_text: manifest_text,
274         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
275       }
276     }
277     assert_response :success
278     resp = JSON.parse(@response.body)
279     assert_equal 'zzzzz-j7d0g-rew6elm53kancon', resp['owner_uuid']
280   end
281
282   test "create fails with duplicate name" do
283     permit_unsigned_manifests
284     authorize_with :admin
285     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
286     post :create, {
287       collection: {
288         owner_uuid: 'zzzzz-tpzed-000000000000000',
289         manifest_text: manifest_text,
290         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47",
291         name: "foo_file"
292       }
293     }
294     assert_response 422
295     response_errors = json_response['errors']
296     assert_not_nil response_errors, 'Expected error in response'
297     assert(response_errors.first.include?('duplicate key'),
298            "Expected 'duplicate key' error in #{response_errors.first}")
299   end
300
301   [false, true].each do |unsigned|
302     test "create with duplicate name, ensure_unique_name, unsigned=#{unsigned}" do
303       permit_unsigned_manifests unsigned
304       authorize_with :active
305       manifest_text = ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:0:foo.txt\n"
306       if !unsigned
307         manifest_text = Collection.sign_manifest manifest_text, api_token(:active)
308       end
309       post :create, {
310         collection: {
311           owner_uuid: users(:active).uuid,
312           manifest_text: manifest_text,
313           name: "owned_by_active"
314         },
315         ensure_unique_name: true
316       }
317       assert_response :success
318       assert_equal 'owned_by_active (2)', json_response['name']
319     end
320   end
321
322   test "create with owner_uuid set to group i can_manage" do
323     permit_unsigned_manifests
324     authorize_with :active
325     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
326     post :create, {
327       collection: {
328         owner_uuid: groups(:active_user_has_can_manage).uuid,
329         manifest_text: manifest_text,
330         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
331       }
332     }
333     assert_response :success
334     resp = JSON.parse(@response.body)
335     assert_equal groups(:active_user_has_can_manage).uuid, resp['owner_uuid']
336   end
337
338   test "create with owner_uuid fails on group with only can_read permission" do
339     permit_unsigned_manifests
340     authorize_with :active
341     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
342     post :create, {
343       collection: {
344         owner_uuid: groups(:all_users).uuid,
345         manifest_text: manifest_text,
346         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
347       }
348     }
349     assert_response 403
350   end
351
352   test "create with owner_uuid fails on group with no permission" do
353     permit_unsigned_manifests
354     authorize_with :active
355     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
356     post :create, {
357       collection: {
358         owner_uuid: groups(:public).uuid,
359         manifest_text: manifest_text,
360         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
361       }
362     }
363     assert_response 422
364   end
365
366   test "admin create with owner_uuid set to group with no permission" do
367     permit_unsigned_manifests
368     authorize_with :admin
369     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
370     post :create, {
371       collection: {
372         owner_uuid: 'zzzzz-j7d0g-it30l961gq3t0oi',
373         manifest_text: manifest_text,
374         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47"
375       }
376     }
377     assert_response :success
378   end
379
380   test "should create with collection passed as json" do
381     permit_unsigned_manifests
382     authorize_with :active
383     post :create, {
384       collection: <<-EOS
385       {
386         "manifest_text":". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",\
387         "portable_data_hash":"d30fe8ae534397864cb96c544f4cf102+47"\
388       }
389       EOS
390     }
391     assert_response :success
392   end
393
394   test "should fail to create with checksum mismatch" do
395     permit_unsigned_manifests
396     authorize_with :active
397     post :create, {
398       collection: <<-EOS
399       {
400         "manifest_text":". d41d8cd98f00b204e9800998ecf8427e 0:0:bar.txt\n",\
401         "portable_data_hash":"d30fe8ae534397864cb96c544f4cf102+47"\
402       }
403       EOS
404     }
405     assert_response 422
406   end
407
408   test "collection UUID is normalized when created" do
409     permit_unsigned_manifests
410     authorize_with :active
411     post :create, {
412       collection: {
413         manifest_text: ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
414         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47+Khint+Xhint+Zhint"
415       }
416     }
417     assert_response :success
418     assert_not_nil assigns(:object)
419     resp = JSON.parse(@response.body)
420     assert_equal "d30fe8ae534397864cb96c544f4cf102+47", resp['portable_data_hash']
421   end
422
423   test "get full provenance for baz file" do
424     authorize_with :active
425     get :provenance, id: 'ea10d51bcf88862dbcc36eb292017dfd+45'
426     assert_response :success
427     resp = JSON.parse(@response.body)
428     assert_not_nil resp['ea10d51bcf88862dbcc36eb292017dfd+45'] # baz
429     assert_not_nil resp['fa7aeb5140e2848d39b416daeef4ffc5+45'] # bar
430     assert_not_nil resp['1f4b0bc7583c2a7f9102c395f4ffc5e3+45'] # foo
431     assert_not_nil resp['zzzzz-8i9sb-cjs4pklxxjykyuq'] # bar->baz
432     assert_not_nil resp['zzzzz-8i9sb-aceg2bnq7jt7kon'] # foo->bar
433   end
434
435   test "get no provenance for foo file" do
436     # spectator user cannot even see baz collection
437     authorize_with :spectator
438     get :provenance, id: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
439     assert_response 404
440   end
441
442   test "get partial provenance for baz file" do
443     # spectator user can see bar->baz job, but not foo->bar job
444     authorize_with :spectator
445     get :provenance, id: 'ea10d51bcf88862dbcc36eb292017dfd+45'
446     assert_response :success
447     resp = JSON.parse(@response.body)
448     assert_not_nil resp['ea10d51bcf88862dbcc36eb292017dfd+45'] # baz
449     assert_not_nil resp['fa7aeb5140e2848d39b416daeef4ffc5+45'] # bar
450     assert_not_nil resp['zzzzz-8i9sb-cjs4pklxxjykyuq']     # bar->baz
451     assert_nil resp['zzzzz-8i9sb-aceg2bnq7jt7kon']         # foo->bar
452     assert_nil resp['1f4b0bc7583c2a7f9102c395f4ffc5e3+45'] # foo
453   end
454
455   test "search collections with 'any' operator" do
456     expect_pdh = collections(:docker_image).portable_data_hash
457     authorize_with :active
458     get :index, {
459       where: { any: ['contains', expect_pdh[5..25]] }
460     }
461     assert_response :success
462     found = assigns(:objects)
463     assert_equal 1, found.count
464     assert_equal expect_pdh, found.first.portable_data_hash
465   end
466
467   [false, true].each do |permit_unsigned|
468     test "create collection with signed manifest, permit_unsigned=#{permit_unsigned}" do
469       permit_unsigned_manifests permit_unsigned
470       authorize_with :active
471       locators = %w(
472       d41d8cd98f00b204e9800998ecf8427e+0
473       acbd18db4cc2f85cedef654fccc4a4d8+3
474       ea10d51bcf88862dbcc36eb292017dfd+45)
475
476       unsigned_manifest = locators.map { |loc|
477         ". " + loc + " 0:0:foo.txt\n"
478       }.join()
479       manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
480         '+' +
481         unsigned_manifest.length.to_s
482
483       # Build a manifest with both signed and unsigned locators.
484       signing_opts = {
485         key: Rails.configuration.blob_signing_key,
486         api_token: api_token(:active),
487       }
488       signed_locators = locators.collect do |x|
489         Blob.sign_locator x, signing_opts
490       end
491       if permit_unsigned
492         # Leave a non-empty blob unsigned.
493         signed_locators[1] = locators[1]
494       else
495         # Leave the empty blob unsigned. This should still be allowed.
496         signed_locators[0] = locators[0]
497       end
498       signed_manifest =
499         ". " + signed_locators[0] + " 0:0:foo.txt\n" +
500         ". " + signed_locators[1] + " 0:0:foo.txt\n" +
501         ". " + signed_locators[2] + " 0:0:foo.txt\n"
502
503       post :create, {
504         collection: {
505           manifest_text: signed_manifest,
506           portable_data_hash: manifest_uuid,
507         }
508       }
509       assert_response :success
510       assert_not_nil assigns(:object)
511       resp = JSON.parse(@response.body)
512       assert_equal manifest_uuid, resp['portable_data_hash']
513       # All of the locators in the output must be signed.
514       resp['manifest_text'].lines.each do |entry|
515         m = /([[:xdigit:]]{32}\+\S+)/.match(entry)
516         if m
517           assert Blob.verify_signature m[0], signing_opts
518         end
519       end
520     end
521   end
522
523   test "create collection with signed manifest and explicit TTL" do
524     authorize_with :active
525     locators = %w(
526       d41d8cd98f00b204e9800998ecf8427e+0
527       acbd18db4cc2f85cedef654fccc4a4d8+3
528       ea10d51bcf88862dbcc36eb292017dfd+45)
529
530     unsigned_manifest = locators.map { |loc|
531       ". " + loc + " 0:0:foo.txt\n"
532     }.join()
533     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
534       '+' +
535       unsigned_manifest.length.to_s
536
537     # build a manifest with both signed and unsigned locators.
538     # TODO(twp): in phase 4, all locators will need to be signed, so
539     # this test should break and will need to be rewritten. Issue #2755.
540     signing_opts = {
541       key: Rails.configuration.blob_signing_key,
542       api_token: api_token(:active),
543       ttl: 3600   # 1 hour
544     }
545     signed_manifest =
546       ". " + locators[0] + " 0:0:foo.txt\n" +
547       ". " + Blob.sign_locator(locators[1], signing_opts) + " 0:0:foo.txt\n" +
548       ". " + Blob.sign_locator(locators[2], signing_opts) + " 0:0:foo.txt\n"
549
550     post :create, {
551       collection: {
552         manifest_text: signed_manifest,
553         portable_data_hash: manifest_uuid,
554       }
555     }
556     assert_response :success
557     assert_not_nil assigns(:object)
558     resp = JSON.parse(@response.body)
559     assert_equal manifest_uuid, resp['portable_data_hash']
560     # All of the locators in the output must be signed.
561     resp['manifest_text'].lines.each do |entry|
562       m = /([[:xdigit:]]{32}\+\S+)/.match(entry)
563       if m
564         assert Blob.verify_signature m[0], signing_opts
565       end
566     end
567   end
568
569   test "create fails with invalid signature" do
570     authorize_with :active
571     signing_opts = {
572       key: Rails.configuration.blob_signing_key,
573       api_token: api_token(:active),
574     }
575
576     # Generate a locator with a bad signature.
577     unsigned_locator = "acbd18db4cc2f85cedef654fccc4a4d8+3"
578     bad_locator = unsigned_locator + "+Affffffffffffffffffffffffffffffffffffffff@ffffffff"
579     assert !Blob.verify_signature(bad_locator, signing_opts)
580
581     # Creating a collection with this locator should
582     # produce 403 Permission denied.
583     unsigned_manifest = ". #{unsigned_locator} 0:0:foo.txt\n"
584     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
585       '+' +
586       unsigned_manifest.length.to_s
587
588     bad_manifest = ". #{bad_locator} 0:0:foo.txt\n"
589     post :create, {
590       collection: {
591         manifest_text: bad_manifest,
592         portable_data_hash: manifest_uuid
593       }
594     }
595
596     assert_response 403
597   end
598
599   test "create fails with uuid of signed manifest" do
600     authorize_with :active
601     signing_opts = {
602       key: Rails.configuration.blob_signing_key,
603       api_token: api_token(:active),
604     }
605
606     unsigned_locator = "d41d8cd98f00b204e9800998ecf8427e+0"
607     signed_locator = Blob.sign_locator(unsigned_locator, signing_opts)
608     signed_manifest = ". #{signed_locator} 0:0:foo.txt\n"
609     manifest_uuid = Digest::MD5.hexdigest(signed_manifest) +
610       '+' +
611       signed_manifest.length.to_s
612
613     post :create, {
614       collection: {
615         manifest_text: signed_manifest,
616         portable_data_hash: manifest_uuid
617       }
618     }
619
620     assert_response 422
621   end
622
623   test "reject manifest with unsigned block as stream name" do
624     authorize_with :active
625     post :create, {
626       collection: {
627         manifest_text: "00000000000000000000000000000000+1234 d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo.txt\n"
628       }
629     }
630     assert_includes [422, 403], response.code.to_i
631   end
632
633   test "multiple locators per line" do
634     permit_unsigned_manifests
635     authorize_with :active
636     locators = %w(
637       d41d8cd98f00b204e9800998ecf8427e+0
638       acbd18db4cc2f85cedef654fccc4a4d8+3
639       ea10d51bcf88862dbcc36eb292017dfd+45)
640
641     manifest_text = [".", *locators, "0:0:foo.txt\n"].join(" ")
642     manifest_uuid = Digest::MD5.hexdigest(manifest_text) +
643       '+' +
644       manifest_text.length.to_s
645
646     test_collection = {
647       manifest_text: manifest_text,
648       portable_data_hash: manifest_uuid,
649     }
650     post_collection = Marshal.load(Marshal.dump(test_collection))
651     post :create, {
652       collection: post_collection
653     }
654     assert_response :success
655     assert_not_nil assigns(:object)
656     resp = JSON.parse(@response.body)
657     assert_equal manifest_uuid, resp['portable_data_hash']
658
659     # The manifest in the response will have had permission hints added.
660     # Remove any permission hints in the response before comparing it to the source.
661     stripped_manifest = resp['manifest_text'].gsub(/\+A[A-Za-z0-9@_-]+/, '')
662     assert_equal manifest_text, stripped_manifest
663   end
664
665   test "multiple signed locators per line" do
666     permit_unsigned_manifests
667     authorize_with :active
668     locators = %w(
669       d41d8cd98f00b204e9800998ecf8427e+0
670       acbd18db4cc2f85cedef654fccc4a4d8+3
671       ea10d51bcf88862dbcc36eb292017dfd+45)
672
673     signing_opts = {
674       key: Rails.configuration.blob_signing_key,
675       api_token: api_token(:active),
676     }
677
678     unsigned_manifest = [".", *locators, "0:0:foo.txt\n"].join(" ")
679     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest) +
680       '+' +
681       unsigned_manifest.length.to_s
682
683     signed_locators = locators.map { |loc| Blob.sign_locator loc, signing_opts }
684     signed_manifest = [".", *signed_locators, "0:0:foo.txt\n"].join(" ")
685
686     post :create, {
687       collection: {
688         manifest_text: signed_manifest,
689         portable_data_hash: manifest_uuid,
690       }
691     }
692     assert_response :success
693     assert_not_nil assigns(:object)
694     resp = JSON.parse(@response.body)
695     assert_equal manifest_uuid, resp['portable_data_hash']
696     # All of the locators in the output must be signed.
697     # Each line is of the form "path locator locator ... 0:0:file.txt"
698     # entry.split[1..-2] will yield just the tokens in the middle of the line
699     returned_locator_count = 0
700     resp['manifest_text'].lines.each do |entry|
701       entry.split[1..-2].each do |tok|
702         returned_locator_count += 1
703         assert Blob.verify_signature tok, signing_opts
704       end
705     end
706     assert_equal locators.count, returned_locator_count
707   end
708
709   test 'Reject manifest with unsigned blob' do
710     permit_unsigned_manifests false
711     authorize_with :active
712     unsigned_manifest = ". 0cc175b9c0f1b6a831c399e269772661+1 0:1:a.txt\n"
713     manifest_uuid = Digest::MD5.hexdigest(unsigned_manifest)
714     post :create, {
715       collection: {
716         manifest_text: unsigned_manifest,
717         portable_data_hash: manifest_uuid,
718       }
719     }
720     assert_response 403,
721     "Creating a collection with unsigned blobs should respond 403"
722     assert_empty Collection.where('uuid like ?', manifest_uuid+'%'),
723     "Collection should not exist in database after failed create"
724   end
725
726   test 'List expired collection returns empty list' do
727     authorize_with :active
728     get :index, {
729       where: {name: 'expired_collection'},
730     }
731     assert_response :success
732     found = assigns(:objects)
733     assert_equal 0, found.count
734   end
735
736   test 'Show expired collection returns 404' do
737     authorize_with :active
738     get :show, {
739       id: 'zzzzz-4zz18-mto52zx1s7sn3ih',
740     }
741     assert_response 404
742   end
743
744   test 'Update expired collection returns 404' do
745     authorize_with :active
746     post :update, {
747       id: 'zzzzz-4zz18-mto52zx1s7sn3ih',
748       collection: {
749         name: "still expired"
750       }
751     }
752     assert_response 404
753   end
754
755   test 'List collection with future expiration time succeeds' do
756     authorize_with :active
757     get :index, {
758       where: {name: 'collection_expires_in_future'},
759     }
760     found = assigns(:objects)
761     assert_equal 1, found.count
762   end
763
764
765   test 'Show collection with future expiration time succeeds' do
766     authorize_with :active
767     get :show, {
768       id: 'zzzzz-4zz18-padkqo7yb8d9i3j',
769     }
770     assert_response :success
771   end
772
773   test 'Update collection with future expiration time succeeds' do
774     authorize_with :active
775     post :update, {
776       id: 'zzzzz-4zz18-padkqo7yb8d9i3j',
777       collection: {
778         name: "still not expired"
779       }
780     }
781     assert_response :success
782   end
783
784   test "get collection and verify that file_names is not included" do
785     authorize_with :active
786     get :show, {id: collections(:foo_file).uuid}
787     assert_response :success
788     assert_equal collections(:foo_file).uuid, json_response['uuid']
789     assert_nil json_response['file_names']
790     assert json_response['manifest_text']
791   end
792
793   [
794     [2**8, :success],
795     [2**18, 422],
796   ].each do |description_size, expected_response|
797     test "create collection with description size #{description_size}
798           and expect response #{expected_response}" do
799       skip "(Descriptions are not part of search indexes. Skip until full-text search
800             is implemented, at which point replace with a search in description.)"
801
802       authorize_with :active
803
804       description = 'here is a collection with a very large description'
805       while description.length < description_size
806         description = description + description
807       end
808
809       post :create, collection: {
810         manifest_text: ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:foo.txt\n",
811         description: description,
812       }
813
814       assert_response expected_response
815     end
816   end
817
818   [1, 5, nil].each do |ask|
819     test "Set replication_desired=#{ask.inspect}" do
820       Rails.configuration.default_collection_replication = 2
821       authorize_with :active
822       put :update, {
823         id: collections(:replication_undesired_unconfirmed).uuid,
824         collection: {
825           replication_desired: ask,
826         },
827       }
828       assert_response :success
829       assert_equal ask, json_response['replication_desired']
830     end
831   end
832
833   test "get collection with properties" do
834     authorize_with :active
835     get :show, {id: collections(:collection_with_one_property).uuid}
836     assert_response :success
837     assert_not_nil json_response['uuid']
838     assert_equal 'value1', json_response['properties']['property1']
839   end
840
841   test "create collection with properties" do
842     authorize_with :active
843     manifest_text = ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n"
844     post :create, {
845       collection: {
846         manifest_text: manifest_text,
847         portable_data_hash: "d30fe8ae534397864cb96c544f4cf102+47",
848         properties: {'property_1' => 'value_1'}
849       }
850     }
851     assert_response :success
852     assert_not_nil json_response['uuid']
853     assert_equal 'value_1', json_response['properties']['property_1']
854   end
855
856   [
857     ". 0:0:foo.txt",
858     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
859     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
860     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
861   ].each do |manifest_text|
862     test "create collection with invalid manifest #{manifest_text} and expect error" do
863       authorize_with :active
864       post :create, {
865         collection: {
866           manifest_text: manifest_text,
867           portable_data_hash: "d41d8cd98f00b204e9800998ecf8427e+0"
868         }
869       }
870       assert_response 422
871       response_errors = json_response['errors']
872       assert_not_nil response_errors, 'Expected error in response'
873       assert(response_errors.first.include?('Invalid manifest'),
874              "Expected 'Invalid manifest' error in #{response_errors.first}")
875     end
876   end
877
878   [
879     [nil, "d41d8cd98f00b204e9800998ecf8427e+0"],
880     ["", "d41d8cd98f00b204e9800998ecf8427e+0"],
881     [". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n", "d30fe8ae534397864cb96c544f4cf102+47"],
882   ].each do |manifest_text, pdh|
883     test "create collection with valid manifest #{manifest_text.inspect} and expect success" do
884       authorize_with :active
885       post :create, {
886         collection: {
887           manifest_text: manifest_text,
888           portable_data_hash: pdh
889         }
890       }
891       assert_response 200
892     end
893   end
894
895   [
896     ". 0:0:foo.txt",
897     ". d41d8cd98f00b204e9800998ecf8427e foo.txt",
898     "d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
899     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt",
900   ].each do |manifest_text|
901     test "update collection with invalid manifest #{manifest_text} and expect error" do
902       authorize_with :active
903       post :update, {
904         id: 'zzzzz-4zz18-bv31uwvy3neko21',
905         collection: {
906           manifest_text: manifest_text,
907         }
908       }
909       assert_response 422
910       response_errors = json_response['errors']
911       assert_not_nil response_errors, 'Expected error in response'
912       assert(response_errors.first.include?('Invalid manifest'),
913              "Expected 'Invalid manifest' error in #{response_errors.first}")
914     end
915   end
916
917   [
918     nil,
919     "",
920     ". d41d8cd98f00b204e9800998ecf8427e 0:0:foo.txt\n",
921   ].each do |manifest_text|
922     test "update collection with valid manifest #{manifest_text.inspect} and expect success" do
923       authorize_with :active
924       post :update, {
925         id: 'zzzzz-4zz18-bv31uwvy3neko21',
926         collection: {
927           manifest_text: manifest_text,
928         }
929       }
930       assert_response 200
931     end
932   end
933 end