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