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