3153: return nil if no unique username can be derived from an email address. no setup...
[arvados.git] / services / api / app / models / user.rb
1 require 'can_be_an_owner'
2
3 class User < ArvadosModel
4   include HasUuid
5   include KindAndEtag
6   include CommonApiTemplate
7   include CanBeAnOwner
8
9   serialize :prefs, Hash
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
18
19
20   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
21
22   api_accessible :user, extend: :common do |t|
23     t.add :email
24     t.add :full_name
25     t.add :first_name
26     t.add :last_name
27     t.add :identity_url
28     t.add :is_active
29     t.add :is_admin
30     t.add :is_invited
31     t.add :prefs
32   end
33
34   ALL_PERMISSIONS = {read: true, write: true, manage: true}
35
36   def full_name
37     "#{first_name} #{last_name}".strip
38   end
39
40   def is_invited
41     !!(self.is_active ||
42        Rails.configuration.new_users_are_active ||
43        self.groups_i_can(:read).select { |x| x.match /-f+$/ }.first)
44   end
45
46   def groups_i_can(verb)
47     my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
48     if verb == :read
49       my_groups << anonymous_group_uuid
50     end
51     my_groups
52   end
53
54   def can?(actions)
55     return true if is_admin
56     actions.each do |action, target|
57       unless target.nil?
58         if target.respond_to? :uuid
59           target_uuid = target.uuid
60         else
61           target_uuid = target
62           target = ArvadosModel.find_by_uuid(target_uuid)
63         end
64       end
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])
72       end
73       return false
74     end
75     true
76   end
77
78   def self.invalidate_permissions_cache
79     Rails.cache.delete_matched(/^groups_for_user_/)
80   end
81
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.
85   #
86   # The permission graph is built by repeatedly enumerating all
87   # permission links reachable from self.uuid, and then calling
88   # search_permissions
89   def group_permissions
90     Rails.cache.fetch "groups_for_user_#{self.uuid}" do
91       permissions_from = {}
92       todo = {self.uuid => true}
93       done = {}
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
97       # to evaluate.
98       while !todo.empty?
99         lookup_uuids = todo.keys
100         lookup_uuids.each do |uuid| done[uuid] = true end
101         todo = {}
102         newgroups = []
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']
106         end
107         # add any permission links from the current lookup_uuids to a
108         # User or Group.
109         Link.where('tail_uuid in (?) and link_class = ? and (head_uuid like ? or head_uuid like ?)',
110                    lookup_uuids,
111                    'permission',
112                    Group.uuid_like_pattern,
113                    User.uuid_like_pattern).each do |link|
114           newgroups << [link.tail_uuid, link.head_uuid, link.name]
115         end
116         newgroups.each do |tail_uuid, head_uuid, perm_name|
117           unless done.has_key? head_uuid
118             todo[head_uuid] = true
119           end
120           link_permissions = {}
121           case perm_name
122           when 'can_read'
123             link_permissions = {read:true}
124           when 'can_write'
125             link_permissions = {read:true,write:true}
126           when 'can_manage'
127             link_permissions = ALL_PERMISSIONS
128           end
129           permissions_from[tail_uuid] ||= {}
130           permissions_from[tail_uuid][head_uuid] ||= {}
131           link_permissions.each do |k,v|
132             permissions_from[tail_uuid][head_uuid][k] ||= v
133           end
134         end
135       end
136       search_permissions(self.uuid, permissions_from)
137     end
138   end
139
140   def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
141     return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
142   end
143
144   # create links
145   def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
146     oid_login_perm = create_oid_login_perm openid_prefix
147     repo_perm = create_user_repo_link repo_name
148     vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
149     group_perm = create_user_group_link
150
151     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
152   end
153
154   # delete user signatures, login, repo, and vm perms, and mark as inactive
155   def unsetup
156     # delete oid_login_perms for this user
157     Link.destroy_all(tail_uuid: self.email,
158                      link_class: 'permission',
159                      name: 'can_login')
160
161     # delete repo_perms for this user
162     Link.destroy_all(tail_uuid: self.uuid,
163                      link_class: 'permission',
164                      name: 'can_manage')
165
166     # delete vm_login_perms for this user
167     Link.destroy_all(tail_uuid: self.uuid,
168                      link_class: 'permission',
169                      name: 'can_login')
170
171     # delete "All users" group read permissions for this user
172     group = Group.where(name: 'All users').select do |g|
173       g[:uuid].match /-f+$/
174     end.first
175     Link.destroy_all(tail_uuid: self.uuid,
176                      head_uuid: group[:uuid],
177                      link_class: 'permission',
178                      name: 'can_read')
179
180     # delete any signatures by this user
181     Link.destroy_all(link_class: 'signature',
182                      tail_uuid: self.uuid)
183
184     # delete user preferences (including profile)
185     self.prefs = {}
186
187     # mark the user as inactive
188     self.is_active = false
189     self.save!
190   end
191
192   protected
193
194   def ensure_ownership_path_leads_to_user
195     true
196   end
197
198   def permission_to_update
199     # users must be able to update themselves (even if they are
200     # inactive) in order to create sessions
201     self == current_user or super
202   end
203
204   def permission_to_create
205     current_user.andand.is_admin or
206       (self == current_user and
207        self.is_active == Rails.configuration.new_users_are_active)
208   end
209
210   def check_auto_admin
211     if User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and Rails.configuration.auto_admin_user
212       if self.email == Rails.configuration.auto_admin_user
213         self.is_admin = true
214         self.is_active = true
215       end
216     end
217   end
218
219   def prevent_privilege_escalation
220     if current_user.andand.is_admin
221       return true
222     end
223     if self.is_active_changed?
224       if self.is_active != self.is_active_was
225         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
226         self.is_active = self.is_active_was
227       end
228     end
229     if self.is_admin_changed?
230       if self.is_admin != self.is_admin_was
231         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
232         self.is_admin = self.is_admin_was
233       end
234     end
235     true
236   end
237
238   def prevent_inactive_admin
239     if self.is_admin and not self.is_active
240       # There is no known use case for the strange set of permissions
241       # that would result from this change. It's safest to assume it's
242       # a mistake and disallow it outright.
243       raise "Admin users cannot be inactive"
244     end
245     true
246   end
247
248   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
249     nextpaths = graph[start]
250     return merged if !nextpaths
251     return merged if upstream_path.has_key? start
252     upstream_path[start] = true
253     upstream_mask ||= ALL_PERMISSIONS
254     nextpaths.each do |head, mask|
255       merged[head] ||= {}
256       mask.each do |k,v|
257         merged[head][k] ||= v if upstream_mask[k]
258       end
259       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
260     end
261     upstream_path.delete start
262     merged
263   end
264
265   def create_oid_login_perm (openid_prefix)
266     login_perm_props = { "identity_url_prefix" => openid_prefix}
267
268     # Check oid_login_perm
269     oid_login_perms = Link.where(tail_uuid: self.email,
270                                    link_class: 'permission',
271                                    name: 'can_login').where("head_uuid = ?", self.uuid)
272
273     if !oid_login_perms.any?
274       # create openid login permission
275       oid_login_perm = Link.create(link_class: 'permission',
276                                    name: 'can_login',
277                                    tail_uuid: self.email,
278                                    head_uuid: self.uuid,
279                                    properties: login_perm_props
280                                   )
281       logger.info { "openid login permission: " + oid_login_perm[:uuid] }
282     else
283       oid_login_perm = oid_login_perms.first
284     end
285
286     return oid_login_perm
287   end
288
289   def create_user_repo_link(repo_name)
290     # repo_name is optional
291     if not repo_name
292       logger.warn ("Repository name not given for #{self.uuid}.")
293       return
294     end
295
296     # Check for an existing repository with the same name we're about to use.
297     repo = Repository.where(name: repo_name).first
298
299     if repo
300       logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
301
302       # Look for existing repository access for this repo
303       repo_perms = Link.where(tail_uuid: self.uuid,
304                               head_uuid: repo[:uuid],
305                               link_class: 'permission',
306                               name: 'can_manage')
307       if repo_perms.any?
308         logger.warn "User already has repository access " +
309             repo_perms.collect { |p| p[:uuid] }.inspect
310         return repo_perms.first
311       end
312     end
313
314     # create repo, if does not already exist
315     repo ||= Repository.create(name: repo_name)
316     logger.info { "repo uuid: " + repo[:uuid] }
317
318     repo_perm = Link.create(tail_uuid: self.uuid,
319                             head_uuid: repo[:uuid],
320                             link_class: 'permission',
321                             name: 'can_manage')
322     logger.info { "repo permission: " + repo_perm[:uuid] }
323     return repo_perm
324   end
325
326   # create login permission for the given vm_uuid, if it does not already exist
327   def create_vm_login_permission_link(vm_uuid, repo_name)
328     begin
329
330       # vm uuid is optional
331       if vm_uuid
332         vm = VirtualMachine.where(uuid: vm_uuid).first
333
334         if not vm
335           logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
336           raise "No vm found for #{vm_uuid}"
337         end
338       else
339         return
340       end
341
342       logger.info { "vm uuid: " + vm[:uuid] }
343
344       login_perms = Link.where(tail_uuid: self.uuid,
345                               head_uuid: vm[:uuid],
346                               link_class: 'permission',
347                               name: 'can_login')
348
349       perm_exists = false
350       login_perms.each do |perm|
351         if perm.properties['username'] == repo_name
352           perm_exists = perm
353           break
354         end
355       end
356
357       if perm_exists
358         login_perm = perm_exists
359       else
360         login_perm = Link.create(tail_uuid: self.uuid,
361                                  head_uuid: vm[:uuid],
362                                  link_class: 'permission',
363                                  name: 'can_login',
364                                  properties: {'username' => repo_name})
365         logger.info { "login permission: " + login_perm[:uuid] }
366       end
367
368       return login_perm
369     end
370   end
371
372   # add the user to the 'All users' group
373   def create_user_group_link
374     # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
375     group = Group.where(name: 'All users').select do |g|
376       g[:uuid].match /-f+$/
377     end.first
378
379     if not group
380       logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
381       raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
382     else
383       logger.info { "\"All users\" group uuid: " + group[:uuid] }
384
385       group_perms = Link.where(tail_uuid: self.uuid,
386                               head_uuid: group[:uuid],
387                               link_class: 'permission',
388                               name: 'can_read')
389
390       if !group_perms.any?
391         group_perm = Link.create(tail_uuid: self.uuid,
392                                  head_uuid: group[:uuid],
393                                  link_class: 'permission',
394                                  name: 'can_read')
395         logger.info { "group permission: " + group_perm[:uuid] }
396       else
397         group_perm = group_perms.first
398       end
399
400       return group_perm
401     end
402   end
403
404   # Give the special "System group" permission to manage this user and
405   # all of this user's stuff.
406   #
407   def add_system_group_permission_link
408     act_as_system_user do
409       Link.create(link_class: 'permission',
410                   name: 'can_manage',
411                   tail_uuid: system_group_uuid,
412                   head_uuid: self.uuid)
413     end
414   end
415
416   # Send admin notifications
417   def send_admin_notifications
418     AdminNotifier.new_user(self).deliver
419     if not self.is_active then
420       AdminNotifier.new_inactive_user(self).deliver
421     end
422   end
423
424   # Automatically setup new user during creation
425   def auto_setup_new_user
426     return true if !Rails.configuration.auto_setup_new_users
427     return true if !self.email
428
429     if Rails.configuration.auto_setup_new_users_with_vm_uuid ||
430        Rails.configuration.auto_setup_new_users_with_repository
431       username = self.email.partition('@')[0] if self.email
432       return true if !username
433
434       blacklisted_usernames = Rails.configuration.auto_setup_name_blacklist
435       if blacklisted_usernames.include?(username)
436         return true;
437       elsif !(/^[a-zA-Z][-._a-zA-Z0-9]{0,30}[a-zA-Z0-9]$/.match(username))
438         return true
439       else
440         return true if !(username = derive_unique_username username)
441       end
442     end
443
444     # setup user
445     if !Rails.configuration.auto_setup_new_users_with_vm_uuid &&
446        !Rails.configuration.auto_setup_new_users_with_repository
447       oid_login_perm = create_oid_login_perm Rails.configuration.default_openid_prefix
448       group_perm = create_user_group_link
449     else
450       setup_repo_vm_links(username,
451                           Rails.configuration.auto_setup_new_users_with_vm_uuid,
452                           Rails.configuration.default_openid_prefix)
453     end
454   end
455
456   # Find a username that starts with the given string and does not collide
457   # with any existing repository name or VM login name
458   def derive_unique_username orig_username
459     vm_uuid = Rails.configuration.auto_setup_new_users_with_vm_uuid
460
461     username = String.new orig_username
462     10000.times do |count|
463       if Repository.where(name: username).empty?
464         login_collisions = Link.where(head_uuid: vm_uuid,
465                                       link_class: 'permission',
466                                       name: 'can_login').select do |perm|
467           perm.properties['username'] == username
468         end
469         if login_collisions.empty?
470           return username
471         end
472       end
473
474       username = orig_username + SecureRandom.random_number(1000).to_s
475     end
476     return nil  # count expired and no unused username was available
477   end
478
479   # Send notification if the user saved profile for the first time
480   def send_profile_created_notification
481     if self.prefs_changed?
482       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
483         profile_notification_address = Rails.configuration.user_profile_notification_address
484         ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
485       end
486     end
487   end
488
489 end