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