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