1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 class ApiClientAuthorization < ArvadosModel
8 include CommonApiTemplate
9 include Rails.application.routes.url_helpers
10 extend CurrentApiClient
13 belongs_to :user, optional: true
14 after_initialize :assign_random_api_token
15 serialize :scopes, Array
17 before_validation :clamp_token_expiration
19 api_accessible :user, extend: :common do |t|
21 # NB the "api_token" db column is a misnomer in that it's only the
22 # "secret" part of a token: a v1 token is just the secret, but a
23 # v2 token is "v2/uuid/secret".
25 t.add :created_by_ip_address
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
36 self.api_token ||= rand(2**256).to_s(36)
37 rescue ActiveModel::MissingAttributeError
38 # Ignore the case where self.api_token doesn't exist, which happens when
39 # the select=[...] is used.
47 self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
49 def owner_uuid_changed?
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
73 if method == 'GET' and request.path == url_for(controller: 'arvados/v1/api_client_authorizations', action: 'current', only_path: true)
75 elsif method == 'HEAD'
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_anonymous_user_token(token:, remote:)
116 _, token_uuid, secret, optional = token.split('/')
117 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0 &&
118 token_uuid == Rails.configuration.ClusterID+"-gj3su-anonymouspublic"
119 # invalid v2 token, or v2 token for another user
127 # Usually, the secret is salted
128 salted_secret = OpenSSL::HMAC.hexdigest('sha1', Rails.configuration.Users.AnonymousUserToken, remote)
130 # The anonymous token could be specified as a full v2 token in the config,
131 # but the config loader strips it down to the secret part.
132 # The anonymous token content and minimum length is verified in lib/config
133 if secret.length >= 0 && (secret == Rails.configuration.Users.AnonymousUserToken || secret == salted_secret)
134 return ApiClientAuthorization.new(user: User.find_by_uuid(anonymous_user_uuid),
135 uuid: Rails.configuration.ClusterID+"-gj3su-anonymouspublic",
143 def self.check_system_root_token token
144 if token == Rails.configuration.SystemRootToken
145 return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
146 uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
153 def self.validate(token:, remote: nil)
154 return nil if token.nil? or token.empty?
155 remote ||= Rails.configuration.ClusterID
157 auth = self.check_anonymous_user_token(token: token, remote: remote)
162 auth = self.check_system_root_token(token)
169 stored_secret = nil # ...if different from secret
174 _, token_uuid, secret, optional = token.split('/')
175 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
180 # if "optional" is a container uuid, check that it
181 # matches expections.
182 c = Container.where(uuid: optional).first
184 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
185 # token doesn't match the container's token
188 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
189 # token doesn't match the container's token
192 if ![Container::Locked, Container::Running].include?(c.state)
193 # container isn't locked or running, token shouldn't be used
199 # fast path: look up the token in the local database
200 auth = ApiClientAuthorization.
202 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
204 if auth && auth.user &&
205 (secret == auth.api_token ||
206 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
208 if token_uuid[0..4] != Rails.configuration.ClusterID
209 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
214 upstream_cluster_id = token_uuid[0..4]
215 if upstream_cluster_id == Rails.configuration.ClusterID
216 # Token is supposedly issued by local cluster, but if the
217 # token were valid, we would have been found in the database
218 # in the above query.
220 elsif upstream_cluster_id.length != 5
226 # token is not a 'v2' token. It could be just the secret part
227 # ("v1 token") -- or it could be an OpenIDConnect access token,
228 # in which case either (a) the controller will have inserted a
229 # row with api_token = hmac(systemroottoken,oidctoken) before
230 # forwarding it, or (b) we'll have done that ourselves, or (c)
231 # we'll need to ask LoginCluster to validate it for us below,
232 # and then insert a local row for a faster lookup next time.
233 hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
234 auth = ApiClientAuthorization.
236 where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
240 elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
241 # An unrecognized non-v2 token might be an OIDC Access Token
242 # that can be verified by our login cluster in the code
243 # below. If so, we'll stuff the database with hmac instead of
244 # the real OIDC token.
245 upstream_cluster_id = Rails.configuration.Login.LoginCluster
252 # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
254 # In other words the remaining code in this method decides
255 # whether to accept a token that was issued by a remote cluster
256 # when the token is absent or expired in our database. To
257 # begin, we need to ask the cluster that issued the token to
259 clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
261 host = remote_host(uuid_prefix: upstream_cluster_id)
263 Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
266 remote_url = URI::parse("https://#{host}/")
267 remote_query = {"remote" => Rails.configuration.ClusterID}
268 remote_headers = {"Authorization" => "Bearer #{token}"}
270 # First get the current token. This query is not limited by token scopes,
271 # and tells us the user's UUID via owner_uuid, so this gives us enough
272 # information to load a local user record from the database if one exists.
275 remote_token = SafeJSON.load(
277 remote_url.merge("arvados/v1/api_client_authorizations/current"),
278 remote_query, remote_headers,
280 Rails.logger.debug "retrieved remote token #{remote_token.inspect}"
281 token_uuid = remote_token['uuid']
282 if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
283 raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
285 rescue HTTPClient::BadResponseError => e
286 if e.res.status_code >= 400 && e.res.status_code < 500
287 # Remote cluster does not accept this token.
290 # CurrentApiToken#call and ApplicationController#render_error will
291 # propagate the status code from the #http_status method, so define
297 # TODO #20927: Catch network exceptions and assign a 5xx status to them so
298 # the client knows they're a temporary problem.
300 Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
304 # Next, load the token's user record from the database (might be nil).
305 remote_user_prefix, remote_user_suffix = remote_token['owner_uuid'].split('-', 2)
306 if anonymous_user_uuid.end_with?(remote_user_suffix)
307 # Special case: map the remote anonymous user to local anonymous user
308 remote_user_uuid = anonymous_user_uuid
310 remote_user_uuid = remote_token['owner_uuid']
312 user = User.find_by_uuid(remote_user_uuid)
314 # Next, try to load the remote user. If this succeeds, we'll use this
315 # information to update/create the local database record as necessary.
316 # If this fails for any reason, but we successfully loaded a user record
317 # from the database, we'll just rely on that information.
320 remote_user = SafeJSON.load(
322 remote_url.merge("arvados/v1/users/current"),
323 remote_query, remote_headers,
325 rescue HTTPClient::BadResponseError => e
326 # If user is defined, we will use that alone for auth, see below.
328 # See rationale in the previous BadResponseError rescue.
334 # TODO #20927: Catch network exceptions and assign a 5xx status to them so
335 # the client knows they're a temporary problem.
337 Rails.logger.warn "getting remote user with token #{token.inspect} failed: #{e}"
339 # Check the response is well formed.
340 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
341 Rails.logger.warn "malformed remote user=#{remote_user.inspect}"
343 # Clusters can only authenticate for their own users.
344 elsif remote_user_prefix != upstream_cluster_id
345 Rails.logger.warn "remote user rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
347 # Force our local copy of a remote root to have a static name
348 elsif system_user_uuid.end_with?(remote_user_suffix)
350 "first_name" => "root",
351 "last_name" => "from cluster #{remote_user_prefix}",
356 if user.nil? and remote_user.nil?
357 Rails.logger.warn "remote token #{token.inspect} rejected: cannot get owner #{remote_user_uuid} from database or remote cluster"
361 # Invariant: remote_user_prefix == upstream_cluster_id
362 # therefore: remote_user_prefix != Rails.configuration.ClusterID
363 # Add or update user and token in local database so we can
364 # validate subsequent requests faster.
366 act_as_system_user do
367 if remote_user && remote_user_uuid != anonymous_user_uuid
368 # Sync user record if we loaded a remote user.
369 user = User.update_remote_user remote_user
372 # If stored_secret is set, we save stored_secret in the database
373 # but return the real secret to the caller. This way, if we end
374 # up returning the auth record to the client, they see the same
375 # secret they supplied, instead of the HMAC we saved in the
377 stored_secret = stored_secret || secret
379 # We will accept this token (and avoid reloading the user
380 # record) for 'RemoteTokenRefresh' (default 5 minutes).
381 exp = [db_current_time + Rails.configuration.Login.RemoteTokenRefresh,
382 remote_token.andand['expires_at']].compact.min
383 scopes = remote_token.andand['scopes'] || ['all']
386 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
388 auth.api_token = stored_secret
390 auth.expires_at = exp
392 rescue ActiveRecord::RecordNotUnique
393 Rails.logger.debug("cached remote token #{token_uuid} already exists, retrying...")
394 # Another request won the race (trying to find_or_create the
395 # same token UUID) ...and/or... there is an expired entry with
396 # the same secret but a different UUID (e.g., the token is an
397 # OIDC access token and [a] our database has an expired cached
398 # row that was not used above, and [b] the remote cluster had
399 # deleted its expired cached row so it assigned a new UUID).
401 # Delete any conflicting row if any. Retry twice (in case we
402 # hit both of those situations at once), then give up.
403 if (retries += 1) <= 2
404 ApiClientAuthorization.where('api_token=? and uuid<>?', stored_secret, token_uuid).delete_all
407 Rails.logger.warn("cannot find or create cached remote token #{token_uuid}")
411 auth.update!(user: user,
412 api_token: stored_secret,
415 Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} and scopes #{scopes} in local db"
416 auth.api_token = secret
432 'v2/' + uuid + '/' + api_token
435 def salted_token(remote:)
439 'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
444 def clamp_token_expiration
445 if Rails.configuration.API.MaxTokenLifetime > 0
446 max_token_expiration = db_current_time + Rails.configuration.API.MaxTokenLifetime
447 if (self.new_record? || self.expires_at_changed?) && (self.expires_at.nil? || (self.expires_at > max_token_expiration && !current_user.andand.is_admin))
448 self.expires_at = max_token_expiration
453 def permission_to_create
454 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
457 def permission_to_update
458 permission_to_create && !uuid_changed? &&
459 (current_user.andand.is_admin || !user_id_changed?)
463 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?