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