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