Merge branch '5043-crunchstat-long-lines' closes #5043
[arvados.git] / apps / workbench / test / controllers / collections_controller_test.rb
1 require 'test_helper'
2
3 class CollectionsControllerTest < ActionController::TestCase
4   # These tests don't do state-changing API calls. Save some time by
5   # skipping the database reset.
6   reset_api_fixtures :after_each_test, false
7   reset_api_fixtures :after_suite, true
8
9   include PipelineInstancesHelper
10
11   NONEXISTENT_COLLECTION = "ffffffffffffffffffffffffffffffff+0"
12
13   def stub_file_content
14     # For the duration of the current test case, stub file download
15     # content with a randomized (but recognizable) string. Return the
16     # string, the test case can use it in assertions.
17     txt = 'the quick brown fox ' + rand(2**32).to_s
18     @controller.stubs(:file_enumerator).returns([txt])
19     txt
20   end
21
22   def collection_params(collection_name, file_name=nil)
23     uuid = api_fixture('collections')[collection_name.to_s]['uuid']
24     params = {uuid: uuid, id: uuid}
25     params[:file] = file_name if file_name
26     params
27   end
28
29   def assert_hash_includes(actual_hash, expected_hash, msg=nil)
30     expected_hash.each do |key, value|
31       assert_equal(value, actual_hash[key], msg)
32     end
33   end
34
35   def assert_no_session
36     assert_hash_includes(session, {arvados_api_token: nil},
37                          "session includes unexpected API token")
38   end
39
40   def assert_session_for_auth(client_auth)
41     api_token =
42       api_fixture('api_client_authorizations')[client_auth.to_s]['api_token']
43     assert_hash_includes(session, {arvados_api_token: api_token},
44                          "session token does not belong to #{client_auth}")
45   end
46
47   def show_collection(params, session={}, response=:success)
48     params = collection_params(params) if not params.is_a? Hash
49     session = session_for(session) if not session.is_a? Hash
50     get(:show, params, session)
51     assert_response response
52   end
53
54   test "viewing a collection" do
55     show_collection(:foo_file, :active)
56     assert_equal([['.', 'foo', 3]], assigns(:object).files)
57   end
58
59   test "viewing a collection with spaces in filename" do
60     show_collection(:w_a_z_file, :active)
61     assert_equal([['.', 'w a z', 5]], assigns(:object).files)
62   end
63
64   test "download a file with spaces in filename" do
65     collection = api_fixture('collections')['w_a_z_file']
66     fakepipe = IO.popen(['echo', '-n', 'w a z'], 'rb')
67     IO.expects(:popen).with { |cmd, mode|
68       cmd.include? "#{collection['uuid']}/w a z"
69     }.returns(fakepipe)
70     get :show_file, {
71       uuid: collection['uuid'],
72       file: 'w a z'
73     }, session_for(:active)
74     assert_response :success
75     assert_equal 'w a z', response.body
76   end
77
78   test "viewing a collection fetches related projects" do
79     show_collection({id: api_fixture('collections')["foo_file"]['portable_data_hash']}, :active)
80     assert_includes(assigns(:same_pdh).map(&:owner_uuid),
81                     api_fixture('groups')['aproject']['uuid'],
82                     "controller did not find linked project")
83   end
84
85   test "viewing a collection fetches related permissions" do
86     show_collection(:bar_file, :active)
87     assert_includes(assigns(:permissions).map(&:uuid),
88                     api_fixture('links')['bar_file_readable_by_active']['uuid'],
89                     "controller did not find permission link")
90   end
91
92   test "viewing a collection fetches jobs that output it" do
93     show_collection(:bar_file, :active)
94     assert_includes(assigns(:output_of).map(&:uuid),
95                     api_fixture('jobs')['foobar']['uuid'],
96                     "controller did not find output job")
97   end
98
99   test "viewing a collection fetches jobs that logged it" do
100     show_collection(:baz_file, :active)
101     assert_includes(assigns(:log_of).map(&:uuid),
102                     api_fixture('jobs')['foobar']['uuid'],
103                     "controller did not find logger job")
104   end
105
106   test "viewing a collection fetches logs about it" do
107     show_collection(:foo_file, :active)
108     assert_includes(assigns(:logs).map(&:uuid),
109                     api_fixture('logs')['log4']['uuid'],
110                     "controller did not find related log")
111   end
112
113   test "sharing auths available to admin" do
114     show_collection("collection_owned_by_active", "admin_trustedclient")
115     assert_not_nil assigns(:search_sharing)
116   end
117
118   test "sharing auths available to owner" do
119     show_collection("collection_owned_by_active", "active_trustedclient")
120     assert_not_nil assigns(:search_sharing)
121   end
122
123   test "sharing auths available to reader" do
124     show_collection("foo_collection_in_aproject",
125                     "project_viewer_trustedclient")
126     assert_not_nil assigns(:search_sharing)
127   end
128
129   test "viewing collection files with a reader token" do
130     params = collection_params(:foo_file)
131     params[:reader_token] = api_fixture("api_client_authorizations",
132                                         "active_all_collections", "api_token")
133     get(:show_file_links, params)
134     assert_response :success
135     assert_equal([['.', 'foo', 3]], assigns(:object).files)
136     assert_no_session
137   end
138
139   test "fetching collection file with reader token" do
140     expected = stub_file_content
141     params = collection_params(:foo_file, "foo")
142     params[:reader_token] = api_fixture("api_client_authorizations",
143                                         "active_all_collections", "api_token")
144     get(:show_file, params)
145     assert_response :success
146     assert_equal(expected, @response.body,
147                  "failed to fetch a Collection file with a reader token")
148     assert_no_session
149   end
150
151   test "reader token Collection links end with trailing slash" do
152     # Testing the fix for #2937.
153     session = session_for(:active_trustedclient)
154     post(:share, collection_params(:foo_file), session)
155     assert(@controller.download_link.ends_with? '/',
156            "Collection share link does not end with slash for wget")
157   end
158
159   test "getting a file from Keep" do
160     params = collection_params(:foo_file, 'foo')
161     sess = session_for(:active)
162     expect_content = stub_file_content
163     get(:show_file, params, sess)
164     assert_response :success
165     assert_equal(expect_content, @response.body,
166                  "failed to get a correct file from Keep")
167   end
168
169   test 'anonymous download' do
170     Rails.configuration.anonymous_user_token =
171       api_fixture('api_client_authorizations')['anonymous']['api_token']
172     expect_content = stub_file_content
173     get :show_file, {
174       uuid: api_fixture('collections')['user_agreement_in_anonymously_accessible_project']['uuid'],
175       file: 'GNU_General_Public_License,_version_3.pdf',
176     }
177     assert_response :success
178     assert_equal expect_content, response.body
179   end
180
181   test "can't get a file from Keep without permission" do
182     params = collection_params(:foo_file, 'foo')
183     sess = session_for(:spectator)
184     get(:show_file, params, sess)
185     assert_response 404
186   end
187
188   test "trying to get a nonexistent file from Keep returns a 404" do
189     params = collection_params(:foo_file, 'gone')
190     sess = session_for(:admin)
191     get(:show_file, params, sess)
192     assert_response 404
193   end
194
195   test "getting a file from Keep with a good reader token" do
196     params = collection_params(:foo_file, 'foo')
197     read_token = api_fixture('api_client_authorizations')['active']['api_token']
198     params[:reader_token] = read_token
199     expect_content = stub_file_content
200     get(:show_file, params)
201     assert_response :success
202     assert_equal(expect_content, @response.body,
203                  "failed to get a correct file from Keep using a reader token")
204     assert_not_equal(read_token, session[:arvados_api_token],
205                      "using a reader token set the session's API token")
206   end
207
208   [false, api_fixture('api_client_authorizations')['anonymous']['api_token']].
209     each do |anon_conf|
210     test "download a file using a reader token with insufficient scope (anon_conf=#{!!anon_conf})" do
211       Rails.configuration.anonymous_user_token = anon_conf
212       params = collection_params(:foo_file, 'foo')
213       params[:reader_token] =
214         api_fixture('api_client_authorizations')['active_noscope']['api_token']
215       get(:show_file, params)
216       if anon_conf
217         # Some files can be shown without a valid token, but not this one.
218         assert_response 404
219       else
220         # No files will ever be shown without a valid token. You
221         # should log in and try again.
222         assert_response :redirect
223       end
224     end
225   end
226
227   test "can get a file with an unpermissioned auth but in-scope reader token" do
228     params = collection_params(:foo_file, 'foo')
229     sess = session_for(:expired)
230     read_token = api_fixture('api_client_authorizations')['active']['api_token']
231     params[:reader_token] = read_token
232     expect_content = stub_file_content
233     get(:show_file, params, sess)
234     assert_response :success
235     assert_equal(expect_content, @response.body,
236                  "failed to get a correct file from Keep using a reader token")
237     assert_not_equal(read_token, session[:arvados_api_token],
238                      "using a reader token set the session's API token")
239   end
240
241   test "inactive user can retrieve user agreement" do
242     ua_collection = api_fixture('collections')['user_agreement']
243     # Here we don't test whether the agreement can be retrieved from
244     # Keep. We only test that show_file decides to send file content,
245     # so we use the file content stub.
246     stub_file_content
247     get :show_file, {
248       uuid: ua_collection['uuid'],
249       file: ua_collection['manifest_text'].match(/ \d+:\d+:(\S+)/)[1]
250     }, session_for(:inactive)
251     assert_nil(assigns(:unsigned_user_agreements),
252                "Did not skip check_user_agreements filter " +
253                "when showing the user agreement.")
254     assert_response :success
255   end
256
257   test "requesting nonexistent Collection returns 404" do
258     show_collection({uuid: NONEXISTENT_COLLECTION, id: NONEXISTENT_COLLECTION},
259                     :active, 404)
260   end
261
262   test "use a reasonable read buffer even if client requests a huge range" do
263     fakefiledata = mock
264     IO.expects(:popen).returns(fakefiledata)
265     fakefiledata.expects(:read).twice.with() do |length|
266       # Fail the test if read() is called with length>1MiB:
267       length < 2**20
268       ## Force the ActionController::Live thread to lose the race to
269       ## verify that @response.body.length actually waits for the
270       ## response (see below):
271       # sleep 3
272     end.returns("foo\n", nil)
273     fakefiledata.expects(:close)
274     foo_file = api_fixture('collections')['foo_file']
275     @request.headers['Range'] = 'bytes=0-4294967296/*'
276     get :show_file, {
277       uuid: foo_file['uuid'],
278       file: foo_file['manifest_text'].match(/ \d+:\d+:(\S+)/)[1]
279     }, session_for(:active)
280     # Wait for the whole response to arrive before deciding whether
281     # mocks' expectations were met. Otherwise, Mocha will fail the
282     # test depending on how slowly the ActionController::Live thread
283     # runs.
284     @response.body.length
285   end
286
287   test "show file in a subdirectory of a collection" do
288     params = collection_params(:collection_with_files_in_subdir, 'subdir2/subdir3/subdir4/file1_in_subdir4.txt')
289     expect_content = stub_file_content
290     get(:show_file, params, session_for(:user1_with_load))
291     assert_response :success
292     assert_equal(expect_content, @response.body, "failed to get a correct file from Keep")
293   end
294
295   test 'provenance graph' do
296     use_token 'admin'
297
298     obj = find_fixture Collection, "graph_test_collection3"
299
300     provenance = obj.provenance.stringify_keys
301
302     [obj[:portable_data_hash]].each do |k|
303       assert_not_nil provenance[k], "Expected key #{k} in provenance set"
304     end
305
306     prov_svg = ProvenanceHelper::create_provenance_graph(provenance, "provenance_svg",
307                                                          {:request => RequestDuck,
308                                                            :direction => :bottom_up,
309                                                            :combine_jobs => :script_only})
310
311     stage1 = find_fixture Job, "graph_stage1"
312     stage3 = find_fixture Job, "graph_stage3"
313     previous_job_run = find_fixture Job, "previous_job_run"
314
315     obj_id = obj.portable_data_hash.gsub('+', '\\\+')
316     stage1_out = stage1.output.gsub('+', '\\\+')
317     stage1_id = "#{stage1.script}_#{Digest::MD5.hexdigest(stage1[:script_parameters].to_json)}"
318     stage3_id = "#{stage3.script}_#{Digest::MD5.hexdigest(stage3[:script_parameters].to_json)}"
319
320     assert /#{obj_id}&#45;&gt;#{stage3_id}/.match(prov_svg)
321
322     assert /#{stage3_id}&#45;&gt;#{stage1_out}/.match(prov_svg)
323
324     assert /#{stage1_out}&#45;&gt;#{stage1_id}/.match(prov_svg)
325
326   end
327
328   test 'used_by graph' do
329     use_token 'admin'
330     obj = find_fixture Collection, "graph_test_collection1"
331
332     used_by = obj.used_by.stringify_keys
333
334     used_by_svg = ProvenanceHelper::create_provenance_graph(used_by, "used_by_svg",
335                                                             {:request => RequestDuck,
336                                                               :direction => :top_down,
337                                                               :combine_jobs => :script_only,
338                                                               :pdata_only => true})
339
340     stage2 = find_fixture Job, "graph_stage2"
341     stage3 = find_fixture Job, "graph_stage3"
342
343     stage2_id = "#{stage2.script}_#{Digest::MD5.hexdigest(stage2[:script_parameters].to_json)}"
344     stage3_id = "#{stage3.script}_#{Digest::MD5.hexdigest(stage3[:script_parameters].to_json)}"
345
346     obj_id = obj.portable_data_hash.gsub('+', '\\\+')
347     stage3_out = stage3.output.gsub('+', '\\\+')
348
349     assert /#{obj_id}&#45;&gt;#{stage2_id}/.match(used_by_svg)
350
351     assert /#{obj_id}&#45;&gt;#{stage3_id}/.match(used_by_svg)
352
353     assert /#{stage3_id}&#45;&gt;#{stage3_out}/.match(used_by_svg)
354
355     assert /#{stage3_id}&#45;&gt;#{stage3_out}/.match(used_by_svg)
356
357   end
358
359   test "view collection with empty properties" do
360     fixture_name = :collection_with_empty_properties
361     show_collection(fixture_name, :active)
362     assert_equal(api_fixture('collections')[fixture_name.to_s]['name'], assigns(:object).name)
363     assert_not_nil(assigns(:object).properties)
364     assert_empty(assigns(:object).properties)
365   end
366
367   test "view collection with one property" do
368     fixture_name = :collection_with_one_property
369     show_collection(fixture_name, :active)
370     fixture = api_fixture('collections')[fixture_name.to_s]
371     assert_equal(fixture['name'], assigns(:object).name)
372     assert_equal(fixture['properties'][0], assigns(:object).properties[0])
373   end
374
375   test "create collection with properties" do
376     post :create, {
377       collection: {
378         name: 'collection created with properties',
379         manifest_text: '',
380         properties: {
381           property_1: 'value_1'
382         },
383       },
384       format: :json
385     }, session_for(:active)
386     assert_response :success
387     assert_not_nil assigns(:object).uuid
388     assert_equal 'collection created with properties', assigns(:object).name
389     assert_equal 'value_1', assigns(:object).properties[:property_1]
390   end
391
392   test "update description and check manifest_text is not lost" do
393     collection = api_fixture("collections")["multilevel_collection_1"]
394     post :update, {
395       id: collection["uuid"],
396       collection: {
397         description: 'test description update'
398       },
399       format: :json
400     }, session_for(:active)
401     assert_response :success
402     assert_not_nil assigns(:object)
403     assert_equal 'test description update', assigns(:object).description
404     assert_equal collection['manifest_text'], assigns(:object).manifest_text
405   end
406 end