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 before_update :prevent_privilege_escalation
25 before_update :prevent_inactive_admin
26 before_update :verify_repositories_empty, :if => Proc.new { |user|
27 user.username.nil? and user.username_changed?
29 before_update :setup_on_activate
30 before_create :check_auto_admin
31 before_create :set_initial_username, :if => Proc.new { |user|
32 user.username.nil? and user.email
34 after_create :setup_on_activate
35 after_create :add_system_group_permission_link
36 after_create :invalidate_permissions_cache
37 after_create :auto_setup_new_user, :if => Proc.new { |user|
38 Rails.configuration.Users.AutoSetupNewUsers and
39 (user.uuid != system_user_uuid) and
40 (user.uuid != anonymous_user_uuid)
42 after_create :send_admin_notifications
43 after_update :send_profile_created_notification
44 after_update :sync_repository_names, :if => Proc.new { |user|
45 (user.uuid != system_user_uuid) and
46 user.username_changed? and
47 (not user.username_was.nil?)
50 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
51 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
53 default_scope { where('redirect_to_user_uuid is null') }
55 api_accessible :user, extend: :common do |t|
69 ALL_PERMISSIONS = {read: true, write: true, manage: true}
71 # Map numeric permission levels (see lib/create_permission_view.sql)
72 # back to read/write/manage flags.
76 {read: true, write: true},
77 {read: true, write: true, manage: true}]
80 "#{first_name} #{last_name}".strip
85 Rails.configuration.Users.NewUsersAreActive ||
86 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
89 def groups_i_can(verb)
90 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
92 my_groups << anonymous_group_uuid
98 return true if is_admin
99 actions.each do |action, target|
101 if target.respond_to? :uuid
102 target_uuid = target.uuid
105 target = ArvadosModel.find_by_uuid(target_uuid)
108 next if target_uuid == self.uuid
109 next if (group_permissions[target_uuid] and
110 group_permissions[target_uuid][action])
111 if target.respond_to? :owner_uuid
112 next if target.owner_uuid == self.uuid
113 next if (group_permissions[target.owner_uuid] and
114 group_permissions[target.owner_uuid][action])
116 sufficient_perms = case action
120 ['can_manage', 'can_write']
122 ['can_manage', 'can_write', 'can_read']
124 # (Skip this kind of permission opportunity
125 # if action is an unknown permission type)
128 # Check permission links with head_uuid pointing directly at
129 # the target object. If target is a Group, this is redundant
130 # and will fail except [a] if permission caching is broken or
131 # [b] during a race condition, where a permission link has
133 if Link.where(link_class: 'permission',
134 name: sufficient_perms,
135 tail_uuid: groups_i_can(action) + [self.uuid],
136 head_uuid: target_uuid).any?
145 def self.invalidate_permissions_cache(async=false)
146 refresh_permission_view(async)
149 def invalidate_permissions_cache
150 User.invalidate_permissions_cache
153 # Return a hash of {user_uuid: group_perms}
154 def self.all_group_permissions
156 ActiveRecord::Base.connection.
157 exec_query("SELECT user_uuid, target_owner_uuid, perm_level, trashed
158 FROM #{PERMISSION_VIEW}
159 WHERE target_owner_uuid IS NOT NULL",
160 # "name" arg is a query label that appears in logs:
161 "all_group_permissions",
162 ).rows.each do |user_uuid, group_uuid, max_p_val, trashed|
163 all_perms[user_uuid] ||= {}
164 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
169 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
170 # and perm_hash[:write] are true if this user can read and write
171 # objects owned by group_uuid.
172 def group_permissions
173 group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
174 ActiveRecord::Base.connection.
175 exec_query("SELECT target_owner_uuid, perm_level, trashed
176 FROM #{PERMISSION_VIEW}
178 AND target_owner_uuid IS NOT NULL",
179 # "name" arg is a query label that appears in logs:
180 "group_permissions for #{uuid}",
181 # "binds" arg is an array of [col_id, value] for '$1' vars:
183 ).rows.each do |group_uuid, max_p_val, trashed|
184 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
190 def setup(openid_prefix:, repo_name: nil, vm_uuid: nil)
191 oid_login_perm = create_oid_login_perm openid_prefix
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 [oid_login_perm, 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
202 Link.where(tail_uuid: self.email,
203 link_class: 'permission',
204 name: 'can_login').destroy_all
206 # delete repo_perms for this user
207 Link.where(tail_uuid: self.uuid,
208 link_class: 'permission',
209 name: 'can_manage').destroy_all
211 # delete vm_login_perms for this user
212 Link.where(tail_uuid: self.uuid,
213 link_class: 'permission',
214 name: 'can_login').destroy_all
216 # delete "All users" group read permissions for this user
217 group = Group.where(name: 'All users').select do |g|
218 g[:uuid].match(/-f+$/)
220 Link.where(tail_uuid: self.uuid,
221 head_uuid: group[:uuid],
222 link_class: 'permission',
223 name: 'can_read').destroy_all
225 # delete any signatures by this user
226 Link.where(link_class: 'signature',
227 tail_uuid: self.uuid).destroy_all
229 # delete user preferences (including profile)
232 # mark the user as inactive
233 self.is_active = false
237 def set_initial_username(requested: false)
238 if !requested.is_a?(String) || requested.empty?
239 email_parts = email.partition("@")
240 local_parts = email_parts.first.partition("+")
241 if email_parts.any?(&:empty?)
243 elsif not local_parts.first.empty?
244 requested = local_parts.first
246 requested = email_parts.first
249 requested.sub!(/^[^A-Za-z]+/, "")
250 requested.gsub!(/[^A-Za-z0-9]/, "")
251 unless requested.empty?
252 self.username = find_usable_username_from(requested)
256 def update_uuid(new_uuid:)
257 if !current_user.andand.is_admin
258 raise PermissionDeniedError
260 if uuid == system_user_uuid || uuid == anonymous_user_uuid
261 raise "update_uuid cannot update system accounts"
263 if self.class != self.class.resource_class_for_uuid(new_uuid)
264 raise "invalid new_uuid #{new_uuid.inspect}"
266 transaction(requires_new: true) do
270 save!(validate: false)
271 change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
275 # Move this user's (i.e., self's) owned items to new_owner_uuid and
276 # new_user_uuid (for things normally owned directly by the user).
278 # If redirect_auth is true, also reassign auth tokens and ssh keys,
279 # and redirect this account to redirect_to_user_uuid, i.e., when a
280 # caller authenticates to this account in the future, the account
281 # redirect_to_user_uuid account will be used instead.
283 # current_user must have admin privileges, i.e., the caller is
284 # responsible for checking permission to do this.
285 def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
286 raise PermissionDeniedError if !current_user.andand.is_admin
287 raise "not implemented" if !new_user_uuid
288 transaction(requires_new: true) do
290 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
292 new_user = User.where(uuid: new_user_uuid).first
293 raise "user does not exist" if !new_user
294 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
296 if redirect_to_new_user
297 # Existing API tokens and ssh keys are updated to authenticate
299 ApiClientAuthorization.
301 update_all(user_id: new_user.id)
304 [AuthorizedKey, :owner_uuid],
305 [AuthorizedKey, :authorized_user_uuid],
311 # Destroy API tokens and ssh keys associated with the old
313 ApiClientAuthorization.where(user_id: id).destroy_all
314 AuthorizedKey.where(owner_uuid: uuid).destroy_all
315 AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
322 # References to the old user UUID in the context of a user ID
323 # (rather than a "home project" in the project hierarchy) are
324 # updated to point to the new user.
325 user_updates.each do |klass, column|
326 klass.where(column => uuid).update_all(column => new_user.uuid)
329 # Need to update repository names to new username
330 old_repo_name_re = /^#{Regexp.escape(username)}\//
331 Repository.where(:owner_uuid => uuid).each do |repo|
332 repo.owner_uuid = new_user.uuid
333 repo_name_sub = "#{new_user.username}/"
334 name = repo.name.sub(old_repo_name_re, repo_name_sub)
335 while (conflict = Repository.where(:name => name).first) != nil
336 repo_name_sub += "migrated"
337 name = repo.name.sub(old_repo_name_re, repo_name_sub)
343 # References to the merged user's "home project" are updated to
344 # point to new_owner_uuid.
345 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
346 next if [ApiClientAuthorization,
350 Repository].include?(klass)
351 next if !klass.columns.collect(&:name).include?('owner_uuid')
352 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
355 if redirect_to_new_user
356 update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
358 invalidate_permissions_cache
365 while (uuid = user.redirect_to_user_uuid)
366 user = User.unscoped.find_by_uuid(uuid)
368 raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid #{uuid}")
372 raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
378 def self.register info
379 # login info expected fields, all can be optional but at minimum
380 # must supply either 'identity_url' or 'email'
389 info = info.with_indifferent_access
394 identity_url = info['identity_url']
396 if identity_url && identity_url.length > 0
397 # Only local users can create sessions, hence uuid_like_pattern
399 user = User.unscoped.where('identity_url = ? and uuid like ?',
401 User.uuid_like_pattern).first
402 primary_user = user.redirects_to if user
406 # identity url is unset or didn't find matching record.
407 emails = [info['email']] + (info['alternate_emails'] || [])
408 emails.select! {|em| !em.nil? && !em.empty?}
410 User.unscoped.where('email in (?) and uuid like ?',
412 User.uuid_like_pattern).each do |user|
414 primary_user = user.redirects_to
415 elsif primary_user.uuid != user.redirects_to.uuid
416 raise "Ambigious email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
422 # New user registration
423 primary_user = User.new(:owner_uuid => system_user_uuid,
425 :is_active => Rails.configuration.Users.NewUsersAreActive)
427 primary_user.set_initial_username(requested: info['username']) if info['username']
428 primary_user.identity_url = info['identity_url'] if identity_url
431 primary_user.email = info['email'] if info['email']
432 primary_user.first_name = info['first_name'] if info['first_name']
433 primary_user.last_name = info['last_name'] if info['last_name']
435 if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
436 raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
439 act_as_system_user do
448 def change_all_uuid_refs(old_uuid:, new_uuid:)
449 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
450 klass.columns.each do |col|
451 if col.name.end_with?('_uuid')
452 column = col.name.to_sym
453 klass.where(column => old_uuid).update_all(column => new_uuid)
459 def ensure_ownership_path_leads_to_user
463 def permission_to_update
464 if username_changed? || redirect_to_user_uuid_changed? || email_changed?
465 current_user.andand.is_admin
467 # users must be able to update themselves (even if they are
468 # inactive) in order to create sessions
469 self == current_user or super
473 def permission_to_create
474 current_user.andand.is_admin or
475 (self == current_user &&
476 self.redirect_to_user_uuid.nil? &&
477 self.is_active == Rails.configuration.Users.NewUsersAreActive)
481 return if self.uuid.end_with?('anonymouspublic')
482 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
483 !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
484 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
485 Rails.configuration.Users.AutoAdminFirstUser)
487 self.is_active = true
491 def find_usable_username_from(basename)
492 # If "basename" is a usable username, return that.
493 # Otherwise, find a unique username "basenameN", where N is the
494 # smallest integer greater than 1, and return that.
495 # Return nil if a unique username can't be found after reasonable
497 quoted_name = self.class.connection.quote_string(basename)
498 next_username = basename
500 while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
502 next_username = "%s%i" % [basename, next_suffix]
504 0.upto(6).each do |suffix_len|
505 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
507 where("username like '#{pattern}'").
509 order('username asc').
511 if other_user.username > next_username
513 elsif other_user.username == next_username
515 next_username = "%s%i" % [basename, next_suffix]
518 return next_username if (next_username.size <= pattern.size)
523 def prevent_privilege_escalation
524 if current_user.andand.is_admin
527 if self.is_active_changed?
528 if self.is_active != self.is_active_was
529 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
530 self.is_active = self.is_active_was
533 if self.is_admin_changed?
534 if self.is_admin != self.is_admin_was
535 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
536 self.is_admin = self.is_admin_was
542 def prevent_inactive_admin
543 if self.is_admin and not self.is_active
544 # There is no known use case for the strange set of permissions
545 # that would result from this change. It's safest to assume it's
546 # a mistake and disallow it outright.
547 raise "Admin users cannot be inactive"
552 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
553 nextpaths = graph[start]
554 return merged if !nextpaths
555 return merged if upstream_path.has_key? start
556 upstream_path[start] = true
557 upstream_mask ||= ALL_PERMISSIONS
558 nextpaths.each do |head, mask|
561 merged[head][k] ||= v if upstream_mask[k]
563 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
565 upstream_path.delete start
569 def create_oid_login_perm(openid_prefix)
570 # Check oid_login_perm
571 oid_login_perms = Link.where(tail_uuid: self.email,
572 head_uuid: self.uuid,
573 link_class: 'permission',
576 if !oid_login_perms.any?
577 # create openid login permission
578 oid_login_perm = Link.create!(link_class: 'permission',
580 tail_uuid: self.email,
581 head_uuid: self.uuid,
583 "identity_url_prefix" => openid_prefix,
585 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
587 oid_login_perm = oid_login_perms.first
590 return oid_login_perm
593 def create_user_repo_link(repo_name)
594 # repo_name is optional
596 logger.warn ("Repository name not given for #{self.uuid}.")
600 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
601 logger.info { "repo uuid: " + repo[:uuid] }
602 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
603 link_class: "permission",
604 name: "can_manage").first_or_create!
605 logger.info { "repo permission: " + repo_perm[:uuid] }
609 # create login permission for the given vm_uuid, if it does not already exist
610 def create_vm_login_permission_link(vm_uuid, repo_name)
611 # vm uuid is optional
612 return if vm_uuid == ""
614 vm = VirtualMachine.where(uuid: vm_uuid).first
616 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
617 raise "No vm found for #{vm_uuid}"
620 logger.info { "vm uuid: " + vm[:uuid] }
622 tail_uuid: uuid, head_uuid: vm.uuid,
623 link_class: "permission", name: "can_login",
628 select { |link| link.properties["username"] == repo_name }.
632 create(login_attrs.merge(properties: {"username" => repo_name}))
634 logger.info { "login permission: " + login_perm[:uuid] }
638 # add the user to the 'All users' group
639 def create_user_group_link
640 return (Link.where(tail_uuid: self.uuid,
641 head_uuid: all_users_group[:uuid],
642 link_class: 'permission',
643 name: 'can_read').first or
644 Link.create(tail_uuid: self.uuid,
645 head_uuid: all_users_group[:uuid],
646 link_class: 'permission',
650 # Give the special "System group" permission to manage this user and
651 # all of this user's stuff.
652 def add_system_group_permission_link
653 return true if uuid == system_user_uuid
654 act_as_system_user do
655 Link.create(link_class: 'permission',
657 tail_uuid: system_group_uuid,
658 head_uuid: self.uuid)
662 # Send admin notifications
663 def send_admin_notifications
664 AdminNotifier.new_user(self).deliver_now
665 if not self.is_active then
666 AdminNotifier.new_inactive_user(self).deliver_now
670 # Automatically setup if is_active flag turns on
671 def setup_on_activate
672 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
673 if is_active && (new_record? || is_active_changed?)
674 setup(openid_prefix: Rails.configuration.default_openid_prefix)
678 # Automatically setup new user during creation
679 def auto_setup_new_user
680 setup(openid_prefix: Rails.configuration.default_openid_prefix)
682 create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
684 repo_name = "#{username}/#{username}"
685 if Rails.configuration.Users.AutoSetupNewUsersWithRepository and
686 Repository.where(name: repo_name).first.nil?
687 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
688 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
689 link_class: "permission", name: "can_manage")
694 # Send notification if the user saved profile for the first time
695 def send_profile_created_notification
696 if self.prefs_changed?
697 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
698 profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
699 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
704 def verify_repositories_empty
705 unless repositories.first.nil?
706 errors.add(:username, "can't be unset when the user owns repositories")
711 def sync_repository_names
712 old_name_re = /^#{Regexp.escape(username_was)}\//
713 name_sub = "#{username}/"
714 repositories.find_each do |repo|
715 repo.name = repo.name.sub(old_name_re, name_sub)