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])
78 def self.invalidate_permissions_cache
79 Rails.cache.delete_matched(/^groups_for_user_/)
82 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
83 # and perm_hash[:write] are true if this user can read and write
84 # objects owned by group_uuid.
86 # The permission graph is built by repeatedly enumerating all
87 # permission links reachable from self.uuid, and then calling
90 Rails.cache.fetch "groups_for_user_#{self.uuid}" do
92 todo = {self.uuid => true}
94 # Build the equivalence class of permissions starting with
95 # self.uuid. On each iteration of this loop, todo contains
96 # the next set of uuids in the permission equivalence class
99 lookup_uuids = todo.keys
100 lookup_uuids.each do |uuid| done[uuid] = true end
103 # include all groups owned by the current set of uuids.
104 Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
105 newgroups << [group.owner_uuid, group.uuid, 'can_manage']
107 # add any permission links from the current lookup_uuids to a Group.
108 Link.where('link_class = ? and tail_uuid in (?) and ' \
109 '(head_uuid like ? or (name = ? and head_uuid like ?))',
112 Group.uuid_like_pattern,
114 User.uuid_like_pattern).each do |link|
115 newgroups << [link.tail_uuid, link.head_uuid, link.name]
117 newgroups.each do |tail_uuid, head_uuid, perm_name|
118 unless done.has_key? head_uuid
119 todo[head_uuid] = true
121 link_permissions = {}
124 link_permissions = {read:true}
126 link_permissions = {read:true,write:true}
128 link_permissions = ALL_PERMISSIONS
130 permissions_from[tail_uuid] ||= {}
131 permissions_from[tail_uuid][head_uuid] ||= {}
132 link_permissions.each do |k,v|
133 permissions_from[tail_uuid][head_uuid][k] ||= v
137 search_permissions(self.uuid, permissions_from)
141 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
142 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
146 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
147 oid_login_perm = create_oid_login_perm openid_prefix
148 repo_perm = create_user_repo_link repo_name
149 vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
150 group_perm = create_user_group_link
152 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
155 # delete user signatures, login, repo, and vm perms, and mark as inactive
157 # delete oid_login_perms for this user
158 Link.destroy_all(tail_uuid: self.email,
159 link_class: 'permission',
162 # delete repo_perms for this user
163 Link.destroy_all(tail_uuid: self.uuid,
164 link_class: 'permission',
167 # delete vm_login_perms for this user
168 Link.destroy_all(tail_uuid: self.uuid,
169 link_class: 'permission',
172 # delete "All users" group read permissions for this user
173 group = Group.where(name: 'All users').select do |g|
174 g[:uuid].match /-f+$/
176 Link.destroy_all(tail_uuid: self.uuid,
177 head_uuid: group[:uuid],
178 link_class: 'permission',
181 # delete any signatures by this user
182 Link.destroy_all(link_class: 'signature',
183 tail_uuid: self.uuid)
185 # delete user preferences (including profile)
188 # mark the user as inactive
189 self.is_active = false
195 def ensure_ownership_path_leads_to_user
199 def permission_to_update
200 # users must be able to update themselves (even if they are
201 # inactive) in order to create sessions
202 self == current_user or super
205 def permission_to_create
206 current_user.andand.is_admin or
207 (self == current_user and
208 self.is_active == Rails.configuration.new_users_are_active)
212 if User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and Rails.configuration.auto_admin_user
213 if self.email == Rails.configuration.auto_admin_user
215 self.is_active = true
220 def prevent_privilege_escalation
221 if current_user.andand.is_admin
224 if self.is_active_changed?
225 if self.is_active != self.is_active_was
226 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
227 self.is_active = self.is_active_was
230 if self.is_admin_changed?
231 if self.is_admin != self.is_admin_was
232 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
233 self.is_admin = self.is_admin_was
239 def prevent_inactive_admin
240 if self.is_admin and not self.is_active
241 # There is no known use case for the strange set of permissions
242 # that would result from this change. It's safest to assume it's
243 # a mistake and disallow it outright.
244 raise "Admin users cannot be inactive"
249 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
250 nextpaths = graph[start]
251 return merged if !nextpaths
252 return merged if upstream_path.has_key? start
253 upstream_path[start] = true
254 upstream_mask ||= ALL_PERMISSIONS
255 nextpaths.each do |head, mask|
258 merged[head][k] ||= v if upstream_mask[k]
260 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
262 upstream_path.delete start
266 def create_oid_login_perm (openid_prefix)
267 login_perm_props = { "identity_url_prefix" => openid_prefix}
269 # Check oid_login_perm
270 oid_login_perms = Link.where(tail_uuid: self.email,
271 link_class: 'permission',
272 name: 'can_login').where("head_uuid = ?", self.uuid)
274 if !oid_login_perms.any?
275 # create openid login permission
276 oid_login_perm = Link.create(link_class: 'permission',
278 tail_uuid: self.email,
279 head_uuid: self.uuid,
280 properties: login_perm_props
282 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
284 oid_login_perm = oid_login_perms.first
287 return oid_login_perm
290 def create_user_repo_link(repo_name)
291 # repo_name is optional
293 logger.warn ("Repository name not given for #{self.uuid}.")
297 # Check for an existing repository with the same name we're about to use.
298 repo = Repository.where(name: repo_name).first
301 logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
303 # Look for existing repository access for this repo
304 repo_perms = Link.where(tail_uuid: self.uuid,
305 head_uuid: repo[:uuid],
306 link_class: 'permission',
309 logger.warn "User already has repository access " +
310 repo_perms.collect { |p| p[:uuid] }.inspect
311 return repo_perms.first
315 # create repo, if does not already exist
316 repo ||= Repository.create(name: repo_name)
317 logger.info { "repo uuid: " + repo[:uuid] }
319 repo_perm = Link.create(tail_uuid: self.uuid,
320 head_uuid: repo[:uuid],
321 link_class: 'permission',
323 logger.info { "repo permission: " + repo_perm[:uuid] }
327 # create login permission for the given vm_uuid, if it does not already exist
328 def create_vm_login_permission_link(vm_uuid, repo_name)
331 # vm uuid is optional
333 vm = VirtualMachine.where(uuid: vm_uuid).first
336 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
337 raise "No vm found for #{vm_uuid}"
343 logger.info { "vm uuid: " + vm[:uuid] }
345 login_perms = Link.where(tail_uuid: self.uuid,
346 head_uuid: vm[:uuid],
347 link_class: 'permission',
351 login_perms.each do |perm|
352 if perm.properties['username'] == repo_name
359 login_perm = perm_exists
361 login_perm = Link.create(tail_uuid: self.uuid,
362 head_uuid: vm[:uuid],
363 link_class: 'permission',
365 properties: {'username' => repo_name})
366 logger.info { "login permission: " + login_perm[:uuid] }
373 # add the user to the 'All users' group
374 def create_user_group_link
375 # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
376 group = Group.where(name: 'All users').select do |g|
377 g[:uuid].match /-f+$/
381 logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
382 raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
384 logger.info { "\"All users\" group uuid: " + group[:uuid] }
386 group_perms = Link.where(tail_uuid: self.uuid,
387 head_uuid: group[:uuid],
388 link_class: 'permission',
392 group_perm = Link.create(tail_uuid: self.uuid,
393 head_uuid: group[:uuid],
394 link_class: 'permission',
396 logger.info { "group permission: " + group_perm[:uuid] }
398 group_perm = group_perms.first
405 # Give the special "System group" permission to manage this user and
406 # all of this user's stuff.
408 def add_system_group_permission_link
409 act_as_system_user do
410 Link.create(link_class: 'permission',
412 tail_uuid: system_group_uuid,
413 head_uuid: self.uuid)
417 # Send admin notifications
418 def send_admin_notifications
419 AdminNotifier.new_user(self).deliver
420 if not self.is_active then
421 AdminNotifier.new_inactive_user(self).deliver
425 # Automatically setup new user during creation
426 def auto_setup_new_user
427 return true if !Rails.configuration.auto_setup_new_users
428 return true if !self.email
430 if Rails.configuration.auto_setup_new_users_with_vm_uuid ||
431 Rails.configuration.auto_setup_new_users_with_repository
432 username = self.email.partition('@')[0] if self.email
433 return true if !username
435 blacklisted_usernames = Rails.configuration.auto_setup_name_blacklist
436 if blacklisted_usernames.include?(username)
438 elsif !(/^[a-zA-Z][-._a-zA-Z0-9]{0,30}[a-zA-Z0-9]$/.match(username))
441 return true if !(username = derive_unique_username username)
446 setup_repo_vm_links(username,
447 Rails.configuration.auto_setup_new_users_with_vm_uuid,
448 Rails.configuration.default_openid_prefix)
451 # Find a username that starts with the given string and does not collide
452 # with any existing repository name or VM login name
453 def derive_unique_username username
455 if Repository.where(name: username).empty?
456 login_collisions = Link.where(link_class: 'permission',
457 name: 'can_login').select do |perm|
458 perm.properties['username'] == username
460 return username if login_collisions.empty?
462 username = username + SecureRandom.random_number(10).to_s
466 # Send notification if the user saved profile for the first time
467 def send_profile_created_notification
468 if self.prefs_changed?
469 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
470 profile_notification_address = Rails.configuration.user_profile_notification_address
471 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address