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