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