15529: Support for LoginCluster and RemoteTokenRefresh
[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
96     clnt = HTTPClient.new
97     if Rails.configuration.TLS.Insecure
98       clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
99     else
100       # Use system CA certificates
101       ["/etc/ssl/certs/ca-certificates.crt",
102        "/etc/pki/tls/certs/ca-bundle.crt"]
103         .select { |ca_path| File.readable?(ca_path) }
104         .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
105     end
106     clnt
107   end
108
109   def self.validate(token:, remote: nil)
110     return nil if !token
111     remote ||= Rails.configuration.ClusterID
112
113     case token[0..2]
114     when 'v2/'
115       _, token_uuid, secret, optional = token.split('/')
116       unless token_uuid.andand.length == 27 && secret.andand.length.andand > 0
117         return nil
118       end
119
120       if !optional.nil?
121         # if "optional" is a container uuid, check that it
122         # matches expections.
123         c = Container.where(uuid: optional).first
124         if !c.nil?
125           if !c.auth_uuid.nil? and c.auth_uuid != token_uuid
126             # token doesn't match the container's token
127             return nil
128           end
129           if !c.runtime_token.nil? and "v2/#{token_uuid}/#{secret}" != c.runtime_token
130             # token doesn't match the container's token
131             return nil
132           end
133           if ![Container::Locked, Container::Running].include?(c.state)
134             # container isn't locked or running, token shouldn't be used
135             return nil
136           end
137         end
138       end
139
140       # fast path: look up the token in the local database
141       auth = ApiClientAuthorization.
142              includes(:user, :api_client).
143              where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token_uuid).
144              first
145       if auth && auth.user &&
146          (secret == auth.api_token ||
147           secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
148         # found it
149         return auth
150       end
151
152       token_uuid_prefix = token_uuid[0..4]
153       if token_uuid_prefix == Rails.configuration.ClusterID
154         # Token is supposedly issued by local cluster, but if the
155         # token were valid, we would have been found in the database
156         # in the above query.
157         return nil
158       elsif token_uuid_prefix.length != 5
159         # malformed
160         return nil
161       end
162
163       # Invarient: token_uuid_prefix != Rails.configuration.ClusterID
164       #
165       # In other words the remaing code in this method below is the
166       # case that determines whether to accept a token that was issued
167       # by a remote cluster when the token absent or expired in our
168       # database.  To begin, we need to ask the cluster that issued
169       # the token to [re]validate it.
170       clnt = ApiClientAuthorization.make_http_client
171
172       host = remote_host(uuid_prefix: token_uuid_prefix)
173       if !host
174         Rails.logger.warn "remote authentication rejected: no host for #{token_uuid_prefix.inspect}"
175         return nil
176       end
177
178       begin
179         remote_user = SafeJSON.load(
180           clnt.get_content('https://' + host + '/arvados/v1/users/current',
181                            {'remote' => Rails.configuration.ClusterID},
182                            {'Authorization' => 'Bearer ' + token}))
183       rescue => e
184         Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
185         return nil
186       end
187
188       # Check the response is well formed.
189       if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String)
190         Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
191         return nil
192       end
193
194       remote_user_prefix = remote_user['uuid'][0..4]
195
196       # Clusters can only authenticate for their own users.
197       if remote_user_prefix != token_uuid_prefix
198         Rails.logger.warn "remote authentication rejected: claimed remote user #{remote_user_prefix} but token was issued by #{token_uuid_prefix}"
199         return nil
200       end
201
202       # Invarient:    remote_user_prefix == token_uuid_prefix
203       # therefore:    remote_user_prefix != Rails.configuration.ClusterID
204
205       # Add or update user and token in local database so we can
206       # validate subsequent requests faster.
207
208       user = User.find_by_uuid(remote_user['uuid'])
209
210       if !user
211         # Create a new record for this user.
212         user = User.new(uuid: remote_user['uuid'],
213                         is_active: false,
214                         is_admin: false,
215                         email: remote_user['email'],
216                         owner_uuid: system_user_uuid)
217         user.set_initial_username(requested: remote_user['username'])
218       end
219
220       # Sync user record.
221       if remote_user_prefix == Rails.configuration.Login.LoginCluster
222         # Remote cluster controls our user database, copy both
223         # 'is_active' and 'is_admin'
224         user.is_active = remote_user['is_active']
225         user.is_admin = remote_user['is_admin']
226       else
227         if Rails.configuration.Users.NewUsersAreActive ||
228            Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"]
229           # Default policy is to activate users, so match activate
230           # with the remote record.
231           user.is_active = remote_user['is_active']
232         elsif !remote_user['is_active']
233           # Deactivate user if the remote is inactive, otherwise don't
234           # change 'is_active'.
235           user.is_active = false
236         end
237       end
238
239       %w[first_name last_name email prefs].each do |attr|
240         user.send(attr+'=', remote_user[attr])
241       end
242
243       act_as_system_user do
244         user.save!
245
246         # We will accept this token (and avoid reloading the user
247         # record) for 'RemoteTokenRefresh' (default 5 minutes).
248         # Possible todo:
249         # Request the actual api_client_auth record from the remote
250         # server in case it wants the token to expire sooner.
251         auth = ApiClientAuthorization.find_or_create_by(uuid: token_uuid) do |auth|
252           auth.user = user
253           auth.api_client_id = 0
254         end
255         auth.update_attributes!(user: user,
256                                 api_token: secret,
257                                 api_client_id: 0,
258                                 expires_at: Time.now + Rails.configuration.Login.RemoteTokenRefresh)
259       end
260       return auth
261     else
262       # token is not a 'v2' token
263       auth = ApiClientAuthorization.
264                includes(:user, :api_client).
265                where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token).
266                first
267       if auth && auth.user
268         return auth
269       end
270     end
271
272     return nil
273   end
274
275   def token
276     v2token
277   end
278
279   def v1token
280     api_token
281   end
282
283   def v2token
284     'v2/' + uuid + '/' + api_token
285   end
286
287   def salted_token(remote:)
288     if remote.nil?
289       token
290     end
291     'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
292   end
293
294   protected
295
296   def permission_to_create
297     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
298   end
299
300   def permission_to_update
301     permission_to_create && !uuid_changed? &&
302       (current_user.andand.is_admin || !user_id_changed?)
303   end
304
305   def log_update
306     super unless (changed - UNLOGGED_CHANGES).empty?
307   end
308 end