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}
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 conn = ActiveRecord::Base.connection
148 self.class.transaction do
149 # Check whether the temporary view has already been created
150 # during this connection. If not, create it.
151 conn.exec_query 'SAVEPOINT check_permission_view'
153 conn.exec_query('SELECT 1 FROM permission_view LIMIT 0')
155 conn.exec_query 'ROLLBACK TO SAVEPOINT check_permission_view'
156 sql = File.read(Rails.root.join('lib', 'create_permission_view.sql'))
159 conn.exec_query 'RELEASE SAVEPOINT check_permission_view'
164 conn.exec_query('SELECT target_owner_uuid, max(perm_level)
167 AND target_owner_uuid IS NOT NULL
168 GROUP BY target_owner_uuid',
169 "group_permissions for #{uuid}",
170 [[nil, uuid]]).rows.each do |group_uuid, max_p_val|
171 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
173 Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
177 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
178 # and perm_hash[:write] are true if this user can read and write
179 # objects owned by group_uuid.
180 def group_permissions
181 r = Rails.cache.read "groups_for_user_#{self.uuid}"
183 if Rails.configuration.async_permissions_update
186 r = Rails.cache.read "groups_for_user_#{self.uuid}"
189 r = calculate_group_permissions
195 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
196 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
200 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
201 oid_login_perm = create_oid_login_perm openid_prefix
202 repo_perm = create_user_repo_link repo_name
203 vm_login_perm = create_vm_login_permission_link vm_uuid, username
204 group_perm = create_user_group_link
206 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
209 # delete user signatures, login, repo, and vm perms, and mark as inactive
211 # delete oid_login_perms for this user
212 Link.destroy_all(tail_uuid: self.email,
213 link_class: 'permission',
216 # delete repo_perms for this user
217 Link.destroy_all(tail_uuid: self.uuid,
218 link_class: 'permission',
221 # delete vm_login_perms for this user
222 Link.destroy_all(tail_uuid: self.uuid,
223 link_class: 'permission',
226 # delete "All users" group read permissions for this user
227 group = Group.where(name: 'All users').select do |g|
228 g[:uuid].match(/-f+$/)
230 Link.destroy_all(tail_uuid: self.uuid,
231 head_uuid: group[:uuid],
232 link_class: 'permission',
235 # delete any signatures by this user
236 Link.destroy_all(link_class: 'signature',
237 tail_uuid: self.uuid)
239 # delete user preferences (including profile)
242 # mark the user as inactive
243 self.is_active = false
247 def set_initial_username(requested: false)
248 if !requested.is_a?(String) || requested.empty?
249 email_parts = email.partition("@")
250 local_parts = email_parts.first.partition("+")
251 if email_parts.any?(&:empty?)
253 elsif not local_parts.first.empty?
254 requested = local_parts.first
256 requested = email_parts.first
259 requested.sub!(/^[^A-Za-z]+/, "")
260 requested.gsub!(/[^A-Za-z0-9]/, "")
261 unless requested.empty?
262 self.username = find_usable_username_from(requested)
268 def ensure_ownership_path_leads_to_user
272 def permission_to_update
274 current_user.andand.is_admin
276 # users must be able to update themselves (even if they are
277 # inactive) in order to create sessions
278 self == current_user or super
282 def permission_to_create
283 current_user.andand.is_admin or
284 (self == current_user and
285 self.is_active == Rails.configuration.new_users_are_active)
289 return if self.uuid.end_with?('anonymouspublic')
290 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
291 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
292 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
293 Rails.configuration.auto_admin_first_user)
295 self.is_active = true
299 def find_usable_username_from(basename)
300 # If "basename" is a usable username, return that.
301 # Otherwise, find a unique username "basenameN", where N is the
302 # smallest integer greater than 1, and return that.
303 # Return nil if a unique username can't be found after reasonable
305 quoted_name = self.class.connection.quote_string(basename)
306 next_username = basename
308 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
310 next_username = "%s%i" % [basename, next_suffix]
312 0.upto(6).each do |suffix_len|
313 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
315 where("username like '#{pattern}'").
317 order('username asc').
319 if other_user.username > next_username
321 elsif other_user.username == next_username
323 next_username = "%s%i" % [basename, next_suffix]
326 return next_username if (next_username.size <= pattern.size)
331 def prevent_privilege_escalation
332 if current_user.andand.is_admin
335 if self.is_active_changed?
336 if self.is_active != self.is_active_was
337 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
338 self.is_active = self.is_active_was
341 if self.is_admin_changed?
342 if self.is_admin != self.is_admin_was
343 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
344 self.is_admin = self.is_admin_was
350 def prevent_inactive_admin
351 if self.is_admin and not self.is_active
352 # There is no known use case for the strange set of permissions
353 # that would result from this change. It's safest to assume it's
354 # a mistake and disallow it outright.
355 raise "Admin users cannot be inactive"
360 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
361 nextpaths = graph[start]
362 return merged if !nextpaths
363 return merged if upstream_path.has_key? start
364 upstream_path[start] = true
365 upstream_mask ||= ALL_PERMISSIONS
366 nextpaths.each do |head, mask|
369 merged[head][k] ||= v if upstream_mask[k]
371 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
373 upstream_path.delete start
377 def create_oid_login_perm (openid_prefix)
378 login_perm_props = { "identity_url_prefix" => openid_prefix}
380 # Check oid_login_perm
381 oid_login_perms = Link.where(tail_uuid: self.email,
382 link_class: 'permission',
383 name: 'can_login').where("head_uuid = ?", self.uuid)
385 if !oid_login_perms.any?
386 # create openid login permission
387 oid_login_perm = Link.create(link_class: 'permission',
389 tail_uuid: self.email,
390 head_uuid: self.uuid,
391 properties: login_perm_props
393 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
395 oid_login_perm = oid_login_perms.first
398 return oid_login_perm
401 def create_user_repo_link(repo_name)
402 # repo_name is optional
404 logger.warn ("Repository name not given for #{self.uuid}.")
408 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
409 logger.info { "repo uuid: " + repo[:uuid] }
410 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
411 link_class: "permission",
412 name: "can_manage").first_or_create!
413 logger.info { "repo permission: " + repo_perm[:uuid] }
417 # create login permission for the given vm_uuid, if it does not already exist
418 def create_vm_login_permission_link(vm_uuid, repo_name)
419 # vm uuid is optional
421 vm = VirtualMachine.where(uuid: vm_uuid).first
424 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
425 raise "No vm found for #{vm_uuid}"
431 logger.info { "vm uuid: " + vm[:uuid] }
433 tail_uuid: uuid, head_uuid: vm.uuid,
434 link_class: "permission", name: "can_login",
439 select { |link| link.properties["username"] == repo_name }.
443 create(login_attrs.merge(properties: {"username" => repo_name}))
445 logger.info { "login permission: " + login_perm[:uuid] }
449 # add the user to the 'All users' group
450 def create_user_group_link
451 return (Link.where(tail_uuid: self.uuid,
452 head_uuid: all_users_group[:uuid],
453 link_class: 'permission',
454 name: 'can_read').first or
455 Link.create(tail_uuid: self.uuid,
456 head_uuid: all_users_group[:uuid],
457 link_class: 'permission',
461 # Give the special "System group" permission to manage this user and
462 # all of this user's stuff.
463 def add_system_group_permission_link
464 return true if uuid == system_user_uuid
465 act_as_system_user do
466 Link.create(link_class: 'permission',
468 tail_uuid: system_group_uuid,
469 head_uuid: self.uuid)
473 # Send admin notifications
474 def send_admin_notifications
475 AdminNotifier.new_user(self).deliver
476 if not self.is_active then
477 AdminNotifier.new_inactive_user(self).deliver
481 # Automatically setup new user during creation
482 def auto_setup_new_user
483 setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
485 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
487 repo_name = "#{username}/#{username}"
488 if Rails.configuration.auto_setup_new_users_with_repository and
489 Repository.where(name: repo_name).first.nil?
490 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
491 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
492 link_class: "permission", name: "can_manage")
497 # Send notification if the user saved profile for the first time
498 def send_profile_created_notification
499 if self.prefs_changed?
500 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
501 profile_notification_address = Rails.configuration.user_profile_notification_address
502 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
507 def verify_repositories_empty
508 unless repositories.first.nil?
509 errors.add(:username, "can't be unset when the user owns repositories")
514 def sync_repository_names
515 old_name_re = /^#{Regexp.escape(username_was)}\//
516 name_sub = "#{username}/"
517 repositories.find_each do |repo|
518 repo.name = repo.name.sub(old_name_re, name_sub)