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)
137 _, token_uuid, secret, optional = token.split('/')
138 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
143 # if "optional" is a container uuid, check that it
144 # matches expections.
145 c = Container.where(uuid: optional).first
147 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
148 # token doesn't match the container's token
151 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
152 # token doesn't match the container's token
155 if ![Container::Locked, Container::Running].include?(c.state)
156 # container isn't locked or running, token shouldn't be used
162 # fast path: look up the token in the local database
163 auth = ApiClientAuthorization.
164 includes(:user, :api_client).
165 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
167 if auth && auth.user &&
168 (secret == auth.api_token ||
169 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
171 if token_uuid[0..4] != Rails.configuration.ClusterID
172 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
177 upstream_cluster_id = token_uuid[0..4]
178 if upstream_cluster_id == Rails.configuration.ClusterID
179 # Token is supposedly issued by local cluster, but if the
180 # token were valid, we would have been found in the database
181 # in the above query.
183 elsif upstream_cluster_id.length != 5
189 # token is not a 'v2' token. It could be just the secret part
190 # ("v1 token") -- or it could be an OpenIDConnect access token,
191 # in which case either (a) the controller will have inserted a
192 # row with api_token = hmac(systemroottoken,oidctoken) before
193 # forwarding it, or (b) we'll have done that ourselves, or (c)
194 # we'll need to ask LoginCluster to validate it for us below,
195 # and then insert a local row for a faster lookup next time.
196 hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
197 auth = ApiClientAuthorization.
198 includes(:user, :api_client).
199 where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
203 elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
204 # An unrecognized non-v2 token might be an OIDC Access Token
205 # that can be verified by our login cluster in the code
206 # below. If so, we'll stuff the database with hmac instead of
207 # the real OIDC token.
208 upstream_cluster_id = Rails.configuration.Login.LoginCluster
209 token_uuid = upstream_cluster_id + generate_uuid[5..27]
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]
249 # Clusters can only authenticate for their own users.
250 if remote_user_prefix != upstream_cluster_id
251 Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
255 # Invariant: remote_user_prefix == upstream_cluster_id
256 # therefore: remote_user_prefix != Rails.configuration.ClusterID
258 # Add or update user and token in local database so we can
259 # validate subsequent requests faster.
261 if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
262 # Special case: map the remote anonymous user to local anonymous user
263 remote_user['uuid'] = anonymous_user_uuid
266 user = User.find_by_uuid(remote_user['uuid'])
269 # Create a new record for this user.
270 user = User.new(uuid: remote_user['uuid'],
273 email: remote_user['email'],
274 owner_uuid: system_user_uuid)
275 user.set_initial_username(requested: remote_user['username'])
279 act_as_system_user do
280 %w[first_name last_name email prefs].each do |attr|
281 user.send(attr+'=', remote_user[attr])
284 if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
285 user.first_name = "root"
286 user.last_name = "from cluster #{remote_user_prefix}"
291 if user.is_invited && !remote_user['is_invited']
292 # Remote user is not "invited" state, they should be unsetup, which
293 # also makes them inactive.
296 if !user.is_invited && remote_user['is_invited'] and
297 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
298 Rails.configuration.Users.AutoSetupNewUsers or
299 Rails.configuration.Users.NewUsersAreActive or
300 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
304 if !user.is_active && remote_user['is_active'] && user.is_invited and
305 (remote_user_prefix == Rails.configuration.Login.LoginCluster or
306 Rails.configuration.Users.NewUsersAreActive or
307 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
308 user.update_attributes!(is_active: true)
309 elsif user.is_active && !remote_user['is_active']
310 user.update_attributes!(is_active: false)
313 if remote_user_prefix == Rails.configuration.Login.LoginCluster and
315 user.is_admin != remote_user['is_admin']
316 # Remote cluster controls our user database, including the
318 user.update_attributes!(is_admin: remote_user['is_admin'])
322 # We will accept this token (and avoid reloading the user
323 # record) for 'RemoteTokenRefresh' (default 5 minutes).
325 # Request the actual api_client_auth record from the remote
326 # server in case it wants the token to expire sooner.
327 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
329 auth.api_client_id = 0
331 auth.update_attributes!(user: user,
334 expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
335 Rails.logger.debug "cached remote token #{token_uuid} with secret #{secret} in local db"
351 'v2/' + uuid + '/' + api_token
354 def salted_token(remote:)
358 'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
363 def permission_to_create
364 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
367 def permission_to_update
368 permission_to_create && !uuid_changed? &&
369 (current_user.andand.is_admin || !user_id_changed?)
374 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?