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 :add_system_group_permission_link
34 after_create :invalidate_permissions_cache
35 after_create :auto_setup_new_user, :if => Proc.new { |user|
36 Rails.configuration.auto_setup_new_users and
37 (user.uuid != system_user_uuid) and
38 (user.uuid != anonymous_user_uuid)
40 after_create :send_admin_notifications
41 after_update :send_profile_created_notification
42 after_update :sync_repository_names, :if => Proc.new { |user|
43 (user.uuid != system_user_uuid) and
44 user.username_changed? and
45 (not user.username_was.nil?)
48 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
49 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
51 default_scope { where('redirect_to_user_uuid is null') }
53 api_accessible :user, extend: :common do |t|
67 ALL_PERMISSIONS = {read: true, write: true, manage: true}
69 # Map numeric permission levels (see lib/create_permission_view.sql)
70 # back to read/write/manage flags.
74 {read: true, write: true},
75 {read: true, write: true, manage: true}]
78 "#{first_name} #{last_name}".strip
83 Rails.configuration.new_users_are_active ||
84 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
87 def groups_i_can(verb)
88 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
90 my_groups << anonymous_group_uuid
96 return true if is_admin
97 actions.each do |action, target|
99 if target.respond_to? :uuid
100 target_uuid = target.uuid
103 target = ArvadosModel.find_by_uuid(target_uuid)
106 next if target_uuid == self.uuid
107 next if (group_permissions[target_uuid] and
108 group_permissions[target_uuid][action])
109 if target.respond_to? :owner_uuid
110 next if target.owner_uuid == self.uuid
111 next if (group_permissions[target.owner_uuid] and
112 group_permissions[target.owner_uuid][action])
114 sufficient_perms = case action
118 ['can_manage', 'can_write']
120 ['can_manage', 'can_write', 'can_read']
122 # (Skip this kind of permission opportunity
123 # if action is an unknown permission type)
126 # Check permission links with head_uuid pointing directly at
127 # the target object. If target is a Group, this is redundant
128 # and will fail except [a] if permission caching is broken or
129 # [b] during a race condition, where a permission link has
131 if Link.where(link_class: 'permission',
132 name: sufficient_perms,
133 tail_uuid: groups_i_can(action) + [self.uuid],
134 head_uuid: target_uuid).any?
143 def self.invalidate_permissions_cache(timestamp=nil)
144 if Rails.configuration.async_permissions_update
145 timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
146 connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
148 refresh_permission_view
152 def invalidate_permissions_cache(timestamp=nil)
153 User.invalidate_permissions_cache
156 # Return a hash of {user_uuid: group_perms}
157 def self.all_group_permissions
159 ActiveRecord::Base.connection.
160 exec_query("SELECT user_uuid, target_owner_uuid, perm_level, trashed
161 FROM #{PERMISSION_VIEW}
162 WHERE target_owner_uuid IS NOT NULL",
163 # "name" arg is a query label that appears in logs:
164 "all_group_permissions",
165 ).rows.each do |user_uuid, group_uuid, max_p_val, trashed|
166 all_perms[user_uuid] ||= {}
167 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
172 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
173 # and perm_hash[:write] are true if this user can read and write
174 # objects owned by group_uuid.
175 def group_permissions
176 group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
177 ActiveRecord::Base.connection.
178 exec_query("SELECT target_owner_uuid, perm_level, trashed
179 FROM #{PERMISSION_VIEW}
181 AND target_owner_uuid IS NOT NULL",
182 # "name" arg is a query label that appears in logs:
183 "group_permissions for #{uuid}",
184 # "binds" arg is an array of [col_id, value] for '$1' vars:
186 ).rows.each do |group_uuid, max_p_val, trashed|
187 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
193 def setup(openid_prefix:, repo_name: nil, vm_uuid: nil)
194 oid_login_perm = create_oid_login_perm openid_prefix
195 repo_perm = create_user_repo_link repo_name
196 vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
197 group_perm = create_user_group_link
199 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
202 # delete user signatures, login, repo, and vm perms, and mark as inactive
204 # delete oid_login_perms for this user
205 Link.destroy_all(tail_uuid: self.email,
206 link_class: 'permission',
209 # delete repo_perms for this user
210 Link.destroy_all(tail_uuid: self.uuid,
211 link_class: 'permission',
214 # delete vm_login_perms for this user
215 Link.destroy_all(tail_uuid: self.uuid,
216 link_class: 'permission',
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.destroy_all(tail_uuid: self.uuid,
224 head_uuid: group[:uuid],
225 link_class: 'permission',
228 # delete any signatures by this user
229 Link.destroy_all(link_class: 'signature',
230 tail_uuid: self.uuid)
232 # delete user preferences (including profile)
235 # mark the user as inactive
236 self.is_active = false
240 def set_initial_username(requested: false)
241 if !requested.is_a?(String) || requested.empty?
242 email_parts = email.partition("@")
243 local_parts = email_parts.first.partition("+")
244 if email_parts.any?(&:empty?)
246 elsif not local_parts.first.empty?
247 requested = local_parts.first
249 requested = email_parts.first
252 requested.sub!(/^[^A-Za-z]+/, "")
253 requested.gsub!(/[^A-Za-z0-9]/, "")
254 unless requested.empty?
255 self.username = find_usable_username_from(requested)
259 def update_uuid(new_uuid:)
260 if !current_user.andand.is_admin
261 raise PermissionDeniedError
263 if uuid == system_user_uuid || uuid == anonymous_user_uuid
264 raise "update_uuid cannot update system accounts"
266 if self.class != self.class.resource_class_for_uuid(new_uuid)
267 raise "invalid new_uuid #{new_uuid.inspect}"
269 transaction(requires_new: true) do
273 save!(validate: false)
274 change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
278 # Move this user's (i.e., self's) owned items into new_owner_uuid.
279 # Also redirect future uses of this account to
280 # redirect_to_user_uuid, i.e., when a caller authenticates to this
281 # account in the future, the account redirect_to_user_uuid account
282 # will be used instead.
284 # current_user must have admin privileges, i.e., the caller is
285 # responsible for checking permission to do this.
286 def merge(new_owner_uuid:, redirect_to_user_uuid:)
287 raise PermissionDeniedError if !current_user.andand.is_admin
288 raise "not implemented" if !redirect_to_user_uuid
289 transaction(requires_new: true) do
291 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
293 new_user = User.where(uuid: redirect_to_user_uuid).first
294 raise "user does not exist" if !new_user
295 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
297 # Existing API tokens are updated to authenticate to the new
299 ApiClientAuthorization.
301 update_all(user_id: new_user.id)
303 # References to the old user UUID in the context of a user ID
304 # (rather than a "home project" in the project hierarchy) are
305 # updated to point to the new user.
307 [AuthorizedKey, :owner_uuid],
308 [AuthorizedKey, :authorized_user_uuid],
309 [Repository, :owner_uuid],
313 ].each do |klass, column|
314 klass.where(column => uuid).update_all(column => new_user.uuid)
317 # References to the merged user's "home project" are updated to
318 # point to new_owner_uuid.
319 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
320 next if [ApiClientAuthorization,
324 Repository].include?(klass)
325 next if !klass.columns.collect(&:name).include?('owner_uuid')
326 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
329 update_attributes!(redirect_to_user_uuid: new_user.uuid)
330 invalidate_permissions_cache
336 def change_all_uuid_refs(old_uuid:, new_uuid:)
337 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
338 klass.columns.each do |col|
339 if col.name.end_with?('_uuid')
340 column = col.name.to_sym
341 klass.where(column => old_uuid).update_all(column => new_uuid)
347 def ensure_ownership_path_leads_to_user
351 def permission_to_update
352 if username_changed? || redirect_to_user_uuid_changed?
353 current_user.andand.is_admin
355 # users must be able to update themselves (even if they are
356 # inactive) in order to create sessions
357 self == current_user or super
361 def permission_to_create
362 current_user.andand.is_admin or
363 (self == current_user &&
364 self.redirect_to_user_uuid.nil? &&
365 self.is_active == Rails.configuration.new_users_are_active)
369 return if self.uuid.end_with?('anonymouspublic')
370 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
371 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
372 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
373 Rails.configuration.auto_admin_first_user)
375 self.is_active = true
379 def find_usable_username_from(basename)
380 # If "basename" is a usable username, return that.
381 # Otherwise, find a unique username "basenameN", where N is the
382 # smallest integer greater than 1, and return that.
383 # Return nil if a unique username can't be found after reasonable
385 quoted_name = self.class.connection.quote_string(basename)
386 next_username = basename
388 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
390 next_username = "%s%i" % [basename, next_suffix]
392 0.upto(6).each do |suffix_len|
393 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
395 where("username like '#{pattern}'").
397 order('username asc').
399 if other_user.username > next_username
401 elsif other_user.username == next_username
403 next_username = "%s%i" % [basename, next_suffix]
406 return next_username if (next_username.size <= pattern.size)
411 def prevent_privilege_escalation
412 if current_user.andand.is_admin
415 if self.is_active_changed?
416 if self.is_active != self.is_active_was
417 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
418 self.is_active = self.is_active_was
421 if self.is_admin_changed?
422 if self.is_admin != self.is_admin_was
423 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
424 self.is_admin = self.is_admin_was
430 def prevent_inactive_admin
431 if self.is_admin and not self.is_active
432 # There is no known use case for the strange set of permissions
433 # that would result from this change. It's safest to assume it's
434 # a mistake and disallow it outright.
435 raise "Admin users cannot be inactive"
440 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
441 nextpaths = graph[start]
442 return merged if !nextpaths
443 return merged if upstream_path.has_key? start
444 upstream_path[start] = true
445 upstream_mask ||= ALL_PERMISSIONS
446 nextpaths.each do |head, mask|
449 merged[head][k] ||= v if upstream_mask[k]
451 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
453 upstream_path.delete start
457 def create_oid_login_perm(openid_prefix)
458 # Check oid_login_perm
459 oid_login_perms = Link.where(tail_uuid: self.email,
460 head_uuid: self.uuid,
461 link_class: 'permission',
464 if !oid_login_perms.any?
465 # create openid login permission
466 oid_login_perm = Link.create(link_class: 'permission',
468 tail_uuid: self.email,
469 head_uuid: self.uuid,
471 "identity_url_prefix" => openid_prefix,
473 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
475 oid_login_perm = oid_login_perms.first
478 return oid_login_perm
481 def create_user_repo_link(repo_name)
482 # repo_name is optional
484 logger.warn ("Repository name not given for #{self.uuid}.")
488 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
489 logger.info { "repo uuid: " + repo[:uuid] }
490 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
491 link_class: "permission",
492 name: "can_manage").first_or_create!
493 logger.info { "repo permission: " + repo_perm[:uuid] }
497 # create login permission for the given vm_uuid, if it does not already exist
498 def create_vm_login_permission_link(vm_uuid, repo_name)
499 # vm uuid is optional
502 vm = VirtualMachine.where(uuid: vm_uuid).first
504 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
505 raise "No vm found for #{vm_uuid}"
508 logger.info { "vm uuid: " + vm[:uuid] }
510 tail_uuid: uuid, head_uuid: vm.uuid,
511 link_class: "permission", name: "can_login",
516 select { |link| link.properties["username"] == repo_name }.
520 create(login_attrs.merge(properties: {"username" => repo_name}))
522 logger.info { "login permission: " + login_perm[:uuid] }
526 # add the user to the 'All users' group
527 def create_user_group_link
528 return (Link.where(tail_uuid: self.uuid,
529 head_uuid: all_users_group[:uuid],
530 link_class: 'permission',
531 name: 'can_read').first or
532 Link.create(tail_uuid: self.uuid,
533 head_uuid: all_users_group[:uuid],
534 link_class: 'permission',
538 # Give the special "System group" permission to manage this user and
539 # all of this user's stuff.
540 def add_system_group_permission_link
541 return true if uuid == system_user_uuid
542 act_as_system_user do
543 Link.create(link_class: 'permission',
545 tail_uuid: system_group_uuid,
546 head_uuid: self.uuid)
550 # Send admin notifications
551 def send_admin_notifications
552 AdminNotifier.new_user(self).deliver_now
553 if not self.is_active then
554 AdminNotifier.new_inactive_user(self).deliver_now
558 # Automatically setup if is_active flag turns on
559 def setup_on_activate
560 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
561 if is_active && (new_record? || is_active_changed?)
562 setup(openid_prefix: Rails.configuration.default_openid_prefix)
566 # Automatically setup new user during creation
567 def auto_setup_new_user
568 setup(openid_prefix: Rails.configuration.default_openid_prefix)
570 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
572 repo_name = "#{username}/#{username}"
573 if Rails.configuration.auto_setup_new_users_with_repository and
574 Repository.where(name: repo_name).first.nil?
575 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
576 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
577 link_class: "permission", name: "can_manage")
582 # Send notification if the user saved profile for the first time
583 def send_profile_created_notification
584 if self.prefs_changed?
585 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
586 profile_notification_address = Rails.configuration.user_profile_notification_address
587 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
592 def verify_repositories_empty
593 unless repositories.first.nil?
594 errors.add(:username, "can't be unset when the user owns repositories")
599 def sync_repository_names
600 old_name_re = /^#{Regexp.escape(username_was)}\//
601 name_sub = "#{username}/"
602 repositories.find_each do |repo|
603 repo.name = repo.name.sub(old_name_re, name_sub)