Merge branch 'master' into 13804-no-shutdown-wanted-nodes
[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.remote_hosts['zbbbb'] = @remote_host
67     Rails.configuration.remote_hosts['zbork'] = @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', {format: 'json'}, auth(remote: 'zbbbb')
85     assert_response :success
86     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
87     assert_equal false, json_response['is_admin']
88     assert_equal false, json_response['is_active']
89     assert_equal 'foo@example.com', json_response['email']
90     assert_equal 'barney', json_response['username']
91
92     # revoke original token
93     @stub_status = 401
94
95     # re-authorize before cache expires
96     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
97     assert_response :success
98
99     # simulate cache expiry
100     ApiClientAuthorization.where(
101       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
102       update_all(expires_at: db_current_time - 1.minute)
103
104     # re-authorize after cache expires
105     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
106     assert_response 401
107
108     # simulate cached token indicating wrong user (e.g., local user
109     # entry was migrated out of the way taking the cached token with
110     # it, or authorizing cluster reassigned auth to a different user)
111     ApiClientAuthorization.where(
112       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
113       update_all(user_id: users(:active).id)
114
115     # revive original token and re-authorize
116     @stub_status = 200
117     @stub_content[:username] = 'blarney'
118     @stub_content[:email] = 'blarney@example.com'
119     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
120     assert_response :success
121     assert_equal 'barney', json_response['username'], 'local username should not change once assigned'
122     assert_equal 'blarney@example.com', json_response['email']
123   end
124
125   test 'authenticate with remote token, remote username conflicts with local' do
126     @stub_content[:username] = 'active'
127     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
128     assert_response :success
129     assert_equal 'active2', json_response['username']
130   end
131
132   test 'authenticate with remote token, remote username is nil' do
133     @stub_content.delete :username
134     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
135     assert_response :success
136     assert_equal 'foo', json_response['username']
137   end
138
139   test 'authenticate with remote token from misbhehaving remote cluster' do
140     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbork')
141     assert_response 401
142   end
143
144   test 'authenticate with remote token that fails validate' do
145     @stub_status = 401
146     @stub_content = {
147       error: 'not authorized',
148     }
149     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
150     assert_response 401
151   end
152
153   ['v2',
154    'v2/',
155    'v2//',
156    'v2///',
157    "v2/'; delete from users where 1=1; commit; select '/lol",
158    'v2/foo/bar',
159    'v2/zzzzz-gj3su-077z32aux8dg2s1',
160    'v2/zzzzz-gj3su-077z32aux8dg2s1/',
161    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
162    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi/zzzzz-gj3su-077z32aux8dg2s1',
163    'v2//3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
164    'v8/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
165    '/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
166    '"v2/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi"',
167    '/',
168    '//',
169    '///',
170   ].each do |token|
171     test "authenticate with malformed remote token #{token}" do
172       get '/arvados/v1/users/current', {format: 'json'}, {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
173       assert_response 401
174     end
175   end
176
177   test "ignore extra fields in remote token" do
178     token = salted_active_token(remote: 'zbbbb') + '/foo/bar/baz/*'
179     get '/arvados/v1/users/current', {format: 'json'}, {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
180     assert_response :success
181   end
182
183   test 'remote api server is not an api server' do
184     @stub_status = 200
185     @stub_content = '<html>bad</html>'
186     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
187     assert_response 401
188   end
189
190   ['zbbbb', 'z0000'].each do |token_valid_for|
191     test "validate #{token_valid_for}-salted token for remote cluster zbbbb" do
192       salted_token = salt_token(fixture: :active, remote: token_valid_for)
193       get '/arvados/v1/users/current', {format: 'json', remote: 'zbbbb'}, {
194             "HTTP_AUTHORIZATION" => "Bearer #{salted_token}"
195           }
196       if token_valid_for == 'zbbbb'
197         assert_response 200
198         assert_equal(users(:active).uuid, json_response['uuid'])
199       else
200         assert_response 401
201       end
202     end
203   end
204
205   test "list readable groups with salted token" do
206     salted_token = salt_token(fixture: :active, remote: 'zbbbb')
207     get '/arvados/v1/groups', {
208           format: 'json',
209           remote: 'zbbbb',
210           limit: 10000,
211         }, {
212           "HTTP_AUTHORIZATION" => "Bearer #{salted_token}"
213         }
214     assert_response 200
215     group_uuids = json_response['items'].collect { |i| i['uuid'] }
216     assert_includes(group_uuids, 'zzzzz-j7d0g-fffffffffffffff')
217     refute_includes(group_uuids, 'zzzzz-j7d0g-000000000000000')
218     assert_includes(group_uuids, groups(:aproject).uuid)
219     refute_includes(group_uuids, groups(:trashed_project).uuid)
220     refute_includes(group_uuids, groups(:testusergroup_admins).uuid)
221   end
222
223   test 'auto-activate user from trusted cluster' do
224     Rails.configuration.auto_activate_users_from = ['zbbbb']
225     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
226     assert_response :success
227     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
228     assert_equal false, json_response['is_admin']
229     assert_equal true, json_response['is_active']
230     assert_equal 'foo@example.com', json_response['email']
231     assert_equal 'barney', json_response['username']
232   end
233
234   test 'pre-activate remote user' do
235     post '/arvados/v1/users', {
236            "user" => {
237              "uuid" => "zbbbb-tpzed-000000000000000",
238              "email" => 'foo@example.com',
239              "username" => 'barney',
240              "is_active" => true
241            }
242     }, {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
243     assert_response :success
244
245     get '/arvados/v1/users/current', {format: 'json'}, auth(remote: 'zbbbb')
246     assert_response :success
247     assert_equal 'zbbbb-tpzed-000000000000000', json_response['uuid']
248     assert_equal nil, json_response['is_admin']
249     assert_equal true, json_response['is_active']
250     assert_equal 'foo@example.com', json_response['email']
251     assert_equal 'barney', json_response['username']
252   end
253
254 end