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 :api_client, optional: true
14 belongs_to :user, optional: true
15 after_initialize :assign_random_api_token
16 serialize :scopes, Array
18 before_validation :clamp_token_expiration
20 api_accessible :user, extend: :common do |t|
24 # NB the "api_token" db column is a misnomer in that it's only the
25 # "secret" part of a token: a v1 token is just the secret, but a
26 # v2 token is "v2/uuid/secret".
28 t.add :created_by_ip_address
29 t.add :default_owner_uuid
32 t.add :last_used_by_ip_address
36 UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
38 def assign_random_api_token
40 self.api_token ||= rand(2**256).to_s(36)
41 rescue ActiveModel::MissingAttributeError
42 # Ignore the case where self.api_token doesn't exist, which happens when
43 # the select=[...] is used.
51 self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
53 def owner_uuid_changed?
57 def modified_by_client_uuid
60 def modified_by_client_uuid=(x) end
62 def modified_by_user_uuid
65 def modified_by_user_uuid=(x) end
70 def modified_at=(x) end
72 def scopes_allow?(req_s)
73 scopes.each do |scope|
74 return true if (scope == 'all') or (scope == req_s) or
75 ((scope.end_with? '/') and (req_s.start_with? scope))
80 def scopes_allow_request?(request)
81 method = request.request_method
82 if method == 'GET' and request.path == url_for(controller: 'arvados/v1/api_client_authorizations', action: 'current', only_path: true)
84 elsif method == 'HEAD'
85 (scopes_allow?(['HEAD', request.path].join(' ')) ||
86 scopes_allow?(['GET', request.path].join(' ')))
88 scopes_allow?([method, request.path].join(' '))
93 super.except 'api_token'
96 def self.default_orders
97 ["#{table_name}.id desc"]
100 def self.remote_host(uuid_prefix:)
101 (Rails.configuration.RemoteClusters[uuid_prefix].andand["Host"]) ||
102 (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
103 uuid_prefix+".arvadosapi.com")
106 def self.make_http_client(uuid_prefix:)
107 clnt = HTTPClient.new
109 if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
110 Rails.configuration.RemoteClusters['*'].andand.Insecure)
111 clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
113 # Use system CA certificates
114 ["/etc/ssl/certs/ca-certificates.crt",
115 "/etc/pki/tls/certs/ca-bundle.crt"]
116 .select { |ca_path| File.readable?(ca_path) }
117 .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
122 def self.check_anonymous_user_token(token:, remote:)
125 _, token_uuid, secret, optional = token.split('/')
126 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0 &&
127 token_uuid == Rails.configuration.ClusterID+"-gj3su-anonymouspublic"
128 # invalid v2 token, or v2 token for another user
136 # Usually, the secret is salted
137 salted_secret = OpenSSL::HMAC.hexdigest('sha1', Rails.configuration.Users.AnonymousUserToken, remote)
139 # The anonymous token could be specified as a full v2 token in the config,
140 # but the config loader strips it down to the secret part.
141 # The anonymous token content and minimum length is verified in lib/config
142 if secret.length >= 0 && (secret == Rails.configuration.Users.AnonymousUserToken || secret == salted_secret)
143 return ApiClientAuthorization.new(user: User.find_by_uuid(anonymous_user_uuid),
144 uuid: Rails.configuration.ClusterID+"-gj3su-anonymouspublic",
146 api_client: anonymous_user_token_api_client,
153 def self.check_system_root_token token
154 if token == Rails.configuration.SystemRootToken
155 return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
156 uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
158 api_client: system_root_token_api_client)
164 def self.validate(token:, remote: nil)
165 return nil if token.nil? or token.empty?
166 remote ||= Rails.configuration.ClusterID
168 auth = self.check_anonymous_user_token(token: token, remote: remote)
173 auth = self.check_system_root_token(token)
180 stored_secret = nil # ...if different from secret
185 _, token_uuid, secret, optional = token.split('/')
186 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
191 # if "optional" is a container uuid, check that it
192 # matches expections.
193 c = Container.where(uuid: optional).first
195 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
196 # token doesn't match the container's token
199 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
200 # token doesn't match the container's token
203 if ![Container::Locked, Container::Running].include?(c.state)
204 # container isn't locked or running, token shouldn't be used
210 # fast path: look up the token in the local database
211 auth = ApiClientAuthorization.
212 includes(:user, :api_client).
213 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
215 if auth && auth.user &&
216 (secret == auth.api_token ||
217 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
219 if token_uuid[0..4] != Rails.configuration.ClusterID
220 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
225 upstream_cluster_id = token_uuid[0..4]
226 if upstream_cluster_id == Rails.configuration.ClusterID
227 # Token is supposedly issued by local cluster, but if the
228 # token were valid, we would have been found in the database
229 # in the above query.
231 elsif upstream_cluster_id.length != 5
237 # token is not a 'v2' token. It could be just the secret part
238 # ("v1 token") -- or it could be an OpenIDConnect access token,
239 # in which case either (a) the controller will have inserted a
240 # row with api_token = hmac(systemroottoken,oidctoken) before
241 # forwarding it, or (b) we'll have done that ourselves, or (c)
242 # we'll need to ask LoginCluster to validate it for us below,
243 # and then insert a local row for a faster lookup next time.
244 hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
245 auth = ApiClientAuthorization.
246 includes(:user, :api_client).
247 where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
251 elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
252 # An unrecognized non-v2 token might be an OIDC Access Token
253 # that can be verified by our login cluster in the code
254 # below. If so, we'll stuff the database with hmac instead of
255 # the real OIDC token.
256 upstream_cluster_id = Rails.configuration.Login.LoginCluster
263 # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
265 # In other words the remaining code in this method decides
266 # whether to accept a token that was issued by a remote cluster
267 # when the token is absent or expired in our database. To
268 # begin, we need to ask the cluster that issued the token to
270 clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
272 host = remote_host(uuid_prefix: upstream_cluster_id)
274 Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
277 remote_url = URI::parse("https://#{host}/")
278 remote_query = {"remote" => Rails.configuration.ClusterID}
279 remote_headers = {"Authorization" => "Bearer #{token}"}
281 # First get the current token. This query is not limited by token scopes,
282 # and tells us the user's UUID via owner_uuid, so this gives us enough
283 # information to load a local user record from the database if one exists.
286 remote_token = SafeJSON.load(
288 remote_url.merge("arvados/v1/api_client_authorizations/current"),
289 remote_query, remote_headers,
291 Rails.logger.debug "retrieved remote token #{remote_token.inspect}"
292 token_uuid = remote_token['uuid']
293 if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
294 raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
296 rescue HTTPClient::BadResponseError => e
297 # CurrentApiToken#call and ApplicationController#render_error will
298 # propagate the status code from the #http_status method, so define
304 # TODO #20927: Catch network exceptions and assign a 5xx status to them so
305 # the client knows they're a temporary problem.
307 Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
311 # Next, load the token's user record from the database (might be nil).
312 remote_user_prefix, remote_user_suffix = remote_token['owner_uuid'].split('-', 2)
313 if anonymous_user_uuid.end_with?(remote_user_suffix)
314 # Special case: map the remote anonymous user to local anonymous user
315 remote_user_uuid = anonymous_user_uuid
317 remote_user_uuid = remote_token['owner_uuid']
319 user = User.find_by_uuid(remote_user_uuid)
321 # Next, try to load the remote user. If this succeeds, we'll use this
322 # information to update/create the local database record as necessary.
323 # If this fails for any reason, but we successfully loaded a user record
324 # from the database, we'll just rely on that information.
327 remote_user = SafeJSON.load(
329 remote_url.merge("arvados/v1/users/current"),
330 remote_query, remote_headers,
332 rescue HTTPClient::BadResponseError => e
333 # If user is defined, we will use that alone for auth, see below.
335 # See rationale in the previous BadResponseError rescue.
341 # TODO #20927: Catch network exceptions and assign a 5xx status to them so
342 # the client knows they're a temporary problem.
344 Rails.logger.warn "getting remote user with token #{token.inspect} failed: #{e}"
346 # Check the response is well formed.
347 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
348 Rails.logger.warn "malformed remote user=#{remote_user.inspect}"
350 # Clusters can only authenticate for their own users.
351 elsif remote_user_prefix != upstream_cluster_id
352 Rails.logger.warn "remote user rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
354 # Force our local copy of a remote root to have a static name
355 elsif system_user_uuid.end_with?(remote_user_suffix)
357 "first_name" => "root",
358 "last_name" => "from cluster #{remote_user_prefix}",
363 if user.nil? and remote_user.nil?
364 Rails.logger.warn "remote token #{token.inspect} rejected: cannot get owner #{remote_user_uuid} from database or remote cluster"
368 # Invariant: remote_user_prefix == upstream_cluster_id
369 # therefore: remote_user_prefix != Rails.configuration.ClusterID
370 # Add or update user and token in local database so we can
371 # validate subsequent requests faster.
373 act_as_system_user do
374 if remote_user && remote_user_uuid != anonymous_user_uuid
375 # Sync user record if we loaded a remote user.
376 user = User.update_remote_user remote_user
379 # If stored_secret is set, we save stored_secret in the database
380 # but return the real secret to the caller. This way, if we end
381 # up returning the auth record to the client, they see the same
382 # secret they supplied, instead of the HMAC we saved in the
384 stored_secret = stored_secret || secret
386 # We will accept this token (and avoid reloading the user
387 # record) for 'RemoteTokenRefresh' (default 5 minutes).
388 exp = [db_current_time + Rails.configuration.Login.RemoteTokenRefresh,
389 remote_token.andand['expires_at']].compact.min
390 scopes = remote_token.andand['scopes'] || ['all']
393 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
395 auth.api_token = stored_secret
396 auth.api_client_id = 0
398 auth.expires_at = exp
400 rescue ActiveRecord::RecordNotUnique
401 Rails.logger.debug("cached remote token #{token_uuid} already exists, retrying...")
402 # Some other request won the race: retry just once before erroring out
403 if (retries += 1) <= 1
406 Rails.logger.warn("cannot find or create cached remote token #{token_uuid}")
410 auth.update!(user: user,
411 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?