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 # "name" arg is a query label that appears in logs:
170 "group_permissions for #{uuid}",
171 # "binds" arg is an array of [col_id, value] for '$1' vars:
173 ).rows.each do |group_uuid, max_p_val|
174 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
176 Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
180 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
181 # and perm_hash[:write] are true if this user can read and write
182 # objects owned by group_uuid.
183 def group_permissions
184 r = Rails.cache.read "groups_for_user_#{self.uuid}"
186 if Rails.configuration.async_permissions_update
189 r = Rails.cache.read "groups_for_user_#{self.uuid}"
192 r = calculate_group_permissions
198 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
199 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
203 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
204 oid_login_perm = create_oid_login_perm openid_prefix
205 repo_perm = create_user_repo_link repo_name
206 vm_login_perm = create_vm_login_permission_link vm_uuid, username
207 group_perm = create_user_group_link
209 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
212 # delete user signatures, login, repo, and vm perms, and mark as inactive
214 # delete oid_login_perms for this user
215 Link.destroy_all(tail_uuid: self.email,
216 link_class: 'permission',
219 # delete repo_perms for this user
220 Link.destroy_all(tail_uuid: self.uuid,
221 link_class: 'permission',
224 # delete vm_login_perms for this user
225 Link.destroy_all(tail_uuid: self.uuid,
226 link_class: 'permission',
229 # delete "All users" group read permissions for this user
230 group = Group.where(name: 'All users').select do |g|
231 g[:uuid].match(/-f+$/)
233 Link.destroy_all(tail_uuid: self.uuid,
234 head_uuid: group[:uuid],
235 link_class: 'permission',
238 # delete any signatures by this user
239 Link.destroy_all(link_class: 'signature',
240 tail_uuid: self.uuid)
242 # delete user preferences (including profile)
245 # mark the user as inactive
246 self.is_active = false
250 def set_initial_username(requested: false)
251 if !requested.is_a?(String) || requested.empty?
252 email_parts = email.partition("@")
253 local_parts = email_parts.first.partition("+")
254 if email_parts.any?(&:empty?)
256 elsif not local_parts.first.empty?
257 requested = local_parts.first
259 requested = email_parts.first
262 requested.sub!(/^[^A-Za-z]+/, "")
263 requested.gsub!(/[^A-Za-z0-9]/, "")
264 unless requested.empty?
265 self.username = find_usable_username_from(requested)
271 def ensure_ownership_path_leads_to_user
275 def permission_to_update
277 current_user.andand.is_admin
279 # users must be able to update themselves (even if they are
280 # inactive) in order to create sessions
281 self == current_user or super
285 def permission_to_create
286 current_user.andand.is_admin or
287 (self == current_user and
288 self.is_active == Rails.configuration.new_users_are_active)
292 return if self.uuid.end_with?('anonymouspublic')
293 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
294 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
295 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
296 Rails.configuration.auto_admin_first_user)
298 self.is_active = true
302 def find_usable_username_from(basename)
303 # If "basename" is a usable username, return that.
304 # Otherwise, find a unique username "basenameN", where N is the
305 # smallest integer greater than 1, and return that.
306 # Return nil if a unique username can't be found after reasonable
308 quoted_name = self.class.connection.quote_string(basename)
309 next_username = basename
311 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
313 next_username = "%s%i" % [basename, next_suffix]
315 0.upto(6).each do |suffix_len|
316 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
318 where("username like '#{pattern}'").
320 order('username asc').
322 if other_user.username > next_username
324 elsif other_user.username == next_username
326 next_username = "%s%i" % [basename, next_suffix]
329 return next_username if (next_username.size <= pattern.size)
334 def prevent_privilege_escalation
335 if current_user.andand.is_admin
338 if self.is_active_changed?
339 if self.is_active != self.is_active_was
340 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
341 self.is_active = self.is_active_was
344 if self.is_admin_changed?
345 if self.is_admin != self.is_admin_was
346 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
347 self.is_admin = self.is_admin_was
353 def prevent_inactive_admin
354 if self.is_admin and not self.is_active
355 # There is no known use case for the strange set of permissions
356 # that would result from this change. It's safest to assume it's
357 # a mistake and disallow it outright.
358 raise "Admin users cannot be inactive"
363 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
364 nextpaths = graph[start]
365 return merged if !nextpaths
366 return merged if upstream_path.has_key? start
367 upstream_path[start] = true
368 upstream_mask ||= ALL_PERMISSIONS
369 nextpaths.each do |head, mask|
372 merged[head][k] ||= v if upstream_mask[k]
374 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
376 upstream_path.delete start
380 def create_oid_login_perm (openid_prefix)
381 login_perm_props = { "identity_url_prefix" => openid_prefix}
383 # Check oid_login_perm
384 oid_login_perms = Link.where(tail_uuid: self.email,
385 link_class: 'permission',
386 name: 'can_login').where("head_uuid = ?", self.uuid)
388 if !oid_login_perms.any?
389 # create openid login permission
390 oid_login_perm = Link.create(link_class: 'permission',
392 tail_uuid: self.email,
393 head_uuid: self.uuid,
394 properties: login_perm_props
396 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
398 oid_login_perm = oid_login_perms.first
401 return oid_login_perm
404 def create_user_repo_link(repo_name)
405 # repo_name is optional
407 logger.warn ("Repository name not given for #{self.uuid}.")
411 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
412 logger.info { "repo uuid: " + repo[:uuid] }
413 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
414 link_class: "permission",
415 name: "can_manage").first_or_create!
416 logger.info { "repo permission: " + repo_perm[:uuid] }
420 # create login permission for the given vm_uuid, if it does not already exist
421 def create_vm_login_permission_link(vm_uuid, repo_name)
422 # vm uuid is optional
424 vm = VirtualMachine.where(uuid: vm_uuid).first
427 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
428 raise "No vm found for #{vm_uuid}"
434 logger.info { "vm uuid: " + vm[:uuid] }
436 tail_uuid: uuid, head_uuid: vm.uuid,
437 link_class: "permission", name: "can_login",
442 select { |link| link.properties["username"] == repo_name }.
446 create(login_attrs.merge(properties: {"username" => repo_name}))
448 logger.info { "login permission: " + login_perm[:uuid] }
452 # add the user to the 'All users' group
453 def create_user_group_link
454 return (Link.where(tail_uuid: self.uuid,
455 head_uuid: all_users_group[:uuid],
456 link_class: 'permission',
457 name: 'can_read').first or
458 Link.create(tail_uuid: self.uuid,
459 head_uuid: all_users_group[:uuid],
460 link_class: 'permission',
464 # Give the special "System group" permission to manage this user and
465 # all of this user's stuff.
466 def add_system_group_permission_link
467 return true if uuid == system_user_uuid
468 act_as_system_user do
469 Link.create(link_class: 'permission',
471 tail_uuid: system_group_uuid,
472 head_uuid: self.uuid)
476 # Send admin notifications
477 def send_admin_notifications
478 AdminNotifier.new_user(self).deliver
479 if not self.is_active then
480 AdminNotifier.new_inactive_user(self).deliver
484 # Automatically setup new user during creation
485 def auto_setup_new_user
486 setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
488 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
490 repo_name = "#{username}/#{username}"
491 if Rails.configuration.auto_setup_new_users_with_repository and
492 Repository.where(name: repo_name).first.nil?
493 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
494 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
495 link_class: "permission", name: "can_manage")
500 # Send notification if the user saved profile for the first time
501 def send_profile_created_notification
502 if self.prefs_changed?
503 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
504 profile_notification_address = Rails.configuration.user_profile_notification_address
505 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
510 def verify_repositories_empty
511 unless repositories.first.nil?
512 errors.add(:username, "can't be unset when the user owns repositories")
517 def sync_repository_names
518 old_name_re = /^#{Regexp.escape(username_was)}\//
519 name_sub = "#{username}/"
520 repositories.find_each do |repo|
521 repo.name = repo.name.sub(old_name_re, name_sub)