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|
35 ALL_PERMISSIONS = {read: true, write: true, manage: true}
38 "#{first_name} #{last_name}".strip
43 Rails.configuration.new_users_are_active ||
44 self.groups_i_can(:read).select { |x| x.match /-f+$/ }.first)
47 def groups_i_can(verb)
48 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
50 my_groups << anonymous_group_uuid
56 return true if is_admin
57 actions.each do |action, target|
59 if target.respond_to? :uuid
60 target_uuid = target.uuid
63 target = ArvadosModel.find_by_uuid(target_uuid)
66 next if target_uuid == self.uuid
67 next if (group_permissions[target_uuid] and
68 group_permissions[target_uuid][action])
69 if target.respond_to? :owner_uuid
70 next if target.owner_uuid == self.uuid
71 next if (group_permissions[target.owner_uuid] and
72 group_permissions[target.owner_uuid][action])
74 sufficient_perms = case action
78 ['can_manage', 'can_write']
80 ['can_manage', 'can_write', 'can_read']
82 # (Skip this kind of permission opportunity
83 # if action is an unknown permission type)
86 # Check permission links with head_uuid pointing directly at
87 # the target object. If target is a Group, this is redundant
88 # and will fail except [a] if permission caching is broken or
89 # [b] during a race condition, where a permission link has
91 if Link.where(link_class: 'permission',
92 name: sufficient_perms,
93 tail_uuid: groups_i_can(action) + [self.uuid],
94 head_uuid: target_uuid).any?
103 def self.invalidate_permissions_cache
104 Rails.cache.delete_matched(/^groups_for_user_/)
107 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
108 # and perm_hash[:write] are true if this user can read and write
109 # objects owned by group_uuid.
111 # The permission graph is built by repeatedly enumerating all
112 # permission links reachable from self.uuid, and then calling
114 def group_permissions
115 Rails.cache.fetch "groups_for_user_#{self.uuid}" do
116 permissions_from = {}
117 todo = {self.uuid => true}
119 # Build the equivalence class of permissions starting with
120 # self.uuid. On each iteration of this loop, todo contains
121 # the next set of uuids in the permission equivalence class
124 lookup_uuids = todo.keys
125 lookup_uuids.each do |uuid| done[uuid] = true end
128 # include all groups owned by the current set of uuids.
129 Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
130 newgroups << [group.owner_uuid, group.uuid, 'can_manage']
132 # add any permission links from the current lookup_uuids to a Group.
133 Link.where('link_class = ? and tail_uuid in (?) and ' \
134 '(head_uuid like ? or (name = ? and head_uuid like ?))',
137 Group.uuid_like_pattern,
139 User.uuid_like_pattern).each do |link|
140 newgroups << [link.tail_uuid, link.head_uuid, link.name]
142 newgroups.each do |tail_uuid, head_uuid, perm_name|
143 unless done.has_key? head_uuid
144 todo[head_uuid] = true
146 link_permissions = {}
149 link_permissions = {read:true}
151 link_permissions = {read:true,write:true}
153 link_permissions = ALL_PERMISSIONS
155 permissions_from[tail_uuid] ||= {}
156 permissions_from[tail_uuid][head_uuid] ||= {}
157 link_permissions.each do |k,v|
158 permissions_from[tail_uuid][head_uuid][k] ||= v
162 search_permissions(self.uuid, permissions_from)
166 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
167 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
171 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
172 oid_login_perm = create_oid_login_perm openid_prefix
173 repo_perm = create_user_repo_link repo_name
174 vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
175 group_perm = create_user_group_link
177 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
180 # delete user signatures, login, repo, and vm perms, and mark as inactive
182 # delete oid_login_perms for this user
183 Link.destroy_all(tail_uuid: self.email,
184 link_class: 'permission',
187 # delete repo_perms for this user
188 Link.destroy_all(tail_uuid: self.uuid,
189 link_class: 'permission',
192 # delete vm_login_perms for this user
193 Link.destroy_all(tail_uuid: self.uuid,
194 link_class: 'permission',
197 # delete "All users" group read permissions for this user
198 group = Group.where(name: 'All users').select do |g|
199 g[:uuid].match /-f+$/
201 Link.destroy_all(tail_uuid: self.uuid,
202 head_uuid: group[:uuid],
203 link_class: 'permission',
206 # delete any signatures by this user
207 Link.destroy_all(link_class: 'signature',
208 tail_uuid: self.uuid)
210 # delete user preferences (including profile)
213 # mark the user as inactive
214 self.is_active = false
220 def ensure_ownership_path_leads_to_user
224 def permission_to_update
225 # users must be able to update themselves (even if they are
226 # inactive) in order to create sessions
227 self == current_user or super
230 def permission_to_create
231 current_user.andand.is_admin or
232 (self == current_user and
233 self.is_active == Rails.configuration.new_users_are_active)
237 return if self.uuid.end_with?('anonymouspublic')
238 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
239 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
240 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
241 Rails.configuration.auto_admin_first_user)
243 self.is_active = true
247 def prevent_privilege_escalation
248 if current_user.andand.is_admin
251 if self.is_active_changed?
252 if self.is_active != self.is_active_was
253 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
254 self.is_active = self.is_active_was
257 if self.is_admin_changed?
258 if self.is_admin != self.is_admin_was
259 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
260 self.is_admin = self.is_admin_was
266 def prevent_inactive_admin
267 if self.is_admin and not self.is_active
268 # There is no known use case for the strange set of permissions
269 # that would result from this change. It's safest to assume it's
270 # a mistake and disallow it outright.
271 raise "Admin users cannot be inactive"
276 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
277 nextpaths = graph[start]
278 return merged if !nextpaths
279 return merged if upstream_path.has_key? start
280 upstream_path[start] = true
281 upstream_mask ||= ALL_PERMISSIONS
282 nextpaths.each do |head, mask|
285 merged[head][k] ||= v if upstream_mask[k]
287 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
289 upstream_path.delete start
293 def create_oid_login_perm (openid_prefix)
294 login_perm_props = { "identity_url_prefix" => openid_prefix}
296 # Check oid_login_perm
297 oid_login_perms = Link.where(tail_uuid: self.email,
298 link_class: 'permission',
299 name: 'can_login').where("head_uuid = ?", self.uuid)
301 if !oid_login_perms.any?
302 # create openid login permission
303 oid_login_perm = Link.create(link_class: 'permission',
305 tail_uuid: self.email,
306 head_uuid: self.uuid,
307 properties: login_perm_props
309 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
311 oid_login_perm = oid_login_perms.first
314 return oid_login_perm
317 def create_user_repo_link(repo_name)
318 # repo_name is optional
320 logger.warn ("Repository name not given for #{self.uuid}.")
324 # Check for an existing repository with the same name we're about to use.
325 repo = Repository.where(name: repo_name).first
328 logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
330 # Look for existing repository access for this repo
331 repo_perms = Link.where(tail_uuid: self.uuid,
332 head_uuid: repo[:uuid],
333 link_class: 'permission',
336 logger.warn "User already has repository access " +
337 repo_perms.collect { |p| p[:uuid] }.inspect
338 return repo_perms.first
342 # create repo, if does not already exist
343 repo ||= Repository.create(name: repo_name)
344 logger.info { "repo uuid: " + repo[:uuid] }
346 repo_perm = Link.create(tail_uuid: self.uuid,
347 head_uuid: repo[:uuid],
348 link_class: 'permission',
350 logger.info { "repo permission: " + repo_perm[:uuid] }
354 # create login permission for the given vm_uuid, if it does not already exist
355 def create_vm_login_permission_link(vm_uuid, repo_name)
358 # vm uuid is optional
360 vm = VirtualMachine.where(uuid: vm_uuid).first
363 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
364 raise "No vm found for #{vm_uuid}"
370 logger.info { "vm uuid: " + vm[:uuid] }
372 login_perms = Link.where(tail_uuid: self.uuid,
373 head_uuid: vm[:uuid],
374 link_class: 'permission',
378 login_perms.each do |perm|
379 if perm.properties['username'] == repo_name
386 login_perm = perm_exists
388 login_perm = Link.create(tail_uuid: self.uuid,
389 head_uuid: vm[:uuid],
390 link_class: 'permission',
392 properties: {'username' => repo_name})
393 logger.info { "login permission: " + login_perm[:uuid] }
400 # add the user to the 'All users' group
401 def create_user_group_link
402 return (Link.where(tail_uuid: self.uuid,
403 head_uuid: all_users_group[:uuid],
404 link_class: 'permission',
405 name: 'can_read').first or
406 Link.create(tail_uuid: self.uuid,
407 head_uuid: all_users_group[:uuid],
408 link_class: 'permission',
412 # Give the special "System group" permission to manage this user and
413 # all of this user's stuff.
414 def add_system_group_permission_link
415 return true if uuid == system_user_uuid
416 act_as_system_user do
417 Link.create(link_class: 'permission',
419 tail_uuid: system_group_uuid,
420 head_uuid: self.uuid)
424 # Send admin notifications
425 def send_admin_notifications
426 AdminNotifier.new_user(self).deliver
427 if not self.is_active then
428 AdminNotifier.new_inactive_user(self).deliver
432 # Automatically setup new user during creation
433 def auto_setup_new_user
434 return true if !Rails.configuration.auto_setup_new_users
435 return true if !self.email
436 return true if self.uuid == system_user_uuid
437 return true if self.uuid == anonymous_user_uuid
439 if Rails.configuration.auto_setup_new_users_with_vm_uuid ||
440 Rails.configuration.auto_setup_new_users_with_repository
441 username = self.email.partition('@')[0] if self.email
442 return true if !username
444 blacklisted_usernames = Rails.configuration.auto_setup_name_blacklist
445 if blacklisted_usernames.include?(username)
447 elsif !(/^[a-zA-Z][-._a-zA-Z0-9]{0,30}[a-zA-Z0-9]$/.match(username))
450 return true if !(username = derive_unique_username username)
455 setup_repo_vm_links(username,
456 Rails.configuration.auto_setup_new_users_with_vm_uuid,
457 Rails.configuration.default_openid_prefix)
460 # Find a username that starts with the given string and does not collide
461 # with any existing repository name or VM login name
462 def derive_unique_username username
464 if Repository.where(name: username).empty?
465 login_collisions = Link.where(link_class: 'permission',
466 name: 'can_login').select do |perm|
467 perm.properties['username'] == username
469 return username if login_collisions.empty?
471 username = username + SecureRandom.random_number(10).to_s
475 # Send notification if the user saved profile for the first time
476 def send_profile_created_notification
477 if self.prefs_changed?
478 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
479 profile_notification_address = Rails.configuration.user_profile_notification_address
480 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address