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
13 serialize :prefs, Hash
14 has_many :api_client_authorizations
17 with: /\A[A-Za-z][A-Za-z0-9]*\z/,
18 message: "must begin with a letter and contain only alphanumerics",
22 before_update :prevent_privilege_escalation
23 before_update :prevent_inactive_admin
24 before_update :verify_repositories_empty, :if => Proc.new { |user|
25 user.username.nil? and user.username_changed?
27 before_update :setup_on_activate
28 before_create :check_auto_admin
29 before_create :set_initial_username, :if => Proc.new { |user|
30 user.username.nil? and user.email
32 after_create :add_system_group_permission_link
33 after_create :auto_setup_new_user, :if => Proc.new { |user|
34 Rails.configuration.auto_setup_new_users and
35 (user.uuid != system_user_uuid) and
36 (user.uuid != anonymous_user_uuid)
38 after_create :send_admin_notifications
39 after_update :send_profile_created_notification
40 after_update :sync_repository_names, :if => Proc.new { |user|
41 (user.uuid != system_user_uuid) and
42 user.username_changed? and
43 (not user.username_was.nil?)
46 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
47 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
49 api_accessible :user, extend: :common do |t|
63 ALL_PERMISSIONS = {read: true, write: true, manage: true}
65 # Map numeric permission levels (see lib/create_permission_view.sql)
66 # back to read/write/manage flags.
70 {read: true, write: true},
71 {read: true, write: true, manage: true}]
74 "#{first_name} #{last_name}".strip
79 Rails.configuration.new_users_are_active ||
80 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
83 def groups_i_can(verb)
84 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
86 my_groups << anonymous_group_uuid
92 return true if is_admin
93 actions.each do |action, target|
95 if target.respond_to? :uuid
96 target_uuid = target.uuid
99 target = ArvadosModel.find_by_uuid(target_uuid)
102 next if target_uuid == self.uuid
103 next if (group_permissions[target_uuid] and
104 group_permissions[target_uuid][action])
105 if target.respond_to? :owner_uuid
106 next if target.owner_uuid == self.uuid
107 next if (group_permissions[target.owner_uuid] and
108 group_permissions[target.owner_uuid][action])
110 sufficient_perms = case action
114 ['can_manage', 'can_write']
116 ['can_manage', 'can_write', 'can_read']
118 # (Skip this kind of permission opportunity
119 # if action is an unknown permission type)
122 # Check permission links with head_uuid pointing directly at
123 # the target object. If target is a Group, this is redundant
124 # and will fail except [a] if permission caching is broken or
125 # [b] during a race condition, where a permission link has
127 if Link.where(link_class: 'permission',
128 name: sufficient_perms,
129 tail_uuid: groups_i_can(action) + [self.uuid],
130 head_uuid: target_uuid).any?
139 def self.invalidate_permissions_cache(timestamp=nil)
140 if Rails.configuration.async_permissions_update
141 timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
142 connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
144 Rails.cache.delete_matched(/^groups_for_user_/)
148 # Return a hash of {user_uuid: group_perms}
149 def self.all_group_permissions
150 install_view('permission')
152 ActiveRecord::Base.connection.
153 exec_query('SELECT user_uuid, target_owner_uuid, max(perm_level)
155 WHERE target_owner_uuid IS NOT NULL
156 GROUP BY user_uuid, target_owner_uuid',
157 # "name" arg is a query label that appears in logs:
158 "all_group_permissions",
159 ).rows.each do |user_uuid, group_uuid, max_p_val|
160 all_perms[user_uuid] ||= {}
161 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
166 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
167 # and perm_hash[:write] are true if this user can read and write
168 # objects owned by group_uuid.
169 def calculate_group_permissions
170 self.class.install_view('permission')
173 ActiveRecord::Base.connection.
174 exec_query('SELECT target_owner_uuid, max(perm_level)
177 AND target_owner_uuid IS NOT NULL
178 GROUP BY target_owner_uuid',
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|
184 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
186 Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
190 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
191 # and perm_hash[:write] are true if this user can read and write
192 # objects owned by group_uuid.
193 def group_permissions
194 r = Rails.cache.read "groups_for_user_#{self.uuid}"
196 if Rails.configuration.async_permissions_update
199 r = Rails.cache.read "groups_for_user_#{self.uuid}"
202 r = calculate_group_permissions
209 def setup(openid_prefix:, repo_name: nil, vm_uuid: nil)
210 oid_login_perm = create_oid_login_perm openid_prefix
211 repo_perm = create_user_repo_link repo_name
212 vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
213 group_perm = create_user_group_link
215 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
218 # delete user signatures, login, repo, and vm perms, and mark as inactive
220 # delete oid_login_perms for this user
221 Link.destroy_all(tail_uuid: self.email,
222 link_class: 'permission',
225 # delete repo_perms for this user
226 Link.destroy_all(tail_uuid: self.uuid,
227 link_class: 'permission',
230 # delete vm_login_perms for this user
231 Link.destroy_all(tail_uuid: self.uuid,
232 link_class: 'permission',
235 # delete "All users" group read permissions for this user
236 group = Group.where(name: 'All users').select do |g|
237 g[:uuid].match(/-f+$/)
239 Link.destroy_all(tail_uuid: self.uuid,
240 head_uuid: group[:uuid],
241 link_class: 'permission',
244 # delete any signatures by this user
245 Link.destroy_all(link_class: 'signature',
246 tail_uuid: self.uuid)
248 # delete user preferences (including profile)
251 # mark the user as inactive
252 self.is_active = false
256 def set_initial_username(requested: false)
257 if !requested.is_a?(String) || requested.empty?
258 email_parts = email.partition("@")
259 local_parts = email_parts.first.partition("+")
260 if email_parts.any?(&:empty?)
262 elsif not local_parts.first.empty?
263 requested = local_parts.first
265 requested = email_parts.first
268 requested.sub!(/^[^A-Za-z]+/, "")
269 requested.gsub!(/[^A-Za-z0-9]/, "")
270 unless requested.empty?
271 self.username = find_usable_username_from(requested)
277 def ensure_ownership_path_leads_to_user
281 def permission_to_update
283 current_user.andand.is_admin
285 # users must be able to update themselves (even if they are
286 # inactive) in order to create sessions
287 self == current_user or super
291 def permission_to_create
292 current_user.andand.is_admin or
293 (self == current_user and
294 self.is_active == Rails.configuration.new_users_are_active)
298 return if self.uuid.end_with?('anonymouspublic')
299 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
300 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
301 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
302 Rails.configuration.auto_admin_first_user)
304 self.is_active = true
308 def find_usable_username_from(basename)
309 # If "basename" is a usable username, return that.
310 # Otherwise, find a unique username "basenameN", where N is the
311 # smallest integer greater than 1, and return that.
312 # Return nil if a unique username can't be found after reasonable
314 quoted_name = self.class.connection.quote_string(basename)
315 next_username = basename
317 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
319 next_username = "%s%i" % [basename, next_suffix]
321 0.upto(6).each do |suffix_len|
322 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
324 where("username like '#{pattern}'").
326 order('username asc').
328 if other_user.username > next_username
330 elsif other_user.username == next_username
332 next_username = "%s%i" % [basename, next_suffix]
335 return next_username if (next_username.size <= pattern.size)
340 def prevent_privilege_escalation
341 if current_user.andand.is_admin
344 if self.is_active_changed?
345 if self.is_active != self.is_active_was
346 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
347 self.is_active = self.is_active_was
350 if self.is_admin_changed?
351 if self.is_admin != self.is_admin_was
352 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
353 self.is_admin = self.is_admin_was
359 def prevent_inactive_admin
360 if self.is_admin and not self.is_active
361 # There is no known use case for the strange set of permissions
362 # that would result from this change. It's safest to assume it's
363 # a mistake and disallow it outright.
364 raise "Admin users cannot be inactive"
369 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
370 nextpaths = graph[start]
371 return merged if !nextpaths
372 return merged if upstream_path.has_key? start
373 upstream_path[start] = true
374 upstream_mask ||= ALL_PERMISSIONS
375 nextpaths.each do |head, mask|
378 merged[head][k] ||= v if upstream_mask[k]
380 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
382 upstream_path.delete start
386 def create_oid_login_perm(openid_prefix)
387 # Check oid_login_perm
388 oid_login_perms = Link.where(tail_uuid: self.email,
389 head_uuid: self.uuid,
390 link_class: 'permission',
393 if !oid_login_perms.any?
394 # create openid login permission
395 oid_login_perm = Link.create(link_class: 'permission',
397 tail_uuid: self.email,
398 head_uuid: self.uuid,
400 "identity_url_prefix" => openid_prefix,
402 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
404 oid_login_perm = oid_login_perms.first
407 return oid_login_perm
410 def create_user_repo_link(repo_name)
411 # repo_name is optional
413 logger.warn ("Repository name not given for #{self.uuid}.")
417 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
418 logger.info { "repo uuid: " + repo[:uuid] }
419 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
420 link_class: "permission",
421 name: "can_manage").first_or_create!
422 logger.info { "repo permission: " + repo_perm[:uuid] }
426 # create login permission for the given vm_uuid, if it does not already exist
427 def create_vm_login_permission_link(vm_uuid, repo_name)
428 # vm uuid is optional
431 vm = VirtualMachine.where(uuid: vm_uuid).first
433 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
434 raise "No vm found for #{vm_uuid}"
437 logger.info { "vm uuid: " + vm[:uuid] }
439 tail_uuid: uuid, head_uuid: vm.uuid,
440 link_class: "permission", name: "can_login",
445 select { |link| link.properties["username"] == repo_name }.
449 create(login_attrs.merge(properties: {"username" => repo_name}))
451 logger.info { "login permission: " + login_perm[:uuid] }
455 # add the user to the 'All users' group
456 def create_user_group_link
457 return (Link.where(tail_uuid: self.uuid,
458 head_uuid: all_users_group[:uuid],
459 link_class: 'permission',
460 name: 'can_read').first or
461 Link.create(tail_uuid: self.uuid,
462 head_uuid: all_users_group[:uuid],
463 link_class: 'permission',
467 # Give the special "System group" permission to manage this user and
468 # all of this user's stuff.
469 def add_system_group_permission_link
470 return true if uuid == system_user_uuid
471 act_as_system_user do
472 Link.create(link_class: 'permission',
474 tail_uuid: system_group_uuid,
475 head_uuid: self.uuid)
479 # Send admin notifications
480 def send_admin_notifications
481 AdminNotifier.new_user(self).deliver_now
482 if not self.is_active then
483 AdminNotifier.new_inactive_user(self).deliver_now
487 # Automatically setup if is_active flag turns on
488 def setup_on_activate
489 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
490 if is_active && (new_record? || is_active_changed?)
491 setup(openid_prefix: Rails.configuration.default_openid_prefix)
495 # Automatically setup new user during creation
496 def auto_setup_new_user
497 setup(openid_prefix: Rails.configuration.default_openid_prefix)
499 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
501 repo_name = "#{username}/#{username}"
502 if Rails.configuration.auto_setup_new_users_with_repository and
503 Repository.where(name: repo_name).first.nil?
504 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
505 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
506 link_class: "permission", name: "can_manage")
511 # Send notification if the user saved profile for the first time
512 def send_profile_created_notification
513 if self.prefs_changed?
514 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
515 profile_notification_address = Rails.configuration.user_profile_notification_address
516 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
521 def verify_repositories_empty
522 unless repositories.first.nil?
523 errors.add(:username, "can't be unset when the user owns repositories")
528 def sync_repository_names
529 old_name_re = /^#{Regexp.escape(username_was)}\//
530 name_sub = "#{username}/"
531 repositories.find_each do |repo|
532 repo.name = repo.name.sub(old_name_re, name_sub)