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 actions.each do |action, target|
117 if target.respond_to? :uuid
118 target_uuid = target.uuid
121 target = ArvadosModel.find_by_uuid(target_uuid)
124 next if target_uuid == self.uuid
126 if action == :write && target && !target.new_record? &&
127 target.respond_to?(:frozen_by_uuid) &&
128 target.frozen_by_uuid_was
129 # Just an optimization to skip the PERMISSION_VIEW and
130 # FrozenGroup queries below
134 target_owner_uuid = target.owner_uuid if target.respond_to? :owner_uuid
136 user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: "$1", perm_level: "$3"}
138 if !is_admin && !ActiveRecord::Base.connection.
140 SELECT 1 FROM #{PERMISSION_VIEW}
141 WHERE user_uuid in (#{user_uuids_subquery}) and
142 ((target_uuid = $2 and perm_level >= $3)
143 or (target_uuid = $4 and perm_level >= $3 and traverse_owned))
145 # "name" arg is a query label that appears in logs:
149 [nil, VAL_FOR_PERM[action]],
150 [nil, target_owner_uuid]]
156 if FrozenGroup.where(uuid: [target_uuid, target_owner_uuid]).any?
157 # self or parent is frozen
160 elsif action == :unfreeze
161 # "unfreeze" permission means "can write, but only if
162 # explicitly un-freezing at the same time" (see
163 # ArvadosModel#ensure_owner_uuid_is_permitted). If the
164 # permission query above passed the permission level of
165 # :unfreeze (which is the same as :manage), and the parent
166 # isn't also frozen, then un-freeze is allowed.
167 if FrozenGroup.where(uuid: target_owner_uuid).any?
175 def before_ownership_change
176 if owner_uuid_changed? and !self.owner_uuid_was.nil?
177 MaterializedPermission.where(user_uuid: owner_uuid_was, target_uuid: uuid).delete_all
178 update_permissions self.owner_uuid_was, self.uuid, REVOKE_PERM
182 def after_ownership_change
183 if saved_change_to_owner_uuid?
184 update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM
188 def clear_permissions
189 MaterializedPermission.where("user_uuid = ? and target_uuid != ?", uuid, uuid).delete_all
192 def forget_cached_group_perms
196 def remove_self_from_permissions
197 MaterializedPermission.where("target_uuid = ?", uuid).delete_all
198 check_permissions_against_full_refresh
201 # Return a hash of {user_uuid: group_perms}
203 # note: this does not account for permissions that a user gains by
204 # having can_manage on another user.
205 def self.all_group_permissions
207 ActiveRecord::Base.connection.
209 SELECT user_uuid, target_uuid, perm_level
210 FROM #{PERMISSION_VIEW}
213 # "name" arg is a query label that appears in logs:
214 "all_group_permissions").
215 rows.each do |user_uuid, group_uuid, max_p_val|
216 all_perms[user_uuid] ||= {}
217 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
222 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
223 # and perm_hash[:write] are true if this user can read and write
224 # objects owned by group_uuid.
225 def group_permissions(level=1)
227 if @group_perms.empty?
228 user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: "$1", perm_level: 1}
230 ActiveRecord::Base.connection.
232 SELECT target_uuid, perm_level
233 FROM #{PERMISSION_VIEW}
234 WHERE user_uuid in (#{user_uuids_subquery}) and perm_level >= 1
236 # "name" arg is a query label that appears in logs:
237 "User.group_permissions",
238 # "binds" arg is an array of [col_id, value] for '$1' vars:
240 rows.each do |group_uuid, max_p_val|
241 @group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
249 @group_perms.select {|k,v| v[:write] }
251 @group_perms.select {|k,v| v[:manage] }
253 raise "level must be 1, 2 or 3"
258 def setup(repo_name: nil, vm_uuid: nil, send_notification_email: nil)
259 newly_invited = Link.where(tail_uuid: self.uuid,
260 head_uuid: all_users_group_uuid,
261 link_class: 'permission',
262 name: 'can_read').empty?
264 # Add can_read link from this user to "all users" which makes this
265 # user "invited", and (depending on config) a link in the opposite
266 # direction which makes this user visible to other users.
267 group_perms = add_to_all_users_group
270 repo_perm = if (!repo_name.nil? || Rails.configuration.Users.AutoSetupNewUsersWithRepository) and !username.nil?
271 repo_name ||= "#{username}/#{username}"
272 create_user_repo_link repo_name
275 # Add virtual machine
276 if vm_uuid.nil? and !Rails.configuration.Users.AutoSetupNewUsersWithVmUUID.empty?
277 vm_uuid = Rails.configuration.Users.AutoSetupNewUsersWithVmUUID
280 vm_login_perm = if vm_uuid && username
281 create_vm_login_permission_link(vm_uuid, username)
285 if send_notification_email.nil?
286 send_notification_email = Rails.configuration.Mail.SendUserSetupNotificationEmail
289 if newly_invited and send_notification_email and !Rails.configuration.Users.UserSetupMailText.empty?
291 UserNotifier.account_is_setup(self).deliver_now
293 logger.warn "Failed to send email to #{self.email}: #{e}"
297 forget_cached_group_perms
299 return [repo_perm, vm_login_perm, *group_perms, self].compact
302 # delete user signatures, login, repo, and vm perms, and mark as inactive
304 # delete oid_login_perms for this user
306 # note: these permission links are obsolete, they have no effect
307 # on anything and they are not created for new users.
308 Link.where(tail_uuid: self.email,
309 link_class: 'permission',
310 name: 'can_login').destroy_all
312 # delete repo_perms for this user
313 Link.where(tail_uuid: self.uuid,
314 link_class: 'permission',
315 name: 'can_manage').destroy_all
317 # delete vm_login_perms for this user
318 Link.where(tail_uuid: self.uuid,
319 link_class: 'permission',
320 name: 'can_login').destroy_all
322 # delete "All users" group read permissions for this user
323 Link.where(tail_uuid: self.uuid,
324 head_uuid: all_users_group_uuid,
325 link_class: 'permission',
326 name: 'can_read').destroy_all
328 # delete any signatures by this user
329 Link.where(link_class: 'signature',
330 tail_uuid: self.uuid).destroy_all
332 # delete tokens for this user
333 ApiClientAuthorization.where(user_id: self.id).destroy_all
334 # delete ssh keys for this user
335 AuthorizedKey.where(owner_uuid: self.uuid).destroy_all
336 AuthorizedKey.where(authorized_user_uuid: self.uuid).destroy_all
338 # delete user preferences (including profile)
341 # mark the user as inactive
342 self.is_admin = false # can't be admin and inactive
343 self.is_active = false
344 forget_cached_group_perms
348 def must_unsetup_to_deactivate
349 if !self.new_record? &&
350 self.uuid[0..4] == Rails.configuration.Login.LoginCluster &&
351 self.uuid[0..4] != Rails.configuration.ClusterID
352 # OK to update our local record to whatever the LoginCluster
353 # reports, because self-activate is not allowed.
355 elsif self.is_active_changed? &&
356 self.is_active_was &&
359 # When a user is set up, they are added to the "All users"
360 # group. A user that is part of the "All users" group is
361 # allowed to self-activate.
363 # It doesn't make sense to deactivate a user (set is_active =
364 # false) without first removing them from the "All users" group,
365 # because they would be able to immediately reactivate
368 # The 'unsetup' method removes the user from the "All users"
369 # group (and also sets is_active = false) so send a message
370 # explaining the correct way to deactivate a user.
372 if Link.where(tail_uuid: self.uuid,
373 head_uuid: all_users_group_uuid,
374 link_class: 'permission',
375 name: 'can_read').any?
376 errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
381 def set_initial_username(requested: false)
382 if !requested.is_a?(String) || requested.empty?
383 email_parts = email.partition("@")
384 local_parts = email_parts.first.partition("+")
385 if email_parts.any?(&:empty?)
387 elsif not local_parts.first.empty?
388 requested = local_parts.first
390 requested = email_parts.first
393 requested.sub!(/^[^A-Za-z]+/, "")
394 requested.gsub!(/[^A-Za-z0-9]/, "")
395 unless requested.empty?
396 self.username = find_usable_username_from(requested)
400 # Move this user's (i.e., self's) owned items to new_owner_uuid and
401 # new_user_uuid (for things normally owned directly by the user).
403 # If redirect_auth is true, also reassign auth tokens and ssh keys,
404 # and redirect this account to redirect_to_user_uuid, i.e., when a
405 # caller authenticates to this account in the future, the account
406 # redirect_to_user_uuid account will be used instead.
408 # current_user must have admin privileges, i.e., the caller is
409 # responsible for checking permission to do this.
410 def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
411 raise PermissionDeniedError if !current_user.andand.is_admin
412 raise "Missing new_owner_uuid" if !new_owner_uuid
413 raise "Missing new_user_uuid" if !new_user_uuid
414 transaction(requires_new: true) do
416 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
418 new_user = User.where(uuid: new_user_uuid).first
419 raise "user does not exist" if !new_user
420 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
422 self.clear_permissions
423 new_user.clear_permissions
425 # If 'self' is a remote user, don't transfer authorizations
426 # (i.e. ability to access the account) to the new user, because
427 # that gives the remote site the ability to access the 'new'
428 # user account that takes over the 'self' account.
430 # If 'self' is a local user, it is okay to transfer
431 # authorizations, even if the 'new' user is a remote account,
432 # because the remote site does not gain the ability to access an
433 # account it could not before.
435 if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
436 # Existing API tokens and ssh keys are updated to authenticate
438 ApiClientAuthorization.
440 update_all(user_id: new_user.id)
443 [AuthorizedKey, :owner_uuid],
444 [AuthorizedKey, :authorized_user_uuid],
450 # Destroy API tokens and ssh keys associated with the old
452 ApiClientAuthorization.where(user_id: id).destroy_all
453 AuthorizedKey.where(owner_uuid: uuid).destroy_all
454 AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
461 # References to the old user UUID in the context of a user ID
462 # (rather than a "home project" in the project hierarchy) are
463 # updated to point to the new user.
464 user_updates.each do |klass, column|
465 klass.where(column => uuid).update_all(column => new_user.uuid)
468 # Need to update repository names to new username
470 old_repo_name_re = /^#{Regexp.escape(username)}\//
471 Repository.where(:owner_uuid => uuid).each do |repo|
472 repo.owner_uuid = new_user.uuid
473 repo_name_sub = "#{new_user.username}/"
474 name = repo.name.sub(old_repo_name_re, repo_name_sub)
475 while (conflict = Repository.where(:name => name).first) != nil
476 repo_name_sub += "migrated"
477 name = repo.name.sub(old_repo_name_re, repo_name_sub)
484 # References to the merged user's "home project" are updated to
485 # point to new_owner_uuid.
486 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
487 next if [ApiClientAuthorization,
491 Repository].include?(klass)
492 next if !klass.columns.collect(&:name).include?('owner_uuid')
493 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
496 if redirect_to_new_user
497 update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
499 skip_check_permissions_against_full_refresh do
500 update_permissions self.uuid, self.uuid, CAN_MANAGE_PERM
501 update_permissions new_user.uuid, new_user.uuid, CAN_MANAGE_PERM
502 update_permissions new_user.owner_uuid, new_user.uuid, CAN_MANAGE_PERM
504 update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM
511 while (uuid = user.redirect_to_user_uuid)
513 nextuser = User.unscoped.find_by_uuid(uuid)
515 raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
520 raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
526 def self.register info
527 # login info expected fields, all can be optional but at minimum
528 # must supply either 'identity_url' or 'email'
540 identity_url = info['identity_url']
542 if identity_url && identity_url.length > 0
543 # Only local users can create sessions, hence uuid_like_pattern
545 user = User.unscoped.where('identity_url = ? and uuid like ?',
547 User.uuid_like_pattern).first
548 primary_user = user.redirects_to if user
552 # identity url is unset or didn't find matching record.
553 emails = [info['email']] + (info['alternate_emails'] || [])
554 emails.select! {|em| !em.nil? && !em.empty?}
556 User.unscoped.where('email in (?) and uuid like ?',
558 User.uuid_like_pattern).each do |user|
560 primary_user = user.redirects_to
561 elsif primary_user.uuid != user.redirects_to.uuid
562 raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
568 # New user registration
569 primary_user = User.new(:owner_uuid => system_user_uuid,
571 :is_active => Rails.configuration.Users.NewUsersAreActive)
573 primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
574 primary_user.identity_url = info['identity_url'] if identity_url
577 primary_user.email = info['email'] if info['email']
578 primary_user.first_name = info['first_name'] if info['first_name']
579 primary_user.last_name = info['last_name'] if info['last_name']
581 if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
582 raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
585 act_as_system_user do
594 def self.attributes_required_columns
596 'can_write' => ['owner_uuid', 'uuid'],
597 'can_manage' => ['owner_uuid', 'uuid'],
601 def change_all_uuid_refs(old_uuid:, new_uuid:)
602 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
603 klass.columns.each do |col|
604 if col.name.end_with?('_uuid')
605 column = col.name.to_sym
606 klass.where(column => old_uuid).update_all(column => new_uuid)
612 def ensure_ownership_path_leads_to_user
616 def permission_to_update
617 if username_changed? || redirect_to_user_uuid_changed? || email_changed?
618 current_user.andand.is_admin
620 # users must be able to update themselves (even if they are
621 # inactive) in order to create sessions
622 self == current_user or super
626 def permission_to_create
627 current_user.andand.is_admin or
628 (self == current_user &&
629 self.redirect_to_user_uuid.nil? &&
630 self.is_active == Rails.configuration.Users.NewUsersAreActive)
634 return if self.uuid.end_with?('anonymouspublic')
635 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
636 !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
637 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
638 Rails.configuration.Users.AutoAdminFirstUser)
640 self.is_active = true
644 def find_usable_username_from(basename)
645 # If "basename" is a usable username, return that.
646 # Otherwise, find a unique username "basenameN", where N is the
647 # smallest integer greater than 1, and return that.
648 # Return nil if a unique username can't be found after reasonable
650 quoted_name = self.class.connection.quote_string(basename)
651 next_username = basename
653 while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
655 next_username = "%s%i" % [basename, next_suffix]
657 0.upto(6).each do |suffix_len|
658 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
660 where("username like '#{pattern}'").
662 order('username asc').
664 if other_user.username > next_username
666 elsif other_user.username == next_username
668 next_username = "%s%i" % [basename, next_suffix]
671 return next_username if (next_username.size <= pattern.size)
676 def prevent_privilege_escalation
677 if current_user.andand.is_admin
680 if self.is_active_changed?
681 if self.is_active != self.is_active_was
682 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
683 self.is_active = self.is_active_was
686 if self.is_admin_changed?
687 if self.is_admin != self.is_admin_was
688 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
689 self.is_admin = self.is_admin_was
695 def prevent_inactive_admin
696 if self.is_admin and not self.is_active
697 # There is no known use case for the strange set of permissions
698 # that would result from this change. It's safest to assume it's
699 # a mistake and disallow it outright.
700 raise "Admin users cannot be inactive"
705 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
706 nextpaths = graph[start]
707 return merged if !nextpaths
708 return merged if upstream_path.has_key? start
709 upstream_path[start] = true
710 upstream_mask ||= ALL_PERMISSIONS
711 nextpaths.each do |head, mask|
714 merged[head][k] ||= v if upstream_mask[k]
716 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
718 upstream_path.delete start
722 def create_user_repo_link(repo_name)
723 # repo_name is optional
725 logger.warn ("Repository name not given for #{self.uuid}.")
729 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
730 logger.info { "repo uuid: " + repo[:uuid] }
731 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
732 link_class: "permission",
733 name: "can_manage").first_or_create!
734 logger.info { "repo permission: " + repo_perm[:uuid] }
738 # create login permission for the given vm_uuid, if it does not already exist
739 def create_vm_login_permission_link(vm_uuid, repo_name)
740 # vm uuid is optional
741 return if vm_uuid == ""
743 vm = VirtualMachine.where(uuid: vm_uuid).first
745 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
746 raise "No vm found for #{vm_uuid}"
749 logger.info { "vm uuid: " + vm[:uuid] }
751 tail_uuid: uuid, head_uuid: vm.uuid,
752 link_class: "permission", name: "can_login",
757 select { |link| link.properties["username"] == repo_name }.
761 create(login_attrs.merge(properties: {"username" => repo_name}))
763 logger.info { "login permission: " + login_perm[:uuid] }
767 def add_to_all_users_group
768 resp = [Link.where(tail_uuid: self.uuid,
769 head_uuid: all_users_group_uuid,
770 link_class: 'permission',
771 name: 'can_read').first ||
772 Link.create(tail_uuid: self.uuid,
773 head_uuid: all_users_group_uuid,
774 link_class: 'permission',
776 if Rails.configuration.Users.ActivatedUsersAreVisibleToOthers
777 resp += [Link.where(tail_uuid: all_users_group_uuid,
778 head_uuid: self.uuid,
779 link_class: 'permission',
780 name: 'can_read').first ||
781 Link.create(tail_uuid: all_users_group_uuid,
782 head_uuid: self.uuid,
783 link_class: 'permission',
789 # Give the special "System group" permission to manage this user and
790 # all of this user's stuff.
791 def add_system_group_permission_link
792 return true if uuid == system_user_uuid
793 act_as_system_user do
794 Link.create(link_class: 'permission',
796 tail_uuid: system_group_uuid,
797 head_uuid: self.uuid)
801 # Send admin notifications
802 def send_admin_notifications
803 AdminNotifier.new_user(self).deliver_now
804 if not self.is_active then
805 AdminNotifier.new_inactive_user(self).deliver_now
809 # Automatically setup if is_active flag turns on
810 def setup_on_activate
811 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
813 (new_record? || saved_change_to_is_active? || will_save_change_to_is_active?)
818 # Automatically setup new user during creation
819 def auto_setup_new_user
823 # Send notification if the user saved profile for the first time
824 def send_profile_created_notification
825 if saved_change_to_prefs?
826 if prefs_before_last_save.andand.empty? || !prefs_before_last_save.andand['profile']
827 profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
828 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
833 def verify_repositories_empty
834 unless repositories.first.nil?
835 errors.add(:username, "can't be unset when the user owns repositories")
840 def sync_repository_names
841 old_name_re = /^#{Regexp.escape(username_before_last_save)}\//
842 name_sub = "#{username}/"
843 repositories.find_each do |repo|
844 repo.name = repo.name.sub(old_name_re, name_sub)
849 def identity_url_nil_if_empty
850 if identity_url == ""
851 self.identity_url = nil