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