16989: Test all combinations of remote user status
[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-000000000000001',
83       email: 'foo@example.com',
84       username: 'barney',
85       is_admin: true,
86       is_active: true,
87       is_invited: true,
88     }
89   end
90
91   teardown do
92     @remote_server.each do |srv|
93       srv.stop
94     end
95   end
96
97   test 'authenticate with remote token' do
98     get '/arvados/v1/users/current',
99       params: {format: 'json'},
100       headers: auth(remote: 'zbbbb')
101     assert_response :success
102     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
103     assert_equal false, json_response['is_admin']
104     assert_equal false, json_response['is_active']
105     assert_equal 'foo@example.com', json_response['email']
106     assert_equal 'barney', json_response['username']
107
108     # revoke original token
109     @stub_status = 401
110
111     # re-authorize before cache expires
112     get '/arvados/v1/users/current',
113       params: {format: 'json'},
114       headers: auth(remote: 'zbbbb')
115     assert_response :success
116
117     # simulate cache expiry
118     ApiClientAuthorization.where(
119       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
120       update_all(expires_at: db_current_time - 1.minute)
121
122     # re-authorize after cache expires
123     get '/arvados/v1/users/current',
124       params: {format: 'json'},
125       headers: auth(remote: 'zbbbb')
126     assert_response 401
127
128     # simulate cached token indicating wrong user (e.g., local user
129     # entry was migrated out of the way taking the cached token with
130     # it, or authorizing cluster reassigned auth to a different user)
131     ApiClientAuthorization.where(
132       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
133       update_all(user_id: users(:active).id)
134
135     # revive original token and re-authorize
136     @stub_status = 200
137     @stub_content[:username] = 'blarney'
138     @stub_content[:email] = 'blarney@example.com'
139     get '/arvados/v1/users/current',
140       params: {format: 'json'},
141       headers: auth(remote: 'zbbbb')
142     assert_response :success
143     assert_equal 'barney', json_response['username'], 'local username should not change once assigned'
144     assert_equal 'blarney@example.com', json_response['email']
145   end
146
147   test 'remote user is deactivated' do
148     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
149     get '/arvados/v1/users/current',
150       params: {format: 'json'},
151       headers: auth(remote: 'zbbbb')
152     assert_response :success
153     assert_equal true, json_response['is_active']
154
155     # revoke original token
156     @stub_content[:is_active] = false
157     @stub_content[:is_invited] = false
158
159     # simulate cache expiry
160     ApiClientAuthorization.where(
161       uuid: salted_active_token(remote: 'zbbbb').split('/')[1]).
162       update_all(expires_at: db_current_time - 1.minute)
163
164     # re-authorize after cache expires
165     get '/arvados/v1/users/current',
166       params: {format: 'json'},
167       headers: auth(remote: 'zbbbb')
168     assert_equal false, json_response['is_active']
169
170   end
171
172   test 'authenticate with remote token, remote username conflicts with local' do
173     @stub_content[:username] = 'active'
174     get '/arvados/v1/users/current',
175       params: {format: 'json'},
176       headers: auth(remote: 'zbbbb')
177     assert_response :success
178     assert_equal 'active2', json_response['username']
179   end
180
181   test 'authenticate with remote token, remote username is nil' do
182     @stub_content.delete :username
183     get '/arvados/v1/users/current',
184       params: {format: 'json'},
185       headers: auth(remote: 'zbbbb')
186     assert_response :success
187     assert_equal 'foo', json_response['username']
188   end
189
190   test 'authenticate with remote token from misbehaving remote cluster' do
191     get '/arvados/v1/users/current',
192       params: {format: 'json'},
193       headers: auth(remote: 'zbork')
194     assert_response 401
195   end
196
197   test 'authenticate with remote token that fails validate' do
198     @stub_status = 401
199     @stub_content = {
200       error: 'not authorized',
201     }
202     get '/arvados/v1/users/current',
203       params: {format: 'json'},
204       headers: auth(remote: 'zbbbb')
205     assert_response 401
206   end
207
208   ['v2',
209    'v2/',
210    'v2//',
211    'v2///',
212    "v2/'; delete from users where 1=1; commit; select '/lol",
213    'v2/foo/bar',
214    'v2/zzzzz-gj3su-077z32aux8dg2s1',
215    'v2/zzzzz-gj3su-077z32aux8dg2s1/',
216    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
217    'v2/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi/zzzzz-gj3su-077z32aux8dg2s1',
218    'v2//3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
219    'v8/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
220    '/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi',
221    '"v2/zzzzz-gj3su-077z32aux8dg2s1/3kg6k6lzmp9kj5cpkcoxie963cmvjahbt2fod9zru30k1jqdmi"',
222    '/',
223    '//',
224    '///',
225   ].each do |token|
226     test "authenticate with malformed remote token #{token}" do
227       get '/arvados/v1/users/current',
228         params: {format: 'json'},
229         headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
230       assert_response 401
231     end
232   end
233
234   test "ignore extra fields in remote token" do
235     token = salted_active_token(remote: 'zbbbb') + '/foo/bar/baz/*'
236     get '/arvados/v1/users/current',
237       params: {format: 'json'},
238       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
239     assert_response :success
240   end
241
242   test 'remote api server is not an api server' do
243     @stub_status = 200
244     @stub_content = '<html>bad</html>'
245     get '/arvados/v1/users/current',
246       params: {format: 'json'},
247       headers: auth(remote: 'zbbbb')
248     assert_response 401
249   end
250
251   ['zbbbb', 'z0000'].each do |token_valid_for|
252     test "validate #{token_valid_for}-salted token for remote cluster zbbbb" do
253       salted_token = salt_token(fixture: :active, remote: token_valid_for)
254       get '/arvados/v1/users/current',
255         params: {format: 'json', remote: 'zbbbb'},
256         headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
257       if token_valid_for == 'zbbbb'
258         assert_response 200
259         assert_equal(users(:active).uuid, json_response['uuid'])
260       else
261         assert_response 401
262       end
263     end
264   end
265
266   test "list readable groups with salted token" do
267     salted_token = salt_token(fixture: :active, remote: 'zbbbb')
268     get '/arvados/v1/groups',
269       params: {
270         format: 'json',
271         remote: 'zbbbb',
272         limit: 10000,
273       },
274       headers: {"HTTP_AUTHORIZATION" => "Bearer #{salted_token}"}
275     assert_response 200
276     group_uuids = json_response['items'].collect { |i| i['uuid'] }
277     assert_includes(group_uuids, 'zzzzz-j7d0g-fffffffffffffff')
278     refute_includes(group_uuids, 'zzzzz-j7d0g-000000000000000')
279     assert_includes(group_uuids, groups(:aproject).uuid)
280     refute_includes(group_uuids, groups(:trashed_project).uuid)
281     refute_includes(group_uuids, groups(:testusergroup_admins).uuid)
282   end
283
284   test 'do not auto-activate user from untrusted cluster' do
285     Rails.configuration.RemoteClusters['zbbbb'].AutoSetupNewUsers = false
286     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = false
287     get '/arvados/v1/users/current',
288       params: {format: 'json'},
289       headers: auth(remote: 'zbbbb')
290     assert_response :success
291     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
292     assert_equal false, json_response['is_admin']
293     assert_equal false, json_response['is_active']
294     assert_equal 'foo@example.com', json_response['email']
295     assert_equal 'barney', json_response['username']
296     post '/arvados/v1/users/zbbbb-tpzed-000000000000001/activate',
297       params: {format: 'json'},
298       headers: auth(remote: 'zbbbb')
299     assert_response 422
300   end
301
302   test 'auto-activate user from trusted cluster' do
303     Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = true
304     get '/arvados/v1/users/current',
305       params: {format: 'json'},
306       headers: auth(remote: 'zbbbb')
307     assert_response :success
308     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
309     assert_equal false, json_response['is_admin']
310     assert_equal true, json_response['is_active']
311     assert_equal 'foo@example.com', json_response['email']
312     assert_equal 'barney', json_response['username']
313   end
314
315   test 'get user from Login cluster' do
316     Rails.configuration.Login.LoginCluster = 'zbbbb'
317     get '/arvados/v1/users/current',
318       params: {format: 'json'},
319       headers: auth(remote: 'zbbbb')
320     assert_response :success
321     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
322     assert_equal true, json_response['is_admin']
323     assert_equal true, json_response['is_active']
324     assert_equal 'foo@example.com', json_response['email']
325     assert_equal 'barney', json_response['username']
326   end
327
328   [true, false].each do |trusted|
329     [true, false].each do |logincluster|
330       [true, false].each do |admin|
331         [true, false].each do |active|
332           [true, false].each do |autosetup|
333             [true, false].each do |invited|
334               test "get invited=#{invited}, active=#{active}, admin=#{admin} user from #{if logincluster then "Login" else "peer" end} cluster when AutoSetupNewUsers=#{autosetup} ActivateUsers=#{trusted}" do
335                 Rails.configuration.Login.LoginCluster = 'zbbbb' if logincluster
336                 Rails.configuration.RemoteClusters['zbbbb'].ActivateUsers = trusted
337                 Rails.configuration.Users.AutoSetupNewUsers = autosetup
338                 @stub_content = {
339                   uuid: 'zbbbb-tpzed-000000000000001',
340                   email: 'foo@example.com',
341                   username: 'barney',
342                   is_admin: admin,
343                   is_active: active,
344                   is_invited: invited,
345                 }
346                 get '/arvados/v1/users/current',
347                     params: {format: 'json'},
348                     headers: auth(remote: 'zbbbb')
349                 assert_response :success
350                 assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
351                 assert_equal (logincluster && admin && invited && active), json_response['is_admin']
352                 assert_equal (invited and (logincluster || trusted || autosetup)), json_response['is_invited']
353                 assert_equal (invited and (logincluster || trusted) and active), json_response['is_active']
354                 assert_equal 'foo@example.com', json_response['email']
355                 assert_equal 'barney', json_response['username']
356               end
357             end
358           end
359         end
360       end
361     end
362   end
363
364   test 'get active user from Login cluster when AutoSetupNewUsers is set' do
365     Rails.configuration.Login.LoginCluster = 'zbbbb'
366     Rails.configuration.Users.AutoSetupNewUsers = true
367     @stub_content = {
368       uuid: 'zbbbb-tpzed-000000000000001',
369       email: 'foo@example.com',
370       username: 'barney',
371       is_admin: false,
372       is_active: true,
373       is_invited: true,
374     }
375     get '/arvados/v1/users/current',
376       params: {format: 'json'},
377       headers: auth(remote: 'zbbbb')
378     assert_response :success
379     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
380     assert_equal false, json_response['is_admin']
381     assert_equal true, json_response['is_active']
382     assert_equal true, json_response['is_invited']
383     assert_equal 'foo@example.com', json_response['email']
384     assert_equal 'barney', json_response['username']
385
386     @stub_content = {
387       uuid: 'zbbbb-tpzed-000000000000001',
388       email: 'foo@example.com',
389       username: 'barney',
390       is_admin: false,
391       is_active: false,
392       is_invited: false,
393     }
394
395     # Use cached value.  User will still be active because we haven't
396     # re-queried the upstream cluster.
397     get '/arvados/v1/users/current',
398       params: {format: 'json'},
399       headers: auth(remote: 'zbbbb')
400     assert_response :success
401     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
402     assert_equal false, json_response['is_admin']
403     assert_equal true, json_response['is_active']
404     assert_equal true, json_response['is_invited']
405     assert_equal 'foo@example.com', json_response['email']
406     assert_equal 'barney', json_response['username']
407
408     # Delete cached value.  User should be inactive now.
409     act_as_system_user do
410       ApiClientAuthorization.delete_all
411     end
412
413     get '/arvados/v1/users/current',
414       params: {format: 'json'},
415       headers: auth(remote: 'zbbbb')
416     assert_response :success
417     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
418     assert_equal false, json_response['is_admin']
419     assert_equal false, json_response['is_active']
420     assert_equal false, json_response['is_invited']
421     assert_equal 'foo@example.com', json_response['email']
422     assert_equal 'barney', json_response['username']
423
424   end
425
426   test 'pre-activate remote user' do
427     @stub_content = {
428       uuid: 'zbbbb-tpzed-000000000001234',
429       email: 'foo@example.com',
430       username: 'barney',
431       is_admin: true,
432       is_active: true,
433       is_invited: true,
434     }
435
436     post '/arvados/v1/users',
437       params: {
438         "user" => {
439           "uuid" => "zbbbb-tpzed-000000000001234",
440           "email" => 'foo@example.com',
441           "username" => 'barney',
442           "is_active" => true,
443           "is_admin" => false
444         }
445       },
446       headers: {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
447     assert_response :success
448
449     get '/arvados/v1/users/current',
450       params: {format: 'json'},
451       headers: auth(remote: 'zbbbb')
452     assert_response :success
453     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
454     assert_equal false, json_response['is_admin']
455     assert_equal true, json_response['is_active']
456     assert_equal 'foo@example.com', json_response['email']
457     assert_equal 'barney', json_response['username']
458   end
459
460
461   test 'remote user inactive without pre-activation' do
462     @stub_content = {
463       uuid: 'zbbbb-tpzed-000000000001234',
464       email: 'foo@example.com',
465       username: 'barney',
466       is_admin: true,
467       is_active: true,
468       is_invited: true,
469     }
470
471     get '/arvados/v1/users/current',
472       params: {format: 'json'},
473       headers: auth(remote: 'zbbbb')
474     assert_response :success
475     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
476     assert_equal false, json_response['is_admin']
477     assert_equal false, json_response['is_active']
478     assert_equal 'foo@example.com', json_response['email']
479     assert_equal 'barney', json_response['username']
480   end
481
482   test "validate unsalted v2 token for remote cluster zbbbb" do
483     auth = api_client_authorizations(:active)
484     token = "v2/#{auth.uuid}/#{auth.api_token}"
485     get '/arvados/v1/users/current',
486       params: {format: 'json', remote: 'zbbbb'},
487       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
488     assert_response :success
489     assert_equal(users(:active).uuid, json_response['uuid'])
490   end
491
492   test 'container request with runtime_token' do
493     [["valid local", "v2/#{api_client_authorizations(:active).uuid}/#{api_client_authorizations(:active).api_token}"],
494      ["valid remote", "v2/zbbbb-gj3su-000000000000000/abc"],
495      ["invalid local", "v2/#{api_client_authorizations(:active).uuid}/fakefakefake"],
496      ["invalid remote", "v2/zbork-gj3su-000000000000000/abc"],
497     ].each do |label, runtime_token|
498       post '/arvados/v1/container_requests',
499         params: {
500           "container_request" => {
501             "command" => ["echo"],
502             "container_image" => "xyz",
503             "output_path" => "/",
504             "cwd" => "/",
505             "runtime_token" => runtime_token
506           }
507         },
508         headers: {"HTTP_AUTHORIZATION" => "Bearer #{api_client_authorizations(:active).api_token}"}
509       if label.include? "invalid"
510         assert_response 422
511       else
512         assert_response :success
513       end
514     end
515   end
516
517   test 'authenticate with remote token, remote user is system user' do
518     @stub_content[:uuid] = 'zbbbb-tpzed-000000000000000'
519     get '/arvados/v1/users/current',
520       params: {format: 'json'},
521       headers: auth(remote: 'zbbbb')
522     assert_equal 'from cluster zbbbb', json_response['last_name']
523   end
524
525   test 'authenticate with remote token, remote user is anonymous user' do
526     @stub_content[:uuid] = 'zbbbb-tpzed-anonymouspublic'
527     get '/arvados/v1/users/current',
528       params: {format: 'json'},
529       headers: auth(remote: 'zbbbb')
530     assert_response :success
531     assert_equal 'zzzzz-tpzed-anonymouspublic', json_response['uuid']
532   end
533
534
535 end