1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'can_be_an_owner'
7 class User < ArvadosModel
10 include CommonApiTemplate
12 extend CurrentApiClient
14 serialize :prefs, Hash
15 has_many :api_client_authorizations
18 with: /\A[A-Za-z][A-Za-z0-9]*\z/,
19 message: "must begin with a letter and contain only alphanumerics",
23 validate :must_unsetup_to_deactivate
24 validate :identity_url_nil_if_empty
25 before_update :prevent_privilege_escalation
26 before_update :prevent_inactive_admin
27 before_update :verify_repositories_empty, :if => Proc.new {
28 username.nil? and username_changed?
30 after_update :setup_on_activate
32 before_create :check_auto_admin
33 before_create :set_initial_username, :if => Proc.new {
34 username.nil? and email
36 after_create :after_ownership_change
37 after_create :setup_on_activate
38 after_create :add_system_group_permission_link
39 after_create :auto_setup_new_user, :if => Proc.new {
40 Rails.configuration.Users.AutoSetupNewUsers and
41 (uuid != system_user_uuid) and
42 (uuid != anonymous_user_uuid) and
43 (uuid[0..4] == Rails.configuration.ClusterID)
45 after_create :send_admin_notifications
47 before_update :before_ownership_change
48 after_update :after_ownership_change
49 after_update :send_profile_created_notification
50 after_update :sync_repository_names, :if => Proc.new {
51 (uuid != system_user_uuid) and
52 saved_change_to_username? and
53 (not username_before_last_save.nil?)
55 before_destroy :clear_permissions
56 after_destroy :remove_self_from_permissions
58 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
59 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
61 default_scope { where('redirect_to_user_uuid is null') }
63 api_accessible :user, extend: :common do |t|
79 ALL_PERMISSIONS = {read: true, write: true, manage: true}
81 # Map numeric permission levels (see lib/create_permission_view.sql)
82 # back to read/write/manage flags.
86 {read: true, write: true},
87 {read: true, write: true, manage: true}]
97 "#{first_name} #{last_name}".strip
102 Rails.configuration.Users.NewUsersAreActive ||
103 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
106 def groups_i_can(verb)
107 my_groups = self.group_permissions(VAL_FOR_PERM[verb]).keys
109 my_groups << anonymous_group_uuid
115 return true if is_admin
116 actions.each do |action, target|
118 if target.respond_to? :uuid
119 target_uuid = target.uuid
122 target = ArvadosModel.find_by_uuid(target_uuid)
125 next if target_uuid == self.uuid
127 target_owner_uuid = target.owner_uuid if target.respond_to? :owner_uuid
129 user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: "$1", perm_level: "$3"}
131 unless ActiveRecord::Base.connection.
133 SELECT 1 FROM #{PERMISSION_VIEW}
134 WHERE user_uuid in (#{user_uuids_subquery}) and
135 ((target_uuid = $2 and perm_level >= $3)
136 or (target_uuid = $4 and perm_level >= $3 and traverse_owned))
138 # "name" arg is a query label that appears in logs:
142 [nil, VAL_FOR_PERM[action]],
143 [nil, target_owner_uuid]]
149 if FrozenGroup.where(uuid: [target_uuid, target_owner_uuid]).any?
150 # self or parent is frozen
153 elsif action == :unfreeze
154 # "unfreeze" permission means "can write, but only if
155 # explicitly un-freezing at the same time" (see
156 # ArvadosModel#ensure_owner_uuid_is_permitted). If the
157 # permission query above passed the permission level of
158 # :unfreeze (which is the same as :manage), and the parent
159 # isn't also frozen, then un-freeze is allowed.
160 if FrozenGroup.where(uuid: target_owner_uuid).any?
168 def before_ownership_change
169 if owner_uuid_changed? and !self.owner_uuid_was.nil?
170 MaterializedPermission.where(user_uuid: owner_uuid_was, target_uuid: uuid).delete_all
171 update_permissions self.owner_uuid_was, self.uuid, REVOKE_PERM
175 def after_ownership_change
176 if saved_change_to_owner_uuid?
177 update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM
181 def clear_permissions
182 MaterializedPermission.where("user_uuid = ? and target_uuid != ?", uuid, uuid).delete_all
185 def forget_cached_group_perms
189 def remove_self_from_permissions
190 MaterializedPermission.where("target_uuid = ?", uuid).delete_all
191 check_permissions_against_full_refresh
194 # Return a hash of {user_uuid: group_perms}
196 # note: this does not account for permissions that a user gains by
197 # having can_manage on another user.
198 def self.all_group_permissions
200 ActiveRecord::Base.connection.
202 SELECT user_uuid, target_uuid, perm_level
203 FROM #{PERMISSION_VIEW}
206 # "name" arg is a query label that appears in logs:
207 "all_group_permissions").
208 rows.each do |user_uuid, group_uuid, max_p_val|
209 all_perms[user_uuid] ||= {}
210 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
215 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
216 # and perm_hash[:write] are true if this user can read and write
217 # objects owned by group_uuid.
218 def group_permissions(level=1)
220 if @group_perms.empty?
221 user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: "$1", perm_level: 1}
223 ActiveRecord::Base.connection.
225 SELECT target_uuid, perm_level
226 FROM #{PERMISSION_VIEW}
227 WHERE user_uuid in (#{user_uuids_subquery}) and perm_level >= 1
229 # "name" arg is a query label that appears in logs:
230 "User.group_permissions",
231 # "binds" arg is an array of [col_id, value] for '$1' vars:
233 rows.each do |group_uuid, max_p_val|
234 @group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
242 @group_perms.select {|k,v| v[:write] }
244 @group_perms.select {|k,v| v[:manage] }
246 raise "level must be 1, 2 or 3"
251 def setup(repo_name: nil, vm_uuid: nil, send_notification_email: nil)
252 newly_invited = Link.where(tail_uuid: self.uuid,
253 head_uuid: all_users_group_uuid,
254 link_class: 'permission',
255 name: 'can_read').empty?
257 # Add can_read link from this user to "all users" which makes this
258 # user "invited", and (depending on config) a link in the opposite
259 # direction which makes this user visible to other users.
260 group_perms = add_to_all_users_group
263 repo_perm = if (!repo_name.nil? || Rails.configuration.Users.AutoSetupNewUsersWithRepository) and !username.nil?
264 repo_name ||= "#{username}/#{username}"
265 create_user_repo_link repo_name
268 # Add virtual machine
269 if vm_uuid.nil? and !Rails.configuration.Users.AutoSetupNewUsersWithVmUUID.empty?
270 vm_uuid = Rails.configuration.Users.AutoSetupNewUsersWithVmUUID
273 vm_login_perm = if vm_uuid && username
274 create_vm_login_permission_link(vm_uuid, username)
278 if send_notification_email.nil?
279 send_notification_email = Rails.configuration.Mail.SendUserSetupNotificationEmail
282 if newly_invited and send_notification_email and !Rails.configuration.Users.UserSetupMailText.empty?
284 UserNotifier.account_is_setup(self).deliver_now
286 logger.warn "Failed to send email to #{self.email}: #{e}"
290 forget_cached_group_perms
292 return [repo_perm, vm_login_perm, *group_perms, self].compact
295 # delete user signatures, login, repo, and vm perms, and mark as inactive
297 # delete oid_login_perms for this user
299 # note: these permission links are obsolete, they have no effect
300 # on anything and they are not created for new users.
301 Link.where(tail_uuid: self.email,
302 link_class: 'permission',
303 name: 'can_login').destroy_all
305 # delete repo_perms for this user
306 Link.where(tail_uuid: self.uuid,
307 link_class: 'permission',
308 name: 'can_manage').destroy_all
310 # delete vm_login_perms for this user
311 Link.where(tail_uuid: self.uuid,
312 link_class: 'permission',
313 name: 'can_login').destroy_all
315 # delete "All users" group read permissions for this user
316 Link.where(tail_uuid: self.uuid,
317 head_uuid: all_users_group_uuid,
318 link_class: 'permission',
319 name: 'can_read').destroy_all
321 # delete any signatures by this user
322 Link.where(link_class: 'signature',
323 tail_uuid: self.uuid).destroy_all
325 # delete tokens for this user
326 ApiClientAuthorization.where(user_id: self.id).destroy_all
327 # delete ssh keys for this user
328 AuthorizedKey.where(owner_uuid: self.uuid).destroy_all
329 AuthorizedKey.where(authorized_user_uuid: self.uuid).destroy_all
331 # delete user preferences (including profile)
334 # mark the user as inactive
335 self.is_admin = false # can't be admin and inactive
336 self.is_active = false
337 forget_cached_group_perms
341 def must_unsetup_to_deactivate
342 if !self.new_record? &&
343 self.uuid[0..4] == Rails.configuration.Login.LoginCluster &&
344 self.uuid[0..4] != Rails.configuration.ClusterID
345 # OK to update our local record to whatever the LoginCluster
346 # reports, because self-activate is not allowed.
348 elsif self.is_active_changed? &&
349 self.is_active_was &&
352 # When a user is set up, they are added to the "All users"
353 # group. A user that is part of the "All users" group is
354 # allowed to self-activate.
356 # It doesn't make sense to deactivate a user (set is_active =
357 # false) without first removing them from the "All users" group,
358 # because they would be able to immediately reactivate
361 # The 'unsetup' method removes the user from the "All users"
362 # group (and also sets is_active = false) so send a message
363 # explaining the correct way to deactivate a user.
365 if Link.where(tail_uuid: self.uuid,
366 head_uuid: all_users_group_uuid,
367 link_class: 'permission',
368 name: 'can_read').any?
369 errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
374 def set_initial_username(requested: false)
375 if !requested.is_a?(String) || requested.empty?
376 email_parts = email.partition("@")
377 local_parts = email_parts.first.partition("+")
378 if email_parts.any?(&:empty?)
380 elsif not local_parts.first.empty?
381 requested = local_parts.first
383 requested = email_parts.first
386 requested.sub!(/^[^A-Za-z]+/, "")
387 requested.gsub!(/[^A-Za-z0-9]/, "")
388 unless requested.empty?
389 self.username = find_usable_username_from(requested)
393 # Move this user's (i.e., self's) owned items to new_owner_uuid and
394 # new_user_uuid (for things normally owned directly by the user).
396 # If redirect_auth is true, also reassign auth tokens and ssh keys,
397 # and redirect this account to redirect_to_user_uuid, i.e., when a
398 # caller authenticates to this account in the future, the account
399 # redirect_to_user_uuid account will be used instead.
401 # current_user must have admin privileges, i.e., the caller is
402 # responsible for checking permission to do this.
403 def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
404 raise PermissionDeniedError if !current_user.andand.is_admin
405 raise "Missing new_owner_uuid" if !new_owner_uuid
406 raise "Missing new_user_uuid" if !new_user_uuid
407 transaction(requires_new: true) do
409 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
411 new_user = User.where(uuid: new_user_uuid).first
412 raise "user does not exist" if !new_user
413 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
415 self.clear_permissions
416 new_user.clear_permissions
418 # If 'self' is a remote user, don't transfer authorizations
419 # (i.e. ability to access the account) to the new user, because
420 # that gives the remote site the ability to access the 'new'
421 # user account that takes over the 'self' account.
423 # If 'self' is a local user, it is okay to transfer
424 # authorizations, even if the 'new' user is a remote account,
425 # because the remote site does not gain the ability to access an
426 # account it could not before.
428 if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
429 # Existing API tokens and ssh keys are updated to authenticate
431 ApiClientAuthorization.
433 update_all(user_id: new_user.id)
436 [AuthorizedKey, :owner_uuid],
437 [AuthorizedKey, :authorized_user_uuid],
443 # Destroy API tokens and ssh keys associated with the old
445 ApiClientAuthorization.where(user_id: id).destroy_all
446 AuthorizedKey.where(owner_uuid: uuid).destroy_all
447 AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
454 # References to the old user UUID in the context of a user ID
455 # (rather than a "home project" in the project hierarchy) are
456 # updated to point to the new user.
457 user_updates.each do |klass, column|
458 klass.where(column => uuid).update_all(column => new_user.uuid)
461 # Need to update repository names to new username
463 old_repo_name_re = /^#{Regexp.escape(username)}\//
464 Repository.where(:owner_uuid => uuid).each do |repo|
465 repo.owner_uuid = new_user.uuid
466 repo_name_sub = "#{new_user.username}/"
467 name = repo.name.sub(old_repo_name_re, repo_name_sub)
468 while (conflict = Repository.where(:name => name).first) != nil
469 repo_name_sub += "migrated"
470 name = repo.name.sub(old_repo_name_re, repo_name_sub)
477 # References to the merged user's "home project" are updated to
478 # point to new_owner_uuid.
479 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
480 next if [ApiClientAuthorization,
484 Repository].include?(klass)
485 next if !klass.columns.collect(&:name).include?('owner_uuid')
486 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
489 if redirect_to_new_user
490 update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
492 skip_check_permissions_against_full_refresh do
493 update_permissions self.uuid, self.uuid, CAN_MANAGE_PERM
494 update_permissions new_user.uuid, new_user.uuid, CAN_MANAGE_PERM
495 update_permissions new_user.owner_uuid, new_user.uuid, CAN_MANAGE_PERM
497 update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM
504 while (uuid = user.redirect_to_user_uuid)
506 nextuser = User.unscoped.find_by_uuid(uuid)
508 raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
513 raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
519 def self.register info
520 # login info expected fields, all can be optional but at minimum
521 # must supply either 'identity_url' or 'email'
533 identity_url = info['identity_url']
535 if identity_url && identity_url.length > 0
536 # Only local users can create sessions, hence uuid_like_pattern
538 user = User.unscoped.where('identity_url = ? and uuid like ?',
540 User.uuid_like_pattern).first
541 primary_user = user.redirects_to if user
545 # identity url is unset or didn't find matching record.
546 emails = [info['email']] + (info['alternate_emails'] || [])
547 emails.select! {|em| !em.nil? && !em.empty?}
549 User.unscoped.where('email in (?) and uuid like ?',
551 User.uuid_like_pattern).each do |user|
553 primary_user = user.redirects_to
554 elsif primary_user.uuid != user.redirects_to.uuid
555 raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
561 # New user registration
562 primary_user = User.new(:owner_uuid => system_user_uuid,
564 :is_active => Rails.configuration.Users.NewUsersAreActive)
566 primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
567 primary_user.identity_url = info['identity_url'] if identity_url
570 primary_user.email = info['email'] if info['email']
571 primary_user.first_name = info['first_name'] if info['first_name']
572 primary_user.last_name = info['last_name'] if info['last_name']
574 if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
575 raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
578 act_as_system_user do
587 def self.attributes_required_columns
589 'can_write' => ['owner_uuid', 'uuid'],
590 'can_manage' => ['owner_uuid', 'uuid'],
594 def change_all_uuid_refs(old_uuid:, new_uuid:)
595 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
596 klass.columns.each do |col|
597 if col.name.end_with?('_uuid')
598 column = col.name.to_sym
599 klass.where(column => old_uuid).update_all(column => new_uuid)
605 def ensure_ownership_path_leads_to_user
609 def permission_to_update
610 if username_changed? || redirect_to_user_uuid_changed? || email_changed?
611 current_user.andand.is_admin
613 # users must be able to update themselves (even if they are
614 # inactive) in order to create sessions
615 self == current_user or super
619 def permission_to_create
620 current_user.andand.is_admin or
621 (self == current_user &&
622 self.redirect_to_user_uuid.nil? &&
623 self.is_active == Rails.configuration.Users.NewUsersAreActive)
627 return if self.uuid.end_with?('anonymouspublic')
628 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
629 !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
630 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
631 Rails.configuration.Users.AutoAdminFirstUser)
633 self.is_active = true
637 def find_usable_username_from(basename)
638 # If "basename" is a usable username, return that.
639 # Otherwise, find a unique username "basenameN", where N is the
640 # smallest integer greater than 1, and return that.
641 # Return nil if a unique username can't be found after reasonable
643 quoted_name = self.class.connection.quote_string(basename)
644 next_username = basename
646 while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
648 next_username = "%s%i" % [basename, next_suffix]
650 0.upto(6).each do |suffix_len|
651 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
653 where("username like '#{pattern}'").
655 order('username asc').
657 if other_user.username > next_username
659 elsif other_user.username == next_username
661 next_username = "%s%i" % [basename, next_suffix]
664 return next_username if (next_username.size <= pattern.size)
669 def prevent_privilege_escalation
670 if current_user.andand.is_admin
673 if self.is_active_changed?
674 if self.is_active != self.is_active_was
675 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
676 self.is_active = self.is_active_was
679 if self.is_admin_changed?
680 if self.is_admin != self.is_admin_was
681 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
682 self.is_admin = self.is_admin_was
688 def prevent_inactive_admin
689 if self.is_admin and not self.is_active
690 # There is no known use case for the strange set of permissions
691 # that would result from this change. It's safest to assume it's
692 # a mistake and disallow it outright.
693 raise "Admin users cannot be inactive"
698 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
699 nextpaths = graph[start]
700 return merged if !nextpaths
701 return merged if upstream_path.has_key? start
702 upstream_path[start] = true
703 upstream_mask ||= ALL_PERMISSIONS
704 nextpaths.each do |head, mask|
707 merged[head][k] ||= v if upstream_mask[k]
709 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
711 upstream_path.delete start
715 def create_user_repo_link(repo_name)
716 # repo_name is optional
718 logger.warn ("Repository name not given for #{self.uuid}.")
722 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
723 logger.info { "repo uuid: " + repo[:uuid] }
724 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
725 link_class: "permission",
726 name: "can_manage").first_or_create!
727 logger.info { "repo permission: " + repo_perm[:uuid] }
731 # create login permission for the given vm_uuid, if it does not already exist
732 def create_vm_login_permission_link(vm_uuid, repo_name)
733 # vm uuid is optional
734 return if vm_uuid == ""
736 vm = VirtualMachine.where(uuid: vm_uuid).first
738 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
739 raise "No vm found for #{vm_uuid}"
742 logger.info { "vm uuid: " + vm[:uuid] }
744 tail_uuid: uuid, head_uuid: vm.uuid,
745 link_class: "permission", name: "can_login",
750 select { |link| link.properties["username"] == repo_name }.
754 create(login_attrs.merge(properties: {"username" => repo_name}))
756 logger.info { "login permission: " + login_perm[:uuid] }
760 def add_to_all_users_group
761 resp = [Link.where(tail_uuid: self.uuid,
762 head_uuid: all_users_group_uuid,
763 link_class: 'permission',
764 name: 'can_read').first ||
765 Link.create(tail_uuid: self.uuid,
766 head_uuid: all_users_group_uuid,
767 link_class: 'permission',
769 if Rails.configuration.Users.ActivatedUsersAreVisibleToOthers
770 resp += [Link.where(tail_uuid: all_users_group_uuid,
771 head_uuid: self.uuid,
772 link_class: 'permission',
773 name: 'can_read').first ||
774 Link.create(tail_uuid: all_users_group_uuid,
775 head_uuid: self.uuid,
776 link_class: 'permission',
782 # Give the special "System group" permission to manage this user and
783 # all of this user's stuff.
784 def add_system_group_permission_link
785 return true if uuid == system_user_uuid
786 act_as_system_user do
787 Link.create(link_class: 'permission',
789 tail_uuid: system_group_uuid,
790 head_uuid: self.uuid)
794 # Send admin notifications
795 def send_admin_notifications
796 AdminNotifier.new_user(self).deliver_now
797 if not self.is_active then
798 AdminNotifier.new_inactive_user(self).deliver_now
802 # Automatically setup if is_active flag turns on
803 def setup_on_activate
804 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
806 (new_record? || saved_change_to_is_active? || will_save_change_to_is_active?)
811 # Automatically setup new user during creation
812 def auto_setup_new_user
816 # Send notification if the user saved profile for the first time
817 def send_profile_created_notification
818 if saved_change_to_prefs?
819 if prefs_before_last_save.andand.empty? || !prefs_before_last_save.andand['profile']
820 profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
821 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
826 def verify_repositories_empty
827 unless repositories.first.nil?
828 errors.add(:username, "can't be unset when the user owns repositories")
833 def sync_repository_names
834 old_name_re = /^#{Regexp.escape(username_before_last_save)}\//
835 name_sub = "#{username}/"
836 repositories.find_each do |repo|
837 repo.name = repo.name.sub(old_name_re, name_sub)
842 def identity_url_nil_if_empty
843 if identity_url == ""
844 self.identity_url = nil