11803: Get group permissions with 1 query instead of N queries.
[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[A-Za-z][A-Za-z0-9]*\z/,
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   # Map numeric permission levels (see lib/create_permission_view.sql)
61   # back to read/write/manage flags.
62   PERMS_FOR_VAL =
63     [{},
64      {read: true},
65      {read: true, write: true},
66      {read: true, write: true, manage: true}]
67
68   def full_name
69     "#{first_name} #{last_name}".strip
70   end
71
72   def is_invited
73     !!(self.is_active ||
74        Rails.configuration.new_users_are_active ||
75        self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
76   end
77
78   def groups_i_can(verb)
79     my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
80     if verb == :read
81       my_groups << anonymous_group_uuid
82     end
83     my_groups
84   end
85
86   def can?(actions)
87     return true if is_admin
88     actions.each do |action, target|
89       unless target.nil?
90         if target.respond_to? :uuid
91           target_uuid = target.uuid
92         else
93           target_uuid = target
94           target = ArvadosModel.find_by_uuid(target_uuid)
95         end
96       end
97       next if target_uuid == self.uuid
98       next if (group_permissions[target_uuid] and
99                group_permissions[target_uuid][action])
100       if target.respond_to? :owner_uuid
101         next if target.owner_uuid == self.uuid
102         next if (group_permissions[target.owner_uuid] and
103                  group_permissions[target.owner_uuid][action])
104       end
105       sufficient_perms = case action
106                          when :manage
107                            ['can_manage']
108                          when :write
109                            ['can_manage', 'can_write']
110                          when :read
111                            ['can_manage', 'can_write', 'can_read']
112                          else
113                            # (Skip this kind of permission opportunity
114                            # if action is an unknown permission type)
115                          end
116       if sufficient_perms
117         # Check permission links with head_uuid pointing directly at
118         # the target object. If target is a Group, this is redundant
119         # and will fail except [a] if permission caching is broken or
120         # [b] during a race condition, where a permission link has
121         # *just* been added.
122         if Link.where(link_class: 'permission',
123                       name: sufficient_perms,
124                       tail_uuid: groups_i_can(action) + [self.uuid],
125                       head_uuid: target_uuid).any?
126           next
127         end
128       end
129       return false
130     end
131     true
132   end
133
134   def self.invalidate_permissions_cache(timestamp=nil)
135     if Rails.configuration.async_permissions_update
136       timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
137       connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
138     else
139       Rails.cache.delete_matched(/^groups_for_user_/)
140     end
141   end
142
143   # Return a hash of {user_uuid: group_perms}
144   def self.all_group_permissions
145     install_view('permission')
146     all_perms = {}
147     ActiveRecord::Base.connection.
148       exec_query('SELECT user_uuid, target_owner_uuid, max(perm_level)
149                   FROM permission_view
150                   WHERE target_owner_uuid IS NOT NULL
151                   GROUP BY user_uuid, target_owner_uuid',
152                   # "name" arg is a query label that appears in logs:
153                   "all_group_permissions",
154                   ).rows.each do |user_uuid, group_uuid, max_p_val|
155       all_perms[user_uuid] ||= {}
156       all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
157     end
158     all_perms
159   end
160
161   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
162   # and perm_hash[:write] are true if this user can read and write
163   # objects owned by group_uuid.
164   def calculate_group_permissions
165     self.class.install_view('permission')
166
167     group_perms = {}
168     ActiveRecord::Base.connection.
169       exec_query('SELECT target_owner_uuid, max(perm_level)
170                   FROM permission_view
171                   WHERE user_uuid = $1
172                   AND target_owner_uuid IS NOT NULL
173                   GROUP BY target_owner_uuid',
174                   # "name" arg is a query label that appears in logs:
175                   "group_permissions for #{uuid}",
176                   # "binds" arg is an array of [col_id, value] for '$1' vars:
177                   [[nil, uuid]],
178                   ).rows.each do |group_uuid, max_p_val|
179       group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
180     end
181     Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
182     group_perms
183   end
184
185   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
186   # and perm_hash[:write] are true if this user can read and write
187   # objects owned by group_uuid.
188   def group_permissions
189     r = Rails.cache.read "groups_for_user_#{self.uuid}"
190     if r.nil?
191       if Rails.configuration.async_permissions_update
192         while r.nil?
193           sleep(0.1)
194           r = Rails.cache.read "groups_for_user_#{self.uuid}"
195         end
196       else
197         r = calculate_group_permissions
198       end
199     end
200     r
201   end
202
203   def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
204     return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
205   end
206
207   # create links
208   def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
209     oid_login_perm = create_oid_login_perm openid_prefix
210     repo_perm = create_user_repo_link repo_name
211     vm_login_perm = create_vm_login_permission_link vm_uuid, username
212     group_perm = create_user_group_link
213
214     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
215   end
216
217   # delete user signatures, login, repo, and vm perms, and mark as inactive
218   def unsetup
219     # delete oid_login_perms for this user
220     Link.destroy_all(tail_uuid: self.email,
221                      link_class: 'permission',
222                      name: 'can_login')
223
224     # delete repo_perms for this user
225     Link.destroy_all(tail_uuid: self.uuid,
226                      link_class: 'permission',
227                      name: 'can_manage')
228
229     # delete vm_login_perms for this user
230     Link.destroy_all(tail_uuid: self.uuid,
231                      link_class: 'permission',
232                      name: 'can_login')
233
234     # delete "All users" group read permissions for this user
235     group = Group.where(name: 'All users').select do |g|
236       g[:uuid].match(/-f+$/)
237     end.first
238     Link.destroy_all(tail_uuid: self.uuid,
239                      head_uuid: group[:uuid],
240                      link_class: 'permission',
241                      name: 'can_read')
242
243     # delete any signatures by this user
244     Link.destroy_all(link_class: 'signature',
245                      tail_uuid: self.uuid)
246
247     # delete user preferences (including profile)
248     self.prefs = {}
249
250     # mark the user as inactive
251     self.is_active = false
252     self.save!
253   end
254
255   def set_initial_username(requested: false)
256     if !requested.is_a?(String) || requested.empty?
257       email_parts = email.partition("@")
258       local_parts = email_parts.first.partition("+")
259       if email_parts.any?(&:empty?)
260         return
261       elsif not local_parts.first.empty?
262         requested = local_parts.first
263       else
264         requested = email_parts.first
265       end
266     end
267     requested.sub!(/^[^A-Za-z]+/, "")
268     requested.gsub!(/[^A-Za-z0-9]/, "")
269     unless requested.empty?
270       self.username = find_usable_username_from(requested)
271     end
272   end
273
274   protected
275
276   def ensure_ownership_path_leads_to_user
277     true
278   end
279
280   def permission_to_update
281     if username_changed?
282       current_user.andand.is_admin
283     else
284       # users must be able to update themselves (even if they are
285       # inactive) in order to create sessions
286       self == current_user or super
287     end
288   end
289
290   def permission_to_create
291     current_user.andand.is_admin or
292       (self == current_user and
293        self.is_active == Rails.configuration.new_users_are_active)
294   end
295
296   def check_auto_admin
297     return if self.uuid.end_with?('anonymouspublic')
298     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
299         Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
300        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
301         Rails.configuration.auto_admin_first_user)
302       self.is_admin = true
303       self.is_active = true
304     end
305   end
306
307   def find_usable_username_from(basename)
308     # If "basename" is a usable username, return that.
309     # Otherwise, find a unique username "basenameN", where N is the
310     # smallest integer greater than 1, and return that.
311     # Return nil if a unique username can't be found after reasonable
312     # searching.
313     quoted_name = self.class.connection.quote_string(basename)
314     next_username = basename
315     next_suffix = 1
316     while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
317       next_suffix += 1
318       next_username = "%s%i" % [basename, next_suffix]
319     end
320     0.upto(6).each do |suffix_len|
321       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
322       self.class.
323           where("username like '#{pattern}'").
324           select(:username).
325           order('username asc').
326           each do |other_user|
327         if other_user.username > next_username
328           break
329         elsif other_user.username == next_username
330           next_suffix += 1
331           next_username = "%s%i" % [basename, next_suffix]
332         end
333       end
334       return next_username if (next_username.size <= pattern.size)
335     end
336     nil
337   end
338
339   def prevent_privilege_escalation
340     if current_user.andand.is_admin
341       return true
342     end
343     if self.is_active_changed?
344       if self.is_active != self.is_active_was
345         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
346         self.is_active = self.is_active_was
347       end
348     end
349     if self.is_admin_changed?
350       if self.is_admin != self.is_admin_was
351         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
352         self.is_admin = self.is_admin_was
353       end
354     end
355     true
356   end
357
358   def prevent_inactive_admin
359     if self.is_admin and not self.is_active
360       # There is no known use case for the strange set of permissions
361       # that would result from this change. It's safest to assume it's
362       # a mistake and disallow it outright.
363       raise "Admin users cannot be inactive"
364     end
365     true
366   end
367
368   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
369     nextpaths = graph[start]
370     return merged if !nextpaths
371     return merged if upstream_path.has_key? start
372     upstream_path[start] = true
373     upstream_mask ||= ALL_PERMISSIONS
374     nextpaths.each do |head, mask|
375       merged[head] ||= {}
376       mask.each do |k,v|
377         merged[head][k] ||= v if upstream_mask[k]
378       end
379       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
380     end
381     upstream_path.delete start
382     merged
383   end
384
385   def create_oid_login_perm (openid_prefix)
386     login_perm_props = { "identity_url_prefix" => openid_prefix}
387
388     # Check oid_login_perm
389     oid_login_perms = Link.where(tail_uuid: self.email,
390                                    link_class: 'permission',
391                                    name: 'can_login').where("head_uuid = ?", self.uuid)
392
393     if !oid_login_perms.any?
394       # create openid login permission
395       oid_login_perm = Link.create(link_class: 'permission',
396                                    name: 'can_login',
397                                    tail_uuid: self.email,
398                                    head_uuid: self.uuid,
399                                    properties: login_perm_props
400                                   )
401       logger.info { "openid login permission: " + oid_login_perm[:uuid] }
402     else
403       oid_login_perm = oid_login_perms.first
404     end
405
406     return oid_login_perm
407   end
408
409   def create_user_repo_link(repo_name)
410     # repo_name is optional
411     if not repo_name
412       logger.warn ("Repository name not given for #{self.uuid}.")
413       return
414     end
415
416     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
417     logger.info { "repo uuid: " + repo[:uuid] }
418     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
419                            link_class: "permission",
420                            name: "can_manage").first_or_create!
421     logger.info { "repo permission: " + repo_perm[:uuid] }
422     return repo_perm
423   end
424
425   # create login permission for the given vm_uuid, if it does not already exist
426   def create_vm_login_permission_link(vm_uuid, repo_name)
427     # vm uuid is optional
428     if vm_uuid
429       vm = VirtualMachine.where(uuid: vm_uuid).first
430
431       if not vm
432         logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
433         raise "No vm found for #{vm_uuid}"
434       end
435     else
436       return
437     end
438
439     logger.info { "vm uuid: " + vm[:uuid] }
440     login_attrs = {
441       tail_uuid: uuid, head_uuid: vm.uuid,
442       link_class: "permission", name: "can_login",
443     }
444
445     login_perm = Link.
446       where(login_attrs).
447       select { |link| link.properties["username"] == repo_name }.
448       first
449
450     login_perm ||= Link.
451       create(login_attrs.merge(properties: {"username" => repo_name}))
452
453     logger.info { "login permission: " + login_perm[:uuid] }
454     login_perm
455   end
456
457   # add the user to the 'All users' group
458   def create_user_group_link
459     return (Link.where(tail_uuid: self.uuid,
460                        head_uuid: all_users_group[:uuid],
461                        link_class: 'permission',
462                        name: 'can_read').first or
463             Link.create(tail_uuid: self.uuid,
464                         head_uuid: all_users_group[:uuid],
465                         link_class: 'permission',
466                         name: 'can_read'))
467   end
468
469   # Give the special "System group" permission to manage this user and
470   # all of this user's stuff.
471   def add_system_group_permission_link
472     return true if uuid == system_user_uuid
473     act_as_system_user do
474       Link.create(link_class: 'permission',
475                   name: 'can_manage',
476                   tail_uuid: system_group_uuid,
477                   head_uuid: self.uuid)
478     end
479   end
480
481   # Send admin notifications
482   def send_admin_notifications
483     AdminNotifier.new_user(self).deliver_now
484     if not self.is_active then
485       AdminNotifier.new_inactive_user(self).deliver_now
486     end
487   end
488
489   # Automatically setup new user during creation
490   def auto_setup_new_user
491     setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
492     if username
493       create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
494                                       username)
495       repo_name = "#{username}/#{username}"
496       if Rails.configuration.auto_setup_new_users_with_repository and
497           Repository.where(name: repo_name).first.nil?
498         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
499         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
500                      link_class: "permission", name: "can_manage")
501       end
502     end
503   end
504
505   # Send notification if the user saved profile for the first time
506   def send_profile_created_notification
507     if self.prefs_changed?
508       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
509         profile_notification_address = Rails.configuration.user_profile_notification_address
510         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
511       end
512     end
513   end
514
515   def verify_repositories_empty
516     unless repositories.first.nil?
517       errors.add(:username, "can't be unset when the user owns repositories")
518       false
519     end
520   end
521
522   def sync_repository_names
523     old_name_re = /^#{Regexp.escape(username_was)}\//
524     name_sub = "#{username}/"
525     repositories.find_each do |repo|
526       repo.name = repo.name.sub(old_name_re, name_sub)
527       repo.save!
528     end
529   end
530 end