Merge branch '10585-crunchstat-lost-parent' refs #10585
[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   validates(:username,
12             format: {
13               with: /^[A-Za-z][A-Za-z0-9]*$/,
14               message: "must begin with a letter and contain only alphanumerics",
15             },
16             uniqueness: true,
17             allow_nil: true)
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?
22   }
23   before_create :check_auto_admin
24   before_create :set_initial_username, :if => Proc.new { |user|
25     user.username.nil? and user.email
26   }
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)
32   }
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?)
39   }
40
41   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
42   has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
43
44   api_accessible :user, extend: :common do |t|
45     t.add :email
46     t.add :username
47     t.add :full_name
48     t.add :first_name
49     t.add :last_name
50     t.add :identity_url
51     t.add :is_active
52     t.add :is_admin
53     t.add :is_invited
54     t.add :prefs
55     t.add :writable_by
56   end
57
58   ALL_PERMISSIONS = {read: true, write: true, manage: true}
59
60   def full_name
61     "#{first_name} #{last_name}".strip
62   end
63
64   def is_invited
65     !!(self.is_active ||
66        Rails.configuration.new_users_are_active ||
67        self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
68   end
69
70   def groups_i_can(verb)
71     my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
72     if verb == :read
73       my_groups << anonymous_group_uuid
74     end
75     my_groups
76   end
77
78   def can?(actions)
79     return true if is_admin
80     actions.each do |action, target|
81       unless target.nil?
82         if target.respond_to? :uuid
83           target_uuid = target.uuid
84         else
85           target_uuid = target
86           target = ArvadosModel.find_by_uuid(target_uuid)
87         end
88       end
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])
96       end
97       sufficient_perms = case action
98                          when :manage
99                            ['can_manage']
100                          when :write
101                            ['can_manage', 'can_write']
102                          when :read
103                            ['can_manage', 'can_write', 'can_read']
104                          else
105                            # (Skip this kind of permission opportunity
106                            # if action is an unknown permission type)
107                          end
108       if sufficient_perms
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
113         # *just* been added.
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?
118           next
119         end
120       end
121       return false
122     end
123     true
124   end
125
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}'"
130     else
131       Rails.cache.delete_matched(/^groups_for_user_/)
132     end
133   end
134
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.
138   #
139   # The permission graph is built by repeatedly enumerating all
140   # permission links reachable from self.uuid, and then calling
141   # search_permissions
142   def calculate_group_permissions
143       permissions_from = {}
144       todo = {self.uuid => true}
145       done = {}
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
149       # to evaluate.
150       while !todo.empty?
151         lookup_uuids = todo.keys
152         lookup_uuids.each do |uuid| done[uuid] = true end
153         todo = {}
154         newgroups = []
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']
158         end
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 ?))',
162                    'permission',
163                    lookup_uuids,
164                    Group.uuid_like_pattern,
165                    'can_manage',
166                    User.uuid_like_pattern).each do |link|
167           newgroups << [link.tail_uuid, link.head_uuid, link.name]
168         end
169         newgroups.each do |tail_uuid, head_uuid, perm_name|
170           unless done.has_key? head_uuid
171             todo[head_uuid] = true
172           end
173           link_permissions = {}
174           case perm_name
175           when 'can_read'
176             link_permissions = {read:true}
177           when 'can_write'
178             link_permissions = {read:true,write:true}
179           when 'can_manage'
180             link_permissions = ALL_PERMISSIONS
181           end
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
186           end
187         end
188       end
189       perms = search_permissions(self.uuid, permissions_from)
190       Rails.cache.write "groups_for_user_#{self.uuid}", perms
191       perms
192   end
193
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}"
199     if r.nil?
200       if Rails.configuration.async_permissions_update
201         while r.nil?
202           sleep(0.1)
203           r = Rails.cache.read "groups_for_user_#{self.uuid}"
204         end
205       else
206         r = calculate_group_permissions
207       end
208     end
209     r
210   end
211
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)
214   end
215
216   # create links
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
222
223     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
224   end
225
226   # delete user signatures, login, repo, and vm perms, and mark as inactive
227   def unsetup
228     # delete oid_login_perms for this user
229     Link.destroy_all(tail_uuid: self.email,
230                      link_class: 'permission',
231                      name: 'can_login')
232
233     # delete repo_perms for this user
234     Link.destroy_all(tail_uuid: self.uuid,
235                      link_class: 'permission',
236                      name: 'can_manage')
237
238     # delete vm_login_perms for this user
239     Link.destroy_all(tail_uuid: self.uuid,
240                      link_class: 'permission',
241                      name: 'can_login')
242
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+$/)
246     end.first
247     Link.destroy_all(tail_uuid: self.uuid,
248                      head_uuid: group[:uuid],
249                      link_class: 'permission',
250                      name: 'can_read')
251
252     # delete any signatures by this user
253     Link.destroy_all(link_class: 'signature',
254                      tail_uuid: self.uuid)
255
256     # delete user preferences (including profile)
257     self.prefs = {}
258
259     # mark the user as inactive
260     self.is_active = false
261     self.save!
262   end
263
264   def set_initial_username(requested: false)
265     if !requested.is_a?(String) || requested.empty?
266       email_parts = email.partition("@")
267       local_parts = email_parts.first.partition("+")
268       if email_parts.any?(&:empty?)
269         return
270       elsif not local_parts.first.empty?
271         requested = local_parts.first
272       else
273         requested = email_parts.first
274       end
275     end
276     requested.sub!(/^[^A-Za-z]+/, "")
277     requested.gsub!(/[^A-Za-z0-9]/, "")
278     unless requested.empty?
279       self.username = find_usable_username_from(requested)
280     end
281   end
282
283   protected
284
285   def ensure_ownership_path_leads_to_user
286     true
287   end
288
289   def permission_to_update
290     if username_changed?
291       current_user.andand.is_admin
292     else
293       # users must be able to update themselves (even if they are
294       # inactive) in order to create sessions
295       self == current_user or super
296     end
297   end
298
299   def permission_to_create
300     current_user.andand.is_admin or
301       (self == current_user and
302        self.is_active == Rails.configuration.new_users_are_active)
303   end
304
305   def check_auto_admin
306     return if self.uuid.end_with?('anonymouspublic')
307     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
308         Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
309        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
310         Rails.configuration.auto_admin_first_user)
311       self.is_admin = true
312       self.is_active = true
313     end
314   end
315
316   def find_usable_username_from(basename)
317     # If "basename" is a usable username, return that.
318     # Otherwise, find a unique username "basenameN", where N is the
319     # smallest integer greater than 1, and return that.
320     # Return nil if a unique username can't be found after reasonable
321     # searching.
322     quoted_name = self.class.connection.quote_string(basename)
323     next_username = basename
324     next_suffix = 1
325     while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
326       next_suffix += 1
327       next_username = "%s%i" % [basename, next_suffix]
328     end
329     0.upto(6).each do |suffix_len|
330       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
331       self.class.
332           where("username like '#{pattern}'").
333           select(:username).
334           order('username asc').
335           each do |other_user|
336         if other_user.username > next_username
337           break
338         elsif other_user.username == next_username
339           next_suffix += 1
340           next_username = "%s%i" % [basename, next_suffix]
341         end
342       end
343       return next_username if (next_username.size <= pattern.size)
344     end
345     nil
346   end
347
348   def prevent_privilege_escalation
349     if current_user.andand.is_admin
350       return true
351     end
352     if self.is_active_changed?
353       if self.is_active != self.is_active_was
354         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
355         self.is_active = self.is_active_was
356       end
357     end
358     if self.is_admin_changed?
359       if self.is_admin != self.is_admin_was
360         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
361         self.is_admin = self.is_admin_was
362       end
363     end
364     true
365   end
366
367   def prevent_inactive_admin
368     if self.is_admin and not self.is_active
369       # There is no known use case for the strange set of permissions
370       # that would result from this change. It's safest to assume it's
371       # a mistake and disallow it outright.
372       raise "Admin users cannot be inactive"
373     end
374     true
375   end
376
377   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
378     nextpaths = graph[start]
379     return merged if !nextpaths
380     return merged if upstream_path.has_key? start
381     upstream_path[start] = true
382     upstream_mask ||= ALL_PERMISSIONS
383     nextpaths.each do |head, mask|
384       merged[head] ||= {}
385       mask.each do |k,v|
386         merged[head][k] ||= v if upstream_mask[k]
387       end
388       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
389     end
390     upstream_path.delete start
391     merged
392   end
393
394   def create_oid_login_perm (openid_prefix)
395     login_perm_props = { "identity_url_prefix" => openid_prefix}
396
397     # Check oid_login_perm
398     oid_login_perms = Link.where(tail_uuid: self.email,
399                                    link_class: 'permission',
400                                    name: 'can_login').where("head_uuid = ?", self.uuid)
401
402     if !oid_login_perms.any?
403       # create openid login permission
404       oid_login_perm = Link.create(link_class: 'permission',
405                                    name: 'can_login',
406                                    tail_uuid: self.email,
407                                    head_uuid: self.uuid,
408                                    properties: login_perm_props
409                                   )
410       logger.info { "openid login permission: " + oid_login_perm[:uuid] }
411     else
412       oid_login_perm = oid_login_perms.first
413     end
414
415     return oid_login_perm
416   end
417
418   def create_user_repo_link(repo_name)
419     # repo_name is optional
420     if not repo_name
421       logger.warn ("Repository name not given for #{self.uuid}.")
422       return
423     end
424
425     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
426     logger.info { "repo uuid: " + repo[:uuid] }
427     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
428                            link_class: "permission",
429                            name: "can_manage").first_or_create!
430     logger.info { "repo permission: " + repo_perm[:uuid] }
431     return repo_perm
432   end
433
434   # create login permission for the given vm_uuid, if it does not already exist
435   def create_vm_login_permission_link(vm_uuid, repo_name)
436     # vm uuid is optional
437     if vm_uuid
438       vm = VirtualMachine.where(uuid: vm_uuid).first
439
440       if not vm
441         logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
442         raise "No vm found for #{vm_uuid}"
443       end
444     else
445       return
446     end
447
448     logger.info { "vm uuid: " + vm[:uuid] }
449     login_attrs = {
450       tail_uuid: uuid, head_uuid: vm.uuid,
451       link_class: "permission", name: "can_login",
452     }
453
454     login_perm = Link.
455       where(login_attrs).
456       select { |link| link.properties["username"] == repo_name }.
457       first
458
459     login_perm ||= Link.
460       create(login_attrs.merge(properties: {"username" => repo_name}))
461
462     logger.info { "login permission: " + login_perm[:uuid] }
463     login_perm
464   end
465
466   # add the user to the 'All users' group
467   def create_user_group_link
468     return (Link.where(tail_uuid: self.uuid,
469                        head_uuid: all_users_group[:uuid],
470                        link_class: 'permission',
471                        name: 'can_read').first or
472             Link.create(tail_uuid: self.uuid,
473                         head_uuid: all_users_group[:uuid],
474                         link_class: 'permission',
475                         name: 'can_read'))
476   end
477
478   # Give the special "System group" permission to manage this user and
479   # all of this user's stuff.
480   def add_system_group_permission_link
481     return true if uuid == system_user_uuid
482     act_as_system_user do
483       Link.create(link_class: 'permission',
484                   name: 'can_manage',
485                   tail_uuid: system_group_uuid,
486                   head_uuid: self.uuid)
487     end
488   end
489
490   # Send admin notifications
491   def send_admin_notifications
492     AdminNotifier.new_user(self).deliver
493     if not self.is_active then
494       AdminNotifier.new_inactive_user(self).deliver
495     end
496   end
497
498   # Automatically setup new user during creation
499   def auto_setup_new_user
500     setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
501     if username
502       create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
503                                       username)
504       repo_name = "#{username}/#{username}"
505       if Rails.configuration.auto_setup_new_users_with_repository and
506           Repository.where(name: repo_name).first.nil?
507         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
508         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
509                      link_class: "permission", name: "can_manage")
510       end
511     end
512   end
513
514   # Send notification if the user saved profile for the first time
515   def send_profile_created_notification
516     if self.prefs_changed?
517       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
518         profile_notification_address = Rails.configuration.user_profile_notification_address
519         ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
520       end
521     end
522   end
523
524   def verify_repositories_empty
525     unless repositories.first.nil?
526       errors.add(:username, "can't be unset when the user owns repositories")
527       false
528     end
529   end
530
531   def sync_repository_names
532     old_name_re = /^#{Regexp.escape(username_was)}\//
533     name_sub = "#{username}/"
534     repositories.find_each do |repo|
535       repo.name = repo.name.sub(old_name_re, name_sub)
536       repo.save!
537     end
538   end
539 end