Merge branch '15877-accept-json-in-json'
[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 'remote user is deactivated' do
147     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
148     get '/arvados/v1/users/current',
149       params: {format: 'json'},
150       headers: auth(remote: 'zbbbb')
151     assert_response :success
152     assert_equal true, json_response['is_active']
153
154     # revoke original token
155     @stub_content[:is_active] = false
156
157     # simulate cache expiry
158     ApiClientAuthorization.where(
159       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
160       update_all(expires_at: db_current_time - 1.minute)
161
162     # re-authorize after cache expires
163     get '/arvados/v1/users/current',
164       params: {format: 'json'},
165       headers: auth(remote: 'zbbbb')
166     assert_equal false, json_response['is_active']
167
168   end
169
170   test 'authenticate with remote token, remote username conflicts with local' do
171     @stub_content[:username] = 'active'
172     get '/arvados/v1/users/current',
173       params: {format: 'json'},
174       headers: auth(remote: 'zbbbb')
175     assert_response :success
176     assert_equal 'active2', json_response['username']
177   end
178
179   test 'authenticate with remote token, remote username is nil' do
180     @stub_content.delete :username
181     get '/arvados/v1/users/current',
182       params: {format: 'json'},
183       headers: auth(remote: 'zbbbb')
184     assert_response :success
185     assert_equal 'foo', json_response['username']
186   end
187
188   test 'authenticate with remote token from misbehaving remote cluster' do
189     get '/arvados/v1/users/current',
190       params: {format: 'json'},
191       headers: auth(remote: 'zbork')
192     assert_response 401
193   end
194
195   test 'authenticate with remote token that fails validate' do
196     @stub_status = 401
197     @stub_content = {
198       error: 'not authorized',
199     }
200     get '/arvados/v1/users/current',
201       params: {format: 'json'},
202       headers: auth(remote: 'zbbbb')
203     assert_response 401
204   end
205
206   ['v2',
207    'v2/',
208    'v2//',
209    'v2///',
210    "v2/'; delete from users where 1=1; commit; select '/lol",
211    'v2/foo/bar',
212    'v2/zzzzz-gj3su-077z32aux8dg2s1',
213    'v2/zzzzz-gj3su-077z32aux8dg2s1/',
214    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
215    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi/zzzzz-gj3su-077z32aux8dg2s1',
216    'v2//3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
217    'v8/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
218    '/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
219    '"v2/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi"',
220    '/',
221    '//',
222    '///',
223   ].each do |token|
224     test "authenticate with malformed remote token #{token}" do
225       get '/arvados/v1/users/current',
226         params: {format: 'json'},
227         headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
228       assert_response 401
229     end
230   end
231
232   test "ignore extra fields in remote token" do
233     token = salted_active_token(remote: 'zbbbb') + '/foo/bar/baz/*'
234     get '/arvados/v1/users/current',
235       params: {format: 'json'},
236       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
237     assert_response :success
238   end
239
240   test 'remote api server is not an api server' do
241     @stub_status = 200
242     @stub_content = '<html>bad</html>'
243     get '/arvados/v1/users/current',
244       params: {format: 'json'},
245       headers: auth(remote: 'zbbbb')
246     assert_response 401
247   end
248
249   ['zbbbb', 'z0000'].each do |token_valid_for|
250     test "validate #{token_valid_for}-salted token for remote cluster zbbbb" do
251       salted_token = salt_token(fixture: :active, remote: token_valid_for)
252       get '/arvados/v1/users/current',
253         params: {format: 'json', remote: 'zbbbb'},
254         headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
255       if token_valid_for == 'zbbbb'
256         assert_response 200
257         assert_equal(users(:active).uuid, json_response['uuid'])
258       else
259         assert_response 401
260       end
261     end
262   end
263
264   test "list readable groups with salted token" do
265     salted_token = salt_token(fixture: :active, remote: 'zbbbb')
266     get '/arvados/v1/groups',
267       params: {
268         format: 'json',
269         remote: 'zbbbb',
270         limit: 10000,
271       },
272       headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
273     assert_response 200
274     group_uuids = json_response['items'].collect { |i| i['uuid'] }
275     assert_includes(group_uuids, 'zzzzz-j7d0g-fffffffffffffff')
276     refute_includes(group_uuids, 'zzzzz-j7d0g-000000000000000')
277     assert_includes(group_uuids, groups(:aproject).uuid)
278     refute_includes(group_uuids, groups(:trashed_project).uuid)
279     refute_includes(group_uuids, groups(:testusergroup_admins).uuid)
280   end
281
282   test 'do not auto-activate user from untrusted cluster' do
283     Rails.configuration.RemoteClusters['zbbbb'].AutoSetupNewUsers = false
284     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = false
285     get '/arvados/v1/users/current',
286       params: {format: 'json'},
287       headers: auth(remote: 'zbbbb')
288     assert_response :success
289     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
290     assert_equal false, json_response['is_admin']
291     assert_equal false, json_response['is_active']
292     assert_equal 'foo@example.com', json_response['email']
293     assert_equal 'barney', json_response['username']
294     post '/arvados/v1/users/zbbbb-tpzed-000000000000000/activate',
295       params: {format: 'json'},
296       headers: auth(remote: 'zbbbb')
297     assert_response 422
298   end
299
300   test 'auto-activate user from trusted cluster' do
301     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
302     get '/arvados/v1/users/current',
303       params: {format: 'json'},
304       headers: auth(remote: 'zbbbb')
305     assert_response :success
306     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
307     assert_equal false, json_response['is_admin']
308     assert_equal true, json_response['is_active']
309     assert_equal 'foo@example.com', json_response['email']
310     assert_equal 'barney', json_response['username']
311   end
312
313   test 'get user from Login cluster' do
314     Rails.configuration.Login.LoginCluster = 'zbbbb'
315     get '/arvados/v1/users/current',
316       params: {format: 'json'},
317       headers: auth(remote: 'zbbbb')
318     assert_response :success
319     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
320     assert_equal true, json_response['is_admin']
321     assert_equal true, json_response['is_active']
322     assert_equal 'foo@example.com', json_response['email']
323     assert_equal 'barney', json_response['username']
324   end
325
326   test 'pre-activate remote user' do
327     @stub_content = {
328       uuid: 'zbbbb-tpzed-000000000001234',
329       email: 'foo@example.com',
330       username: 'barney',
331       is_admin: true,
332       is_active: true,
333     }
334
335     post '/arvados/v1/users',
336       params: {
337         "user" => {
338           "uuid" => "zbbbb-tpzed-000000000001234",
339           "email" => 'foo@example.com',
340           "username" => 'barney',
341           "is_active" => true,
342           "is_admin" => false
343         }
344       },
345       headers: {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
346     assert_response :success
347
348     get '/arvados/v1/users/current',
349       params: {format: 'json'},
350       headers: auth(remote: 'zbbbb')
351     assert_response :success
352     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
353     assert_equal false, json_response['is_admin']
354     assert_equal true, json_response['is_active']
355     assert_equal 'foo@example.com', json_response['email']
356     assert_equal 'barney', json_response['username']
357   end
358
359
360   test 'remote user inactive without pre-activation' do
361     @stub_content = {
362       uuid: 'zbbbb-tpzed-000000000001234',
363       email: 'foo@example.com',
364       username: 'barney',
365       is_admin: true,
366       is_active: true,
367     }
368
369     get '/arvados/v1/users/current',
370       params: {format: 'json'},
371       headers: auth(remote: 'zbbbb')
372     assert_response :success
373     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
374     assert_equal false, json_response['is_admin']
375     assert_equal false, json_response['is_active']
376     assert_equal 'foo@example.com', json_response['email']
377     assert_equal 'barney', json_response['username']
378   end
379
380   test "validate unsalted v2 token for remote cluster zbbbb" do
381     auth = api_client_authorizations(:active)
382     token = "v2/#{auth.uuid}/#{auth.api_token}"
383     get '/arvados/v1/users/current',
384       params: {format: 'json', remote: 'zbbbb'},
385       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
386     assert_response :success
387     assert_equal(users(:active).uuid, json_response['uuid'])
388   end
389
390   test 'container request with runtime_token' do
391     [["valid local", "v2/#{api_client_authorizations(:active).uuid}/#{api_client_authorizations(:active).api_token}"],
392      ["valid remote", "v2/zbbbb-gj3su-000000000000000/abc"],
393      ["invalid local", "v2/#{api_client_authorizations(:active).uuid}/fakefakefake"],
394      ["invalid remote", "v2/zbork-gj3su-000000000000000/abc"],
395     ].each do |label, runtime_token|
396       post '/arvados/v1/container_requests',
397         params: {
398           "container_request" => {
399             "command" => ["echo"],
400             "container_image" => "xyz",
401             "output_path" => "/",
402             "cwd" => "/",
403             "runtime_token" => runtime_token
404           }
405         },
406         headers: {"HTTP_AUTHORIZATION" => "Bearer #{api_client_authorizations(:active).api_token}"}
407       if label.include? "invalid"
408         assert_response 422
409       else
410         assert_response :success
411       end
412     end
413   end
414
415 end