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
12 belongs_to :api_client
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|
23 # NB the "api_token" db column is a misnomer in that it's only the
24 # "secret" part of a token: a v1 token is just the secret, but a
25 # v2 token is "v2/uuid/secret".
27 t.add :created_by_ip_address
28 t.add :default_owner_uuid
31 t.add :last_used_by_ip_address
35 UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
37 def assign_random_api_token
39 self.api_token ||= rand(2**256).to_s(36)
40 rescue ActiveModel::MissingAttributeError
41 # Ignore the case where self.api_token doesn't exist, which happens when
42 # the select=[...] is used.
50 self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
52 def owner_uuid_changed?
56 def modified_by_client_uuid
59 def modified_by_client_uuid=(x) end
61 def modified_by_user_uuid
64 def modified_by_user_uuid=(x) end
69 def modified_at=(x) end
71 def scopes_allow?(req_s)
72 scopes.each do |scope|
73 return true if (scope == 'all') or (scope == req_s) or
74 ((scope.end_with? '/') and (req_s.start_with? scope))
79 def scopes_allow_request?(request)
80 method = request.request_method
82 (scopes_allow?(['HEAD', request.path].join(' ')) ||
83 scopes_allow?(['GET', request.path].join(' ')))
85 scopes_allow?([method, request.path].join(' '))
90 super.except 'api_token'
93 def self.default_orders
94 ["#{table_name}.id desc"]
97 def self.remote_host(uuid_prefix:)
98 (Rails.configuration.RemoteClusters[uuid_prefix].andand["Host"]) ||
99 (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
100 uuid_prefix+".arvadosapi.com")
103 def self.make_http_client(uuid_prefix:)
104 clnt = HTTPClient.new
106 if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
107 Rails.configuration.RemoteClusters['*'].andand.Insecure)
108 clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
110 # Use system CA certificates
111 ["/etc/ssl/certs/ca-certificates.crt",
112 "/etc/pki/tls/certs/ca-bundle.crt"]
113 .select { |ca_path| File.readable?(ca_path) }
114 .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
119 def self.check_anonymous_user_token token
122 _, token_uuid, secret, optional = token.split('/')
123 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0 &&
124 token_uuid == Rails.configuration.ClusterID+"-gj3su-anonymouspublic"
125 # invalid v2 token, or v2 token for another user
133 # The anonymous token content and minimum length is verified in lib/config
134 if secret.length >= 0 && secret == Rails.configuration.Users.AnonymousUserToken
135 return ApiClientAuthorization.new(user: User.find_by_uuid(anonymous_user_uuid),
136 uuid: Rails.configuration.ClusterID+"-gj3su-anonymouspublic",
138 api_client: anonymous_user_token_api_client,
145 def self.check_system_root_token token
146 if token == Rails.configuration.SystemRootToken
147 return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
148 uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
150 api_client: system_root_token_api_client)
156 def self.validate(token:, remote: nil)
157 return nil if token.nil? or token.empty?
158 remote ||= Rails.configuration.ClusterID
160 auth = self.check_anonymous_user_token(token)
165 auth = self.check_system_root_token(token)
172 stored_secret = nil # ...if different from secret
177 _, token_uuid, secret, optional = token.split('/')
178 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
183 # if "optional" is a container uuid, check that it
184 # matches expections.
185 c = Container.where(uuid: optional).first
187 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
188 # token doesn't match the container's token
191 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
192 # token doesn't match the container's token
195 if ![Container::Locked, Container::Running].include?(c.state)
196 # container isn't locked or running, token shouldn't be used
202 # fast path: look up the token in the local database
203 auth = ApiClientAuthorization.
204 includes(:user, :api_client).
205 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
207 if auth && auth.user &&
208 (secret == auth.api_token ||
209 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
211 if token_uuid[0..4] != Rails.configuration.ClusterID
212 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
217 upstream_cluster_id = token_uuid[0..4]
218 if upstream_cluster_id == Rails.configuration.ClusterID
219 # Token is supposedly issued by local cluster, but if the
220 # token were valid, we would have been found in the database
221 # in the above query.
223 elsif upstream_cluster_id.length != 5
229 # token is not a 'v2' token. It could be just the secret part
230 # ("v1 token") -- or it could be an OpenIDConnect access token,
231 # in which case either (a) the controller will have inserted a
232 # row with api_token = hmac(systemroottoken,oidctoken) before
233 # forwarding it, or (b) we'll have done that ourselves, or (c)
234 # we'll need to ask LoginCluster to validate it for us below,
235 # and then insert a local row for a faster lookup next time.
236 hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
237 auth = ApiClientAuthorization.
238 includes(:user, :api_client).
239 where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
243 elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
244 # An unrecognized non-v2 token might be an OIDC Access Token
245 # that can be verified by our login cluster in the code
246 # below. If so, we'll stuff the database with hmac instead of
247 # the real OIDC token.
248 upstream_cluster_id = Rails.configuration.Login.LoginCluster
255 # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
257 # In other words the remaining code in this method decides
258 # whether to accept a token that was issued by a remote cluster
259 # when the token is absent or expired in our database. To
260 # begin, we need to ask the cluster that issued the token to
262 clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
264 host = remote_host(uuid_prefix: upstream_cluster_id)
266 Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
271 remote_user = SafeJSON.load(
272 clnt.get_content('https://' + host + '/arvados/v1/users/current',
273 {'remote' => Rails.configuration.ClusterID},
274 {'Authorization' => 'Bearer ' + token}))
276 Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
280 # Check the response is well formed.
281 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
282 Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
286 remote_user_prefix = remote_user['uuid'][0..4]
288 # Get token scope, and make sure we use the same UUID as the
289 # remote when caching the token.
292 remote_token = SafeJSON.load(
293 clnt.get_content('https://' + host + '/arvados/v1/api_client_authorizations/current',
294 {'remote' => Rails.configuration.ClusterID},
295 {'Authorization' => 'Bearer ' + token}))
296 Rails.logger.debug "retrieved remote token #{remote_token.inspect}"
297 token_uuid = remote_token['uuid']
298 if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
299 raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
301 rescue HTTPClient::BadResponseError => e
302 if e.res.status != 401
305 rev = SafeJSON.load(clnt.get_content('https://' + host + '/discovery/v1/apis/arvados/v1/rest'))['revision']
306 if rev >= '20010101' && rev < '20210503'
307 Rails.logger.warn "remote cluster #{upstream_cluster_id} at #{host} with api rev #{rev} does not provide token expiry and scopes; using scopes=['all']"
309 # remote server is new enough that it should have accepted
310 # this request if the token was valid
314 Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
318 # Clusters can only authenticate for their own users.
319 if remote_user_prefix != upstream_cluster_id
320 Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
324 # Invariant: remote_user_prefix == upstream_cluster_id
325 # therefore: remote_user_prefix != Rails.configuration.ClusterID
327 # Add or update user and token in local database so we can
328 # validate subsequent requests faster.
330 if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
331 # Special case: map the remote anonymous user to local anonymous user
332 remote_user['uuid'] = anonymous_user_uuid
335 user = User.find_by_uuid(remote_user['uuid'])
338 # Create a new record for this user.
339 user = User.new(uuid: remote_user['uuid'],
342 email: remote_user['email'],
343 owner_uuid: system_user_uuid)
344 user.set_initial_username(requested: remote_user['username'])
348 act_as_system_user do
349 %w[first_name last_name email prefs].each do |attr|
350 user.send(attr+'=', remote_user[attr])
353 if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
354 user.first_name = "root"
355 user.last_name = "from cluster #{remote_user_prefix}"
360 rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
361 Rails.logger.debug("remote user #{remote_user['uuid']} already exists, retrying...")
362 # Some other request won the race: retry fetching the user record.
363 user = User.find_by_uuid(remote_user['uuid'])
365 Rails.logger.warn("cannot find or create remote user #{remote_user['uuid']}")
370 if user.is_invited && !remote_user['is_invited']
371 # Remote user is not "invited" state, they should be unsetup, which
372 # also makes them inactive.
375 if !user.is_invited && remote_user['is_invited'] and
376 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
377 Rails.configuration.Users.AutoSetupNewUsers or
378 Rails.configuration.Users.NewUsersAreActive or
379 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
383 if !user.is_active && remote_user['is_active'] && user.is_invited and
384 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
385 Rails.configuration.Users.NewUsersAreActive or
386 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
387 user.update_attributes!(is_active: true)
388 elsif user.is_active && !remote_user['is_active']
389 user.update_attributes!(is_active: false)
392 if remote_user_prefix == Rails.configuration.Login.LoginCluster and
394 user.is_admin != remote_user['is_admin']
395 # Remote cluster controls our user database, including the
397 user.update_attributes!(is_admin: remote_user['is_admin'])
401 # If stored_secret is set, we save stored_secret in the database
402 # but return the real secret to the caller. This way, if we end
403 # up returning the auth record to the client, they see the same
404 # secret they supplied, instead of the HMAC we saved in the
406 stored_secret = stored_secret || secret
408 # We will accept this token (and avoid reloading the user
409 # record) for 'RemoteTokenRefresh' (default 5 minutes).
410 exp = [db_current_time + Rails.configuration.Login.RemoteTokenRefresh,
411 remote_token.andand['expires_at']].compact.min
412 scopes = remote_token.andand['scopes'] || ['all']
415 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
417 auth.api_token = stored_secret
418 auth.api_client_id = 0
420 auth.expires_at = exp
422 rescue ActiveRecord::RecordNotUnique
423 Rails.logger.debug("cached remote token #{token_uuid} already exists, retrying...")
424 # Some other request won the race: retry just once before erroring out
425 if (retries += 1) <= 1
428 Rails.logger.warn("cannot find or create cached remote token #{token_uuid}")
432 auth.update_attributes!(user: user,
433 api_token: stored_secret,
437 Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} and scopes #{scopes} in local db"
438 auth.api_token = secret
454 'v2/' + uuid + '/' + api_token
457 def salted_token(remote:)
461 'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
466 def clamp_token_expiration
467 if Rails.configuration.API.MaxTokenLifetime > 0
468 max_token_expiration = db_current_time + Rails.configuration.API.MaxTokenLifetime
469 if (self.new_record? || self.expires_at_changed?) && (self.expires_at.nil? || (self.expires_at > max_token_expiration && !current_user.andand.is_admin))
470 self.expires_at = max_token_expiration
475 def permission_to_create
476 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
479 def permission_to_update
480 permission_to_create && !uuid_changed? &&
481 (current_user.andand.is_admin || !user_id_changed?)
485 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?