868405f043a6fcd25adfa437f8ca17ecc909822c
[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     optional = nil
134
135     case token[0..2]
136     when 'v2/'
137       _, token_uuid, secret, optional = token.split('/')
138       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
139         return nil
140       end
141
142       if !optional.nil?
143         # if "optional" is a container uuid, check that it
144         # matches expections.
145         c = Container.where(uuid: optional).first
146         if !c.nil?
147           if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
148             # token doesn't match the container's token
149             return nil
150           end
151           if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
152             # token doesn't match the container's token
153             return nil
154           end
155           if ![Container::Locked, Container::Running].include?(c.state)
156             # container isn't locked or running, token shouldn't be used
157             return nil
158           end
159         end
160       end
161
162       # fast path: look up the token in the local database
163       auth = ApiClientAuthorization.
164              includes(:user, :api_client).
165              where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
166              first
167       if auth && auth.user &&
168          (secret == auth.api_token ||
169           secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
170         # found it
171         if token_uuid[0..4] != Rails.configuration.ClusterID
172           Rails.logger.debug "found cached remote token #{token_uuid} with secret #{secret} in local db"
173         end
174         return auth
175       end
176
177       upstream_cluster_id = token_uuid[0..4]
178       if upstream_cluster_id == Rails.configuration.ClusterID
179         # Token is supposedly issued by local cluster, but if the
180         # token were valid, we would have been found in the database
181         # in the above query.
182         return nil
183       elsif upstream_cluster_id.length != 5
184         # malformed
185         return nil
186       end
187
188     else
189       # token is not a 'v2' token
190       auth = ApiClientAuthorization.
191                includes(:user, :api_client).
192                where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token).
193                first
194       if auth && auth.user
195         return auth
196       elsif Rails.configuration.Login.LoginCluster && Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
197         # An unrecognized non-v2 token might be an OIDC Access Token
198         # that can be verified by our login cluster in the code below.
199         upstream_cluster_id = Rails.configuration.Login.LoginCluster
200       else
201         return nil
202       end
203     end
204
205     # Invariant: upstream_cluster_id != Rails.configuration.ClusterID
206     #
207     # In other words the remaining code in this method decides
208     # whether to accept a token that was issued by a remote cluster
209     # when the token is absent or expired in our database.  To
210     # begin, we need to ask the cluster that issued the token to
211     # [re]validate it.
212     clnt = ApiClientAuthorization.make_http_client(uuid_prefix: upstream_cluster_id)
213
214     host = remote_host(uuid_prefix: upstream_cluster_id)
215     if !host
216       Rails.logger.warn "remote authentication rejected: no host for #{upstream_cluster_id.inspect}"
217       return nil
218     end
219
220     begin
221       remote_user = SafeJSON.load(
222         clnt.get_content('https://' + host + '/arvados/v1/users/current',
223                          {'remote' => Rails.configuration.ClusterID},
224                          {'Authorization' => 'Bearer ' + token}))
225     rescue => e
226       Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
227       return nil
228     end
229
230     # Check the response is well formed.
231     if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
232       Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
233       return nil
234     end
235
236     remote_user_prefix = remote_user['uuid'][0..4]
237
238     # Clusters can only authenticate for their own users.
239     if remote_user_prefix != upstream_cluster_id
240       Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{upstream_cluster_id}"
241       return nil
242     end
243
244     # Invariant:    remote_user_prefix == upstream_cluster_id
245     # therefore:    remote_user_prefix != Rails.configuration.ClusterID
246
247     # Add or update user and token in local database so we can
248     # validate subsequent requests faster.
249
250     if remote_user['uuid'][-22..-1] == '-tpzed-anonymouspublic'
251       # Special case: map the remote anonymous user to local anonymous user
252       remote_user['uuid'] = anonymous_user_uuid
253     end
254
255     user = User.find_by_uuid(remote_user['uuid'])
256
257     if !user
258       # Create a new record for this user.
259       user = User.new(uuid: remote_user['uuid'],
260                       is_active: false,
261                       is_admin: false,
262                       email: remote_user['email'],
263                       owner_uuid: system_user_uuid)
264       user.set_initial_username(requested: remote_user['username'])
265     end
266
267     # Sync user record.
268     act_as_system_user do
269       %w[first_name last_name email prefs].each do |attr|
270         user.send(attr+'=', remote_user[attr])
271       end
272
273       if remote_user['uuid'][-22..-1] == '-tpzed-000000000000000'
274         user.first_name = "root"
275         user.last_name = "from cluster #{remote_user_prefix}"
276       end
277
278       user.save!
279
280       if user.is_invited && !remote_user['is_invited']
281         # Remote user is not "invited" state, they should be unsetup, which
282         # also makes them inactive.
283         user.unsetup
284       else
285         if !user.is_invited && remote_user['is_invited'] and
286           (remote_user_prefix == Rails.configuration.Login.LoginCluster or
287            Rails.configuration.Users.AutoSetupNewUsers or
288            Rails.configuration.Users.NewUsersAreActive or
289            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
290           user.setup
291         end
292
293         if !user.is_active && remote_user['is_active'] && user.is_invited and
294           (remote_user_prefix == Rails.configuration.Login.LoginCluster or
295            Rails.configuration.Users.NewUsersAreActive or
296            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
297           user.update_attributes!(is_active: true)
298         elsif user.is_active && !remote_user['is_active']
299           user.update_attributes!(is_active: false)
300         end
301
302         if remote_user_prefix == Rails.configuration.Login.LoginCluster and
303           user.is_active and
304           user.is_admin != remote_user['is_admin']
305           # Remote cluster controls our user database, including the
306           # admin flag.
307           user.update_attributes!(is_admin: remote_user['is_admin'])
308         end
309       end
310
311       # We will accept this token (and avoid reloading the user
312       # record) for 'RemoteTokenRefresh' (default 5 minutes).
313       # Possible todo:
314       # Request the actual api_client_auth record from the remote
315       # server in case it wants the token to expire sooner.
316       auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
317         auth.user = user
318         auth.api_client_id = 0
319       end
320       auth.update_attributes!(user: user,
321                               api_token: secret,
322                               api_client_id: 0,
323                               expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
324       Rails.logger.debug "cached remote token #{token_uuid} with secret #{secret} in local db"
325       return auth
326     end
327
328     return nil
329   end
330
331   def token
332     v2token
333   end
334
335   def v1token
336     api_token
337   end
338
339   def v2token
340     'v2/' + uuid + '/' + api_token
341   end
342
343   def salted_token(remote:)
344     if remote.nil?
345       token
346     end
347     'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
348   end
349
350   protected
351
352   def permission_to_create
353     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
354   end
355
356   def permission_to_update
357     permission_to_create && !uuid_changed? &&
358       (current_user.andand.is_admin || !user_id_changed?)
359   end
360
361   def log_update
362
363     super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?
364   end
365 end