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