15877: Accept JSON-encoded param values in JSON request body.
[arvados.git] / services / api / test / integration / remote_user_test.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'webrick'
6 require 'webrick/https'
7 require 'test_helper'
8 require 'helpers/users_test_helper'
9
10 class RemoteUsersTest < ActionDispatch::IntegrationTest
11   include DbCurrentTime
12
13   def salted_active_token(remote:)
14     salt_token(fixture: :active, remote: remote).sub('/zzzzz-', '/'+remote+'-')
15   end
16
17   def auth(remote:)
18     token = salted_active_token(remote: remote)
19     {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
20   end
21
22   # For remote authentication tests, we bring up a simple stub server
23   # (on a port chosen by webrick) and configure the SUT so the stub is
24   # responsible for clusters "zbbbb" (a well-behaved cluster) and
25   # "zbork" (a misbehaving cluster).
26   #
27   # Test cases can override the stub's default response to
28   # .../users/current by changing @stub_status and @stub_content.
29   setup do
30     clnt = HTTPClient.new
31     clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
32     HTTPClient.stubs(:new).returns clnt
33
34     @controller = Arvados::V1::UsersController.new
35     ready = Thread::Queue.new
36
37     @remote_server = []
38     @remote_host = []
39
40     ['zbbbb', 'zbork'].each do |clusterid|
41       srv = WEBrick::HTTPServer.new(
42         Port: 0,
43         Logger: WEBrick::Log.new(
44           Rails.root.join("log", "webrick.log").to_s,
45           WEBrick::Log::INFO),
46         AccessLog: [[File.open(Rails.root.join(
47                                  "log", "webrick_access.log").to_s, 'a+'),
48                      WEBrick::AccessLog::COMBINED_LOG_FORMAT]],
49         SSLEnable: true,
50         SSLVerifyClient: OpenSSL::SSL::VERIFY_NONE,
51         SSLPrivateKey: OpenSSL::PKey::RSA.new(
52           File.open(Rails.root.join("tmp", "self-signed.key")).read),
53         SSLCertificate: OpenSSL::X509::Certificate.new(
54           File.open(Rails.root.join("tmp", "self-signed.pem")).read),
55         SSLCertName: [["CN", WEBrick::Utils::getservername]],
56         StartCallback: lambda { ready.push(true) })
57       srv.mount_proc '/discovery/v1/apis/arvados/v1/rest' do |req, res|
58         Rails.cache.delete 'arvados_v1_rest_discovery'
59         res.body = Arvados::V1::SchemaController.new.send(:discovery_doc).to_json
60       end
61       srv.mount_proc '/arvados/v1/users/current' do |req, res|
62         if clusterid == 'zbbbb' and req.header['authorization'][0][10..14] == 'zbork'
63           # asking zbbbb about zbork should yield an error, zbbbb doesn't trust zbork
64           res.status = 401
65           return
66         end
67         res.status = @stub_status
68         res.body = @stub_content.is_a?(String) ? @stub_content : @stub_content.to_json
69       end
70       Thread.new do
71         srv.start
72       end
73       ready.pop
74       @remote_server << srv
75       @remote_host << "127.0.0.1:#{srv.config[:Port]}"
76     end
77     Rails.configuration.RemoteClusters = Rails.configuration.RemoteClusters.merge({zbbbb: ActiveSupport::InheritableOptions.new({Host: @remote_host[0]}),
78                                                                                    zbork: ActiveSupport::InheritableOptions.new({Host: @remote_host[1]})})
79     Arvados::V1::SchemaController.any_instance.stubs(:root_url).returns "https://#{@remote_host[0]}"
80     @stub_status = 200
81     @stub_content = {
82       uuid: 'zbbbb-tpzed-000000000000000',
83       email: 'foo@example.com',
84       username: 'barney',
85       is_admin: true,
86       is_active: true,
87     }
88   end
89
90   teardown do
91     @remote_server.each do |srv|
92       srv.stop
93     end
94   end
95
96   test 'authenticate with remote token' do
97     get '/arvados/v1/users/current',
98       params: {format: 'json'},
99       headers: auth(remote: 'zbbbb')
100     assert_response :success
101     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
102     assert_equal false, json_response['is_admin']
103     assert_equal false, json_response['is_active']
104     assert_equal 'foo@example.com', json_response['email']
105     assert_equal 'barney', json_response['username']
106
107     # revoke original token
108     @stub_status = 401
109
110     # re-authorize before cache expires
111     get '/arvados/v1/users/current',
112       params: {format: 'json'},
113       headers: auth(remote: 'zbbbb')
114     assert_response :success
115
116     # simulate cache expiry
117     ApiClientAuthorization.where(
118       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
119       update_all(expires_at: db_current_time - 1.minute)
120
121     # re-authorize after cache expires
122     get '/arvados/v1/users/current',
123       params: {format: 'json'},
124       headers: auth(remote: 'zbbbb')
125     assert_response 401
126
127     # simulate cached token indicating wrong user (e.g., local user
128     # entry was migrated out of the way taking the cached token with
129     # it, or authorizing cluster reassigned auth to a different user)
130     ApiClientAuthorization.where(
131       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
132       update_all(user_id: users(:active).id)
133
134     # revive original token and re-authorize
135     @stub_status = 200
136     @stub_content[:username] = 'blarney'
137     @stub_content[:email] = 'blarney@example.com'
138     get '/arvados/v1/users/current',
139       params: {format: 'json'},
140       headers: auth(remote: 'zbbbb')
141     assert_response :success
142     assert_equal 'barney', json_response['username'], 'local username should not change once assigned'
143     assert_equal 'blarney@example.com', json_response['email']
144   end
145
146   test 'authenticate with remote token, remote username conflicts with local' do
147     @stub_content[:username] = 'active'
148     get '/arvados/v1/users/current',
149       params: {format: 'json'},
150       headers: auth(remote: 'zbbbb')
151     assert_response :success
152     assert_equal 'active2', json_response['username']
153   end
154
155   test 'authenticate with remote token, remote username is nil' do
156     @stub_content.delete :username
157     get '/arvados/v1/users/current',
158       params: {format: 'json'},
159       headers: auth(remote: 'zbbbb')
160     assert_response :success
161     assert_equal 'foo', json_response['username']
162   end
163
164   test 'authenticate with remote token from misbehaving remote cluster' do
165     get '/arvados/v1/users/current',
166       params: {format: 'json'},
167       headers: auth(remote: 'zbork')
168     assert_response 401
169   end
170
171   test 'authenticate with remote token that fails validate' do
172     @stub_status = 401
173     @stub_content = {
174       error: 'not authorized',
175     }
176     get '/arvados/v1/users/current',
177       params: {format: 'json'},
178       headers: auth(remote: 'zbbbb')
179     assert_response 401
180   end
181
182   ['v2',
183    'v2/',
184    'v2//',
185    'v2///',
186    "v2/'; delete from users where 1=1; commit; select '/lol",
187    'v2/foo/bar',
188    'v2/zzzzz-gj3su-077z32aux8dg2s1',
189    'v2/zzzzz-gj3su-077z32aux8dg2s1/',
190    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
191    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi/zzzzz-gj3su-077z32aux8dg2s1',
192    'v2//3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
193    'v8/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
194    '/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
195    '"v2/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi"',
196    '/',
197    '//',
198    '///',
199   ].each do |token|
200     test "authenticate with malformed remote token #{token}" do
201       get '/arvados/v1/users/current',
202         params: {format: 'json'},
203         headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
204       assert_response 401
205     end
206   end
207
208   test "ignore extra fields in remote token" do
209     token = salted_active_token(remote: 'zbbbb') + '/foo/bar/baz/*'
210     get '/arvados/v1/users/current',
211       params: {format: 'json'},
212       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
213     assert_response :success
214   end
215
216   test 'remote api server is not an api server' do
217     @stub_status = 200
218     @stub_content = '<html>bad</html>'
219     get '/arvados/v1/users/current',
220       params: {format: 'json'},
221       headers: auth(remote: 'zbbbb')
222     assert_response 401
223   end
224
225   ['zbbbb', 'z0000'].each do |token_valid_for|
226     test "validate #{token_valid_for}-salted token for remote cluster zbbbb" do
227       salted_token = salt_token(fixture: :active, remote: token_valid_for)
228       get '/arvados/v1/users/current',
229         params: {format: 'json', remote: 'zbbbb'},
230         headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
231       if token_valid_for == 'zbbbb'
232         assert_response 200
233         assert_equal(users(:active).uuid, json_response['uuid'])
234       else
235         assert_response 401
236       end
237     end
238   end
239
240   test "list readable groups with salted token" do
241     salted_token = salt_token(fixture: :active, remote: 'zbbbb')
242     get '/arvados/v1/groups',
243       params: {
244         format: 'json',
245         remote: 'zbbbb',
246         limit: 10000,
247       },
248       headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
249     assert_response 200
250     group_uuids = json_response['items'].collect { |i| i['uuid'] }
251     assert_includes(group_uuids, 'zzzzz-j7d0g-fffffffffffffff')
252     refute_includes(group_uuids, 'zzzzz-j7d0g-000000000000000')
253     assert_includes(group_uuids, groups(:aproject).uuid)
254     refute_includes(group_uuids, groups(:trashed_project).uuid)
255     refute_includes(group_uuids, groups(:testusergroup_admins).uuid)
256   end
257
258   test 'auto-activate user from trusted cluster' do
259     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
260     get '/arvados/v1/users/current',
261       params: {format: 'json'},
262       headers: auth(remote: 'zbbbb')
263     assert_response :success
264     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
265     assert_equal false, json_response['is_admin']
266     assert_equal true, json_response['is_active']
267     assert_equal 'foo@example.com', json_response['email']
268     assert_equal 'barney', json_response['username']
269   end
270
271   test 'get user from Login cluster' do
272     Rails.configuration.Login.LoginCluster = 'zbbbb'
273     get '/arvados/v1/users/current',
274       params: {format: 'json'},
275       headers: auth(remote: 'zbbbb')
276     assert_response :success
277     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
278     assert_equal true, json_response['is_admin']
279     assert_equal true, json_response['is_active']
280     assert_equal 'foo@example.com', json_response['email']
281     assert_equal 'barney', json_response['username']
282   end
283
284   test 'pre-activate remote user' do
285     @stub_content = {
286       uuid: 'zbbbb-tpzed-000000000001234',
287       email: 'foo@example.com',
288       username: 'barney',
289       is_admin: true,
290       is_active: true,
291     }
292
293     post '/arvados/v1/users',
294       params: {
295         "user" => {
296           "uuid" => "zbbbb-tpzed-000000000001234",
297           "email" => 'foo@example.com',
298           "username" => 'barney',
299           "is_active" => true,
300           "is_admin" => false
301         }
302       },
303       headers: {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
304     assert_response :success
305
306     get '/arvados/v1/users/current',
307       params: {format: 'json'},
308       headers: auth(remote: 'zbbbb')
309     assert_response :success
310     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
311     assert_equal false, json_response['is_admin']
312     assert_equal true, json_response['is_active']
313     assert_equal 'foo@example.com', json_response['email']
314     assert_equal 'barney', json_response['username']
315   end
316
317
318   test 'remote user inactive without pre-activation' do
319     @stub_content = {
320       uuid: 'zbbbb-tpzed-000000000001234',
321       email: 'foo@example.com',
322       username: 'barney',
323       is_admin: true,
324       is_active: true,
325     }
326
327     get '/arvados/v1/users/current',
328       params: {format: 'json'},
329       headers: auth(remote: 'zbbbb')
330     assert_response :success
331     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
332     assert_equal false, json_response['is_admin']
333     assert_equal false, json_response['is_active']
334     assert_equal 'foo@example.com', json_response['email']
335     assert_equal 'barney', json_response['username']
336   end
337
338   test "validate unsalted v2 token for remote cluster zbbbb" do
339     auth = api_client_authorizations(:active)
340     token = "v2/#{auth.uuid}/#{auth.api_token}"
341     get '/arvados/v1/users/current',
342       params: {format: 'json', remote: 'zbbbb'},
343       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
344     assert_response :success
345     assert_equal(users(:active).uuid, json_response['uuid'])
346   end
347
348   test 'container request with runtime_token' do
349     [["valid local", "v2/#{api_client_authorizations(:active).uuid}/#{api_client_authorizations(:active).api_token}"],
350      ["valid remote", "v2/zbbbb-gj3su-000000000000000/abc"],
351      ["invalid local", "v2/#{api_client_authorizations(:active).uuid}/fakefakefake"],
352      ["invalid remote", "v2/zbork-gj3su-000000000000000/abc"],
353     ].each do |label, runtime_token|
354       post '/arvados/v1/container_requests',
355         params: {
356           "container_request" => {
357             "command" => ["echo"],
358             "container_image" => "xyz",
359             "output_path" => "/",
360             "cwd" => "/",
361             "runtime_token" => runtime_token
362           }
363         },
364         headers: {"HTTP_AUTHORIZATION" => "Bearer #{api_client_authorizations(:active).api_token}"}
365       if label.include? "invalid"
366         assert_response 422
367       else
368         assert_response :success
369       end
370     end
371   end
372
373 end