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 _, token_uuid, secret, optional = token.split('/')
134 unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
139 # if "optional" is a container uuid, check that it
140 # matches expections.
141 c = Container.where(uuid: optional).first
143 if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
144 # token doesn't match the container's token
147 if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
148 # token doesn't match the container's token
151 if ![Container::Locked, Container::Running].include?(c.state)
152 # container isn't locked or running, token shouldn't be used
158 # fast path: look up the token in the local database
159 auth = ApiClientAuthorization.
160 includes(:user, :api_client).
161 where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
163 if auth && auth.user &&
164 (secret == auth.api_token ||
165 secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
167 if token_uuid[0..4] != Rails.configuration.ClusterID
168 Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
173 token_uuid_prefix = token_uuid[0..4]
174 if token_uuid_prefix == Rails.configuration.ClusterID
175 # Token is supposedly issued by local cluster, but if the
176 # token were valid, we would have been found in the database
177 # in the above query.
179 elsif token_uuid_prefix.length != 5
184 # Invariant: token_uuid_prefix != Rails.configuration.ClusterID
186 # In other words the remaing code in this method below is the
187 # case that determines whether to accept a token that was issued
188 # by a remote cluster when the token absent or expired in our
189 # database. To begin, we need to ask the cluster that issued
190 # the token to [re]validate it.
191 clnt = ApiClientAuthorization.make_http_client(uuid_prefix: token_uuid_prefix)
193 host = remote_host(uuid_prefix: token_uuid_prefix)
195 Rails.logger.warn "remote authentication rejected: no host for #{token_uuid_prefix.inspect}"
200 remote_user = SafeJSON.load(
201 clnt.get_content('https://' + host + '/arvados/v1/users/current',
202 {'remote' => Rails.configuration.ClusterID},
203 {'Authorization' => 'Bearer ' + token}))
205 Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
209 # Check the response is well formed.
210 if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
211 Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
215 remote_user_prefix = remote_user['uuid'][0..4]
217 # Clusters can only authenticate for their own users.
218 if remote_user_prefix != token_uuid_prefix
219 Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{token_uuid_prefix}"
223 # Invariant: remote_user_prefix == token_uuid_prefix
224 # therefore: remote_user_prefix != Rails.configuration.ClusterID
226 # Add or update user and token in local database so we can
227 # validate subsequent requests faster.
229 if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
230 # Special case: map the remote anonymous user to local anonymous user
231 remote_user['uuid'] = anonymous_user_uuid
234 user = User.find_by_uuid(remote_user['uuid'])
237 # Create a new record for this user.
238 user = User.new(uuid: remote_user['uuid'],
241 email: remote_user['email'],
242 owner_uuid: system_user_uuid)
243 user.set_initial_username(requested: remote_user['username'])
247 if remote_user_prefix == Rails.configuration.Login.LoginCluster
248 # Remote cluster controls our user database, set is_active if
249 # remote is active. If remote is not active, user will be
250 # unsetup (see below).
251 user.is_active = true if remote_user['is_active']
252 user.is_admin = remote_user['is_admin']
254 if Rails.configuration.Users.NewUsersAreActive ||
255 Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"]
256 # Default policy is to activate users
257 user.is_active = true if remote_user['is_active']
261 %w[first_name last_name email prefs].each do |attr|
262 user.send(attr+'=', remote_user[attr])
265 if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
266 user.first_name = "root"
267 user.last_name = "from cluster #{remote_user_prefix}"
270 act_as_system_user do
271 if (user.is_active && !remote_user['is_active']) or (user.is_invited && !remote_user['is_invited'])
272 # Synchronize the user's "active/invited" state state. This
273 # also saves the record.
279 # We will accept this token (and avoid reloading the user
280 # record) for 'RemoteTokenRefresh' (default 5 minutes).
282 # Request the actual api_client_auth record from the remote
283 # server in case it wants the token to expire sooner.
284 auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
286 auth.api_client_id = 0
288 auth.update_attributes!(user: user,
291 expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
292 Rails.logger.debug "cached remote token #{token_uuid} with secret #{secret} in local db"
296 # token is not a 'v2' token
297 auth = ApiClientAuthorization.
298 includes(:user, :api_client).
299 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token).
318 'v2/' + uuid + '/' + api_token
321 def salted_token(remote:)
325 'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
330 def permission_to_create
331 current_user.andand.is_admin or (current_user.andand.id == self.user_id)
334 def permission_to_update
335 permission_to_create && !uuid_changed? &&
336 (current_user.andand.is_admin || !user_id_changed?)
341 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?