20284: Fix test and update code comment.
[arvados.git] / services / api / app / controllers / arvados / v1 / users_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class Arvados::V1::UsersController < ApplicationController
6   accept_attribute_as_json :prefs, Hash
7   accept_param_as_json :updates
8
9   skip_before_action :find_object_by_uuid, only:
10     [:activate, :current, :system, :setup, :merge, :batch_update]
11   skip_before_action :render_404_if_no_object, only:
12     [:activate, :current, :system, :setup, :merge, :batch_update]
13   before_action :admin_required, only: [:setup, :unsetup, :batch_update]
14
15   # Internal API used by controller to update local cache of user
16   # records from LoginCluster.
17   def batch_update
18     @objects = []
19     params[:updates].andand.each do |uuid, attrs|
20       begin
21         u = User.find_or_create_by(uuid: uuid)
22       rescue ActiveRecord::RecordNotUnique
23         retry
24       end
25       needupdate = {}
26       nullify_attrs(attrs).each do |k,v|
27         if !v.nil? && u.send(k) != v
28           needupdate[k] = v
29         end
30       end
31       if needupdate.length > 0
32         begin
33           u.update!(needupdate)
34         rescue ActiveRecord::RecordInvalid
35           loginCluster = Rails.configuration.Login.LoginCluster
36           if u.uuid[0..4] == loginCluster && !needupdate[:username].nil?
37             local_user = User.find_by_username(needupdate[:username])
38             # The username of this record conflicts with an existing,
39             # different user record.  This can happen because the
40             # username changed upstream on the login cluster, or
41             # because we're federated with another cluster with a user
42             # by the same username.  The login cluster is the source
43             # of truth, so change the username on the conflicting
44             # record and retry the update operation.
45             if local_user.uuid != u.uuid
46               new_username = "#{needupdate[:username]}#{rand(99999999)}"
47               Rails.logger.warn("cached username '#{needupdate[:username]}' collision with user '#{local_user.uuid}' - renaming to '#{new_username}' before retrying")
48               local_user.update!({username: new_username})
49               retry
50             end
51           end
52           raise # Not the issue we're handling above
53         end
54       end
55       @objects << u
56     end
57     @offset = 0
58     @limit = -1
59     render_list
60   end
61
62   def current
63     if current_user
64       @object = current_user
65       show
66     else
67       send_error("Not logged in", status: 401)
68     end
69   end
70
71   def system
72     @object = system_user
73     show
74   end
75
76   def activate
77     if params[:id] and params[:id].match(/\D/)
78       params[:uuid] = params.delete :id
79     end
80     if current_user.andand.is_admin && params[:uuid]
81       @object = User.find_by_uuid params[:uuid]
82     else
83       @object = current_user
84     end
85     if not @object.is_active
86       if @object.uuid[0..4] == Rails.configuration.Login.LoginCluster &&
87          @object.uuid[0..4] != Rails.configuration.ClusterID
88         logger.warn "Local user #{@object.uuid} called users#activate but only LoginCluster can do that"
89         raise ArgumentError.new "cannot activate user #{@object.uuid} here, only the #{@object.uuid[0..4]} cluster can do that"
90       elsif not (current_user.is_admin or @object.is_invited)
91         logger.warn "User #{@object.uuid} called users.activate " +
92           "but is not invited"
93         raise ArgumentError.new "Cannot activate without being invited."
94       end
95       act_as_system_user do
96         required_uuids = Link.where("owner_uuid = ? and link_class = ? and name = ? and tail_uuid = ? and head_uuid like ?",
97                                     system_user_uuid,
98                                     'signature',
99                                     'require',
100                                     system_user_uuid,
101                                     Collection.uuid_like_pattern).
102           collect(&:head_uuid)
103         signed_uuids = Link.where(owner_uuid: system_user_uuid,
104                                   link_class: 'signature',
105                                   name: 'click',
106                                   tail_uuid: @object.uuid,
107                                   head_uuid: required_uuids).
108           collect(&:head_uuid)
109         todo_uuids = required_uuids - signed_uuids
110         if todo_uuids.empty?
111           @object.update is_active: true
112           logger.info "User #{@object.uuid} activated"
113         else
114           logger.warn "User #{@object.uuid} called users.activate " +
115             "before signing agreements #{todo_uuids.inspect}"
116           raise ArvadosModel::PermissionDeniedError.new \
117           "Cannot activate without user agreements #{todo_uuids.inspect}."
118         end
119       end
120     end
121     show
122   end
123
124   # create user object and all the needed links
125   def setup
126     if params[:uuid]
127       @object = User.find_by_uuid(params[:uuid])
128       if !@object
129         return render_404_if_no_object
130       end
131     elsif !params[:user] || params[:user].empty?
132       raise ArgumentError.new "Required uuid or user"
133     elsif !params[:user]['email']
134       raise ArgumentError.new "Require user email"
135     else
136       @object = model_class.create! resource_attrs
137     end
138
139     # It's not always possible for the client to know the user's
140     # username when submitting this request: the username might have
141     # been assigned automatically in create!() above. If client
142     # provided a plain repository name, prefix it with the username
143     # now that we know what it is.
144     if params[:repo_name].nil?
145       full_repo_name = nil
146     elsif @object.username.nil?
147       raise ArgumentError.
148         new("cannot setup a repository because user has no username")
149     elsif params[:repo_name].index("/")
150       full_repo_name = params[:repo_name]
151     else
152       full_repo_name = "#{@object.username}/#{params[:repo_name]}"
153     end
154
155     @response = @object.setup(repo_name: full_repo_name,
156                               vm_uuid: params[:vm_uuid],
157                               send_notification_email: params[:send_notification_email])
158
159     send_json kind: "arvados#HashList", items: @response.as_api_response(nil)
160   end
161
162   # delete user agreements, vm, repository, login links; set state to inactive
163   def unsetup
164     reload_object_before_update
165     @object.unsetup
166     show
167   end
168
169   def merge
170     if (params[:old_user_uuid] || params[:new_user_uuid])
171       if !current_user.andand.is_admin
172         return send_error("Must be admin to use old_user_uuid/new_user_uuid", status: 403)
173       end
174       if !params[:old_user_uuid] || !params[:new_user_uuid]
175         return send_error("Must supply both old_user_uuid and new_user_uuid", status: 422)
176       end
177       new_user = User.find_by_uuid(params[:new_user_uuid])
178       if !new_user
179         return send_error("User in new_user_uuid not found", status: 422)
180       end
181       @object = User.find_by_uuid(params[:old_user_uuid])
182       if !@object
183         return send_error("User in old_user_uuid not found", status: 422)
184       end
185     else
186       if !Thread.current[:api_client].andand.is_trusted
187         return send_error("supplied API token is not from a trusted client", status: 403)
188       elsif Thread.current[:api_client_authorization].scopes != ['all']
189         return send_error("cannot merge with a scoped token", status: 403)
190       end
191
192       new_auth = ApiClientAuthorization.validate(token: params[:new_user_token])
193       if !new_auth
194         return send_error("invalid new_user_token", status: 401)
195       end
196
197       if new_auth.user.uuid[0..4] == Rails.configuration.ClusterID
198         if !new_auth.api_client.andand.is_trusted
199           return send_error("supplied new_user_token is not from a trusted client", status: 403)
200         elsif new_auth.scopes != ['all']
201           return send_error("supplied new_user_token has restricted scope", status: 403)
202         end
203       end
204       new_user = new_auth.user
205       @object = current_user
206     end
207
208     if @object.uuid == new_user.uuid
209       return send_error("cannot merge user to self", status: 422)
210     end
211
212     if !params[:new_owner_uuid]
213       return send_error("missing new_owner_uuid", status: 422)
214     end
215
216     if !new_user.can?(write: params[:new_owner_uuid])
217       return send_error("cannot move objects into supplied new_owner_uuid: new user does not have write permission", status: 403)
218     end
219
220     act_as_system_user do
221       @object.merge(new_owner_uuid: params[:new_owner_uuid],
222                     new_user_uuid: new_user.uuid,
223                     redirect_to_new_user: params[:redirect_to_new_user])
224     end
225     show
226   end
227
228   protected
229
230   def self._merge_requires_parameters
231     {
232       new_owner_uuid: {
233         type: 'string', required: true,
234       },
235       new_user_token: {
236         type: 'string', required: false,
237       },
238       redirect_to_new_user: {
239         type: 'boolean', required: false, default: false,
240       },
241       old_user_uuid: {
242         type: 'string', required: false,
243       },
244       new_user_uuid: {
245         type: 'string', required: false,
246       }
247     }
248   end
249
250   def self._setup_requires_parameters
251     {
252       uuid: {
253         type: 'string', required: false,
254       },
255       user: {
256         type: 'object', required: false,
257       },
258       repo_name: {
259         type: 'string', required: false,
260       },
261       vm_uuid: {
262         type: 'string', required: false,
263       },
264       send_notification_email: {
265         type: 'boolean', required: false, default: false,
266       },
267     }
268   end
269
270   def self._update_requires_parameters
271     super.merge({
272       bypass_federation: {
273         type: 'boolean', required: false, default: false,
274       },
275     })
276   end
277
278   def apply_filters(model_class=nil)
279     return super if @read_users.any?(&:is_admin)
280     if params[:uuid] != current_user.andand.uuid
281       # Non-admin index/show returns very basic information about readable users.
282       safe_attrs = ["uuid", "is_active", "email", "first_name", "last_name", "username", "can_write", "can_manage", "kind"]
283       if @select
284         @select = @select & safe_attrs
285       else
286         @select = safe_attrs
287       end
288       @filters += [['is_active', '=', true]]
289     end
290     # This gets called from within find_object_by_uuid.
291     # find_object_by_uuid stores the original value of @select in
292     # @preserve_select, edits the value of @select, calls
293     # find_objects_for_index, then restores @select from the value
294     # of @preserve_select.  So if we want our updated value of
295     # @select here to stick, we have to set @preserve_select.
296     @preserve_select = @select
297     super
298   end
299
300   def nullable_attributes
301     super + [:email, :first_name, :last_name, :username]
302   end
303 end