1 require 'can_be_an_owner'
3 class User < ArvadosModel
6 include CommonApiTemplate
10 has_many :api_client_authorizations
13 with: /\A[A-Za-z][A-Za-z0-9]*\z/,
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}
60 # Map numeric permission levels (see lib/create_permission_view.sql)
61 # back to read/write/manage flags.
65 {read: true, write: true},
66 {read: true, write: true, manage: true}]
69 "#{first_name} #{last_name}".strip
74 Rails.configuration.new_users_are_active ||
75 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
78 def groups_i_can(verb)
79 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
81 my_groups << anonymous_group_uuid
87 return true if is_admin
88 actions.each do |action, target|
90 if target.respond_to? :uuid
91 target_uuid = target.uuid
94 target = ArvadosModel.find_by_uuid(target_uuid)
97 next if target_uuid == self.uuid
98 next if (group_permissions[target_uuid] and
99 group_permissions[target_uuid][action])
100 if target.respond_to? :owner_uuid
101 next if target.owner_uuid == self.uuid
102 next if (group_permissions[target.owner_uuid] and
103 group_permissions[target.owner_uuid][action])
105 sufficient_perms = case action
109 ['can_manage', 'can_write']
111 ['can_manage', 'can_write', 'can_read']
113 # (Skip this kind of permission opportunity
114 # if action is an unknown permission type)
117 # Check permission links with head_uuid pointing directly at
118 # the target object. If target is a Group, this is redundant
119 # and will fail except [a] if permission caching is broken or
120 # [b] during a race condition, where a permission link has
122 if Link.where(link_class: 'permission',
123 name: sufficient_perms,
124 tail_uuid: groups_i_can(action) + [self.uuid],
125 head_uuid: target_uuid).any?
134 def self.invalidate_permissions_cache(timestamp=nil)
135 if Rails.configuration.async_permissions_update
136 timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
137 connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
139 Rails.cache.delete_matched(/^groups_for_user_/)
143 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
144 # and perm_hash[:write] are true if this user can read and write
145 # objects owned by group_uuid.
146 def calculate_group_permissions
147 install_view('permission')
150 ActiveRecord::Base.connection.
151 exec_query('SELECT target_owner_uuid, max(perm_level)
154 AND target_owner_uuid IS NOT NULL
155 GROUP BY target_owner_uuid',
156 # "name" arg is a query label that appears in logs:
157 "group_permissions for #{uuid}",
158 # "binds" arg is an array of [col_id, value] for '$1' vars:
160 ).rows.each do |group_uuid, max_p_val|
161 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
163 Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
167 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
168 # and perm_hash[:write] are true if this user can read and write
169 # objects owned by group_uuid.
170 def group_permissions
171 r = Rails.cache.read "groups_for_user_#{self.uuid}"
173 if Rails.configuration.async_permissions_update
176 r = Rails.cache.read "groups_for_user_#{self.uuid}"
179 r = calculate_group_permissions
185 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
186 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
190 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
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
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.destroy_all(tail_uuid: self.email,
203 link_class: 'permission',
206 # delete repo_perms for this user
207 Link.destroy_all(tail_uuid: self.uuid,
208 link_class: 'permission',
211 # delete vm_login_perms for this user
212 Link.destroy_all(tail_uuid: self.uuid,
213 link_class: 'permission',
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.destroy_all(tail_uuid: self.uuid,
221 head_uuid: group[:uuid],
222 link_class: 'permission',
225 # delete any signatures by this user
226 Link.destroy_all(link_class: 'signature',
227 tail_uuid: self.uuid)
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)
258 def ensure_ownership_path_leads_to_user
262 def permission_to_update
264 current_user.andand.is_admin
266 # users must be able to update themselves (even if they are
267 # inactive) in order to create sessions
268 self == current_user or super
272 def permission_to_create
273 current_user.andand.is_admin or
274 (self == current_user and
275 self.is_active == Rails.configuration.new_users_are_active)
279 return if self.uuid.end_with?('anonymouspublic')
280 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
281 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
282 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
283 Rails.configuration.auto_admin_first_user)
285 self.is_active = true
289 def find_usable_username_from(basename)
290 # If "basename" is a usable username, return that.
291 # Otherwise, find a unique username "basenameN", where N is the
292 # smallest integer greater than 1, and return that.
293 # Return nil if a unique username can't be found after reasonable
295 quoted_name = self.class.connection.quote_string(basename)
296 next_username = basename
298 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
300 next_username = "%s%i" % [basename, next_suffix]
302 0.upto(6).each do |suffix_len|
303 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
305 where("username like '#{pattern}'").
307 order('username asc').
309 if other_user.username > next_username
311 elsif other_user.username == next_username
313 next_username = "%s%i" % [basename, next_suffix]
316 return next_username if (next_username.size <= pattern.size)
321 def prevent_privilege_escalation
322 if current_user.andand.is_admin
325 if self.is_active_changed?
326 if self.is_active != self.is_active_was
327 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
328 self.is_active = self.is_active_was
331 if self.is_admin_changed?
332 if self.is_admin != self.is_admin_was
333 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
334 self.is_admin = self.is_admin_was
340 def prevent_inactive_admin
341 if self.is_admin and not self.is_active
342 # There is no known use case for the strange set of permissions
343 # that would result from this change. It's safest to assume it's
344 # a mistake and disallow it outright.
345 raise "Admin users cannot be inactive"
350 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
351 nextpaths = graph[start]
352 return merged if !nextpaths
353 return merged if upstream_path.has_key? start
354 upstream_path[start] = true
355 upstream_mask ||= ALL_PERMISSIONS
356 nextpaths.each do |head, mask|
359 merged[head][k] ||= v if upstream_mask[k]
361 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
363 upstream_path.delete start
367 def create_oid_login_perm (openid_prefix)
368 login_perm_props = { "identity_url_prefix" => openid_prefix}
370 # Check oid_login_perm
371 oid_login_perms = Link.where(tail_uuid: self.email,
372 link_class: 'permission',
373 name: 'can_login').where("head_uuid = ?", self.uuid)
375 if !oid_login_perms.any?
376 # create openid login permission
377 oid_login_perm = Link.create(link_class: 'permission',
379 tail_uuid: self.email,
380 head_uuid: self.uuid,
381 properties: login_perm_props
383 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
385 oid_login_perm = oid_login_perms.first
388 return oid_login_perm
391 def create_user_repo_link(repo_name)
392 # repo_name is optional
394 logger.warn ("Repository name not given for #{self.uuid}.")
398 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
399 logger.info { "repo uuid: " + repo[:uuid] }
400 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
401 link_class: "permission",
402 name: "can_manage").first_or_create!
403 logger.info { "repo permission: " + repo_perm[:uuid] }
407 # create login permission for the given vm_uuid, if it does not already exist
408 def create_vm_login_permission_link(vm_uuid, repo_name)
409 # vm uuid is optional
411 vm = VirtualMachine.where(uuid: vm_uuid).first
414 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
415 raise "No vm found for #{vm_uuid}"
421 logger.info { "vm uuid: " + vm[:uuid] }
423 tail_uuid: uuid, head_uuid: vm.uuid,
424 link_class: "permission", name: "can_login",
429 select { |link| link.properties["username"] == repo_name }.
433 create(login_attrs.merge(properties: {"username" => repo_name}))
435 logger.info { "login permission: " + login_perm[:uuid] }
439 # add the user to the 'All users' group
440 def create_user_group_link
441 return (Link.where(tail_uuid: self.uuid,
442 head_uuid: all_users_group[:uuid],
443 link_class: 'permission',
444 name: 'can_read').first or
445 Link.create(tail_uuid: self.uuid,
446 head_uuid: all_users_group[:uuid],
447 link_class: 'permission',
451 # Give the special "System group" permission to manage this user and
452 # all of this user's stuff.
453 def add_system_group_permission_link
454 return true if uuid == system_user_uuid
455 act_as_system_user do
456 Link.create(link_class: 'permission',
458 tail_uuid: system_group_uuid,
459 head_uuid: self.uuid)
463 # Send admin notifications
464 def send_admin_notifications
465 AdminNotifier.new_user(self).deliver_now
466 if not self.is_active then
467 AdminNotifier.new_inactive_user(self).deliver_now
471 # Automatically setup new user during creation
472 def auto_setup_new_user
473 setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
475 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
477 repo_name = "#{username}/#{username}"
478 if Rails.configuration.auto_setup_new_users_with_repository and
479 Repository.where(name: repo_name).first.nil?
480 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
481 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
482 link_class: "permission", name: "can_manage")
487 # Send notification if the user saved profile for the first time
488 def send_profile_created_notification
489 if self.prefs_changed?
490 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
491 profile_notification_address = Rails.configuration.user_profile_notification_address
492 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
497 def verify_repositories_empty
498 unless repositories.first.nil?
499 errors.add(:username, "can't be unset when the user owns repositories")
504 def sync_repository_names
505 old_name_re = /^#{Regexp.escape(username_was)}\//
506 name_sub = "#{username}/"
507 repositories.find_each do |repo|
508 repo.name = repo.name.sub(old_name_re, name_sub)