13822: Don't call list_sizes() in cloud client constructor.
[arvados.git] / services / api / app / models / user.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'can_be_an_owner'
6 require 'refresh_permission_view'
7
8 class User < ArvadosModel
9   include HasUuid
10   include KindAndEtag
11   include CommonApiTemplate
12   include CanBeAnOwner
13
14   serialize :prefs, Hash
15   has_many :api_client_authorizations
16   validates(:username,
17             format: {
18               with: /\A[A-Za-z][A-Za-z0-9]*\z/,
19               message: "must begin with a letter and contain only alphanumerics",
20             },
21             uniqueness: true,
22             allow_nil: true)
23   before_update :prevent_privilege_escalation
24   before_update :prevent_inactive_admin
25   before_update :verify_repositories_empty, :if => Proc.new { |user|
26     user.username.nil? and user.username_changed?
27   }
28   before_update :setup_on_activate
29   before_create :check_auto_admin
30   before_create :set_initial_username, :if => Proc.new { |user|
31     user.username.nil? and user.email
32   }
33   after_create :add_system_group_permission_link
34   after_create :invalidate_permissions_cache
35   after_create :auto_setup_new_user, :if => Proc.new { |user|
36     Rails.configuration.auto_setup_new_users and
37     (user.uuid != system_user_uuid) and
38     (user.uuid != anonymous_user_uuid)
39   }
40   after_create :send_admin_notifications
41   after_update :send_profile_created_notification
42   after_update :sync_repository_names, :if => Proc.new { |user|
43     (user.uuid != system_user_uuid) and
44     user.username_changed? and
45     (not user.username_was.nil?)
46   }
47
48   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
49   has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
50
51   api_accessible :user, extend: :common do |t|
52     t.add :email
53     t.add :username
54     t.add :full_name
55     t.add :first_name
56     t.add :last_name
57     t.add :identity_url
58     t.add :is_active
59     t.add :is_admin
60     t.add :is_invited
61     t.add :prefs
62     t.add :writable_by
63   end
64
65   ALL_PERMISSIONS = {read: true, write: true, manage: true}
66
67   # Map numeric permission levels (see lib/create_permission_view.sql)
68   # back to read/write/manage flags.
69   PERMS_FOR_VAL =
70     [{},
71      {read: true},
72      {read: true, write: true},
73      {read: true, write: true, manage: true}]
74
75   def full_name
76     "#{first_name} #{last_name}".strip
77   end
78
79   def is_invited
80     !!(self.is_active ||
81        Rails.configuration.new_users_are_active ||
82        self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
83   end
84
85   def groups_i_can(verb)
86     my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
87     if verb == :read
88       my_groups << anonymous_group_uuid
89     end
90     my_groups
91   end
92
93   def can?(actions)
94     return true if is_admin
95     actions.each do |action, target|
96       unless target.nil?
97         if target.respond_to? :uuid
98           target_uuid = target.uuid
99         else
100           target_uuid = target
101           target = ArvadosModel.find_by_uuid(target_uuid)
102         end
103       end
104       next if target_uuid == self.uuid
105       next if (group_permissions[target_uuid] and
106                group_permissions[target_uuid][action])
107       if target.respond_to? :owner_uuid
108         next if target.owner_uuid == self.uuid
109         next if (group_permissions[target.owner_uuid] and
110                  group_permissions[target.owner_uuid][action])
111       end
112       sufficient_perms = case action
113                          when :manage
114                            ['can_manage']
115                          when :write
116                            ['can_manage', 'can_write']
117                          when :read
118                            ['can_manage', 'can_write', 'can_read']
119                          else
120                            # (Skip this kind of permission opportunity
121                            # if action is an unknown permission type)
122                          end
123       if sufficient_perms
124         # Check permission links with head_uuid pointing directly at
125         # the target object. If target is a Group, this is redundant
126         # and will fail except [a] if permission caching is broken or
127         # [b] during a race condition, where a permission link has
128         # *just* been added.
129         if Link.where(link_class: 'permission',
130                       name: sufficient_perms,
131                       tail_uuid: groups_i_can(action) + [self.uuid],
132                       head_uuid: target_uuid).any?
133           next
134         end
135       end
136       return false
137     end
138     true
139   end
140
141   def self.invalidate_permissions_cache(timestamp=nil)
142     if Rails.configuration.async_permissions_update
143       timestamp = DbCurrentTime::db_current_time.to_i if timestamp.nil?
144       connection.execute "NOTIFY invalidate_permissions_cache, '#{timestamp}'"
145     else
146       refresh_permission_view
147     end
148   end
149
150   def invalidate_permissions_cache(timestamp=nil)
151     User.invalidate_permissions_cache
152   end
153
154   # Return a hash of {user_uuid: group_perms}
155   def self.all_group_permissions
156     all_perms = {}
157     ActiveRecord::Base.connection.
158       exec_query("SELECT user_uuid, target_owner_uuid, perm_level, trashed
159                   FROM #{PERMISSION_VIEW}
160                   WHERE target_owner_uuid IS NOT NULL",
161                   # "name" arg is a query label that appears in logs:
162                   "all_group_permissions",
163                   ).rows.each do |user_uuid, group_uuid, max_p_val, trashed|
164       all_perms[user_uuid] ||= {}
165       all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
166     end
167     all_perms
168   end
169
170   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
171   # and perm_hash[:write] are true if this user can read and write
172   # objects owned by group_uuid.
173   def group_permissions
174     group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
175     ActiveRecord::Base.connection.
176       exec_query("SELECT target_owner_uuid, perm_level, trashed
177                   FROM #{PERMISSION_VIEW}
178                   WHERE user_uuid = $1
179                   AND target_owner_uuid IS NOT NULL",
180                   # "name" arg is a query label that appears in logs:
181                   "group_permissions for #{uuid}",
182                   # "binds" arg is an array of [col_id, value] for '$1' vars:
183                   [[nil, uuid]],
184                 ).rows.each do |group_uuid, max_p_val, trashed|
185       group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
186     end
187     group_perms
188   end
189
190   # create links
191   def setup(openid_prefix:, repo_name: nil, vm_uuid: nil)
192     oid_login_perm = create_oid_login_perm openid_prefix
193     repo_perm = create_user_repo_link repo_name
194     vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
195     group_perm = create_user_group_link
196
197     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
198   end
199
200   # delete user signatures, login, repo, and vm perms, and mark as inactive
201   def unsetup
202     # delete oid_login_perms for this user
203     Link.destroy_all(tail_uuid: self.email,
204                      link_class: 'permission',
205                      name: 'can_login')
206
207     # delete repo_perms for this user
208     Link.destroy_all(tail_uuid: self.uuid,
209                      link_class: 'permission',
210                      name: 'can_manage')
211
212     # delete vm_login_perms for this user
213     Link.destroy_all(tail_uuid: self.uuid,
214                      link_class: 'permission',
215                      name: 'can_login')
216
217     # delete "All users" group read permissions for this user
218     group = Group.where(name: 'All users').select do |g|
219       g[:uuid].match(/-f+$/)
220     end.first
221     Link.destroy_all(tail_uuid: self.uuid,
222                      head_uuid: group[:uuid],
223                      link_class: 'permission',
224                      name: 'can_read')
225
226     # delete any signatures by this user
227     Link.destroy_all(link_class: 'signature',
228                      tail_uuid: self.uuid)
229
230     # delete user preferences (including profile)
231     self.prefs = {}
232
233     # mark the user as inactive
234     self.is_active = false
235     self.save!
236   end
237
238   def set_initial_username(requested: false)
239     if !requested.is_a?(String) || requested.empty?
240       email_parts = email.partition("@")
241       local_parts = email_parts.first.partition("+")
242       if email_parts.any?(&:empty?)
243         return
244       elsif not local_parts.first.empty?
245         requested = local_parts.first
246       else
247         requested = email_parts.first
248       end
249     end
250     requested.sub!(/^[^A-Za-z]+/, "")
251     requested.gsub!(/[^A-Za-z0-9]/, "")
252     unless requested.empty?
253       self.username = find_usable_username_from(requested)
254     end
255   end
256
257   def update_uuid(new_uuid:)
258     if !current_user.andand.is_admin
259       raise PermissionDeniedError
260     end
261     if uuid == system_user_uuid || uuid == anonymous_user_uuid
262       raise "update_uuid cannot update system accounts"
263     end
264     if self.class != self.class.resource_class_for_uuid(new_uuid)
265       raise "invalid new_uuid #{new_uuid.inspect}"
266     end
267     transaction(requires_new: true) do
268       reload
269       old_uuid = self.uuid
270       self.uuid = new_uuid
271       save!(validate: false)
272       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
273         klass.columns.each do |col|
274           if col.name.end_with?('_uuid')
275             column = col.name.to_sym
276             klass.where(column => old_uuid).update_all(column => new_uuid)
277           end
278         end
279       end
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     # Check oid_login_perm
396     oid_login_perms = Link.where(tail_uuid: self.email,
397                                  head_uuid: self.uuid,
398                                  link_class: 'permission',
399                                  name: 'can_login')
400
401     if !oid_login_perms.any?
402       # create openid login permission
403       oid_login_perm = Link.create(link_class: 'permission',
404                                    name: 'can_login',
405                                    tail_uuid: self.email,
406                                    head_uuid: self.uuid,
407                                    properties: {
408                                      "identity_url_prefix" => openid_prefix,
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     return if !vm_uuid
438
439     vm = VirtualMachine.where(uuid: vm_uuid).first
440     if !vm
441       logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
442       raise "No vm found for #{vm_uuid}"
443     end
444
445     logger.info { "vm uuid: " + vm[:uuid] }
446     login_attrs = {
447       tail_uuid: uuid, head_uuid: vm.uuid,
448       link_class: "permission", name: "can_login",
449     }
450
451     login_perm = Link.
452       where(login_attrs).
453       select { |link| link.properties["username"] == repo_name }.
454       first
455
456     login_perm ||= Link.
457       create(login_attrs.merge(properties: {"username" => repo_name}))
458
459     logger.info { "login permission: " + login_perm[:uuid] }
460     login_perm
461   end
462
463   # add the user to the 'All users' group
464   def create_user_group_link
465     return (Link.where(tail_uuid: self.uuid,
466                        head_uuid: all_users_group[:uuid],
467                        link_class: 'permission',
468                        name: 'can_read').first or
469             Link.create(tail_uuid: self.uuid,
470                         head_uuid: all_users_group[:uuid],
471                         link_class: 'permission',
472                         name: 'can_read'))
473   end
474
475   # Give the special "System group" permission to manage this user and
476   # all of this user's stuff.
477   def add_system_group_permission_link
478     return true if uuid == system_user_uuid
479     act_as_system_user do
480       Link.create(link_class: 'permission',
481                   name: 'can_manage',
482                   tail_uuid: system_group_uuid,
483                   head_uuid: self.uuid)
484     end
485   end
486
487   # Send admin notifications
488   def send_admin_notifications
489     AdminNotifier.new_user(self).deliver_now
490     if not self.is_active then
491       AdminNotifier.new_inactive_user(self).deliver_now
492     end
493   end
494
495   # Automatically setup if is_active flag turns on
496   def setup_on_activate
497     return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
498     if is_active && (new_record? || is_active_changed?)
499       setup(openid_prefix: Rails.configuration.default_openid_prefix)
500     end
501   end
502
503   # Automatically setup new user during creation
504   def auto_setup_new_user
505     setup(openid_prefix: Rails.configuration.default_openid_prefix)
506     if username
507       create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
508                                       username)
509       repo_name = "#{username}/#{username}"
510       if Rails.configuration.auto_setup_new_users_with_repository and
511           Repository.where(name: repo_name).first.nil?
512         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
513         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
514                      link_class: "permission", name: "can_manage")
515       end
516     end
517   end
518
519   # Send notification if the user saved profile for the first time
520   def send_profile_created_notification
521     if self.prefs_changed?
522       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
523         profile_notification_address = Rails.configuration.user_profile_notification_address
524         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
525       end
526     end
527   end
528
529   def verify_repositories_empty
530     unless repositories.first.nil?
531       errors.add(:username, "can't be unset when the user owns repositories")
532       false
533     end
534   end
535
536   def sync_repository_names
537     old_name_re = /^#{Regexp.escape(username_was)}\//
538     name_sub = "#{username}/"
539     repositories.find_each do |repo|
540       repo.name = repo.name.sub(old_name_re, name_sub)
541       repo.save!
542     end
543   end
544 end