4218645d5daf3014369f693ea7faa68fed9546dd
[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
11   belongs_to :api_client
12   belongs_to :user
13   after_initialize :assign_random_api_token
14   serialize :scopes, Array
15
16   before_validation :clamp_token_expiration
17
18   api_accessible :user, extend: :common do |t|
19     t.add :owner_uuid
20     t.add :user_id
21     t.add :api_client_id
22     # NB the "api_token" db column is a misnomer in that it's only the
23     # "secret" part of a token: a v1 token is just the secret, but a
24     # v2 token is "v2/uuid/secret".
25     t.add :api_token
26     t.add :created_by_ip_address
27     t.add :default_owner_uuid
28     t.add :expires_at
29     t.add :last_used_at
30     t.add :last_used_by_ip_address
31     t.add :scopes
32   end
33
34   UNLOGGED_CHANGES = ['last_used_at', 'last_used_by_ip_address', 'updated_at']
35
36   def assign_random_api_token
37     self.api_token ||= rand(2**256).to_s(36)
38   end
39
40   def owner_uuid
41     self.user.andand.uuid
42   end
43   def owner_uuid_was
44     self.user_id_changed? ? User.where(id: self.user_id_was).first.andand.uuid : self.user.andand.uuid
45   end
46   def owner_uuid_changed?
47     self.user_id_changed?
48   end
49
50   def modified_by_client_uuid
51     nil
52   end
53   def modified_by_client_uuid=(x) end
54
55   def modified_by_user_uuid
56     nil
57   end
58   def modified_by_user_uuid=(x) end
59
60   def modified_at
61     nil
62   end
63   def modified_at=(x) end
64
65   def scopes_allow?(req_s)
66     scopes.each do |scope|
67       return true if (scope == 'all') or (scope == req_s) or
68         ((scope.end_with? '/') and (req_s.start_with? scope))
69     end
70     false
71   end
72
73   def scopes_allow_request?(request)
74     method = request.request_method
75     if method == 'HEAD'
76       (scopes_allow?(['HEAD', request.path].join(' ')) ||
77        scopes_allow?(['GET', request.path].join(' ')))
78     else
79       scopes_allow?([method, request.path].join(' '))
80     end
81   end
82
83   def logged_attributes
84     super.except 'api_token'
85   end
86
87   def self.default_orders
88     ["#{table_name}.id desc"]
89   end
90
91   def self.remote_host(uuid_prefix:)
92     (Rails.configuration.RemoteClusters[uuid_prefix].andand["Host"]) ||
93       (Rails.configuration.RemoteClusters["*"]["Proxy"] &&
94        uuid_prefix+".arvadosapi.com")
95   end
96
97   def self.make_http_client(uuid_prefix:)
98     clnt = HTTPClient.new
99
100     if uuid_prefix && (Rails.configuration.RemoteClusters[uuid_prefix].andand.Insecure ||
101                        Rails.configuration.RemoteClusters['*'].andand.Insecure)
102       clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
103     else
104       # Use system CA certificates
105       ["/etc/ssl/certs/ca-certificates.crt",
106        "/etc/pki/tls/certs/ca-bundle.crt"]
107         .select { |ca_path| File.readable?(ca_path) }
108         .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
109     end
110     clnt
111   end
112
113   def self.check_system_root_token token
114     if token == Rails.configuration.SystemRootToken
115       return ApiClientAuthorization.new(user: User.find_by_uuid(system_user_uuid),
116                                         uuid: Rails.configuration.ClusterID+"-gj3su-000000000000000",
117                                         api_token: token,
118                                         api_client: system_root_token_api_client)
119     else
120       return nil
121     end
122   end
123
124   def self.validate(token:, remote: nil)
125     return nil if token.nil? or token.empty?
126     remote ||= Rails.configuration.ClusterID
127
128     auth = self.check_system_root_token(token)
129     if !auth.nil?
130       return auth
131     end
132
133     token_uuid = ''
134     secret = token
135     stored_secret = nil         # ...if different from secret
136     optional = nil
137
138     case token[0..2]
139     when 'v2/'
140       _, token_uuid, secret, optional = token.split('/')
141       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
142         return nil
143       end
144
145       if !optional.nil?
146         # if "optional" is a container uuid, check that it
147         # matches expections.
148         c = Container.where(uuid: optional).first
149         if !c.nil?
150           if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
151             # token doesn't match the container's token
152             return nil
153           end
154           if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
155             # token doesn't match the container's token
156             return nil
157           end
158           if ![Container::Locked, Container::Running].include?(c.state)
159             # container isn't locked or running, token shouldn't be used
160             return nil
161           end
162         end
163       end
164
165       # fast path: look up the token in the local database
166       auth = ApiClientAuthorization.
167              includes(:user, :api_client).
168              where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
169              first
170       if auth && auth.user &&
171          (secret == auth.api_token ||
172           secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
173         # found it
174         if token_uuid[0..4] != Rails.configuration.ClusterID
175           Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
176         end
177         return auth
178       end
179
180       upstream_cluster_id = token_uuid[0..4]
181       if upstream_cluster_id == Rails.configuration.ClusterID
182         # Token is supposedly issued by local cluster, but if the
183         # token were valid, we would have been found in the database
184         # in the above query.
185         return nil
186       elsif upstream_cluster_id.length != 5
187         # malformed
188         return nil
189       end
190
191     else
192       # token is not a 'v2' token. It could be just the secret part
193       # ("v1 token") -- or it could be an OpenIDConnect access token,
194       # in which case either (a) the controller will have inserted a
195       # row with api_token = hmac(systemroottoken,oidctoken) before
196       # forwarding it, or (b) we'll have done that ourselves, or (c)
197       # we'll need to ask LoginCluster to validate it for us below,
198       # and then insert a local row for a faster lookup next time.
199       hmac = OpenSSL::HMAC.hexdigest('sha256', Rails.configuration.SystemRootToken, token)
200       auth = ApiClientAuthorization.
201                includes(:user, :api_client).
202                where('api_token in (?, ?) and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token, hmac).
203                first
204       if auth && auth.user
205         return auth
206       elsif !Rails.configuration.Login.LoginCluster.blank? && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
207         # An unrecognized non-v2 token might be an OIDC Access Token
208         # that can be verified by our login cluster in the code
209         # below. If so, we'll stuff the database with hmac instead of
210         # the real OIDC token.
211         upstream_cluster_id = Rails.configuration.Login.LoginCluster
212         stored_secret = hmac
213       else
214         return nil
215       end
216     end
217
218     # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
219     #
220     # In other words the remaining code in this method decides
221     # whether to accept a token that was issued by a remote cluster
222     # when the token is absent or expired in our database.  To
223     # begin, we need to ask the cluster that issued the token to
224     # [re]validate it.
225     clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
226
227     host = remote_host(uuid_prefix: upstream_cluster_id)
228     if !host
229       Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
230       return nil
231     end
232
233     begin
234       remote_user = SafeJSON.load(
235         clnt.get_content('https://' + host + '/arvados/v1/users/current',
236                          {'remote' => Rails.configuration.ClusterID},
237                          {'Authorization' => 'Bearer ' + token}))
238     rescue => e
239       Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
240       return nil
241     end
242
243     # Check the response is well formed.
244     if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
245       Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
246       return nil
247     end
248
249     remote_user_prefix = remote_user['uuid'][0..4]
250
251     if token_uuid == ''
252       # Use the same UUID as the remote when caching the token.
253       begin
254         remote_token = SafeJSON.load(
255           clnt.get_content('https://' + host + '/arvados/v1/api_client_authorizations/current',
256                            {'remote' => Rails.configuration.ClusterID},
257                            {'Authorization' => 'Bearer ' + token}))
258         token_uuid = remote_token['uuid']
259         if !token_uuid.match(HasUuid::UUID_REGEX) || token_uuid[0..4] != upstream_cluster_id
260           raise "remote cluster #{upstream_cluster_id} returned invalid token uuid #{token_uuid.inspect}"
261         end
262       rescue => e
263         Rails.logger.warn "error getting remote token details for #{token.inspect}: #{e}"
264         return nil
265       end
266     end
267
268     # Clusters can only authenticate for their own users.
269     if remote_user_prefix != upstream_cluster_id
270       Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
271       return nil
272     end
273
274     # Invariant:    remote_user_prefix == upstream_cluster_id
275     # therefore:    remote_user_prefix != Rails.configuration.ClusterID
276
277     # Add or update user and token in local database so we can
278     # validate subsequent requests faster.
279
280     if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
281       # Special case: map the remote anonymous user to local anonymous user
282       remote_user['uuid'] = anonymous_user_uuid
283     end
284
285     user = User.find_by_uuid(remote_user['uuid'])
286
287     if !user
288       # Create a new record for this user.
289       user = User.new(uuid: remote_user['uuid'],
290                       is_active: false,
291                       is_admin: false,
292                       email: remote_user['email'],
293                       owner_uuid: system_user_uuid)
294       user.set_initial_username(requested: remote_user['username'])
295     end
296
297     # Sync user record.
298     act_as_system_user do
299       %w[first_name last_name email prefs].each do |attr|
300         user.send(attr+'=', remote_user[attr])
301       end
302
303       if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
304         user.first_name = "root"
305         user.last_name = "from cluster #{remote_user_prefix}"
306       end
307
308       user.save!
309
310       if user.is_invited && !remote_user['is_invited']
311         # Remote user is not "invited" state, they should be unsetup, which
312         # also makes them inactive.
313         user.unsetup
314       else
315         if !user.is_invited && remote_user['is_invited'] and
316           (remote_user_prefix == Rails.configuration.Login.LoginCluster or
317            Rails.configuration.Users.AutoSetupNewUsers or
318            Rails.configuration.Users.NewUsersAreActive or
319            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
320           user.setup
321         end
322
323         if !user.is_active && remote_user['is_active'] && user.is_invited and
324           (remote_user_prefix == Rails.configuration.Login.LoginCluster or
325            Rails.configuration.Users.NewUsersAreActive or
326            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
327           user.update_attributes!(is_active: true)
328         elsif user.is_active && !remote_user['is_active']
329           user.update_attributes!(is_active: false)
330         end
331
332         if remote_user_prefix == Rails.configuration.Login.LoginCluster and
333           user.is_active and
334           user.is_admin != remote_user['is_admin']
335           # Remote cluster controls our user database, including the
336           # admin flag.
337           user.update_attributes!(is_admin: remote_user['is_admin'])
338         end
339       end
340
341       # We will accept this token (and avoid reloading the user
342       # record) for 'RemoteTokenRefresh' (default 5 minutes).
343       # Possible todo:
344       # Request the actual api_client_auth record from the remote
345       # server in case it wants the token to expire sooner.
346       auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
347         auth.user = user
348         auth.api_client_id = 0
349       end
350       # If stored_secret is set, we save stored_secret in the database
351       # but return the real secret to the caller. This way, if we end
352       # up returning the auth record to the client, they see the same
353       # secret they supplied, instead of the HMAC we saved in the
354       # database.
355       stored_secret = stored_secret || secret
356       auth.update_attributes!(user: user,
357                               api_token: stored_secret,
358                               api_client_id: 0,
359                               expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
360       Rails.logger.debug "cached remote token #{token_uuid} with secret #{stored_secret} in local db"
361       auth.api_token = secret
362       return auth
363     end
364
365     return nil
366   end
367
368   def token
369     v2token
370   end
371
372   def v1token
373     api_token
374   end
375
376   def v2token
377     'v2/' + uuid + '/' + api_token
378   end
379
380   def salted_token(remote:)
381     if remote.nil?
382       token
383     end
384     'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
385   end
386
387   protected
388
389   def clamp_token_expiration
390     if !current_user.andand.is_admin && Rails.configuration.API.MaxTokenLifetime > 0
391       max_token_expiration = Time.now + Rails.configuration.API.MaxTokenLifetime
392       if self.new_record? && (self.expires_at.nil? || self.expires_at > max_token_expiration)
393         self.expires_at = max_token_expiration
394       elsif !self.new_record? && self.expires_at_changed? && (self.expires_at.nil? || self.expires_at > max_token_expiration)
395         self.expires_at = max_token_expiration
396       end
397     end
398   end
399
400   def permission_to_create
401     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
402   end
403
404   def permission_to_update
405     permission_to_create && !uuid_changed? &&
406       (current_user.andand.is_admin || !user_id_changed?)
407   end
408
409   def log_update
410     super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?
411   end
412 end