18676: more tweaks after review comments: clarify logic in checkToken
[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   extend CurrentApiClient
10   extend DbCurrentTime
11
12   belongs_to :api_client
13   belongs_to :user
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     t.add :user_id
22     t.add :api_client_id
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".
26     t.add :api_token
27     t.add :created_by_ip_address
28     t.add :default_owner_uuid
29     t.add :expires_at
30     t.add :last_used_at
31     t.add :last_used_by_ip_address
32     t.add :scopes
33   end
34
35   UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
36
37   def assign_random_api_token
38     self.api_token ||= rand(2**256).to_s(36)
39   end
40
41   def owner_uuid
42     self.user.andand.uuid
43   end
44   def owner_uuid_was
45     self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
46   end
47   def owner_uuid_changed?
48     self.user_id_changed?
49   end
50
51   def modified_by_client_uuid
52     nil
53   end
54   def modified_by_client_uuid=(x) end
55
56   def modified_by_user_uuid
57     nil
58   end
59   def modified_by_user_uuid=(x) end
60
61   def modified_at
62     nil
63   end
64   def modified_at=(x) end
65
66   def scopes_allow?(req_s)
67     scopes.each do |scope|
68       return true if (scope == 'all') or (scope == req_s) or
69         ((scope.end_with? '/') and (req_s.start_with? scope))
70     end
71     false
72   end
73
74   def scopes_allow_request?(request)
75     method = request.request_method
76     if method == 'HEAD'
77       (scopes_allow?(['HEAD', request.path].join(' ')) ||
78        scopes_allow?(['GET', request.path].join(' ')))
79     else
80       scopes_allow?([method, request.path].join(' '))
81     end
82   end
83
84   def logged_attributes
85     super.except 'api_token'
86   end
87
88   def self.default_orders
89     ["#{table_name}.id desc"]
90   end
91
92   def self.remote_host(uuid_prefix:)
93     (Rails.configuration.RemoteClusters[uuid_prefix].andand["Host"]) ||
94       (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
95        uuid_prefix+".arvadosapi.com")
96   end
97
98   def self.make_http_client(uuid_prefix:)
99     clnt = HTTPClient.new
100
101     if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
102                        Rails.configuration.RemoteClusters['*'].andand.Insecure)
103       clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
104     else
105       # Use system CA certificates
106       ["/etc/ssl/certs/ca-certificates.crt",
107        "/etc/pki/tls/certs/ca-bundle.crt"]
108         .select { |ca_path| File.readable?(ca_path) }
109         .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
110     end
111     clnt
112   end
113
114   def self.check_anonymous_user_token token
115     case token[0..2]
116     when 'v2/'
117       _, token_uuid, secret, optional = token.split('/')
118       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0 &&
119              token_uuid == Rails.configuration.ClusterID+"-gj3su-anonymouspublic"
120         # invalid v2 token, or v2 token for another user
121         return nil
122       end
123     else
124       # v1 token
125       secret = token
126     end
127
128     # The anonymous token content and minimum length is verified in lib/config
129     if secret.length >= 0 && secret == Rails.configuration.Users.AnonymousUserToken
130       return ApiClientAuthorization.new(user: User.find_by_uuid(anonymous_user_uuid),
131                                         uuid: Rails.configuration.ClusterID+"-gj3su-anonymouspublic",
132                                         api_token: token,
133                                         api_client: anonymous_user_token_api_client)
134     else
135       return nil
136     end
137   end
138
139   def self.check_system_root_token token
140     if token == Rails.configuration.SystemRootToken
141       return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
142                                         uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
143                                         api_token: token,
144                                         api_client: system_root_token_api_client)
145     else
146       return nil
147     end
148   end
149
150   def self.validate(token:, remote: nil)
151     return nil if token.nil? or token.empty?
152     remote ||= Rails.configuration.ClusterID
153
154     auth = self.check_anonymous_user_token(token)
155     if !auth.nil?
156       return auth
157     end
158
159     auth = self.check_system_root_token(token)
160     if !auth.nil?
161       return auth
162     end
163
164     token_uuid = ''
165     secret = token
166     stored_secret = nil         # ...if different from secret
167     optional = nil
168
169     case token[0..2]
170     when 'v2/'
171       _, token_uuid, secret, optional = token.split('/')
172       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
173         return nil
174       end
175
176       if !optional.nil?
177         # if "optional" is a container uuid, check that it
178         # matches expections.
179         c = Container.where(uuid: optional).first
180         if !c.nil?
181           if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
182             # token doesn't match the container's token
183             return nil
184           end
185           if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
186             # token doesn't match the container's token
187             return nil
188           end
189           if ![Container::Locked, Container::Running].include?(c.state)
190             # container isn't locked or running, token shouldn't be used
191             return nil
192           end
193         end
194       end
195
196       # fast path: look up the token in the local database
197       auth = ApiClientAuthorization.
198              includes(:user, :api_client).
199              where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
200              first
201       if auth && auth.user &&
202          (secret == auth.api_token ||
203           secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
204         # found it
205         if token_uuid[0..4] != Rails.configuration.ClusterID
206           Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
207         end
208         return auth
209       end
210
211       upstream_cluster_id = token_uuid[0..4]
212       if upstream_cluster_id == Rails.configuration.ClusterID
213         # Token is supposedly issued by local cluster, but if the
214         # token were valid, we would have been found in the database
215         # in the above query.
216         return nil
217       elsif upstream_cluster_id.length != 5
218         # malformed
219         return nil
220       end
221
222     else
223       # token is not a 'v2' token. It could be just the secret part
224       # ("v1 token") -- or it could be an OpenIDConnect access token,
225       # in which case either (a) the controller will have inserted a
226       # row with api_token = hmac(systemroottoken,oidctoken) before
227       # forwarding it, or (b) we'll have done that ourselves, or (c)
228       # we'll need to ask LoginCluster to validate it for us below,
229       # and then insert a local row for a faster lookup next time.
230       hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
231       auth = ApiClientAuthorization.
232                includes(:user, :api_client).
233                where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
234                first
235       if auth && auth.user
236         return auth
237       elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
238         # An unrecognized non-v2 token might be an OIDC Access Token
239         # that can be verified by our login cluster in the code
240         # below. If so, we'll stuff the database with hmac instead of
241         # the real OIDC token.
242         upstream_cluster_id = Rails.configuration.Login.LoginCluster
243         stored_secret = hmac
244       else
245         return nil
246       end
247     end
248
249     # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
250     #
251     # In other words the remaining code in this method decides
252     # whether to accept a token that was issued by a remote cluster
253     # when the token is absent or expired in our database.  To
254     # begin, we need to ask the cluster that issued the token to
255     # [re]validate it.
256     clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
257
258     host = remote_host(uuid_prefix: upstream_cluster_id)
259     if !host
260       Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
261       return nil
262     end
263
264     begin
265       remote_user = SafeJSON.load(
266         clnt.get_content('https://' + host + '/arvados/v1/users/current',
267                          {'remote' => Rails.configuration.ClusterID},
268                          {'Authorization' => 'Bearer ' + token}))
269     rescue => e
270       Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
271       return nil
272     end
273
274     # Check the response is well formed.
275     if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
276       Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
277       return nil
278     end
279
280     remote_user_prefix = remote_user['uuid'][0..4]
281
282     # Get token scope, and make sure we use the same UUID as the
283     # remote when caching the token.
284     remote_token = nil
285     begin
286       remote_token = SafeJSON.load(
287         clnt.get_content('https://' + host + '/arvados/v1/api_client_authorizations/current',
288                          {'remote' => Rails.configuration.ClusterID},
289                          {'Authorization' => 'Bearer ' + token}))
290       Rails.logger.debug "retrieved remote token #{remote_token.inspect}"
291       token_uuid = remote_token['uuid']
292       if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
293         raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
294       end
295     rescue HTTPClient::BadResponseError => e
296       if e.res.status != 401
297         raise
298       end
299       rev = SafeJSON.load(clnt.get_content('https://' + host + '/discovery/v1/apis/arvados/v1/rest'))['revision']
300       if rev >= '20010101' && rev < '20210503'
301         Rails.logger.warn "remote cluster #{upstream_cluster_id} at #{host} with api rev #{rev} does not provide token expiry and scopes; using scopes=['all']"
302       else
303         # remote server is new enough that it should have accepted
304         # this request if the token was valid
305         raise
306       end
307     rescue => e
308       Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
309       return nil
310     end
311
312     # Clusters can only authenticate for their own users.
313     if remote_user_prefix != upstream_cluster_id
314       Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
315       return nil
316     end
317
318     # Invariant:    remote_user_prefix == upstream_cluster_id
319     # therefore:    remote_user_prefix != Rails.configuration.ClusterID
320
321     # Add or update user and token in local database so we can
322     # validate subsequent requests faster.
323
324     if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
325       # Special case: map the remote anonymous user to local anonymous user
326       remote_user['uuid'] = anonymous_user_uuid
327     end
328
329     user = User.find_by_uuid(remote_user['uuid'])
330
331     if !user
332       # Create a new record for this user.
333       user = User.new(uuid: remote_user['uuid'],
334                       is_active: false,
335                       is_admin: false,
336                       email: remote_user['email'],
337                       owner_uuid: system_user_uuid)
338       user.set_initial_username(requested: remote_user['username'])
339     end
340
341     # Sync user record.
342     act_as_system_user do
343       %w[first_name last_name email prefs].each do |attr|
344         user.send(attr+'=', remote_user[attr])
345       end
346
347       if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
348         user.first_name = "root"
349         user.last_name = "from cluster #{remote_user_prefix}"
350       end
351
352       begin
353         user.save!
354       rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
355         Rails.logger.debug("remote user #{remote_user['uuid']} already exists, retrying...")
356         # Some other request won the race: retry fetching the user record.
357         user = User.find_by_uuid(remote_user['uuid'])
358         if !user
359           Rails.logger.warn("cannot find or create remote user #{remote_user['uuid']}")
360           return nil
361         end
362       end
363
364       if user.is_invited && !remote_user['is_invited']
365         # Remote user is not "invited" state, they should be unsetup, which
366         # also makes them inactive.
367         user.unsetup
368       else
369         if !user.is_invited && remote_user['is_invited'] and
370           (remote_user_prefix == Rails.configuration.Login.LoginCluster or
371            Rails.configuration.Users.AutoSetupNewUsers or
372            Rails.configuration.Users.NewUsersAreActive or
373            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
374           user.setup
375         end
376
377         if !user.is_active && remote_user['is_active'] && user.is_invited and
378           (remote_user_prefix == Rails.configuration.Login.LoginCluster or
379            Rails.configuration.Users.NewUsersAreActive or
380            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
381           user.update_attributes!(is_active: true)
382         elsif user.is_active && !remote_user['is_active']
383           user.update_attributes!(is_active: false)
384         end
385
386         if remote_user_prefix == Rails.configuration.Login.LoginCluster and
387           user.is_active and
388           user.is_admin != remote_user['is_admin']
389           # Remote cluster controls our user database, including the
390           # admin flag.
391           user.update_attributes!(is_admin: remote_user['is_admin'])
392         end
393       end
394
395       # If stored_secret is set, we save stored_secret in the database
396       # but return the real secret to the caller. This way, if we end
397       # up returning the auth record to the client, they see the same
398       # secret they supplied, instead of the HMAC we saved in the
399       # database.
400       stored_secret = stored_secret || secret
401
402       # We will accept this token (and avoid reloading the user
403       # record) for 'RemoteTokenRefresh' (default 5 minutes).
404       exp = [db_current_time + Rails.configuration.Login.RemoteTokenRefresh,
405              remote_token.andand['expires_at']].compact.min
406       scopes = remote_token.andand['scopes'] || ['all']
407       begin
408         retries ||= 0
409         auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
410           auth.user = user
411           auth.api_token = stored_secret
412           auth.api_client_id = 0
413           auth.scopes = scopes
414           auth.expires_at = exp
415         end
416       rescue ActiveRecord::RecordNotUnique
417         Rails.logger.debug("cached remote token #{token_uuid} already exists, retrying...")
418         # Some other request won the race: retry just once before erroring out
419         if (retries += 1) <= 1
420           retry
421         else
422           Rails.logger.warn("cannot find or create cached remote token #{token_uuid}")
423           return nil
424         end
425       end
426       auth.update_attributes!(user: user,
427                               api_token: stored_secret,
428                               api_client_id: 0,
429                               scopes: scopes,
430                               expires_at: exp)
431       Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} and scopes #{scopes} in local db"
432       auth.api_token = secret
433       return auth
434     end
435
436     return nil
437   end
438
439   def token
440     v2token
441   end
442
443   def v1token
444     api_token
445   end
446
447   def v2token
448     'v2/' + uuid + '/' + api_token
449   end
450
451   def salted_token(remote:)
452     if remote.nil?
453       token
454     end
455     'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
456   end
457
458   protected
459
460   def clamp_token_expiration
461     if Rails.configuration.API.MaxTokenLifetime > 0
462       max_token_expiration = db_current_time + Rails.configuration.API.MaxTokenLifetime
463       if (self.new_record? || self.expires_at_changed?) && (self.expires_at.nil? || (self.expires_at > max_token_expiration && !current_user.andand.is_admin))
464         self.expires_at = max_token_expiration
465       end
466     end
467   end
468
469   def permission_to_create
470     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
471   end
472
473   def permission_to_update
474     permission_to_create && !uuid_changed? &&
475       (current_user.andand.is_admin || !user_id_changed?)
476   end
477
478   def log_update
479     super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?
480   end
481 end