]> git.arvados.org - arvados.git/blob - services/api/app/models/api_client_authorization.rb
19929: Add descriptions to all discovery document methods and parameters
[arvados.git] / services / api / app / models / api_client_authorization.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class ApiClientAuthorization < ArvadosModel
6   include HasUuid
7   include KindAndEtag
8   include CommonApiTemplate
9   include Rails.application.routes.url_helpers
10   extend CurrentApiClient
11   extend DbCurrentTime
12
13   belongs_to :user, optional: true
14   after_initialize :assign_random_api_token
15   serialize :scopes, Array
16
17   before_validation :clamp_token_expiration
18
19   api_accessible :user, extend: :common do |t|
20     t.add :owner_uuid
21     # NB the "api_token" db column is a misnomer in that it's only the
22     # "secret" part of a token: a v1 token is just the secret, but a
23     # v2 token is "v2/uuid/secret".
24     t.add :api_token
25     t.add :created_by_ip_address
26     t.add :expires_at
27     t.add :last_used_at
28     t.add :last_used_by_ip_address
29     t.add :scopes
30   end
31
32   UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
33
34   def assign_random_api_token
35     begin
36       self.api_token ||= rand(2**256).to_s(36)
37     rescue ActiveModel::MissingAttributeError
38       # Ignore the case where self.api_token doesn't exist, which happens when
39       # the select=[...] is used.
40     end
41   end
42
43   def owner_uuid
44     self.user.andand.uuid
45   end
46   def owner_uuid_was
47     self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
48   end
49   def owner_uuid_changed?
50     self.user_id_changed?
51   end
52
53   def modified_by_user_uuid
54     nil
55   end
56   def modified_by_user_uuid=(x) end
57
58   def modified_at
59     nil
60   end
61   def modified_at=(x) end
62
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))
67     end
68     false
69   end
70
71   def scopes_allow_request?(request)
72     method = request.request_method
73     if method == 'GET' and request.path == url_for(controller: 'arvados/v1/api_client_authorizations', action: 'current', only_path: true)
74       true
75     elsif method == 'HEAD'
76       (scopes_allow?(['HEAD', request.path].join(' ')) ||
77        scopes_allow?(['GET', request.path].join(' ')))
78     else
79       scopes_allow?([method, request.path].join(' '))
80     end
81   end
82
83   def logged_attributes
84     super.except 'api_token'
85   end
86
87   def self.default_orders
88     ["#{table_name}.id desc"]
89   end
90
91   def self.remote_host(uuid_prefix:)
92     (Rails.configuration.RemoteClusters[uuid_prefix].andand["Host"]) ||
93       (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
94        uuid_prefix+".arvadosapi.com")
95   end
96
97   def self.make_http_client(uuid_prefix:)
98     clnt = HTTPClient.new
99
100     if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
101                        Rails.configuration.RemoteClusters['*'].andand.Insecure)
102       clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
103     else
104       # Use system CA certificates
105       ["/etc/ssl/certs/ca-certificates.crt",
106        "/etc/pki/tls/certs/ca-bundle.crt"]
107         .select { |ca_path| File.readable?(ca_path) }
108         .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
109     end
110     clnt
111   end
112
113   def self.check_anonymous_user_token(token:, remote:)
114     case token[0..2]
115     when 'v2/'
116       _, token_uuid, secret, optional = token.split('/')
117       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0 &&
118              token_uuid == Rails.configuration.ClusterID+"-gj3su-anonymouspublic"
119         # invalid v2 token, or v2 token for another user
120         return nil
121       end
122     else
123       # v1 token
124       secret = token
125     end
126
127     # Usually, the secret is salted
128     salted_secret = OpenSSL::HMAC.hexdigest('sha1', Rails.configuration.Users.AnonymousUserToken, remote)
129
130     # The anonymous token could be specified as a full v2 token in the config,
131     # but the config loader strips it down to the secret part.
132     # The anonymous token content and minimum length is verified in lib/config
133     if secret.length >= 0 && (secret == Rails.configuration.Users.AnonymousUserToken || secret == salted_secret)
134       return ApiClientAuthorization.new(user: User.find_by_uuid(anonymous_user_uuid),
135                                         uuid: Rails.configuration.ClusterID+"-gj3su-anonymouspublic",
136                                         api_token: secret,
137                                         scopes: ['GET /'])
138     else
139       return nil
140     end
141   end
142
143   def self.check_system_root_token token
144     if token == Rails.configuration.SystemRootToken
145       return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
146                                         uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
147                                         api_token: token)
148     else
149       return nil
150     end
151   end
152
153   def self.validate(token:, remote: nil)
154     return nil if token.nil? or token.empty?
155     remote ||= Rails.configuration.ClusterID
156
157     auth = self.check_anonymous_user_token(token: token, remote: remote)
158     if !auth.nil?
159       return auth
160     end
161
162     auth = self.check_system_root_token(token)
163     if !auth.nil?
164       return auth
165     end
166
167     token_uuid = ''
168     secret = token
169     stored_secret = nil         # ...if different from secret
170     optional = nil
171
172     case token[0..2]
173     when 'v2/'
174       _, token_uuid, secret, optional = token.split('/')
175       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
176         return nil
177       end
178
179       if !optional.nil?
180         # if "optional" is a container uuid, check that it
181         # matches expections.
182         c = Container.where(uuid: optional).first
183         if !c.nil?
184           if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
185             # token doesn't match the container's token
186             return nil
187           end
188           if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
189             # token doesn't match the container's token
190             return nil
191           end
192           if ![Container::Locked, Container::Running].include?(c.state)
193             # container isn't locked or running, token shouldn't be used
194             return nil
195           end
196         end
197       end
198
199       # fast path: look up the token in the local database
200       auth = ApiClientAuthorization.
201              includes(:user).
202              where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
203              first
204       if auth && auth.user &&
205          (secret == auth.api_token ||
206           secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
207         # found it
208         if token_uuid[0..4] != Rails.configuration.ClusterID
209           Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
210         end
211         return auth
212       end
213
214       upstream_cluster_id = token_uuid[0..4]
215       if upstream_cluster_id == Rails.configuration.ClusterID
216         # Token is supposedly issued by local cluster, but if the
217         # token were valid, we would have been found in the database
218         # in the above query.
219         return nil
220       elsif upstream_cluster_id.length != 5
221         # malformed
222         return nil
223       end
224
225     else
226       # token is not a 'v2' token. It could be just the secret part
227       # ("v1 token") -- or it could be an OpenIDConnect access token,
228       # in which case either (a) the controller will have inserted a
229       # row with api_token = hmac(systemroottoken,oidctoken) before
230       # forwarding it, or (b) we'll have done that ourselves, or (c)
231       # we'll need to ask LoginCluster to validate it for us below,
232       # and then insert a local row for a faster lookup next time.
233       hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
234       auth = ApiClientAuthorization.
235                includes(:user).
236                where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
237                first
238       if auth && auth.user
239         return auth
240       elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
241         # An unrecognized non-v2 token might be an OIDC Access Token
242         # that can be verified by our login cluster in the code
243         # below. If so, we'll stuff the database with hmac instead of
244         # the real OIDC token.
245         upstream_cluster_id = Rails.configuration.Login.LoginCluster
246         stored_secret = hmac
247       else
248         return nil
249       end
250     end
251
252     # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
253     #
254     # In other words the remaining code in this method decides
255     # whether to accept a token that was issued by a remote cluster
256     # when the token is absent or expired in our database.  To
257     # begin, we need to ask the cluster that issued the token to
258     # [re]validate it.
259     clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
260
261     host = remote_host(uuid_prefix: upstream_cluster_id)
262     if !host
263       Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
264       return nil
265     end
266     remote_url = URI::parse("https://#{host}/")
267     remote_query = {"remote" => Rails.configuration.ClusterID}
268     remote_headers = {"Authorization" => "Bearer #{token}"}
269
270     # First get the current token. This query is not limited by token scopes,
271     # and tells us the user's UUID via owner_uuid, so this gives us enough
272     # information to load a local user record from the database if one exists.
273     remote_token = nil
274     begin
275       remote_token = SafeJSON.load(
276         clnt.get_content(
277           remote_url.merge("arvados/v1/api_client_authorizations/current"),
278           remote_query, remote_headers,
279         ))
280       Rails.logger.debug "retrieved remote token #{remote_token.inspect}"
281       token_uuid = remote_token['uuid']
282       if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
283         raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
284       end
285     rescue HTTPClient::BadResponseError => e
286       if e.res.status_code >= 400 && e.res.status_code < 500
287         # Remote cluster does not accept this token.
288         return nil
289       end
290       # CurrentApiToken#call and ApplicationController#render_error will
291       # propagate the status code from the #http_status method, so define
292       # that here.
293       def e.http_status
294         self.res.status_code
295       end
296       raise
297     # TODO #20927: Catch network exceptions and assign a 5xx status to them so
298     # the client knows they're a temporary problem.
299     rescue => e
300       Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
301       return nil
302     end
303
304     # Next, load the token's user record from the database (might be nil).
305     remote_user_prefix, remote_user_suffix = remote_token['owner_uuid'].split('-', 2)
306     if anonymous_user_uuid.end_with?(remote_user_suffix)
307       # Special case: map the remote anonymous user to local anonymous user
308       remote_user_uuid = anonymous_user_uuid
309     else
310       remote_user_uuid = remote_token['owner_uuid']
311     end
312     user = User.find_by_uuid(remote_user_uuid)
313
314     # Next, try to load the remote user. If this succeeds, we'll use this
315     # information to update/create the local database record as necessary.
316     # If this fails for any reason, but we successfully loaded a user record
317     # from the database, we'll just rely on that information.
318     remote_user = nil
319     begin
320       remote_user = SafeJSON.load(
321         clnt.get_content(
322           remote_url.merge("arvados/v1/users/current"),
323           remote_query, remote_headers,
324         ))
325     rescue HTTPClient::BadResponseError => e
326       # If user is defined, we will use that alone for auth, see below.
327       if user.nil?
328         # See rationale in the previous BadResponseError rescue.
329         def e.http_status
330           self.res.status_code
331         end
332         raise
333       end
334     # TODO #20927: Catch network exceptions and assign a 5xx status to them so
335     # the client knows they're a temporary problem.
336     rescue => e
337       Rails.logger.warn "getting remote user with token #{token.inspect} failed: #{e}"
338     else
339       # Check the response is well formed.
340       if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
341         Rails.logger.warn "malformed remote user=#{remote_user.inspect}"
342         remote_user = nil
343       # Clusters can only authenticate for their own users.
344       elsif remote_user_prefix != upstream_cluster_id
345         Rails.logger.warn "remote user rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
346         remote_user = nil
347       # Force our local copy of a remote root to have a static name
348       elsif system_user_uuid.end_with?(remote_user_suffix)
349         remote_user.update(
350           "first_name" => "root",
351           "last_name" => "from cluster #{remote_user_prefix}",
352         )
353       end
354     end
355
356     if user.nil? and remote_user.nil?
357       Rails.logger.warn "remote token #{token.inspect} rejected: cannot get owner #{remote_user_uuid} from database or remote cluster"
358       return nil
359     end
360
361     # Invariant:    remote_user_prefix == upstream_cluster_id
362     # therefore:    remote_user_prefix != Rails.configuration.ClusterID
363     # Add or update user and token in local database so we can
364     # validate subsequent requests faster.
365
366     act_as_system_user do
367       if remote_user && remote_user_uuid != anonymous_user_uuid
368         # Sync user record if we loaded a remote user.
369         user = User.update_remote_user remote_user
370       end
371
372       # If stored_secret is set, we save stored_secret in the database
373       # but return the real secret to the caller. This way, if we end
374       # up returning the auth record to the client, they see the same
375       # secret they supplied, instead of the HMAC we saved in the
376       # database.
377       stored_secret = stored_secret || secret
378
379       # We will accept this token (and avoid reloading the user
380       # record) for 'RemoteTokenRefresh' (default 5 minutes).
381       exp = [db_current_time + Rails.configuration.Login.RemoteTokenRefresh,
382              remote_token.andand['expires_at']].compact.min
383       scopes = remote_token.andand['scopes'] || ['all']
384       begin
385         retries ||= 0
386         auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
387           auth.user = user
388           auth.api_token = stored_secret
389           auth.scopes = scopes
390           auth.expires_at = exp
391         end
392       rescue ActiveRecord::RecordNotUnique
393         Rails.logger.debug("cached remote token #{token_uuid} already exists, retrying...")
394         # Another request won the race (trying to find_or_create the
395         # same token UUID) ...and/or... there is an expired entry with
396         # the same secret but a different UUID (e.g., the token is an
397         # OIDC access token and [a] our database has an expired cached
398         # row that was not used above, and [b] the remote cluster had
399         # deleted its expired cached row so it assigned a new UUID).
400         #
401         # Delete any conflicting row if any. Retry twice (in case we
402         # hit both of those situations at once), then give up.
403         if (retries += 1) <= 2
404           ApiClientAuthorization.where('api_token=? and uuid<>?', stored_secret, token_uuid).delete_all
405           retry
406         else
407           Rails.logger.warn("cannot find or create cached remote token #{token_uuid}")
408           return nil
409         end
410       end
411       auth.update!(user: user,
412                    api_token: stored_secret,
413                    scopes: scopes,
414                    expires_at: exp)
415       Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} and scopes #{scopes} in local db"
416       auth.api_token = secret
417       return auth
418     end
419
420     return nil
421   end
422
423   def token
424     v2token
425   end
426
427   def v1token
428     api_token
429   end
430
431   def v2token
432     'v2/' + uuid + '/' + api_token
433   end
434
435   def salted_token(remote:)
436     if remote.nil?
437       token
438     end
439     'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
440   end
441
442   protected
443
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
449       end
450     end
451   end
452
453   def permission_to_create
454     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
455   end
456
457   def permission_to_update
458     permission_to_create && !uuid_changed? &&
459       (current_user.andand.is_admin || !user_id_changed?)
460   end
461
462   def log_update
463     super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?
464   end
465 end