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
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 before_update :prevent_privilege_escalation
24 before_update :prevent_inactive_admin
25 before_update :verify_repositories_empty, :if => Proc.new { |user|
26 user.username.nil? and user.username_changed?
28 before_update :setup_on_activate
29 before_create :check_auto_admin
30 before_create :set_initial_username, :if => Proc.new { |user|
31 user.username.nil? and user.email
33 after_create :setup_on_activate
34 after_create :add_system_group_permission_link
35 after_create :invalidate_permissions_cache
36 after_create :auto_setup_new_user, :if => Proc.new { |user|
37 Rails.configuration.Users.AutoSetupNewUsers and
38 (user.uuid != system_user_uuid) and
39 (user.uuid != anonymous_user_uuid)
41 after_create :send_admin_notifications
42 after_update :send_profile_created_notification
43 after_update :sync_repository_names, :if => Proc.new { |user|
44 (user.uuid != system_user_uuid) and
45 user.username_changed? and
46 (not user.username_was.nil?)
49 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
50 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
52 default_scope { where('redirect_to_user_uuid is null') }
54 api_accessible :user, extend: :common do |t|
68 ALL_PERMISSIONS = {read: true, write: true, manage: true}
70 # Map numeric permission levels (see lib/create_permission_view.sql)
71 # back to read/write/manage flags.
75 {read: true, write: true},
76 {read: true, write: true, manage: true}]
79 "#{first_name} #{last_name}".strip
84 Rails.configuration.Users.NewUsersAreActive ||
85 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
88 def groups_i_can(verb)
89 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
91 my_groups << anonymous_group_uuid
97 return true if is_admin
98 actions.each do |action, target|
100 if target.respond_to? :uuid
101 target_uuid = target.uuid
104 target = ArvadosModel.find_by_uuid(target_uuid)
107 next if target_uuid == self.uuid
108 next if (group_permissions[target_uuid] and
109 group_permissions[target_uuid][action])
110 if target.respond_to? :owner_uuid
111 next if target.owner_uuid == self.uuid
112 next if (group_permissions[target.owner_uuid] and
113 group_permissions[target.owner_uuid][action])
115 sufficient_perms = case action
119 ['can_manage', 'can_write']
121 ['can_manage', 'can_write', 'can_read']
123 # (Skip this kind of permission opportunity
124 # if action is an unknown permission type)
127 # Check permission links with head_uuid pointing directly at
128 # the target object. If target is a Group, this is redundant
129 # and will fail except [a] if permission caching is broken or
130 # [b] during a race condition, where a permission link has
132 if Link.where(link_class: 'permission',
133 name: sufficient_perms,
134 tail_uuid: groups_i_can(action) + [self.uuid],
135 head_uuid: target_uuid).any?
144 def self.invalidate_permissions_cache(async=false)
145 refresh_permission_view(async)
148 def invalidate_permissions_cache
149 User.invalidate_permissions_cache
152 # Return a hash of {user_uuid: group_perms}
153 def self.all_group_permissions
155 ActiveRecord::Base.connection.
156 exec_query("SELECT user_uuid, target_owner_uuid, perm_level, trashed
157 FROM #{PERMISSION_VIEW}
158 WHERE target_owner_uuid IS NOT NULL",
159 # "name" arg is a query label that appears in logs:
160 "all_group_permissions",
161 ).rows.each do |user_uuid, group_uuid, max_p_val, trashed|
162 all_perms[user_uuid] ||= {}
163 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
168 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
169 # and perm_hash[:write] are true if this user can read and write
170 # objects owned by group_uuid.
171 def group_permissions
172 group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
173 ActiveRecord::Base.connection.
174 exec_query("SELECT target_owner_uuid, perm_level, trashed
175 FROM #{PERMISSION_VIEW}
177 AND target_owner_uuid IS NOT NULL",
178 # "name" arg is a query label that appears in logs:
179 "group_permissions for #{uuid}",
180 # "binds" arg is an array of [col_id, value] for '$1' vars:
182 ).rows.each do |group_uuid, max_p_val, trashed|
183 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
189 def setup(openid_prefix:, repo_name: nil, vm_uuid: nil)
190 oid_login_perm = create_oid_login_perm openid_prefix
191 repo_perm = create_user_repo_link repo_name
192 vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
193 group_perm = create_user_group_link
195 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
198 # delete user signatures, login, repo, and vm perms, and mark as inactive
200 # delete oid_login_perms for this user
201 Link.where(tail_uuid: self.email,
202 link_class: 'permission',
203 name: 'can_login').destroy_all
205 # delete repo_perms for this user
206 Link.where(tail_uuid: self.uuid,
207 link_class: 'permission',
208 name: 'can_manage').destroy_all
210 # delete vm_login_perms for this user
211 Link.where(tail_uuid: self.uuid,
212 link_class: 'permission',
213 name: 'can_login').destroy_all
215 # delete "All users" group read permissions for this user
216 group = Group.where(name: 'All users').select do |g|
217 g[:uuid].match(/-f+$/)
219 Link.where(tail_uuid: self.uuid,
220 head_uuid: group[:uuid],
221 link_class: 'permission',
222 name: 'can_read').destroy_all
224 # delete any signatures by this user
225 Link.where(link_class: 'signature',
226 tail_uuid: self.uuid).destroy_all
228 # delete user preferences (including profile)
231 # mark the user as inactive
232 self.is_active = false
236 def set_initial_username(requested: false)
237 if !requested.is_a?(String) || requested.empty?
238 email_parts = email.partition("@")
239 local_parts = email_parts.first.partition("+")
240 if email_parts.any?(&:empty?)
242 elsif not local_parts.first.empty?
243 requested = local_parts.first
245 requested = email_parts.first
248 requested.sub!(/^[^A-Za-z]+/, "")
249 requested.gsub!(/[^A-Za-z0-9]/, "")
250 unless requested.empty?
251 self.username = find_usable_username_from(requested)
255 def update_uuid(new_uuid:)
256 if !current_user.andand.is_admin
257 raise PermissionDeniedError
259 if uuid == system_user_uuid || uuid == anonymous_user_uuid
260 raise "update_uuid cannot update system accounts"
262 if self.class != self.class.resource_class_for_uuid(new_uuid)
263 raise "invalid new_uuid #{new_uuid.inspect}"
265 transaction(requires_new: true) do
269 save!(validate: false)
270 change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
274 # Move this user's (i.e., self's) owned items into new_owner_uuid.
275 # Also redirect future uses of this account to
276 # redirect_to_user_uuid, i.e., when a caller authenticates to this
277 # account in the future, the account redirect_to_user_uuid account
278 # will be used instead.
280 # current_user must have admin privileges, i.e., the caller is
281 # responsible for checking permission to do this.
282 def merge(new_owner_uuid:, redirect_to_user_uuid:)
283 raise PermissionDeniedError if !current_user.andand.is_admin
284 raise "not implemented" if !redirect_to_user_uuid
285 transaction(requires_new: true) do
287 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
289 new_user = User.where(uuid: redirect_to_user_uuid).first
290 raise "user does not exist" if !new_user
291 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
293 # Existing API tokens are updated to authenticate to the new
295 ApiClientAuthorization.
297 update_all(user_id: new_user.id)
299 # References to the old user UUID in the context of a user ID
300 # (rather than a "home project" in the project hierarchy) are
301 # updated to point to the new user.
303 [AuthorizedKey, :owner_uuid],
304 [AuthorizedKey, :authorized_user_uuid],
305 [Repository, :owner_uuid],
309 ].each do |klass, column|
310 klass.where(column => uuid).update_all(column => new_user.uuid)
313 # References to the merged user's "home project" are updated to
314 # point to new_owner_uuid.
315 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
316 next if [ApiClientAuthorization,
320 Repository].include?(klass)
321 next if !klass.columns.collect(&:name).include?('owner_uuid')
322 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
325 update_attributes!(redirect_to_user_uuid: new_user.uuid)
326 invalidate_permissions_cache
333 while (uuid = user.redirect_to_user_uuid)
334 user = User.unscoped.find_by_uuid(uuid)
336 raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid #{uuid}")
340 raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
346 def self.register info
347 # login info expected fields, all can be optional but at minimum
348 # must supply either 'identity_url' or 'email'
357 info = info.with_indifferent_access
362 identity_url = info['identity_url']
364 if identity_url && identity_url.length > 0
365 # Only local users can create sessions, hence uuid_like_pattern
367 user = User.unscoped.where('identity_url = ? and uuid like ?',
369 User.uuid_like_pattern).first
370 primary_user = user.redirects_to if user
374 # identity url is unset or didn't find matching record.
375 emails = [info['email']] + (info['alternate_emails'] || [])
376 emails.select! {|em| !em.nil? && !em.empty?}
378 # Go through each email address, try to find a user record
379 # corresponding to one of the addresses supplied.
381 user = User.unscoped.where('email = ? and uuid like ?',
383 User.uuid_like_pattern).first
385 primary_user = user.redirects_to
392 # New user registration
393 primary_user = User.new(:owner_uuid => system_user_uuid,
395 :is_active => Rails.configuration.Users.NewUsersAreActive)
397 primary_user.set_initial_username(requested: info['username']) if info['username']
400 primary_user.email = info['email'] if info['email']
401 primary_user.identity_url = info['identity_url'] if identity_url
402 primary_user.first_name = info['first_name'] if info['first_name']
403 primary_user.last_name = info['last_name'] if info['last_name']
405 if (!primary_user.email or primary_user.identity_url.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
406 raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
409 act_as_system_user do
418 def change_all_uuid_refs(old_uuid:, new_uuid:)
419 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
420 klass.columns.each do |col|
421 if col.name.end_with?('_uuid')
422 column = col.name.to_sym
423 klass.where(column => old_uuid).update_all(column => new_uuid)
429 def ensure_ownership_path_leads_to_user
433 def permission_to_update
434 if username_changed? || redirect_to_user_uuid_changed?
435 current_user.andand.is_admin
437 # users must be able to update themselves (even if they are
438 # inactive) in order to create sessions
439 self == current_user or super
443 def permission_to_create
444 current_user.andand.is_admin or
445 (self == current_user &&
446 self.redirect_to_user_uuid.nil? &&
447 self.is_active == Rails.configuration.Users.NewUsersAreActive)
451 return if self.uuid.end_with?('anonymouspublic')
452 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
453 !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
454 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
455 Rails.configuration.Users.AutoAdminFirstUser)
457 self.is_active = true
461 def find_usable_username_from(basename)
462 # If "basename" is a usable username, return that.
463 # Otherwise, find a unique username "basenameN", where N is the
464 # smallest integer greater than 1, and return that.
465 # Return nil if a unique username can't be found after reasonable
467 quoted_name = self.class.connection.quote_string(basename)
468 next_username = basename
470 while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
472 next_username = "%s%i" % [basename, next_suffix]
474 0.upto(6).each do |suffix_len|
475 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
477 where("username like '#{pattern}'").
479 order('username asc').
481 if other_user.username > next_username
483 elsif other_user.username == next_username
485 next_username = "%s%i" % [basename, next_suffix]
488 return next_username if (next_username.size <= pattern.size)
493 def prevent_privilege_escalation
494 if current_user.andand.is_admin
497 if self.is_active_changed?
498 if self.is_active != self.is_active_was
499 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
500 self.is_active = self.is_active_was
503 if self.is_admin_changed?
504 if self.is_admin != self.is_admin_was
505 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
506 self.is_admin = self.is_admin_was
512 def prevent_inactive_admin
513 if self.is_admin and not self.is_active
514 # There is no known use case for the strange set of permissions
515 # that would result from this change. It's safest to assume it's
516 # a mistake and disallow it outright.
517 raise "Admin users cannot be inactive"
522 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
523 nextpaths = graph[start]
524 return merged if !nextpaths
525 return merged if upstream_path.has_key? start
526 upstream_path[start] = true
527 upstream_mask ||= ALL_PERMISSIONS
528 nextpaths.each do |head, mask|
531 merged[head][k] ||= v if upstream_mask[k]
533 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
535 upstream_path.delete start
539 def create_oid_login_perm(openid_prefix)
540 # Check oid_login_perm
541 oid_login_perms = Link.where(tail_uuid: self.email,
542 head_uuid: self.uuid,
543 link_class: 'permission',
546 if !oid_login_perms.any?
547 # create openid login permission
548 oid_login_perm = Link.create!(link_class: 'permission',
550 tail_uuid: self.email,
551 head_uuid: self.uuid,
553 "identity_url_prefix" => openid_prefix,
555 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
557 oid_login_perm = oid_login_perms.first
560 return oid_login_perm
563 def create_user_repo_link(repo_name)
564 # repo_name is optional
566 logger.warn ("Repository name not given for #{self.uuid}.")
570 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
571 logger.info { "repo uuid: " + repo[:uuid] }
572 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
573 link_class: "permission",
574 name: "can_manage").first_or_create!
575 logger.info { "repo permission: " + repo_perm[:uuid] }
579 # create login permission for the given vm_uuid, if it does not already exist
580 def create_vm_login_permission_link(vm_uuid, repo_name)
581 # vm uuid is optional
582 return if vm_uuid == ""
584 vm = VirtualMachine.where(uuid: vm_uuid).first
586 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
587 raise "No vm found for #{vm_uuid}"
590 logger.info { "vm uuid: " + vm[:uuid] }
592 tail_uuid: uuid, head_uuid: vm.uuid,
593 link_class: "permission", name: "can_login",
598 select { |link| link.properties["username"] == repo_name }.
602 create(login_attrs.merge(properties: {"username" => repo_name}))
604 logger.info { "login permission: " + login_perm[:uuid] }
608 # add the user to the 'All users' group
609 def create_user_group_link
610 return (Link.where(tail_uuid: self.uuid,
611 head_uuid: all_users_group[:uuid],
612 link_class: 'permission',
613 name: 'can_read').first or
614 Link.create(tail_uuid: self.uuid,
615 head_uuid: all_users_group[:uuid],
616 link_class: 'permission',
620 # Give the special "System group" permission to manage this user and
621 # all of this user's stuff.
622 def add_system_group_permission_link
623 return true if uuid == system_user_uuid
624 act_as_system_user do
625 Link.create(link_class: 'permission',
627 tail_uuid: system_group_uuid,
628 head_uuid: self.uuid)
632 # Send admin notifications
633 def send_admin_notifications
634 AdminNotifier.new_user(self).deliver_now
635 if not self.is_active then
636 AdminNotifier.new_inactive_user(self).deliver_now
640 # Automatically setup if is_active flag turns on
641 def setup_on_activate
642 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
643 if is_active && (new_record? || is_active_changed?)
644 setup(openid_prefix: Rails.configuration.default_openid_prefix)
648 # Automatically setup new user during creation
649 def auto_setup_new_user
650 setup(openid_prefix: Rails.configuration.default_openid_prefix)
652 create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
654 repo_name = "#{username}/#{username}"
655 if Rails.configuration.Users.AutoSetupNewUsersWithRepository and
656 Repository.where(name: repo_name).first.nil?
657 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
658 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
659 link_class: "permission", name: "can_manage")
664 # Send notification if the user saved profile for the first time
665 def send_profile_created_notification
666 if self.prefs_changed?
667 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
668 profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
669 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
674 def verify_repositories_empty
675 unless repositories.first.nil?
676 errors.add(:username, "can't be unset when the user owns repositories")
681 def sync_repository_names
682 old_name_re = /^#{Regexp.escape(username_was)}\//
683 name_sub = "#{username}/"
684 repositories.find_each do |repo|
685 repo.name = repo.name.sub(old_name_re, name_sub)