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.RemoteClusters[uuid_prefix].andand["Host"]) ||
91 (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
92 uuid_prefix+".arvadosapi.com")
95 def self.make_http_client(uuid_prefix:)
98 if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
99 Rails.configuration.RemoteClusters['*'].andand.Insecure)
100 clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
102 # Use system CA certificates
103 ["/etc/ssl/certs/ca-certificates.crt",
104 "/etc/pki/tls/certs/ca-bundle.crt"]
105 .select { |ca_path| File.readable?(ca_path) }
106 .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
111 def self.check_system_root_token token
112 if token == Rails.configuration.SystemRootToken
113 return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
114 uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
116 api_client: system_root_token_api_client)
122 def self.validate(token:, remote: nil)
123 return nil if token.nil? or token.empty?
124 remote ||= Rails.configuration.ClusterID
126 auth = self.check_system_root_token(token)
133 stored_secret = nil # ...if different from secret
138 _, token_uuid, secret, optional = token.split('/')
139 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
144 # if "optional" is a container uuid, check that it
145 # matches expections.
146 c = Container.where(uuid: optional).first
148 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
149 # token doesn't match the container's token
152 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
153 # token doesn't match the container's token
156 if ![Container::Locked, Container::Running].include?(c.state)
157 # container isn't locked or running, token shouldn't be used
163 # fast path: look up the token in the local database
164 auth = ApiClientAuthorization.
165 includes(:user, :api_client).
166 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
168 if auth && auth.user &&
169 (secret == auth.api_token ||
170 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
172 if token_uuid[0..4] != Rails.configuration.ClusterID
173 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
178 upstream_cluster_id = token_uuid[0..4]
179 if upstream_cluster_id == Rails.configuration.ClusterID
180 # Token is supposedly issued by local cluster, but if the
181 # token were valid, we would have been found in the database
182 # in the above query.
184 elsif upstream_cluster_id.length != 5
190 # token is not a 'v2' token. It could be just the secret part
191 # ("v1 token") -- or it could be an OpenIDConnect access token,
192 # in which case either (a) the controller will have inserted a
193 # row with api_token = hmac(systemroottoken,oidctoken) before
194 # forwarding it, or (b) we'll have done that ourselves, or (c)
195 # we'll need to ask LoginCluster to validate it for us below,
196 # and then insert a local row for a faster lookup next time.
197 hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
198 auth = ApiClientAuthorization.
199 includes(:user, :api_client).
200 where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
204 elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
205 # An unrecognized non-v2 token might be an OIDC Access Token
206 # that can be verified by our login cluster in the code
207 # below. If so, we'll stuff the database with hmac instead of
208 # the real OIDC token.
209 upstream_cluster_id = Rails.configuration.Login.LoginCluster
216 # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
218 # In other words the remaining code in this method decides
219 # whether to accept a token that was issued by a remote cluster
220 # when the token is absent or expired in our database. To
221 # begin, we need to ask the cluster that issued the token to
223 clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
225 host = remote_host(uuid_prefix: upstream_cluster_id)
227 Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
232 remote_user = SafeJSON.load(
233 clnt.get_content('https://' + host + '/arvados/v1/users/current',
234 {'remote' => Rails.configuration.ClusterID},
235 {'Authorization' => 'Bearer ' + token}))
237 Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
241 # Check the response is well formed.
242 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
243 Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
247 remote_user_prefix = remote_user['uuid'][0..4]
250 # Use the same UUID as the remote when caching the token.
252 remote_token = SafeJSON.load(
253 clnt.get_content('https://' + host + '/arvados/v1/api_client_authorizations/current',
254 {'remote' => Rails.configuration.ClusterID},
255 {'Authorization' => 'Bearer ' + token}))
256 token_uuid = remote_token['uuid']
257 if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
258 raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
261 Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
266 # Clusters can only authenticate for their own users.
267 if remote_user_prefix != upstream_cluster_id
268 Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
272 # Invariant: remote_user_prefix == upstream_cluster_id
273 # therefore: remote_user_prefix != Rails.configuration.ClusterID
275 # Add or update user and token in local database so we can
276 # validate subsequent requests faster.
278 if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
279 # Special case: map the remote anonymous user to local anonymous user
280 remote_user['uuid'] = anonymous_user_uuid
283 user = User.find_by_uuid(remote_user['uuid'])
286 # Create a new record for this user.
287 user = User.new(uuid: remote_user['uuid'],
290 email: remote_user['email'],
291 owner_uuid: system_user_uuid)
292 user.set_initial_username(requested: remote_user['username'])
296 act_as_system_user do
297 %w[first_name last_name email prefs].each do |attr|
298 user.send(attr+'=', remote_user[attr])
301 if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
302 user.first_name = "root"
303 user.last_name = "from cluster #{remote_user_prefix}"
308 if user.is_invited && !remote_user['is_invited']
309 # Remote user is not "invited" state, they should be unsetup, which
310 # also makes them inactive.
313 if !user.is_invited && remote_user['is_invited'] and
314 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
315 Rails.configuration.Users.AutoSetupNewUsers or
316 Rails.configuration.Users.NewUsersAreActive or
317 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
321 if !user.is_active && remote_user['is_active'] && user.is_invited and
322 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
323 Rails.configuration.Users.NewUsersAreActive or
324 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
325 user.update_attributes!(is_active: true)
326 elsif user.is_active && !remote_user['is_active']
327 user.update_attributes!(is_active: false)
330 if remote_user_prefix == Rails.configuration.Login.LoginCluster and
332 user.is_admin != remote_user['is_admin']
333 # Remote cluster controls our user database, including the
335 user.update_attributes!(is_admin: remote_user['is_admin'])
339 # We will accept this token (and avoid reloading the user
340 # record) for 'RemoteTokenRefresh' (default 5 minutes).
342 # Request the actual api_client_auth record from the remote
343 # server in case it wants the token to expire sooner.
344 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
346 auth.api_client_id = 0
348 # If stored_secret is set, we save stored_secret in the database
349 # but return the real secret to the caller. This way, if we end
350 # up returning the auth record to the client, they see the same
351 # secret they supplied, instead of the HMAC we saved in the
353 stored_secret = stored_secret || secret
354 auth.update_attributes!(user: user,
355 api_token: stored_secret,
357 expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
358 Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} in local db"
359 auth.api_token = secret
375 'v2/' + uuid + '/' + api_token
378 def salted_token(remote:)
382 'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
387 def permission_to_create
388 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
391 def permission_to_update
392 permission_to_create && !uuid_changed? &&
393 (current_user.andand.is_admin || !user_id_changed?)
397 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?