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 before_validation :clamp_token_expiration
18 api_accessible :user, extend: :common do |t|
22 # NB the "api_token" db column is a misnomer in that it's only the
23 # "secret" part of a token: a v1 token is just the secret, but a
24 # v2 token is "v2/uuid/secret".
26 t.add :created_by_ip_address
27 t.add :default_owner_uuid
30 t.add :last_used_by_ip_address
34 UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
36 def assign_random_api_token
37 self.api_token ||= rand(2**256).to_s(36)
44 self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
46 def owner_uuid_changed?
50 def modified_by_client_uuid
53 def modified_by_client_uuid=(x) end
55 def modified_by_user_uuid
58 def modified_by_user_uuid=(x) end
63 def modified_at=(x) end
65 def scopes_allow?(req_s)
66 scopes.each do |scope|
67 return true if (scope == 'all') or (scope == req_s) or
68 ((scope.end_with? '/') and (req_s.start_with? scope))
73 def scopes_allow_request?(request)
74 method = request.request_method
76 (scopes_allow?(['HEAD', request.path].join(' ')) ||
77 scopes_allow?(['GET', request.path].join(' ')))
79 scopes_allow?([method, request.path].join(' '))
84 super.except 'api_token'
87 def self.default_orders
88 ["#{table_name}.id desc"]
91 def self.remote_host(uuid_prefix:)
92 (Rails.configuration.RemoteClusters[uuid_prefix].andand["Host"]) ||
93 (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
94 uuid_prefix+".arvadosapi.com")
97 def self.make_http_client(uuid_prefix:)
100 if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
101 Rails.configuration.RemoteClusters['*'].andand.Insecure)
102 clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
104 # Use system CA certificates
105 ["/etc/ssl/certs/ca-certificates.crt",
106 "/etc/pki/tls/certs/ca-bundle.crt"]
107 .select { |ca_path| File.readable?(ca_path) }
108 .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
113 def self.check_system_root_token token
114 if token == Rails.configuration.SystemRootToken
115 return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
116 uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
118 api_client: system_root_token_api_client)
124 def self.validate(token:, remote: nil)
125 return nil if token.nil? or token.empty?
126 remote ||= Rails.configuration.ClusterID
128 auth = self.check_system_root_token(token)
135 stored_secret = nil # ...if different from secret
140 _, token_uuid, secret, optional = token.split('/')
141 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
146 # if "optional" is a container uuid, check that it
147 # matches expections.
148 c = Container.where(uuid: optional).first
150 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
151 # token doesn't match the container's token
154 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
155 # token doesn't match the container's token
158 if ![Container::Locked, Container::Running].include?(c.state)
159 # container isn't locked or running, token shouldn't be used
165 # fast path: look up the token in the local database
166 auth = ApiClientAuthorization.
167 includes(:user, :api_client).
168 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
170 if auth && auth.user &&
171 (secret == auth.api_token ||
172 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
174 if token_uuid[0..4] != Rails.configuration.ClusterID
175 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
180 upstream_cluster_id = token_uuid[0..4]
181 if upstream_cluster_id == Rails.configuration.ClusterID
182 # Token is supposedly issued by local cluster, but if the
183 # token were valid, we would have been found in the database
184 # in the above query.
186 elsif upstream_cluster_id.length != 5
192 # token is not a 'v2' token. It could be just the secret part
193 # ("v1 token") -- or it could be an OpenIDConnect access token,
194 # in which case either (a) the controller will have inserted a
195 # row with api_token = hmac(systemroottoken,oidctoken) before
196 # forwarding it, or (b) we'll have done that ourselves, or (c)
197 # we'll need to ask LoginCluster to validate it for us below,
198 # and then insert a local row for a faster lookup next time.
199 hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
200 auth = ApiClientAuthorization.
201 includes(:user, :api_client).
202 where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
206 elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
207 # An unrecognized non-v2 token might be an OIDC Access Token
208 # that can be verified by our login cluster in the code
209 # below. If so, we'll stuff the database with hmac instead of
210 # the real OIDC token.
211 upstream_cluster_id = Rails.configuration.Login.LoginCluster
218 # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
220 # In other words the remaining code in this method decides
221 # whether to accept a token that was issued by a remote cluster
222 # when the token is absent or expired in our database. To
223 # begin, we need to ask the cluster that issued the token to
225 clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
227 host = remote_host(uuid_prefix: upstream_cluster_id)
229 Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
234 remote_user = SafeJSON.load(
235 clnt.get_content('https://' + host + '/arvados/v1/users/current',
236 {'remote' => Rails.configuration.ClusterID},
237 {'Authorization' => 'Bearer ' + token}))
239 Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
243 # Check the response is well formed.
244 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
245 Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
249 remote_user_prefix = remote_user['uuid'][0..4]
252 # Use the same UUID as the remote when caching the token.
254 remote_token = SafeJSON.load(
255 clnt.get_content('https://' + host + '/arvados/v1/api_client_authorizations/current',
256 {'remote' => Rails.configuration.ClusterID},
257 {'Authorization' => 'Bearer ' + token}))
258 token_uuid = remote_token['uuid']
259 if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
260 raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
263 Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
268 # Clusters can only authenticate for their own users.
269 if remote_user_prefix != upstream_cluster_id
270 Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
274 # Invariant: remote_user_prefix == upstream_cluster_id
275 # therefore: remote_user_prefix != Rails.configuration.ClusterID
277 # Add or update user and token in local database so we can
278 # validate subsequent requests faster.
280 if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
281 # Special case: map the remote anonymous user to local anonymous user
282 remote_user['uuid'] = anonymous_user_uuid
285 user = User.find_by_uuid(remote_user['uuid'])
288 # Create a new record for this user.
289 user = User.new(uuid: remote_user['uuid'],
292 email: remote_user['email'],
293 owner_uuid: system_user_uuid)
294 user.set_initial_username(requested: remote_user['username'])
298 act_as_system_user do
299 %w[first_name last_name email prefs].each do |attr|
300 user.send(attr+'=', remote_user[attr])
303 if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
304 user.first_name = "root"
305 user.last_name = "from cluster #{remote_user_prefix}"
310 if user.is_invited && !remote_user['is_invited']
311 # Remote user is not "invited" state, they should be unsetup, which
312 # also makes them inactive.
315 if !user.is_invited && remote_user['is_invited'] and
316 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
317 Rails.configuration.Users.AutoSetupNewUsers or
318 Rails.configuration.Users.NewUsersAreActive or
319 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
323 if !user.is_active && remote_user['is_active'] && user.is_invited and
324 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
325 Rails.configuration.Users.NewUsersAreActive or
326 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
327 user.update_attributes!(is_active: true)
328 elsif user.is_active && !remote_user['is_active']
329 user.update_attributes!(is_active: false)
332 if remote_user_prefix == Rails.configuration.Login.LoginCluster and
334 user.is_admin != remote_user['is_admin']
335 # Remote cluster controls our user database, including the
337 user.update_attributes!(is_admin: remote_user['is_admin'])
341 # We will accept this token (and avoid reloading the user
342 # record) for 'RemoteTokenRefresh' (default 5 minutes).
344 # Request the actual api_client_auth record from the remote
345 # server in case it wants the token to expire sooner.
346 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
348 auth.api_client_id = 0
350 # If stored_secret is set, we save stored_secret in the database
351 # but return the real secret to the caller. This way, if we end
352 # up returning the auth record to the client, they see the same
353 # secret they supplied, instead of the HMAC we saved in the
355 stored_secret = stored_secret || secret
356 auth.update_attributes!(user: user,
357 api_token: stored_secret,
359 expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
360 Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} in local db"
361 auth.api_token = secret
377 'v2/' + uuid + '/' + api_token
380 def salted_token(remote:)
384 'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
389 def clamp_token_expiration
390 if !current_user.andand.is_admin && Rails.configuration.API.MaxTokenLifetime > 0
391 max_token_expiration = Time.now + Rails.configuration.API.MaxTokenLifetime
392 if self.new_record? && (self.expires_at.nil? || self.expires_at > max_token_expiration)
393 self.expires_at = max_token_expiration
394 elsif !self.new_record? && self.expires_at_changed? && (self.expires_at.nil? || self.expires_at > max_token_expiration)
395 self.expires_at = max_token_expiration
400 def permission_to_create
401 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
404 def permission_to_update
405 permission_to_create && !uuid_changed? &&
406 (current_user.andand.is_admin || !user_id_changed?)
410 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?