1 require 'can_be_an_owner'
3 class User < ArvadosModel
6 include CommonApiTemplate
10 has_many :api_client_authorizations
13 with: /^[A-Za-z][A-Za-z0-9]*$/,
14 message: "must begin with a letter and contain only alphanumerics",
18 before_update :prevent_privilege_escalation
19 before_update :prevent_inactive_admin
20 before_update :verify_repositories_empty, :if => Proc.new { |user|
21 user.username.nil? and user.username_changed?
23 before_create :check_auto_admin
24 before_create :set_initial_username, :if => Proc.new { |user|
25 user.username.nil? and user.email
27 after_create :add_system_group_permission_link
28 after_create :auto_setup_new_user, :if => Proc.new { |user|
29 Rails.configuration.auto_setup_new_users and
30 (user.uuid != system_user_uuid) and
31 (user.uuid != anonymous_user_uuid)
33 after_create :send_admin_notifications
34 after_update :send_profile_created_notification
35 after_update :sync_repository_names, :if => Proc.new { |user|
36 (user.uuid != system_user_uuid) and
37 user.username_changed? and
38 (not user.username_was.nil?)
41 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
42 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
44 api_accessible :user, extend: :common do |t|
58 ALL_PERMISSIONS = {read: true, write: true, manage: true}
61 "#{first_name} #{last_name}".strip
66 Rails.configuration.new_users_are_active ||
67 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
70 def groups_i_can(verb)
71 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
73 my_groups << anonymous_group_uuid
79 return true if is_admin
80 actions.each do |action, target|
82 if target.respond_to? :uuid
83 target_uuid = target.uuid
86 target = ArvadosModel.find_by_uuid(target_uuid)
89 next if target_uuid == self.uuid
90 next if (group_permissions[target_uuid] and
91 group_permissions[target_uuid][action])
92 if target.respond_to? :owner_uuid
93 next if target.owner_uuid == self.uuid
94 next if (group_permissions[target.owner_uuid] and
95 group_permissions[target.owner_uuid][action])
97 sufficient_perms = case action
101 ['can_manage', 'can_write']
103 ['can_manage', 'can_write', 'can_read']
105 # (Skip this kind of permission opportunity
106 # if action is an unknown permission type)
109 # Check permission links with head_uuid pointing directly at
110 # the target object. If target is a Group, this is redundant
111 # and will fail except [a] if permission caching is broken or
112 # [b] during a race condition, where a permission link has
114 if Link.where(link_class: 'permission',
115 name: sufficient_perms,
116 tail_uuid: groups_i_can(action) + [self.uuid],
117 head_uuid: target_uuid).any?
126 def self.invalidate_permissions_cache(timestamp=nil)
127 if Rails.configuration.async_permissions_update
128 timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
129 connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
131 Rails.cache.delete_matched(/^groups_for_user_/)
135 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
136 # and perm_hash[:write] are true if this user can read and write
137 # objects owned by group_uuid.
138 def calculate_group_permissions
139 conn = ActiveRecord::Base.connection
140 self.class.transaction do
141 # Check whether the temporary view has already been created
142 # during this connection. If not, create it.
143 conn.execute 'SAVEPOINT check_permission_view'
145 conn.execute('SELECT 1 FROM permission_view LIMIT 0')
147 conn.execute 'ROLLBACK TO SAVEPOINT check_permission_view'
148 sql = File.read(Rails.root.join('lib', 'create_permission_view.sql'))
151 conn.execute 'RELEASE SAVEPOINT check_permission_view'
159 {read: true, write: true},
160 {read: true, write: true, manage: true}]
161 conn.exec_query('SELECT target_owner_uuid, max(perm_level)
164 AND target_owner_uuid IS NOT NULL
165 GROUP BY target_owner_uuid',
166 "group_permissions for #{uuid}",
167 [[nil, uuid]]).rows.each do |group_uuid, max_p_val|
168 group_perms[group_uuid] = perms_for_val[max_p_val.to_i]
170 Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
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 group_permissions
178 r = Rails.cache.read "groups_for_user_#{self.uuid}"
180 if Rails.configuration.async_permissions_update
183 r = Rails.cache.read "groups_for_user_#{self.uuid}"
186 r = calculate_group_permissions
192 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
193 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
197 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
198 oid_login_perm = create_oid_login_perm openid_prefix
199 repo_perm = create_user_repo_link repo_name
200 vm_login_perm = create_vm_login_permission_link vm_uuid, username
201 group_perm = create_user_group_link
203 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
206 # delete user signatures, login, repo, and vm perms, and mark as inactive
208 # delete oid_login_perms for this user
209 Link.destroy_all(tail_uuid: self.email,
210 link_class: 'permission',
213 # delete repo_perms for this user
214 Link.destroy_all(tail_uuid: self.uuid,
215 link_class: 'permission',
218 # delete vm_login_perms for this user
219 Link.destroy_all(tail_uuid: self.uuid,
220 link_class: 'permission',
223 # delete "All users" group read permissions for this user
224 group = Group.where(name: 'All users').select do |g|
225 g[:uuid].match(/-f+$/)
227 Link.destroy_all(tail_uuid: self.uuid,
228 head_uuid: group[:uuid],
229 link_class: 'permission',
232 # delete any signatures by this user
233 Link.destroy_all(link_class: 'signature',
234 tail_uuid: self.uuid)
236 # delete user preferences (including profile)
239 # mark the user as inactive
240 self.is_active = false
244 def set_initial_username(requested: false)
245 if !requested.is_a?(String) || requested.empty?
246 email_parts = email.partition("@")
247 local_parts = email_parts.first.partition("+")
248 if email_parts.any?(&:empty?)
250 elsif not local_parts.first.empty?
251 requested = local_parts.first
253 requested = email_parts.first
256 requested.sub!(/^[^A-Za-z]+/, "")
257 requested.gsub!(/[^A-Za-z0-9]/, "")
258 unless requested.empty?
259 self.username = find_usable_username_from(requested)
265 def ensure_ownership_path_leads_to_user
269 def permission_to_update
271 current_user.andand.is_admin
273 # users must be able to update themselves (even if they are
274 # inactive) in order to create sessions
275 self == current_user or super
279 def permission_to_create
280 current_user.andand.is_admin or
281 (self == current_user and
282 self.is_active == Rails.configuration.new_users_are_active)
286 return if self.uuid.end_with?('anonymouspublic')
287 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
288 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
289 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
290 Rails.configuration.auto_admin_first_user)
292 self.is_active = true
296 def find_usable_username_from(basename)
297 # If "basename" is a usable username, return that.
298 # Otherwise, find a unique username "basenameN", where N is the
299 # smallest integer greater than 1, and return that.
300 # Return nil if a unique username can't be found after reasonable
302 quoted_name = self.class.connection.quote_string(basename)
303 next_username = basename
305 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
307 next_username = "%s%i" % [basename, next_suffix]
309 0.upto(6).each do |suffix_len|
310 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
312 where("username like '#{pattern}'").
314 order('username asc').
316 if other_user.username > next_username
318 elsif other_user.username == next_username
320 next_username = "%s%i" % [basename, next_suffix]
323 return next_username if (next_username.size <= pattern.size)
328 def prevent_privilege_escalation
329 if current_user.andand.is_admin
332 if self.is_active_changed?
333 if self.is_active != self.is_active_was
334 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
335 self.is_active = self.is_active_was
338 if self.is_admin_changed?
339 if self.is_admin != self.is_admin_was
340 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
341 self.is_admin = self.is_admin_was
347 def prevent_inactive_admin
348 if self.is_admin and not self.is_active
349 # There is no known use case for the strange set of permissions
350 # that would result from this change. It's safest to assume it's
351 # a mistake and disallow it outright.
352 raise "Admin users cannot be inactive"
357 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
358 nextpaths = graph[start]
359 return merged if !nextpaths
360 return merged if upstream_path.has_key? start
361 upstream_path[start] = true
362 upstream_mask ||= ALL_PERMISSIONS
363 nextpaths.each do |head, mask|
366 merged[head][k] ||= v if upstream_mask[k]
368 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
370 upstream_path.delete start
374 def create_oid_login_perm (openid_prefix)
375 login_perm_props = { "identity_url_prefix" => openid_prefix}
377 # Check oid_login_perm
378 oid_login_perms = Link.where(tail_uuid: self.email,
379 link_class: 'permission',
380 name: 'can_login').where("head_uuid = ?", self.uuid)
382 if !oid_login_perms.any?
383 # create openid login permission
384 oid_login_perm = Link.create(link_class: 'permission',
386 tail_uuid: self.email,
387 head_uuid: self.uuid,
388 properties: login_perm_props
390 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
392 oid_login_perm = oid_login_perms.first
395 return oid_login_perm
398 def create_user_repo_link(repo_name)
399 # repo_name is optional
401 logger.warn ("Repository name not given for #{self.uuid}.")
405 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
406 logger.info { "repo uuid: " + repo[:uuid] }
407 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
408 link_class: "permission",
409 name: "can_manage").first_or_create!
410 logger.info { "repo permission: " + repo_perm[:uuid] }
414 # create login permission for the given vm_uuid, if it does not already exist
415 def create_vm_login_permission_link(vm_uuid, repo_name)
416 # vm uuid is optional
418 vm = VirtualMachine.where(uuid: vm_uuid).first
421 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
422 raise "No vm found for #{vm_uuid}"
428 logger.info { "vm uuid: " + vm[:uuid] }
430 tail_uuid: uuid, head_uuid: vm.uuid,
431 link_class: "permission", name: "can_login",
436 select { |link| link.properties["username"] == repo_name }.
440 create(login_attrs.merge(properties: {"username" => repo_name}))
442 logger.info { "login permission: " + login_perm[:uuid] }
446 # add the user to the 'All users' group
447 def create_user_group_link
448 return (Link.where(tail_uuid: self.uuid,
449 head_uuid: all_users_group[:uuid],
450 link_class: 'permission',
451 name: 'can_read').first or
452 Link.create(tail_uuid: self.uuid,
453 head_uuid: all_users_group[:uuid],
454 link_class: 'permission',
458 # Give the special "System group" permission to manage this user and
459 # all of this user's stuff.
460 def add_system_group_permission_link
461 return true if uuid == system_user_uuid
462 act_as_system_user do
463 Link.create(link_class: 'permission',
465 tail_uuid: system_group_uuid,
466 head_uuid: self.uuid)
470 # Send admin notifications
471 def send_admin_notifications
472 AdminNotifier.new_user(self).deliver
473 if not self.is_active then
474 AdminNotifier.new_inactive_user(self).deliver
478 # Automatically setup new user during creation
479 def auto_setup_new_user
480 setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
482 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
484 repo_name = "#{username}/#{username}"
485 if Rails.configuration.auto_setup_new_users_with_repository and
486 Repository.where(name: repo_name).first.nil?
487 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
488 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
489 link_class: "permission", name: "can_manage")
494 # Send notification if the user saved profile for the first time
495 def send_profile_created_notification
496 if self.prefs_changed?
497 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
498 profile_notification_address = Rails.configuration.user_profile_notification_address
499 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
504 def verify_repositories_empty
505 unless repositories.first.nil?
506 errors.add(:username, "can't be unset when the user owns repositories")
511 def sync_repository_names
512 old_name_re = /^#{Regexp.escape(username_was)}\//
513 name_sub = "#{username}/"
514 repositories.find_each do |repo|
515 repo.name = repo.name.sub(old_name_re, name_sub)