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