1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'can_be_an_owner'
6 require 'refresh_permission_view'
8 class User < ArvadosModel
11 include CommonApiTemplate
13 extend CurrentApiClient
15 serialize :prefs, Hash
16 has_many :api_client_authorizations
19 with: /\A[A-Za-z][A-Za-z0-9]*\z/,
20 message: "must begin with a letter and contain only alphanumerics",
24 validate :must_unsetup_to_deactivate
25 before_update :prevent_privilege_escalation
26 before_update :prevent_inactive_admin
27 before_update :verify_repositories_empty, :if => Proc.new { |user|
28 user.username.nil? and user.username_changed?
30 before_update :setup_on_activate
31 before_create :check_auto_admin
32 before_create :set_initial_username, :if => Proc.new { |user|
33 user.username.nil? and user.email
35 after_create :setup_on_activate
36 after_create :add_system_group_permission_link
37 after_create :invalidate_permissions_cache
38 after_create :auto_setup_new_user, :if => Proc.new { |user|
39 Rails.configuration.Users.AutoSetupNewUsers and
40 (user.uuid != system_user_uuid) and
41 (user.uuid != anonymous_user_uuid)
43 after_create :send_admin_notifications
44 after_update :send_profile_created_notification
45 after_update :sync_repository_names, :if => Proc.new { |user|
46 (user.uuid != system_user_uuid) and
47 user.username_changed? and
48 (not user.username_was.nil?)
51 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
52 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
54 default_scope { where('redirect_to_user_uuid is null') }
56 api_accessible :user, extend: :common do |t|
70 ALL_PERMISSIONS = {read: true, write: true, manage: true}
72 # Map numeric permission levels (see lib/create_permission_view.sql)
73 # back to read/write/manage flags.
77 {read: true, write: true},
78 {read: true, write: true, manage: true}]
81 "#{first_name} #{last_name}".strip
86 Rails.configuration.Users.NewUsersAreActive ||
87 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
90 def groups_i_can(verb)
91 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
93 my_groups << anonymous_group_uuid
99 return true if is_admin
100 actions.each do |action, target|
102 if target.respond_to? :uuid
103 target_uuid = target.uuid
106 target = ArvadosModel.find_by_uuid(target_uuid)
109 next if target_uuid == self.uuid
110 next if (group_permissions[target_uuid] and
111 group_permissions[target_uuid][action])
112 if target.respond_to? :owner_uuid
113 next if target.owner_uuid == self.uuid
114 next if (group_permissions[target.owner_uuid] and
115 group_permissions[target.owner_uuid][action])
117 sufficient_perms = case action
121 ['can_manage', 'can_write']
123 ['can_manage', 'can_write', 'can_read']
125 # (Skip this kind of permission opportunity
126 # if action is an unknown permission type)
129 # Check permission links with head_uuid pointing directly at
130 # the target object. If target is a Group, this is redundant
131 # and will fail except [a] if permission caching is broken or
132 # [b] during a race condition, where a permission link has
134 if Link.where(link_class: 'permission',
135 name: sufficient_perms,
136 tail_uuid: groups_i_can(action) + [self.uuid],
137 head_uuid: target_uuid).any?
146 def self.invalidate_permissions_cache(async=false)
147 refresh_permission_view(async)
150 def invalidate_permissions_cache
151 User.invalidate_permissions_cache
154 # Return a hash of {user_uuid: group_perms}
155 def self.all_group_permissions
157 ActiveRecord::Base.connection.
158 exec_query("SELECT user_uuid, target_owner_uuid, perm_level, trashed
159 FROM #{PERMISSION_VIEW}
160 WHERE target_owner_uuid IS NOT NULL",
161 # "name" arg is a query label that appears in logs:
162 "all_group_permissions",
163 ).rows.each do |user_uuid, group_uuid, max_p_val, trashed|
164 all_perms[user_uuid] ||= {}
165 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
170 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
171 # and perm_hash[:write] are true if this user can read and write
172 # objects owned by group_uuid.
173 def group_permissions
174 group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
175 ActiveRecord::Base.connection.
176 exec_query("SELECT target_owner_uuid, perm_level, trashed
177 FROM #{PERMISSION_VIEW}
179 AND target_owner_uuid IS NOT NULL",
180 # "name" arg is a query label that appears in logs:
181 "group_permissions for #{uuid}",
182 # "binds" arg is an array of [col_id, value] for '$1' vars:
184 ).rows.each do |group_uuid, max_p_val, trashed|
185 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
191 def setup(repo_name: nil, vm_uuid: nil)
192 repo_perm = create_user_repo_link repo_name
193 vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
194 group_perm = create_user_group_link
196 return [repo_perm, vm_login_perm, group_perm, self].compact
199 # delete user signatures, login, repo, and vm perms, and mark as inactive
201 # delete oid_login_perms for this user
203 # note: these permission links are obsolete, they have no effect
204 # on anything and they are not created for new users.
205 Link.where(tail_uuid: self.email,
206 link_class: 'permission',
207 name: 'can_login').destroy_all
209 # delete repo_perms for this user
210 Link.where(tail_uuid: self.uuid,
211 link_class: 'permission',
212 name: 'can_manage').destroy_all
214 # delete vm_login_perms for this user
215 Link.where(tail_uuid: self.uuid,
216 link_class: 'permission',
217 name: 'can_login').destroy_all
219 # delete "All users" group read permissions for this user
220 group = Group.where(name: 'All users').select do |g|
221 g[:uuid].match(/-f+$/)
223 Link.where(tail_uuid: self.uuid,
224 head_uuid: group[:uuid],
225 link_class: 'permission',
226 name: 'can_read').destroy_all
228 # delete any signatures by this user
229 Link.where(link_class: 'signature',
230 tail_uuid: self.uuid).destroy_all
232 # delete user preferences (including profile)
235 # mark the user as inactive
236 self.is_active = false
240 def must_unsetup_to_deactivate
241 if !self.new_record? &&
242 self.uuid[0..4] == Rails.configuration.Login.LoginCluster &&
243 self.uuid[0..4] != Rails.configuration.ClusterID
244 # OK to update our local record to whatever the LoginCluster
245 # reports, because self-activate is not allowed.
247 elsif self.is_active_changed? &&
248 self.is_active_was &&
251 group = Group.where(name: 'All users').select do |g|
252 g[:uuid].match(/-f+$/)
255 # When a user is set up, they are added to the "All users"
256 # group. A user that is part of the "All users" group is
257 # allowed to self-activate.
259 # It doesn't make sense to deactivate a user (set is_active =
260 # false) without first removing them from the "All users" group,
261 # because they would be able to immediately reactivate
264 # The 'unsetup' method removes the user from the "All users"
265 # group (and also sets is_active = false) so send a message
266 # explaining the correct way to deactivate a user.
268 if Link.where(tail_uuid: self.uuid,
269 head_uuid: group[:uuid],
270 link_class: 'permission',
271 name: 'can_read').any?
272 errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
277 def set_initial_username(requested: false)
278 if !requested.is_a?(String) || requested.empty?
279 email_parts = email.partition("@")
280 local_parts = email_parts.first.partition("+")
281 if email_parts.any?(&:empty?)
283 elsif not local_parts.first.empty?
284 requested = local_parts.first
286 requested = email_parts.first
289 requested.sub!(/^[^A-Za-z]+/, "")
290 requested.gsub!(/[^A-Za-z0-9]/, "")
291 unless requested.empty?
292 self.username = find_usable_username_from(requested)
296 def update_uuid(new_uuid:)
297 if !current_user.andand.is_admin
298 raise PermissionDeniedError
300 if uuid == system_user_uuid || uuid == anonymous_user_uuid
301 raise "update_uuid cannot update system accounts"
303 if self.class != self.class.resource_class_for_uuid(new_uuid)
304 raise "invalid new_uuid #{new_uuid.inspect}"
306 transaction(requires_new: true) do
310 save!(validate: false)
311 change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
315 # Move this user's (i.e., self's) owned items to new_owner_uuid and
316 # new_user_uuid (for things normally owned directly by the user).
318 # If redirect_auth is true, also reassign auth tokens and ssh keys,
319 # and redirect this account to redirect_to_user_uuid, i.e., when a
320 # caller authenticates to this account in the future, the account
321 # redirect_to_user_uuid account will be used instead.
323 # current_user must have admin privileges, i.e., the caller is
324 # responsible for checking permission to do this.
325 def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
326 raise PermissionDeniedError if !current_user.andand.is_admin
327 raise "Missing new_owner_uuid" if !new_owner_uuid
328 raise "Missing new_user_uuid" if !new_user_uuid
329 transaction(requires_new: true) do
331 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
333 new_user = User.where(uuid: new_user_uuid).first
334 raise "user does not exist" if !new_user
335 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
337 # If 'self' is a remote user, don't transfer authorizations
338 # (i.e. ability to access the account) to the new user, because
339 # that gives the remote site the ability to access the 'new'
340 # user account that takes over the 'self' account.
342 # If 'self' is a local user, it is okay to transfer
343 # authorizations, even if the 'new' user is a remote account,
344 # because the remote site does not gain the ability to access an
345 # account it could not before.
347 if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
348 # Existing API tokens and ssh keys are updated to authenticate
350 ApiClientAuthorization.
352 update_all(user_id: new_user.id)
355 [AuthorizedKey, :owner_uuid],
356 [AuthorizedKey, :authorized_user_uuid],
362 # Destroy API tokens and ssh keys associated with the old
364 ApiClientAuthorization.where(user_id: id).destroy_all
365 AuthorizedKey.where(owner_uuid: uuid).destroy_all
366 AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
373 # References to the old user UUID in the context of a user ID
374 # (rather than a "home project" in the project hierarchy) are
375 # updated to point to the new user.
376 user_updates.each do |klass, column|
377 klass.where(column => uuid).update_all(column => new_user.uuid)
380 # Need to update repository names to new username
382 old_repo_name_re = /^#{Regexp.escape(username)}\//
383 Repository.where(:owner_uuid => uuid).each do |repo|
384 repo.owner_uuid = new_user.uuid
385 repo_name_sub = "#{new_user.username}/"
386 name = repo.name.sub(old_repo_name_re, repo_name_sub)
387 while (conflict = Repository.where(:name => name).first) != nil
388 repo_name_sub += "migrated"
389 name = repo.name.sub(old_repo_name_re, repo_name_sub)
396 # References to the merged user's "home project" are updated to
397 # point to new_owner_uuid.
398 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
399 next if [ApiClientAuthorization,
403 Repository].include?(klass)
404 next if !klass.columns.collect(&:name).include?('owner_uuid')
405 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
408 if redirect_to_new_user
409 update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
411 invalidate_permissions_cache
418 while (uuid = user.redirect_to_user_uuid)
420 nextuser = User.unscoped.find_by_uuid(uuid)
422 raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
427 raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
433 def self.register info
434 # login info expected fields, all can be optional but at minimum
435 # must supply either 'identity_url' or 'email'
447 identity_url = info['identity_url']
449 if identity_url && identity_url.length > 0
450 # Only local users can create sessions, hence uuid_like_pattern
452 user = User.unscoped.where('identity_url = ? and uuid like ?',
454 User.uuid_like_pattern).first
455 primary_user = user.redirects_to if user
459 # identity url is unset or didn't find matching record.
460 emails = [info['email']] + (info['alternate_emails'] || [])
461 emails.select! {|em| !em.nil? && !em.empty?}
463 User.unscoped.where('email in (?) and uuid like ?',
465 User.uuid_like_pattern).each do |user|
467 primary_user = user.redirects_to
468 elsif primary_user.uuid != user.redirects_to.uuid
469 raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
475 # New user registration
476 primary_user = User.new(:owner_uuid => system_user_uuid,
478 :is_active => Rails.configuration.Users.NewUsersAreActive)
480 primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
481 primary_user.identity_url = info['identity_url'] if identity_url
484 primary_user.email = info['email'] if info['email']
485 primary_user.first_name = info['first_name'] if info['first_name']
486 primary_user.last_name = info['last_name'] if info['last_name']
488 if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
489 raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
492 act_as_system_user do
501 def change_all_uuid_refs(old_uuid:, new_uuid:)
502 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
503 klass.columns.each do |col|
504 if col.name.end_with?('_uuid')
505 column = col.name.to_sym
506 klass.where(column => old_uuid).update_all(column => new_uuid)
512 def ensure_ownership_path_leads_to_user
516 def permission_to_update
517 if username_changed? || redirect_to_user_uuid_changed? || email_changed?
518 current_user.andand.is_admin
520 # users must be able to update themselves (even if they are
521 # inactive) in order to create sessions
522 self == current_user or super
526 def permission_to_create
527 current_user.andand.is_admin or
528 (self == current_user &&
529 self.redirect_to_user_uuid.nil? &&
530 self.is_active == Rails.configuration.Users.NewUsersAreActive)
534 return if self.uuid.end_with?('anonymouspublic')
535 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
536 !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
537 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
538 Rails.configuration.Users.AutoAdminFirstUser)
540 self.is_active = true
544 def find_usable_username_from(basename)
545 # If "basename" is a usable username, return that.
546 # Otherwise, find a unique username "basenameN", where N is the
547 # smallest integer greater than 1, and return that.
548 # Return nil if a unique username can't be found after reasonable
550 quoted_name = self.class.connection.quote_string(basename)
551 next_username = basename
553 while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
555 next_username = "%s%i" % [basename, next_suffix]
557 0.upto(6).each do |suffix_len|
558 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
560 where("username like '#{pattern}'").
562 order('username asc').
564 if other_user.username > next_username
566 elsif other_user.username == next_username
568 next_username = "%s%i" % [basename, next_suffix]
571 return next_username if (next_username.size <= pattern.size)
576 def prevent_privilege_escalation
577 if current_user.andand.is_admin
580 if self.is_active_changed?
581 if self.is_active != self.is_active_was
582 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
583 self.is_active = self.is_active_was
586 if self.is_admin_changed?
587 if self.is_admin != self.is_admin_was
588 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
589 self.is_admin = self.is_admin_was
595 def prevent_inactive_admin
596 if self.is_admin and not self.is_active
597 # There is no known use case for the strange set of permissions
598 # that would result from this change. It's safest to assume it's
599 # a mistake and disallow it outright.
600 raise "Admin users cannot be inactive"
605 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
606 nextpaths = graph[start]
607 return merged if !nextpaths
608 return merged if upstream_path.has_key? start
609 upstream_path[start] = true
610 upstream_mask ||= ALL_PERMISSIONS
611 nextpaths.each do |head, mask|
614 merged[head][k] ||= v if upstream_mask[k]
616 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
618 upstream_path.delete start
622 def create_user_repo_link(repo_name)
623 # repo_name is optional
625 logger.warn ("Repository name not given for #{self.uuid}.")
629 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
630 logger.info { "repo uuid: " + repo[:uuid] }
631 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
632 link_class: "permission",
633 name: "can_manage").first_or_create!
634 logger.info { "repo permission: " + repo_perm[:uuid] }
638 # create login permission for the given vm_uuid, if it does not already exist
639 def create_vm_login_permission_link(vm_uuid, repo_name)
640 # vm uuid is optional
641 return if vm_uuid == ""
643 vm = VirtualMachine.where(uuid: vm_uuid).first
645 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
646 raise "No vm found for #{vm_uuid}"
649 logger.info { "vm uuid: " + vm[:uuid] }
651 tail_uuid: uuid, head_uuid: vm.uuid,
652 link_class: "permission", name: "can_login",
657 select { |link| link.properties["username"] == repo_name }.
661 create(login_attrs.merge(properties: {"username" => repo_name}))
663 logger.info { "login permission: " + login_perm[:uuid] }
667 # add the user to the 'All users' group
668 def create_user_group_link
669 return (Link.where(tail_uuid: self.uuid,
670 head_uuid: all_users_group[:uuid],
671 link_class: 'permission',
672 name: 'can_read').first or
673 Link.create(tail_uuid: self.uuid,
674 head_uuid: all_users_group[:uuid],
675 link_class: 'permission',
679 # Give the special "System group" permission to manage this user and
680 # all of this user's stuff.
681 def add_system_group_permission_link
682 return true if uuid == system_user_uuid
683 act_as_system_user do
684 Link.create(link_class: 'permission',
686 tail_uuid: system_group_uuid,
687 head_uuid: self.uuid)
691 # Send admin notifications
692 def send_admin_notifications
693 AdminNotifier.new_user(self).deliver_now
694 if not self.is_active then
695 AdminNotifier.new_inactive_user(self).deliver_now
699 # Automatically setup if is_active flag turns on
700 def setup_on_activate
701 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
702 if is_active && (new_record? || is_active_changed?)
707 # Automatically setup new user during creation
708 def auto_setup_new_user
711 create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
713 repo_name = "#{username}/#{username}"
714 if Rails.configuration.Users.AutoSetupNewUsersWithRepository and
715 Repository.where(name: repo_name).first.nil?
716 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
717 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
718 link_class: "permission", name: "can_manage")
723 # Send notification if the user saved profile for the first time
724 def send_profile_created_notification
725 if self.prefs_changed?
726 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
727 profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
728 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
733 def verify_repositories_empty
734 unless repositories.first.nil?
735 errors.add(:username, "can't be unset when the user owns repositories")
740 def sync_repository_names
741 old_name_re = /^#{Regexp.escape(username_was)}\//
742 name_sub = "#{username}/"
743 repositories.find_each do |repo|
744 repo.name = repo.name.sub(old_name_re, name_sub)