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