1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 class ApiClientAuthorization < ArvadosModel
8 include CommonApiTemplate
9 extend CurrentApiClient
11 belongs_to :api_client
13 after_initialize :assign_random_api_token
14 serialize :scopes, Array
16 api_accessible :user, extend: :common do |t|
20 # NB the "api_token" db column is a misnomer in that it's only the
21 # "secret" part of a token: a v1 token is just the secret, but a
22 # v2 token is "v2/uuid/secret".
24 t.add :created_by_ip_address
25 t.add :default_owner_uuid
28 t.add :last_used_by_ip_address
32 UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
34 def assign_random_api_token
35 self.api_token ||= rand(2**256).to_s(36)
42 self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
44 def owner_uuid_changed?
48 def modified_by_client_uuid
51 def modified_by_client_uuid=(x) end
53 def modified_by_user_uuid
56 def modified_by_user_uuid=(x) end
61 def modified_at=(x) end
63 def scopes_allow?(req_s)
64 scopes.each do |scope|
65 return true if (scope == 'all') or (scope == req_s) or
66 ((scope.end_with? '/') and (req_s.start_with? scope))
71 def scopes_allow_request?(request)
72 method = request.request_method
74 (scopes_allow?(['HEAD', request.path].join(' ')) ||
75 scopes_allow?(['GET', request.path].join(' ')))
77 scopes_allow?([method, request.path].join(' '))
82 super.except 'api_token'
85 def self.default_orders
86 ["#{table_name}.id desc"]
89 def self.remote_host(uuid_prefix:)
90 Rails.configuration.remote_hosts[uuid_prefix] ||
91 (Rails.configuration.remote_hosts_via_dns &&
92 uuid_prefix+".arvadosapi.com")
95 def self.validate(token:, remote:)
97 remote ||= Rails.configuration.uuid_prefix
101 _, uuid, secret = token.split('/')
102 auth = ApiClientAuthorization.
103 includes(:user, :api_client).
104 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', uuid).
106 if auth && auth.user &&
107 (secret == auth.api_token ||
108 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
112 uuid_prefix = uuid[0..4]
113 if uuid_prefix == Rails.configuration.uuid_prefix
114 # If the token were valid, we would have validated it above
116 elsif uuid_prefix.length != 5
121 host = remote_host(uuid_prefix: uuid_prefix)
123 Rails.logger.warn "remote authentication rejected: no host for #{uuid_prefix.inspect}"
127 # Token was issued by a different cluster. If it's expired or
128 # missing in our database, ask the originating cluster to
131 clnt = HTTPClient.new
132 remote_user = SafeJSON.load(
133 clnt.get_content('https://' + host + '/arvados/v1/users/current',
134 {'remote' => Rails.configuration.uuid_prefix},
135 {'Authorization' => 'Bearer ' + token}))
137 Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
140 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String) || remote_user['uuid'][0..4] != uuid[0..4]
141 Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
144 act_as_system_user do
145 # Add/update user and token in our database so we can
146 # validate subsequent requests faster.
148 user = User.find_or_create_by(uuid: remote_user['uuid']) do |user|
149 user.is_admin = false
153 [:first_name, :last_name, :email, :prefs].each do |attr|
154 updates[attr] = remote_user[attr.to_s]
157 if Rails.configuration.new_users_are_active
158 # Update is_active to whatever it is at the remote end
159 updates[:is_active] = remote_user['is_active']
160 elsif !updates[:is_active]
161 # Remote user is inactive; our mirror should be, too.
162 updates[:is_active] = false
165 user.update_attributes!(updates)
167 auth = ApiClientAuthorization.find_or_create_by(uuid: uuid) do |auth|
169 auth.api_token = secret
170 auth.api_client_id = 0
173 # Accept this token (and don't reload the user record) for
174 # 5 minutes. TODO: Request the actual api_client_auth
175 # record from the remote server in case it wants the token
177 auth.update_attributes!(expires_at: Time.now + 5.minutes)
181 auth = ApiClientAuthorization.
182 includes(:user, :api_client).
183 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token).
194 def permission_to_create
195 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
198 def permission_to_update
199 (permission_to_create and
200 not uuid_changed? and
201 not user_id_changed? and
202 not owner_uuid_changed?)
206 super unless (changed - UNLOGGED_CHANGES).empty?