Add 'sdk/java-v2/' from commit '55f103e336ca9fb8bf1720d2ef4ee8dd4e221118'
[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.remote_hosts[uuid_prefix] ||
91       (Rails.configuration.remote_hosts_via_dns &&
92        uuid_prefix+".arvadosapi.com")
93   end
94
95   def self.validate(token:, remote: nil)
96     return nil if !token
97     remote ||= Rails.configuration.uuid_prefix
98
99     case token[0..2]
100     when 'v2/'
101       _, uuid, secret, optional = token.split('/')
102       unless uuid.andand.length == 27 && secret.andand.length.andand > 0
103         return nil
104       end
105
106       if !optional.nil?
107         # if "optional" is a container uuid, check that it
108         # matches expections.
109         c = Container.where(uuid: optional).first
110         if !c.nil?
111           if !c.auth_uuid.nil? and c.auth_uuid != uuid
112             # token doesn't match the container's token
113             return nil
114           end
115           if !c.runtime_token.nil? and "v2/#{uuid}/#{secret}" != c.runtime_token
116             # token doesn't match the container's token
117             return nil
118           end
119           if ![Container::Locked, Container::Running].include?(c.state)
120             # container isn't locked or running, token shouldn't be used
121             return nil
122           end
123         end
124       end
125
126       auth = ApiClientAuthorization.
127              includes(:user, :api_client).
128              where('uuid=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', uuid).
129              first
130       if auth && auth.user &&
131          (secret == auth.api_token ||
132           secret == OpenSSL::HMAC.hexdigest('sha1', auth.api_token, remote))
133         return auth
134       end
135
136       uuid_prefix = uuid[0..4]
137       if uuid_prefix == Rails.configuration.uuid_prefix
138         # If the token were valid, we would have validated it above
139         return nil
140       elsif uuid_prefix.length != 5
141         # malformed
142         return nil
143       end
144
145       host = remote_host(uuid_prefix: uuid_prefix)
146       if !host
147         Rails.logger.warn "remote authentication rejected: no host for #{uuid_prefix.inspect}"
148         return nil
149       end
150
151       # Token was issued by a different cluster. If it's expired or
152       # missing in our database, ask the originating cluster to
153       # [re]validate it.
154       begin
155         clnt = HTTPClient.new
156         if Rails.configuration.sso_insecure
157           clnt.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
158         else
159           # Use system CA certificates
160           ["/etc/ssl/certs/ca-certificates.crt",
161            "/etc/pki/tls/certs/ca-bundle.crt"]
162             .select { |ca_path| File.readable?(ca_path) }
163             .each { |ca_path| clnt.ssl_config.add_trust_ca(ca_path) }
164         end
165         remote_user = SafeJSON.load(
166           clnt.get_content('https://' + host + '/arvados/v1/users/current',
167                            {'remote' => Rails.configuration.uuid_prefix},
168                            {'Authorization' => 'Bearer ' + token}))
169       rescue => e
170         Rails.logger.warn "remote authentication with token #{token.inspect} failed: #{e}"
171         return nil
172       end
173       if !remote_user.is_a?(Hash) || !remote_user['uuid'].is_a?(String) || remote_user['uuid'][0..4] != uuid[0..4]
174         Rails.logger.warn "remote authentication rejected: remote_user=#{remote_user.inspect}"
175         return nil
176       end
177       act_as_system_user do
178         # Add/update user and token in our database so we can
179         # validate subsequent requests faster.
180
181         user = User.find_or_create_by(uuid: remote_user['uuid']) do |user|
182           # (this block runs for the "create" case, not for "find")
183           user.is_admin = false
184           user.email = remote_user['email']
185           if remote_user['username'].andand.length.andand > 0
186             user.set_initial_username(requested: remote_user['username'])
187           end
188         end
189
190         if Rails.configuration.new_users_are_active ||
191            Rails.configuration.auto_activate_users_from.include?(remote_user['uuid'][0..4])
192           # Update is_active to whatever it is at the remote end
193           user.is_active = remote_user['is_active']
194         elsif !remote_user['is_active']
195           # Remote user is inactive; our mirror should be, too.
196           user.is_active = false
197         end
198
199         %w[first_name last_name email prefs].each do |attr|
200           user.send(attr+'=', remote_user[attr])
201         end
202
203         user.save!
204
205         auth = ApiClientAuthorization.find_or_create_by(uuid: uuid) do |auth|
206           auth.user = user
207           auth.api_token = secret
208           auth.api_client_id = 0
209         end
210
211         # Accept this token (and don't reload the user record) for
212         # 5 minutes. TODO: Request the actual api_client_auth
213         # record from the remote server in case it wants the token
214         # to expire sooner.
215         auth.update_attributes!(user: user,
216                                 api_token: secret,
217                                 api_client_id: 0,
218                                 expires_at: Time.now + 5.minutes)
219       end
220       return auth
221     else
222       auth = ApiClientAuthorization.
223              includes(:user, :api_client).
224              where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', token).
225              first
226       if auth && auth.user
227         return auth
228       end
229     end
230     return nil
231   end
232
233   def token
234     v2token
235   end
236
237   def v1token
238     api_token
239   end
240
241   def v2token
242     'v2/' + uuid + '/' + api_token
243   end
244
245   def salted_token(remote:)
246     if remote.nil?
247       token
248     end
249     'v2/' + uuid + '/' + OpenSSL::HMAC.hexdigest('sha1', api_token, remote)
250   end
251
252   protected
253
254   def permission_to_create
255     current_user.andand.is_admin or (current_user.andand.id == self.user_id)
256   end
257
258   def permission_to_update
259     permission_to_create && !uuid_changed? &&
260       (current_user.andand.is_admin || !user_id_changed?)
261   end
262
263   def log_update
264     super unless (changed - UNLOGGED_CHANGES).empty?
265   end
266 end