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