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.
139 # The permission graph is built by repeatedly enumerating all
140 # permission links reachable from self.uuid, and then calling
142 def calculate_group_permissions
143 permissions_from = {}
144 todo = {self.uuid => true}
146 # Build the equivalence class of permissions starting with
147 # self.uuid. On each iteration of this loop, todo contains
148 # the next set of uuids in the permission equivalence class
151 lookup_uuids = todo.keys
152 lookup_uuids.each do |uuid| done[uuid] = true end
155 # include all groups owned by the current set of uuids.
156 Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
157 newgroups << [group.owner_uuid, group.uuid, 'can_manage']
159 # add any permission links from the current lookup_uuids to a Group.
160 Link.where('link_class = ? and tail_uuid in (?) and ' \
161 '(head_uuid like ? or (name = ? and head_uuid like ?))',
164 Group.uuid_like_pattern,
166 User.uuid_like_pattern).each do |link|
167 newgroups << [link.tail_uuid, link.head_uuid, link.name]
169 newgroups.each do |tail_uuid, head_uuid, perm_name|
170 unless done.has_key? head_uuid
171 todo[head_uuid] = true
173 link_permissions = {}
176 link_permissions = {read:true}
178 link_permissions = {read:true,write:true}
180 link_permissions = ALL_PERMISSIONS
182 permissions_from[tail_uuid] ||= {}
183 permissions_from[tail_uuid][head_uuid] ||= {}
184 link_permissions.each do |k,v|
185 permissions_from[tail_uuid][head_uuid][k] ||= v
189 perms = search_permissions(self.uuid, permissions_from)
190 Rails.cache.write "groups_for_user_#{self.uuid}", perms
194 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
195 # and perm_hash[:write] are true if this user can read and write
196 # objects owned by group_uuid.
197 def group_permissions
198 r = Rails.cache.read "groups_for_user_#{self.uuid}"
200 if Rails.configuration.async_permissions_update
203 r = Rails.cache.read "groups_for_user_#{self.uuid}"
206 r = calculate_group_permissions
212 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
213 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
217 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
218 oid_login_perm = create_oid_login_perm openid_prefix
219 repo_perm = create_user_repo_link repo_name
220 vm_login_perm = create_vm_login_permission_link vm_uuid, username
221 group_perm = create_user_group_link
223 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
226 # delete user signatures, login, repo, and vm perms, and mark as inactive
228 # delete oid_login_perms for this user
229 Link.destroy_all(tail_uuid: self.email,
230 link_class: 'permission',
233 # delete repo_perms for this user
234 Link.destroy_all(tail_uuid: self.uuid,
235 link_class: 'permission',
238 # delete vm_login_perms for this user
239 Link.destroy_all(tail_uuid: self.uuid,
240 link_class: 'permission',
243 # delete "All users" group read permissions for this user
244 group = Group.where(name: 'All users').select do |g|
245 g[:uuid].match /-f+$/
247 Link.destroy_all(tail_uuid: self.uuid,
248 head_uuid: group[:uuid],
249 link_class: 'permission',
252 # delete any signatures by this user
253 Link.destroy_all(link_class: 'signature',
254 tail_uuid: self.uuid)
256 # delete user preferences (including profile)
259 # mark the user as inactive
260 self.is_active = false
266 def ensure_ownership_path_leads_to_user
270 def permission_to_update
272 current_user.andand.is_admin
274 # users must be able to update themselves (even if they are
275 # inactive) in order to create sessions
276 self == current_user or super
280 def permission_to_create
281 current_user.andand.is_admin or
282 (self == current_user and
283 self.is_active == Rails.configuration.new_users_are_active)
287 return if self.uuid.end_with?('anonymouspublic')
288 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
289 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
290 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
291 Rails.configuration.auto_admin_first_user)
293 self.is_active = true
297 def find_usable_username_from(basename)
298 # If "basename" is a usable username, return that.
299 # Otherwise, find a unique username "basenameN", where N is the
300 # smallest integer greater than 1, and return that.
301 # Return nil if a unique username can't be found after reasonable
303 quoted_name = self.class.connection.quote_string(basename)
304 next_username = basename
306 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
308 next_username = "%s%i" % [basename, next_suffix]
310 0.upto(6).each do |suffix_len|
311 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
313 where("username like '#{pattern}'").
315 order('username asc').
317 if other_user.username > next_username
319 elsif other_user.username == next_username
321 next_username = "%s%i" % [basename, next_suffix]
324 return next_username if (next_username.size <= pattern.size)
329 def set_initial_username
330 email_parts = email.partition("@")
331 local_parts = email_parts.first.partition("+")
332 if email_parts.any?(&:empty?)
334 elsif not local_parts.first.empty?
335 base_username = local_parts.first
337 base_username = email_parts.first
339 base_username.sub!(/^[^A-Za-z]+/, "")
340 base_username.gsub!(/[^A-Za-z0-9]/, "")
341 unless base_username.empty?
342 self.username = find_usable_username_from(base_username)
346 def prevent_privilege_escalation
347 if current_user.andand.is_admin
350 if self.is_active_changed?
351 if self.is_active != self.is_active_was
352 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
353 self.is_active = self.is_active_was
356 if self.is_admin_changed?
357 if self.is_admin != self.is_admin_was
358 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
359 self.is_admin = self.is_admin_was
365 def prevent_inactive_admin
366 if self.is_admin and not self.is_active
367 # There is no known use case for the strange set of permissions
368 # that would result from this change. It's safest to assume it's
369 # a mistake and disallow it outright.
370 raise "Admin users cannot be inactive"
375 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
376 nextpaths = graph[start]
377 return merged if !nextpaths
378 return merged if upstream_path.has_key? start
379 upstream_path[start] = true
380 upstream_mask ||= ALL_PERMISSIONS
381 nextpaths.each do |head, mask|
384 merged[head][k] ||= v if upstream_mask[k]
386 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
388 upstream_path.delete start
392 def create_oid_login_perm (openid_prefix)
393 login_perm_props = { "identity_url_prefix" => openid_prefix}
395 # Check oid_login_perm
396 oid_login_perms = Link.where(tail_uuid: self.email,
397 link_class: 'permission',
398 name: 'can_login').where("head_uuid = ?", self.uuid)
400 if !oid_login_perms.any?
401 # create openid login permission
402 oid_login_perm = Link.create(link_class: 'permission',
404 tail_uuid: self.email,
405 head_uuid: self.uuid,
406 properties: login_perm_props
408 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
410 oid_login_perm = oid_login_perms.first
413 return oid_login_perm
416 def create_user_repo_link(repo_name)
417 # repo_name is optional
419 logger.warn ("Repository name not given for #{self.uuid}.")
423 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
424 logger.info { "repo uuid: " + repo[:uuid] }
425 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
426 link_class: "permission",
427 name: "can_manage").first_or_create!
428 logger.info { "repo permission: " + repo_perm[:uuid] }
432 # create login permission for the given vm_uuid, if it does not already exist
433 def create_vm_login_permission_link(vm_uuid, repo_name)
434 # vm uuid is optional
436 vm = VirtualMachine.where(uuid: vm_uuid).first
439 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
440 raise "No vm found for #{vm_uuid}"
446 logger.info { "vm uuid: " + vm[:uuid] }
448 tail_uuid: uuid, head_uuid: vm.uuid,
449 link_class: "permission", name: "can_login",
454 select { |link| link.properties["username"] == repo_name }.
458 create(login_attrs.merge(properties: {"username" => repo_name}))
460 logger.info { "login permission: " + login_perm[:uuid] }
464 # add the user to the 'All users' group
465 def create_user_group_link
466 return (Link.where(tail_uuid: self.uuid,
467 head_uuid: all_users_group[:uuid],
468 link_class: 'permission',
469 name: 'can_read').first or
470 Link.create(tail_uuid: self.uuid,
471 head_uuid: all_users_group[:uuid],
472 link_class: 'permission',
476 # Give the special "System group" permission to manage this user and
477 # all of this user's stuff.
478 def add_system_group_permission_link
479 return true if uuid == system_user_uuid
480 act_as_system_user do
481 Link.create(link_class: 'permission',
483 tail_uuid: system_group_uuid,
484 head_uuid: self.uuid)
488 # Send admin notifications
489 def send_admin_notifications
490 AdminNotifier.new_user(self).deliver
491 if not self.is_active then
492 AdminNotifier.new_inactive_user(self).deliver
496 # Automatically setup new user during creation
497 def auto_setup_new_user
498 setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
500 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
502 repo_name = "#{username}/#{username}"
503 if Rails.configuration.auto_setup_new_users_with_repository and
504 Repository.where(name: repo_name).first.nil?
505 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
506 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
507 link_class: "permission", name: "can_manage")
512 # Send notification if the user saved profile for the first time
513 def send_profile_created_notification
514 if self.prefs_changed?
515 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
516 profile_notification_address = Rails.configuration.user_profile_notification_address
517 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
522 def verify_repositories_empty
523 unless repositories.first.nil?
524 errors.add(:username, "can't be unset when the user owns repositories")
529 def sync_repository_names
530 old_name_re = /^#{Regexp.escape(username_was)}\//
531 name_sub = "#{username}/"
532 repositories.find_each do |repo|
533 repo.name = repo.name.sub(old_name_re, name_sub)