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 # To avoid upgrade bugs, when changing the permission cache value
14 # format, change PERM_CACHE_PREFIX too:
15 PERM_CACHE_PREFIX = "perm_v20170725_"
16 PERM_CACHE_TTL = 172800
18 serialize :prefs, Hash
19 has_many :api_client_authorizations
22 with: /\A[A-Za-z][A-Za-z0-9]*\z/,
23 message: "must begin with a letter and contain only alphanumerics",
27 before_update :prevent_privilege_escalation
28 before_update :prevent_inactive_admin
29 before_update :verify_repositories_empty, :if => Proc.new { |user|
30 user.username.nil? and user.username_changed?
32 before_update :setup_on_activate
33 before_create :check_auto_admin
34 before_create :set_initial_username, :if => Proc.new { |user|
35 user.username.nil? and user.email
37 after_create :add_system_group_permission_link
38 after_create :invalidate_permissions_cache
39 after_create :auto_setup_new_user, :if => Proc.new { |user|
40 Rails.configuration.auto_setup_new_users and
41 (user.uuid != system_user_uuid) and
42 (user.uuid != anonymous_user_uuid)
44 after_create :send_admin_notifications
45 after_update :send_profile_created_notification
46 after_update :sync_repository_names, :if => Proc.new { |user|
47 (user.uuid != system_user_uuid) and
48 user.username_changed? and
49 (not user.username_was.nil?)
52 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
53 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
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.new_users_are_active ||
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(timestamp=nil)
146 if Rails.configuration.async_permissions_update
147 timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
148 connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
150 Rails.cache.delete_matched(/^#{PERM_CACHE_PREFIX}/)
154 def invalidate_permissions_cache(timestamp=nil)
155 User.invalidate_permissions_cache
158 # Return a hash of {user_uuid: group_perms}
159 def self.all_group_permissions
161 ActiveRecord::Base.connection.
162 exec_query('SELECT user_uuid, target_owner_uuid, perm_level, trashed
164 WHERE target_owner_uuid IS NOT NULL',
165 # "name" arg is a query label that appears in logs:
166 "all_group_permissions",
167 ).rows.each do |user_uuid, group_uuid, max_p_val, trashed|
168 all_perms[user_uuid] ||= {user_uuid => {:read => true, :write => true, :manage => true}}
169 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
174 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
175 # and perm_hash[:write] are true if this user can read and write
176 # objects owned by group_uuid.
177 def calculate_group_permissions
178 group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
179 User.fresh_permission_view
180 ActiveRecord::Base.connection.
181 exec_query('SELECT target_owner_uuid, perm_level, trashed
184 AND target_owner_uuid IS NOT NULL',
185 # "name" arg is a query label that appears in logs:
186 "group_permissions for #{uuid}",
187 # "binds" arg is an array of [col_id, value] for '$1' vars:
189 ).rows.each do |group_uuid, max_p_val, trashed|
190 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
192 Rails.cache.write "#{PERM_CACHE_PREFIX}#{self.uuid}", group_perms, expires_in: PERM_CACHE_TTL
196 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
197 # and perm_hash[:write] are true if this user can read and write
198 # objects owned by group_uuid.
199 def group_permissions
200 r = Rails.cache.read "#{PERM_CACHE_PREFIX}#{self.uuid}"
202 if Rails.configuration.async_permissions_update
205 r = Rails.cache.read "#{PERM_CACHE_PREFIX}#{self.uuid}"
208 r = calculate_group_permissions
214 def self.fresh_permission_view
215 r = Rails.cache.read "#{PERM_CACHE_PREFIX}_fresh"
217 ActiveRecord::Base.connection.exec_query('REFRESH MATERIALIZED VIEW permission_view')
218 Rails.cache.write "#{PERM_CACHE_PREFIX}_fresh", 1, expires_in: PERM_CACHE_TTL
223 def setup(openid_prefix:, repo_name: nil, vm_uuid: nil)
224 oid_login_perm = create_oid_login_perm openid_prefix
225 repo_perm = create_user_repo_link repo_name
226 vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
227 group_perm = create_user_group_link
229 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
232 # delete user signatures, login, repo, and vm perms, and mark as inactive
234 # delete oid_login_perms for this user
235 Link.destroy_all(tail_uuid: self.email,
236 link_class: 'permission',
239 # delete repo_perms for this user
240 Link.destroy_all(tail_uuid: self.uuid,
241 link_class: 'permission',
244 # delete vm_login_perms for this user
245 Link.destroy_all(tail_uuid: self.uuid,
246 link_class: 'permission',
249 # delete "All users" group read permissions for this user
250 group = Group.where(name: 'All users').select do |g|
251 g[:uuid].match(/-f+$/)
253 Link.destroy_all(tail_uuid: self.uuid,
254 head_uuid: group[:uuid],
255 link_class: 'permission',
258 # delete any signatures by this user
259 Link.destroy_all(link_class: 'signature',
260 tail_uuid: self.uuid)
262 # delete user preferences (including profile)
265 # mark the user as inactive
266 self.is_active = false
270 def set_initial_username(requested: false)
271 if !requested.is_a?(String) || requested.empty?
272 email_parts = email.partition("@")
273 local_parts = email_parts.first.partition("+")
274 if email_parts.any?(&:empty?)
276 elsif not local_parts.first.empty?
277 requested = local_parts.first
279 requested = email_parts.first
282 requested.sub!(/^[^A-Za-z]+/, "")
283 requested.gsub!(/[^A-Za-z0-9]/, "")
284 unless requested.empty?
285 self.username = find_usable_username_from(requested)
291 def ensure_ownership_path_leads_to_user
295 def permission_to_update
297 current_user.andand.is_admin
299 # users must be able to update themselves (even if they are
300 # inactive) in order to create sessions
301 self == current_user or super
305 def permission_to_create
306 current_user.andand.is_admin or
307 (self == current_user and
308 self.is_active == Rails.configuration.new_users_are_active)
312 return if self.uuid.end_with?('anonymouspublic')
313 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
314 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
315 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
316 Rails.configuration.auto_admin_first_user)
318 self.is_active = true
322 def find_usable_username_from(basename)
323 # If "basename" is a usable username, return that.
324 # Otherwise, find a unique username "basenameN", where N is the
325 # smallest integer greater than 1, and return that.
326 # Return nil if a unique username can't be found after reasonable
328 quoted_name = self.class.connection.quote_string(basename)
329 next_username = basename
331 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
333 next_username = "%s%i" % [basename, next_suffix]
335 0.upto(6).each do |suffix_len|
336 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
338 where("username like '#{pattern}'").
340 order('username asc').
342 if other_user.username > next_username
344 elsif other_user.username == next_username
346 next_username = "%s%i" % [basename, next_suffix]
349 return next_username if (next_username.size <= pattern.size)
354 def prevent_privilege_escalation
355 if current_user.andand.is_admin
358 if self.is_active_changed?
359 if self.is_active != self.is_active_was
360 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
361 self.is_active = self.is_active_was
364 if self.is_admin_changed?
365 if self.is_admin != self.is_admin_was
366 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
367 self.is_admin = self.is_admin_was
373 def prevent_inactive_admin
374 if self.is_admin and not self.is_active
375 # There is no known use case for the strange set of permissions
376 # that would result from this change. It's safest to assume it's
377 # a mistake and disallow it outright.
378 raise "Admin users cannot be inactive"
383 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
384 nextpaths = graph[start]
385 return merged if !nextpaths
386 return merged if upstream_path.has_key? start
387 upstream_path[start] = true
388 upstream_mask ||= ALL_PERMISSIONS
389 nextpaths.each do |head, mask|
392 merged[head][k] ||= v if upstream_mask[k]
394 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
396 upstream_path.delete start
400 def create_oid_login_perm(openid_prefix)
401 # Check oid_login_perm
402 oid_login_perms = Link.where(tail_uuid: self.email,
403 head_uuid: self.uuid,
404 link_class: 'permission',
407 if !oid_login_perms.any?
408 # create openid login permission
409 oid_login_perm = Link.create(link_class: 'permission',
411 tail_uuid: self.email,
412 head_uuid: self.uuid,
414 "identity_url_prefix" => openid_prefix,
416 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
418 oid_login_perm = oid_login_perms.first
421 return oid_login_perm
424 def create_user_repo_link(repo_name)
425 # repo_name is optional
427 logger.warn ("Repository name not given for #{self.uuid}.")
431 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
432 logger.info { "repo uuid: " + repo[:uuid] }
433 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
434 link_class: "permission",
435 name: "can_manage").first_or_create!
436 logger.info { "repo permission: " + repo_perm[:uuid] }
440 # create login permission for the given vm_uuid, if it does not already exist
441 def create_vm_login_permission_link(vm_uuid, repo_name)
442 # vm uuid is optional
445 vm = VirtualMachine.where(uuid: vm_uuid).first
447 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
448 raise "No vm found for #{vm_uuid}"
451 logger.info { "vm uuid: " + vm[:uuid] }
453 tail_uuid: uuid, head_uuid: vm.uuid,
454 link_class: "permission", name: "can_login",
459 select { |link| link.properties["username"] == repo_name }.
463 create(login_attrs.merge(properties: {"username" => repo_name}))
465 logger.info { "login permission: " + login_perm[:uuid] }
469 # add the user to the 'All users' group
470 def create_user_group_link
471 return (Link.where(tail_uuid: self.uuid,
472 head_uuid: all_users_group[:uuid],
473 link_class: 'permission',
474 name: 'can_read').first or
475 Link.create(tail_uuid: self.uuid,
476 head_uuid: all_users_group[:uuid],
477 link_class: 'permission',
481 # Give the special "System group" permission to manage this user and
482 # all of this user's stuff.
483 def add_system_group_permission_link
484 return true if uuid == system_user_uuid
485 act_as_system_user do
486 Link.create(link_class: 'permission',
488 tail_uuid: system_group_uuid,
489 head_uuid: self.uuid)
493 # Send admin notifications
494 def send_admin_notifications
495 AdminNotifier.new_user(self).deliver_now
496 if not self.is_active then
497 AdminNotifier.new_inactive_user(self).deliver_now
501 # Automatically setup if is_active flag turns on
502 def setup_on_activate
503 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
504 if is_active && (new_record? || is_active_changed?)
505 setup(openid_prefix: Rails.configuration.default_openid_prefix)
509 # Automatically setup new user during creation
510 def auto_setup_new_user
511 setup(openid_prefix: Rails.configuration.default_openid_prefix)
513 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
515 repo_name = "#{username}/#{username}"
516 if Rails.configuration.auto_setup_new_users_with_repository and
517 Repository.where(name: repo_name).first.nil?
518 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
519 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
520 link_class: "permission", name: "can_manage")
525 # Send notification if the user saved profile for the first time
526 def send_profile_created_notification
527 if self.prefs_changed?
528 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
529 profile_notification_address = Rails.configuration.user_profile_notification_address
530 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
535 def verify_repositories_empty
536 unless repositories.first.nil?
537 errors.add(:username, "can't be unset when the user owns repositories")
542 def sync_repository_names
543 old_name_re = /^#{Regexp.escape(username_was)}\//
544 name_sub = "#{username}/"
545 repositories.find_each do |repo|
546 repo.name = repo.name.sub(old_name_re, name_sub)