17074: Refactor and simplify favorites middleware.
[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
7 class ApiClientAuthorizationTest < ActiveSupport::TestCase
8   include CurrentApiClient
9
10   [:admin_trustedclient, :active_trustedclient].each do |token|
11     test "ApiClientAuthorization can be created then deleted by #{token}" do
12       set_user_from_auth token
13       x = ApiClientAuthorization.create!(user_id: current_user.id,
14                                          scopes: [])
15       newtoken = x.api_token
16       assert x.destroy, "Failed to destroy new ApiClientAuth"
17       assert_empty ApiClientAuthorization.where(api_token: newtoken), "Destroyed ApiClientAuth is still in database"
18     end
19   end
20
21   test "accepts SystemRootToken" do
22     assert_nil ApiClientAuthorization.validate(token: "xxxSystemRootTokenxxx")
23
24     # will create a new ApiClientAuthorization record
25     Rails.configuration.SystemRootToken = "xxxSystemRootTokenxxx"
26
27     auth = ApiClientAuthorization.validate(token: "xxxSystemRootTokenxxx")
28     assert_equal "xxxSystemRootTokenxxx", auth.api_token
29     assert_equal User.find_by_uuid(system_user_uuid).id, auth.user_id
30
31     # now change the token and try to use the old one first
32     Rails.configuration.SystemRootToken = "newxxxSystemRootTokenxxx"
33
34     # old token will fail
35     assert_nil ApiClientAuthorization.validate(token: "xxxSystemRootTokenxxx")
36     # new token will work
37     auth = ApiClientAuthorization.validate(token: "newxxxSystemRootTokenxxx")
38     assert_equal "newxxxSystemRootTokenxxx", auth.api_token
39     assert_equal User.find_by_uuid(system_user_uuid).id, auth.user_id
40
41     # now change the token again and use the new one first
42     Rails.configuration.SystemRootToken = "new2xxxSystemRootTokenxxx"
43
44     # new token will work
45     auth = ApiClientAuthorization.validate(token: "new2xxxSystemRootTokenxxx")
46     assert_equal "new2xxxSystemRootTokenxxx", auth.api_token
47     assert_equal User.find_by_uuid(system_user_uuid).id, auth.user_id
48     # old token will fail
49     assert_nil ApiClientAuthorization.validate(token: "newxxxSystemRootTokenxxx")
50   end
51
52
53 end