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