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