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