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