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