1 require 'can_be_an_owner'
3 class User < ArvadosModel
6 include CommonApiTemplate
10 has_many :api_client_authorizations
11 before_update :prevent_privilege_escalation
12 before_update :prevent_inactive_admin
13 before_create :check_auto_admin
14 after_create :add_system_group_permission_link
15 after_create :auto_setup_new_user
16 after_create :send_admin_notifications
17 after_update :send_profile_created_notification
20 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
22 api_accessible :user, extend: :common do |t|
34 ALL_PERMISSIONS = {read: true, write: true, manage: true}
37 "#{first_name} #{last_name}".strip
42 Rails.configuration.new_users_are_active ||
43 self.groups_i_can(:read).select { |x| x.match /-f+$/ }.first)
46 def groups_i_can(verb)
47 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
49 my_groups << anonymous_group_uuid
55 return true if is_admin
56 actions.each do |action, target|
58 if target.respond_to? :uuid
59 target_uuid = target.uuid
62 target = ArvadosModel.find_by_uuid(target_uuid)
65 next if target_uuid == self.uuid
66 next if (group_permissions[target_uuid] and
67 group_permissions[target_uuid][action])
68 if target.respond_to? :owner_uuid
69 next if target.owner_uuid == self.uuid
70 next if (group_permissions[target.owner_uuid] and
71 group_permissions[target.owner_uuid][action])
73 sufficient_perms = case action
77 ['can_manage', 'can_write']
79 ['can_manage', 'can_write', 'can_read']
81 # (Skip this kind of permission opportunity
82 # if action is an unknown permission type)
85 # Check permission links with head_uuid pointing directly at
86 # the target object. If target is a Group, this is redundant
87 # and will fail except [a] if permission caching is broken or
88 # [b] during a race condition, where a permission link has
90 if Link.where(link_class: 'permission',
91 name: sufficient_perms,
92 tail_uuid: groups_i_can(action) + [self.uuid],
93 head_uuid: target_uuid).any?
102 def self.invalidate_permissions_cache
103 Rails.cache.delete_matched(/^groups_for_user_/)
106 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
107 # and perm_hash[:write] are true if this user can read and write
108 # objects owned by group_uuid.
110 # The permission graph is built by repeatedly enumerating all
111 # permission links reachable from self.uuid, and then calling
113 def group_permissions
114 Rails.cache.fetch "groups_for_user_#{self.uuid}" do
115 permissions_from = {}
116 todo = {self.uuid => true}
118 # Build the equivalence class of permissions starting with
119 # self.uuid. On each iteration of this loop, todo contains
120 # the next set of uuids in the permission equivalence class
123 lookup_uuids = todo.keys
124 lookup_uuids.each do |uuid| done[uuid] = true end
127 # include all groups owned by the current set of uuids.
128 Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
129 newgroups << [group.owner_uuid, group.uuid, 'can_manage']
131 # add any permission links from the current lookup_uuids to a Group.
132 Link.where('link_class = ? and tail_uuid in (?) and ' \
133 '(head_uuid like ? or (name = ? and head_uuid like ?))',
136 Group.uuid_like_pattern,
138 User.uuid_like_pattern).each do |link|
139 newgroups << [link.tail_uuid, link.head_uuid, link.name]
141 newgroups.each do |tail_uuid, head_uuid, perm_name|
142 unless done.has_key? head_uuid
143 todo[head_uuid] = true
145 link_permissions = {}
148 link_permissions = {read:true}
150 link_permissions = {read:true,write:true}
152 link_permissions = ALL_PERMISSIONS
154 permissions_from[tail_uuid] ||= {}
155 permissions_from[tail_uuid][head_uuid] ||= {}
156 link_permissions.each do |k,v|
157 permissions_from[tail_uuid][head_uuid][k] ||= v
161 search_permissions(self.uuid, permissions_from)
165 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
166 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
170 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
171 oid_login_perm = create_oid_login_perm openid_prefix
172 repo_perm = create_user_repo_link repo_name
173 vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
174 group_perm = create_user_group_link
176 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
179 # delete user signatures, login, repo, and vm perms, and mark as inactive
181 # delete oid_login_perms for this user
182 Link.destroy_all(tail_uuid: self.email,
183 link_class: 'permission',
186 # delete repo_perms for this user
187 Link.destroy_all(tail_uuid: self.uuid,
188 link_class: 'permission',
191 # delete vm_login_perms for this user
192 Link.destroy_all(tail_uuid: self.uuid,
193 link_class: 'permission',
196 # delete "All users" group read permissions for this user
197 group = Group.where(name: 'All users').select do |g|
198 g[:uuid].match /-f+$/
200 Link.destroy_all(tail_uuid: self.uuid,
201 head_uuid: group[:uuid],
202 link_class: 'permission',
205 # delete any signatures by this user
206 Link.destroy_all(link_class: 'signature',
207 tail_uuid: self.uuid)
209 # delete user preferences (including profile)
212 # mark the user as inactive
213 self.is_active = false
219 def ensure_ownership_path_leads_to_user
223 def permission_to_update
224 # users must be able to update themselves (even if they are
225 # inactive) in order to create sessions
226 self == current_user or super
229 def permission_to_create
230 current_user.andand.is_admin or
231 (self == current_user and
232 self.is_active == Rails.configuration.new_users_are_active)
236 if User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and Rails.configuration.auto_admin_user
237 if self.email == Rails.configuration.auto_admin_user
239 self.is_active = true
244 def prevent_privilege_escalation
245 if current_user.andand.is_admin
248 if self.is_active_changed?
249 if self.is_active != self.is_active_was
250 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
251 self.is_active = self.is_active_was
254 if self.is_admin_changed?
255 if self.is_admin != self.is_admin_was
256 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
257 self.is_admin = self.is_admin_was
263 def prevent_inactive_admin
264 if self.is_admin and not self.is_active
265 # There is no known use case for the strange set of permissions
266 # that would result from this change. It's safest to assume it's
267 # a mistake and disallow it outright.
268 raise "Admin users cannot be inactive"
273 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
274 nextpaths = graph[start]
275 return merged if !nextpaths
276 return merged if upstream_path.has_key? start
277 upstream_path[start] = true
278 upstream_mask ||= ALL_PERMISSIONS
279 nextpaths.each do |head, mask|
282 merged[head][k] ||= v if upstream_mask[k]
284 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
286 upstream_path.delete start
290 def create_oid_login_perm (openid_prefix)
291 login_perm_props = { "identity_url_prefix" => openid_prefix}
293 # Check oid_login_perm
294 oid_login_perms = Link.where(tail_uuid: self.email,
295 link_class: 'permission',
296 name: 'can_login').where("head_uuid = ?", self.uuid)
298 if !oid_login_perms.any?
299 # create openid login permission
300 oid_login_perm = Link.create(link_class: 'permission',
302 tail_uuid: self.email,
303 head_uuid: self.uuid,
304 properties: login_perm_props
306 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
308 oid_login_perm = oid_login_perms.first
311 return oid_login_perm
314 def create_user_repo_link(repo_name)
315 # repo_name is optional
317 logger.warn ("Repository name not given for #{self.uuid}.")
321 # Check for an existing repository with the same name we're about to use.
322 repo = Repository.where(name: repo_name).first
325 logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
327 # Look for existing repository access for this repo
328 repo_perms = Link.where(tail_uuid: self.uuid,
329 head_uuid: repo[:uuid],
330 link_class: 'permission',
333 logger.warn "User already has repository access " +
334 repo_perms.collect { |p| p[:uuid] }.inspect
335 return repo_perms.first
339 # create repo, if does not already exist
340 repo ||= Repository.create(name: repo_name)
341 logger.info { "repo uuid: " + repo[:uuid] }
343 repo_perm = Link.create(tail_uuid: self.uuid,
344 head_uuid: repo[:uuid],
345 link_class: 'permission',
347 logger.info { "repo permission: " + repo_perm[:uuid] }
351 # create login permission for the given vm_uuid, if it does not already exist
352 def create_vm_login_permission_link(vm_uuid, repo_name)
355 # vm uuid is optional
357 vm = VirtualMachine.where(uuid: vm_uuid).first
360 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
361 raise "No vm found for #{vm_uuid}"
367 logger.info { "vm uuid: " + vm[:uuid] }
369 login_perms = Link.where(tail_uuid: self.uuid,
370 head_uuid: vm[:uuid],
371 link_class: 'permission',
375 login_perms.each do |perm|
376 if perm.properties['username'] == repo_name
383 login_perm = perm_exists
385 login_perm = Link.create(tail_uuid: self.uuid,
386 head_uuid: vm[:uuid],
387 link_class: 'permission',
389 properties: {'username' => repo_name})
390 logger.info { "login permission: " + login_perm[:uuid] }
397 # add the user to the 'All users' group
398 def create_user_group_link
399 # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
400 group = Group.where(name: 'All users').select do |g|
401 g[:uuid].match /-f+$/
405 logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
406 raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
408 logger.info { "\"All users\" group uuid: " + group[:uuid] }
410 group_perms = Link.where(tail_uuid: self.uuid,
411 head_uuid: group[:uuid],
412 link_class: 'permission',
416 group_perm = Link.create(tail_uuid: self.uuid,
417 head_uuid: group[:uuid],
418 link_class: 'permission',
420 logger.info { "group permission: " + group_perm[:uuid] }
422 group_perm = group_perms.first
429 # Give the special "System group" permission to manage this user and
430 # all of this user's stuff.
432 def add_system_group_permission_link
433 act_as_system_user do
434 Link.create(link_class: 'permission',
436 tail_uuid: system_group_uuid,
437 head_uuid: self.uuid)
441 # Send admin notifications
442 def send_admin_notifications
443 AdminNotifier.new_user(self).deliver
444 if not self.is_active then
445 AdminNotifier.new_inactive_user(self).deliver
449 # Automatically setup new user during creation
450 def auto_setup_new_user
451 return true if !Rails.configuration.auto_setup_new_users
452 return true if !self.email
454 if Rails.configuration.auto_setup_new_users_with_vm_uuid ||
455 Rails.configuration.auto_setup_new_users_with_repository
456 username = self.email.partition('@')[0] if self.email
457 return true if !username
459 blacklisted_usernames = Rails.configuration.auto_setup_name_blacklist
460 if blacklisted_usernames.include?(username)
462 elsif !(/^[a-zA-Z][-._a-zA-Z0-9]{0,30}[a-zA-Z0-9]$/.match(username))
465 return true if !(username = derive_unique_username username)
470 setup_repo_vm_links(username,
471 Rails.configuration.auto_setup_new_users_with_vm_uuid,
472 Rails.configuration.default_openid_prefix)
475 # Find a username that starts with the given string and does not collide
476 # with any existing repository name or VM login name
477 def derive_unique_username username
479 if Repository.where(name: username).empty?
480 login_collisions = Link.where(link_class: 'permission',
481 name: 'can_login').select do |perm|
482 perm.properties['username'] == username
484 return username if login_collisions.empty?
486 username = username + SecureRandom.random_number(10).to_s
490 # Send notification if the user saved profile for the first time
491 def send_profile_created_notification
492 if self.prefs_changed?
493 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
494 profile_notification_address = Rails.configuration.user_profile_notification_address
495 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address