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