16265: Merge branch 'dependabot/bundler/services/api/nokogiri-1.10.8' into 16265...
[arvados.git] / services / api / test / unit / api_client_authorization_test.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'test_helper'
6 require 'sweep_trashed_objects'
7
8 class ApiClientAuthorizationTest < ActiveSupport::TestCase
9   include CurrentApiClient
10
11   [:admin_trustedclient, :active_trustedclient].each do |token|
12     test "ApiClientAuthorization can be created then deleted by #{token}" do
13       set_user_from_auth token
14       x = ApiClientAuthorization.create!(user_id: current_user.id,
15                                          api_client_id: 0,
16                                          scopes: [])
17       newtoken = x.api_token
18       assert x.destroy, "Failed to destroy new ApiClientAuth"
19       assert_empty ApiClientAuthorization.where(api_token: newtoken), "Destroyed ApiClientAuth is still in database"
20     end
21   end
22
23   test "delete expired in SweepTrashedObjects" do
24     assert_not_empty ApiClientAuthorization.where(uuid: api_client_authorizations(:expired).uuid)
25     SweepTrashedObjects.sweep_now
26     assert_empty ApiClientAuthorization.where(uuid: api_client_authorizations(:expired).uuid)
27   end
28
29   test "accepts SystemRootToken" do
30     assert_nil ApiClientAuthorization.validate(token: "xxxSystemRootTokenxxx")
31
32     # will create a new ApiClientAuthorization record
33     Rails.configuration.SystemRootToken = "xxxSystemRootTokenxxx"
34
35     auth = ApiClientAuthorization.validate(token: "xxxSystemRootTokenxxx")
36     assert_equal "xxxSystemRootTokenxxx", auth.api_token
37     assert_equal User.find_by_uuid(system_user_uuid).id, auth.user_id
38     assert auth.api_client.is_trusted
39
40     # now change the token and try to use the old one first
41     Rails.configuration.SystemRootToken = "newxxxSystemRootTokenxxx"
42
43     # old token will fail
44     assert_nil ApiClientAuthorization.validate(token: "xxxSystemRootTokenxxx")
45     # new token will work
46     auth = ApiClientAuthorization.validate(token: "newxxxSystemRootTokenxxx")
47     assert_equal "newxxxSystemRootTokenxxx", auth.api_token
48     assert_equal User.find_by_uuid(system_user_uuid).id, auth.user_id
49
50     # now change the token again and use the new one first
51     Rails.configuration.SystemRootToken = "new2xxxSystemRootTokenxxx"
52
53     # new token will work
54     auth = ApiClientAuthorization.validate(token: "new2xxxSystemRootTokenxxx")
55     assert_equal "new2xxxSystemRootTokenxxx", auth.api_token
56     assert_equal User.find_by_uuid(system_user_uuid).id, auth.user_id
57     # old token will fail
58     assert_nil ApiClientAuthorization.validate(token: "newxxxSystemRootTokenxxx")
59   end
60
61
62 end