Merge branch 'master' into 15803-unsetup
[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 'auto-activate user from trusted cluster' do
283     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
284     get '/arvados/v1/users/current',
285       params: {format: 'json'},
286       headers: auth(remote: 'zbbbb')
287     assert_response :success
288     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
289     assert_equal false, json_response['is_admin']
290     assert_equal true, json_response['is_active']
291     assert_equal 'foo@example.com', json_response['email']
292     assert_equal 'barney', json_response['username']
293   end
294
295   test 'get user from Login cluster' do
296     Rails.configuration.Login.LoginCluster = 'zbbbb'
297     get '/arvados/v1/users/current',
298       params: {format: 'json'},
299       headers: auth(remote: 'zbbbb')
300     assert_response :success
301     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
302     assert_equal true, json_response['is_admin']
303     assert_equal true, json_response['is_active']
304     assert_equal 'foo@example.com', json_response['email']
305     assert_equal 'barney', json_response['username']
306   end
307
308   test 'pre-activate remote user' do
309     @stub_content = {
310       uuid: 'zbbbb-tpzed-000000000001234',
311       email: 'foo@example.com',
312       username: 'barney',
313       is_admin: true,
314       is_active: true,
315     }
316
317     post '/arvados/v1/users',
318       params: {
319         "user" => {
320           "uuid" => "zbbbb-tpzed-000000000001234",
321           "email" => 'foo@example.com',
322           "username" => 'barney',
323           "is_active" => true,
324           "is_admin" => false
325         }
326       },
327       headers: {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
328     assert_response :success
329
330     get '/arvados/v1/users/current',
331       params: {format: 'json'},
332       headers: auth(remote: 'zbbbb')
333     assert_response :success
334     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
335     assert_equal false, json_response['is_admin']
336     assert_equal true, json_response['is_active']
337     assert_equal 'foo@example.com', json_response['email']
338     assert_equal 'barney', json_response['username']
339   end
340
341
342   test 'remote user inactive without pre-activation' do
343     @stub_content = {
344       uuid: 'zbbbb-tpzed-000000000001234',
345       email: 'foo@example.com',
346       username: 'barney',
347       is_admin: true,
348       is_active: true,
349     }
350
351     get '/arvados/v1/users/current',
352       params: {format: 'json'},
353       headers: auth(remote: 'zbbbb')
354     assert_response :success
355     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
356     assert_equal false, json_response['is_admin']
357     assert_equal false, json_response['is_active']
358     assert_equal 'foo@example.com', json_response['email']
359     assert_equal 'barney', json_response['username']
360   end
361
362   test "validate unsalted v2 token for remote cluster zbbbb" do
363     auth = api_client_authorizations(:active)
364     token = "v2/#{auth.uuid}/#{auth.api_token}"
365     get '/arvados/v1/users/current',
366       params: {format: 'json', remote: 'zbbbb'},
367       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
368     assert_response :success
369     assert_equal(users(:active).uuid, json_response['uuid'])
370   end
371
372   test 'container request with runtime_token' do
373     [["valid local", "v2/#{api_client_authorizations(:active).uuid}/#{api_client_authorizations(:active).api_token}"],
374      ["valid remote", "v2/zbbbb-gj3su-000000000000000/abc"],
375      ["invalid local", "v2/#{api_client_authorizations(:active).uuid}/fakefakefake"],
376      ["invalid remote", "v2/zbork-gj3su-000000000000000/abc"],
377     ].each do |label, runtime_token|
378       post '/arvados/v1/container_requests',
379         params: {
380           "container_request" => {
381             "command" => ["echo"],
382             "container_image" => "xyz",
383             "output_path" => "/",
384             "cwd" => "/",
385             "runtime_token" => runtime_token
386           }
387         },
388         headers: {"HTTP_AUTHORIZATION" => "Bearer #{api_client_authorizations(:active).api_token}"}
389       if label.include? "invalid"
390         assert_response 422
391       else
392         assert_response :success
393       end
394     end
395   end
396
397 end