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