UserGet() passes "select" option along to batch update refs #16914
[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   test 'get inactive user from Login cluster when AutoSetupNewUsers is set' do
329     Rails.configuration.Login.LoginCluster = 'zbbbb'
330     Rails.configuration.Users.AutoSetupNewUsers = true
331     @stub_content = {
332       uuid: 'zbbbb-tpzed-000000000000001',
333       email: 'foo@example.com',
334       username: 'barney',
335       is_admin: false,
336       is_active: false,
337       is_invited: false,
338     }
339     get '/arvados/v1/users/current',
340       params: {format: 'json'},
341       headers: auth(remote: 'zbbbb')
342     assert_response :success
343     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
344     assert_equal false, json_response['is_admin']
345     assert_equal false, json_response['is_active']
346     assert_equal false, json_response['is_invited']
347     assert_equal 'foo@example.com', json_response['email']
348     assert_equal 'barney', json_response['username']
349   end
350
351     test 'get active user from Login cluster when AutoSetupNewUsers is set' do
352     Rails.configuration.Login.LoginCluster = 'zbbbb'
353     Rails.configuration.Users.AutoSetupNewUsers = true
354     @stub_content = {
355       uuid: 'zbbbb-tpzed-000000000000001',
356       email: 'foo@example.com',
357       username: 'barney',
358       is_admin: false,
359       is_active: true,
360       is_invited: true,
361     }
362     get '/arvados/v1/users/current',
363       params: {format: 'json'},
364       headers: auth(remote: 'zbbbb')
365     assert_response :success
366     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
367     assert_equal false, json_response['is_admin']
368     assert_equal true, json_response['is_active']
369     assert_equal true, json_response['is_invited']
370     assert_equal 'foo@example.com', json_response['email']
371     assert_equal 'barney', json_response['username']
372
373     @stub_content = {
374       uuid: 'zbbbb-tpzed-000000000000001',
375       email: 'foo@example.com',
376       username: 'barney',
377       is_admin: false,
378       is_active: false,
379       is_invited: false,
380     }
381
382     # Use cached value.  User will still be active because we haven't
383     # re-queried the upstream cluster.
384     get '/arvados/v1/users/current',
385       params: {format: 'json'},
386       headers: auth(remote: 'zbbbb')
387     assert_response :success
388     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
389     assert_equal false, json_response['is_admin']
390     assert_equal true, json_response['is_active']
391     assert_equal true, json_response['is_invited']
392     assert_equal 'foo@example.com', json_response['email']
393     assert_equal 'barney', json_response['username']
394
395     # Delete cached value.  User should be inactive now.
396     act_as_system_user do
397       ApiClientAuthorization.delete_all
398     end
399
400     get '/arvados/v1/users/current',
401       params: {format: 'json'},
402       headers: auth(remote: 'zbbbb')
403     assert_response :success
404     assert_equal 'zbbbb-tpzed-000000000000001', json_response['uuid']
405     assert_equal false, json_response['is_admin']
406     assert_equal false, json_response['is_active']
407     assert_equal false, json_response['is_invited']
408     assert_equal 'foo@example.com', json_response['email']
409     assert_equal 'barney', json_response['username']
410
411   end
412
413   test 'pre-activate remote user' do
414     @stub_content = {
415       uuid: 'zbbbb-tpzed-000000000001234',
416       email: 'foo@example.com',
417       username: 'barney',
418       is_admin: true,
419       is_active: true,
420       is_invited: true,
421     }
422
423     post '/arvados/v1/users',
424       params: {
425         "user" => {
426           "uuid" => "zbbbb-tpzed-000000000001234",
427           "email" => 'foo@example.com',
428           "username" => 'barney',
429           "is_active" => true,
430           "is_admin" => false
431         }
432       },
433       headers: {'HTTP_AUTHORIZATION' => "OAuth2 #{api_token(:admin)}"}
434     assert_response :success
435
436     get '/arvados/v1/users/current',
437       params: {format: 'json'},
438       headers: auth(remote: 'zbbbb')
439     assert_response :success
440     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
441     assert_equal false, json_response['is_admin']
442     assert_equal true, json_response['is_active']
443     assert_equal 'foo@example.com', json_response['email']
444     assert_equal 'barney', json_response['username']
445   end
446
447
448   test 'remote user inactive without pre-activation' do
449     @stub_content = {
450       uuid: 'zbbbb-tpzed-000000000001234',
451       email: 'foo@example.com',
452       username: 'barney',
453       is_admin: true,
454       is_active: true,
455       is_invited: true,
456     }
457
458     get '/arvados/v1/users/current',
459       params: {format: 'json'},
460       headers: auth(remote: 'zbbbb')
461     assert_response :success
462     assert_equal 'zbbbb-tpzed-000000000001234', json_response['uuid']
463     assert_equal false, json_response['is_admin']
464     assert_equal false, json_response['is_active']
465     assert_equal 'foo@example.com', json_response['email']
466     assert_equal 'barney', json_response['username']
467   end
468
469   test "validate unsalted v2 token for remote cluster zbbbb" do
470     auth = api_client_authorizations(:active)
471     token = "v2/#{auth.uuid}/#{auth.api_token}"
472     get '/arvados/v1/users/current',
473       params: {format: 'json', remote: 'zbbbb'},
474       headers: {"HTTP_AUTHORIZATION" => "Bearer #{token}"}
475     assert_response :success
476     assert_equal(users(:active).uuid, json_response['uuid'])
477   end
478
479   test 'container request with runtime_token' do
480     [["valid local", "v2/#{api_client_authorizations(:active).uuid}/#{api_client_authorizations(:active).api_token}"],
481      ["valid remote", "v2/zbbbb-gj3su-000000000000000/abc"],
482      ["invalid local", "v2/#{api_client_authorizations(:active).uuid}/fakefakefake"],
483      ["invalid remote", "v2/zbork-gj3su-000000000000000/abc"],
484     ].each do |label, runtime_token|
485       post '/arvados/v1/container_requests',
486         params: {
487           "container_request" => {
488             "command" => ["echo"],
489             "container_image" => "xyz",
490             "output_path" => "/",
491             "cwd" => "/",
492             "runtime_token" => runtime_token
493           }
494         },
495         headers: {"HTTP_AUTHORIZATION" => "Bearer #{api_client_authorizations(:active).api_token}"}
496       if label.include? "invalid"
497         assert_response 422
498       else
499         assert_response :success
500       end
501     end
502   end
503
504   test 'authenticate with remote token, remote user is system user' do
505     @stub_content[:uuid] = 'zbbbb-tpzed-000000000000000'
506     get '/arvados/v1/users/current',
507       params: {format: 'json'},
508       headers: auth(remote: 'zbbbb')
509     assert_equal 'from cluster zbbbb', json_response['last_name']
510   end
511
512   test 'authenticate with remote token, remote user is anonymous user' do
513     @stub_content[:uuid] = 'zbbbb-tpzed-anonymouspublic'
514     get '/arvados/v1/users/current',
515       params: {format: 'json'},
516       headers: auth(remote: 'zbbbb')
517     assert_response :success
518     assert_equal 'zzzzz-tpzed-anonymouspublic', json_response['uuid']
519   end
520
521
522 end