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