15529: Support for LoginCluster and RemoteTokenRefresh
[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       srv.mount_proc '/arvados/v1/users/register' do |req, res|
71         res.status = @stub_status
72         res.body = @stub_content.is_a?(String) ? @stub_content : @stub_content.to_json
73       end
74       Thread.new do
75         srv.start
76       end
77       ready.pop
78       @remote_server << srv
79       @remote_host << "127.0.0.1:#{srv.config[:Port]}"
80     end
81     Rails.configuration.RemoteClusters = Rails.configuration.RemoteClusters.merge({zbbbb: ActiveSupport::InheritableOptions.new({Host: @remote_host[0]}),
82                                                                                    zbork: ActiveSupport::InheritableOptions.new({Host: @remote_host[1]})})
83     Arvados::V1::SchemaController.any_instance.stubs(:root_url).returns "https://#{@remote_host[0]}"
84     @stub_status = 200
85     @stub_content = {
86       uuid: 'zbbbb-tpzed-000000000000000',
87       email: 'foo@example.com',
88       username: 'barney',
89       is_admin: true,
90       is_active: true,
91     }
92   end
93
94   teardown do
95     @remote_server.each do |srv|
96       srv.stop
97     end
98   end
99
100   test 'authenticate with remote token' do
101     get '/arvados/v1/users/current',
102       params: {format: 'json'},
103       headers: auth(remote: 'zbbbb')
104     assert_response :success
105     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
106     assert_equal false, json_response['is_admin']
107     assert_equal false, json_response['is_active']
108     assert_equal 'foo@example.com', json_response['email']
109     assert_equal 'barney', json_response['username']
110
111     # revoke original token
112     @stub_status = 401
113
114     # re-authorize before cache expires
115     get '/arvados/v1/users/current',
116       params: {format: 'json'},
117       headers: auth(remote: 'zbbbb')
118     assert_response :success
119
120     # simulate cache expiry
121     ApiClientAuthorization.where(
122       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
123       update_all(expires_at: db_current_time - 1.minute)
124
125     # re-authorize after cache expires
126     get '/arvados/v1/users/current',
127       params: {format: 'json'},
128       headers: auth(remote: 'zbbbb')
129     assert_response 401
130
131     # simulate cached token indicating wrong user (e.g., local user
132     # entry was migrated out of the way taking the cached token with
133     # it, or authorizing cluster reassigned auth to a different user)
134     ApiClientAuthorization.where(
135       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
136       update_all(user_id: users(:active).id)
137
138     # revive original token and re-authorize
139     @stub_status = 200
140     @stub_content[:username] = 'blarney'
141     @stub_content[:email] = 'blarney@example.com'
142     get '/arvados/v1/users/current',
143       params: {format: 'json'},
144       headers: auth(remote: 'zbbbb')
145     assert_response :success
146     assert_equal 'barney', json_response['username'], 'local username should not change once assigned'
147     assert_equal 'blarney@example.com', json_response['email']
148   end
149
150   test 'authenticate with remote token, remote username conflicts with local' do
151     @stub_content[:username] = 'active'
152     get '/arvados/v1/users/current',
153       params: {format: 'json'},
154       headers: auth(remote: 'zbbbb')
155     assert_response :success
156     assert_equal 'active2', json_response['username']
157   end
158
159   test 'authenticate with remote token, remote username is nil' do
160     @stub_content.delete :username
161     get '/arvados/v1/users/current',
162       params: {format: 'json'},
163       headers: auth(remote: 'zbbbb')
164     assert_response :success
165     assert_equal 'foo', json_response['username']
166   end
167
168   test 'authenticate with remote token from misbehaving remote cluster' do
169     get '/arvados/v1/users/current',
170       params: {format: 'json'},
171       headers: auth(remote: 'zbork')
172     assert_response 401
173   end
174
175   test 'authenticate with remote token that fails validate' do
176     @stub_status = 401
177     @stub_content = {
178       error: 'not authorized',
179     }
180     get '/arvados/v1/users/current',
181       params: {format: 'json'},
182       headers: auth(remote: 'zbbbb')
183     assert_response 401
184   end
185
186   ['v2',
187    'v2/',
188    'v2//',
189    'v2///',
190    "v2/'; delete from users where 1=1; commit; select '/lol",
191    'v2/foo/bar',
192    'v2/zzzzz-gj3su-077z32aux8dg2s1',
193    'v2/zzzzz-gj3su-077z32aux8dg2s1/',
194    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
195    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi/zzzzz-gj3su-077z32aux8dg2s1',
196    'v2//3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
197    'v8/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
198    '/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
199    '"v2/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi"',
200    '/',
201    '//',
202    '///',
203   ].each do |token|
204     test "authenticate with malformed remote token #{token}" do
205       get '/arvados/v1/users/current',
206         params: {format: 'json'},
207         headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
208       assert_response 401
209     end
210   end
211
212   test "ignore extra fields in remote token" do
213     token = salted_active_token(remote: 'zbbbb') + '/foo/bar/baz/*'
214     get '/arvados/v1/users/current',
215       params: {format: 'json'},
216       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
217     assert_response :success
218   end
219
220   test 'remote api server is not an api server' do
221     @stub_status = 200
222     @stub_content = '<html>bad</html>'
223     get '/arvados/v1/users/current',
224       params: {format: 'json'},
225       headers: auth(remote: 'zbbbb')
226     assert_response 401
227   end
228
229   ['zbbbb', 'z0000'].each do |token_valid_for|
230     test "validate #{token_valid_for}-salted token for remote cluster zbbbb" do
231       salted_token = salt_token(fixture: :active, remote: token_valid_for)
232       get '/arvados/v1/users/current',
233         params: {format: 'json', remote: 'zbbbb'},
234         headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
235       if token_valid_for == 'zbbbb'
236         assert_response 200
237         assert_equal(users(:active).uuid, json_response['uuid'])
238       else
239         assert_response 401
240       end
241     end
242   end
243
244   test "list readable groups with salted token" do
245     salted_token = salt_token(fixture: :active, remote: 'zbbbb')
246     get '/arvados/v1/groups',
247       params: {
248         format: 'json',
249         remote: 'zbbbb',
250         limit: 10000,
251       },
252       headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
253     assert_response 200
254     group_uuids = json_response['items'].collect { |i| i['uuid'] }
255     assert_includes(group_uuids, 'zzzzz-j7d0g-fffffffffffffff')
256     refute_includes(group_uuids, 'zzzzz-j7d0g-000000000000000')
257     assert_includes(group_uuids, groups(:aproject).uuid)
258     refute_includes(group_uuids, groups(:trashed_project).uuid)
259     refute_includes(group_uuids, groups(:testusergroup_admins).uuid)
260   end
261
262   test 'auto-activate user from trusted cluster' do
263     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
264     get '/arvados/v1/users/current',
265       params: {format: 'json'},
266       headers: auth(remote: 'zbbbb')
267     assert_response :success
268     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
269     assert_equal false, json_response['is_admin']
270     assert_equal true, json_response['is_active']
271     assert_equal 'foo@example.com', json_response['email']
272     assert_equal 'barney', json_response['username']
273   end
274
275   test 'pre-activate remote user' do
276     post '/arvados/v1/users',
277       params: {
278         "user" => {
279           "uuid" => "zbbbb-tpzed-000000000000000",
280           "email" => 'foo@example.com',
281           "username" => 'barney',
282           "is_active" => true
283         }
284       },
285       headers: {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
286     assert_response :success
287
288     get '/arvados/v1/users/current',
289       params: {format: 'json'},
290       headers: auth(remote: 'zbbbb')
291     assert_response :success
292     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
293     assert_equal nil, json_response['is_admin']
294     assert_equal true, json_response['is_active']
295     assert_equal 'foo@example.com', json_response['email']
296     assert_equal 'barney', json_response['username']
297   end
298
299   test "validate unsalted v2 token for remote cluster zbbbb" do
300     auth = api_client_authorizations(:active)
301     token = "v2/#{auth.uuid}/#{auth.api_token}"
302     get '/arvados/v1/users/current',
303       params: {format: 'json', remote: 'zbbbb'},
304       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
305     assert_response :success
306     assert_equal(users(:active).uuid, json_response['uuid'])
307   end
308
309   test 'container request with runtime_token' do
310     [["valid local", "v2/#{api_client_authorizations(:active).uuid}/#{api_client_authorizations(:active).api_token}"],
311      ["valid remote", "v2/zbbbb-gj3su-000000000000000/abc"],
312      ["invalid local", "v2/#{api_client_authorizations(:active).uuid}/fakefakefake"],
313      ["invalid remote", "v2/zbork-gj3su-000000000000000/abc"],
314     ].each do |label, runtime_token|
315       post '/arvados/v1/container_requests',
316         params: {
317           "container_request" => {
318             "command" => ["echo"],
319             "container_image" => "xyz",
320             "output_path" => "/",
321             "cwd" => "/",
322             "runtime_token" => runtime_token
323           }
324         },
325         headers: {"HTTP_AUTHORIZATION" => "Bearer #{api_client_authorizations(:active).api_token}"}
326       if label.include? "invalid"
327         assert_response 422
328       else
329         assert_response :success
330       end
331     end
332   end
333
334 end