Merge branch '11642-null-job-log' refs #11642
[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[A-Za-z][A-Za-z0-9]*\z/,
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     install_view('permission')
148
149     group_perms = {}
150     ActiveRecord::Base.connection.
151       exec_query('SELECT target_owner_uuid, max(perm_level)
152                   FROM permission_view
153                   WHERE user_uuid = $1
154                   AND target_owner_uuid IS NOT NULL
155                   GROUP BY target_owner_uuid',
156                   # "name" arg is a query label that appears in logs:
157                   "group_permissions for #{uuid}",
158                   # "binds" arg is an array of [col_id, value] for '$1' vars:
159                   [[nil, uuid]],
160                   ).rows.each do |group_uuid, max_p_val|
161       group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
162     end
163     Rails.cache.write "groups_for_user_#{self.uuid}", group_perms
164     group_perms
165   end
166
167   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
168   # and perm_hash[:write] are true if this user can read and write
169   # objects owned by group_uuid.
170   def group_permissions
171     r = Rails.cache.read "groups_for_user_#{self.uuid}"
172     if r.nil?
173       if Rails.configuration.async_permissions_update
174         while r.nil?
175           sleep(0.1)
176           r = Rails.cache.read "groups_for_user_#{self.uuid}"
177         end
178       else
179         r = calculate_group_permissions
180       end
181     end
182     r
183   end
184
185   def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
186     return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
187   end
188
189   # create links
190   def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
191     oid_login_perm = create_oid_login_perm openid_prefix
192     repo_perm = create_user_repo_link repo_name
193     vm_login_perm = create_vm_login_permission_link vm_uuid, username
194     group_perm = create_user_group_link
195
196     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
197   end
198
199   # delete user signatures, login, repo, and vm perms, and mark as inactive
200   def unsetup
201     # delete oid_login_perms for this user
202     Link.destroy_all(tail_uuid: self.email,
203                      link_class: 'permission',
204                      name: 'can_login')
205
206     # delete repo_perms for this user
207     Link.destroy_all(tail_uuid: self.uuid,
208                      link_class: 'permission',
209                      name: 'can_manage')
210
211     # delete vm_login_perms for this user
212     Link.destroy_all(tail_uuid: self.uuid,
213                      link_class: 'permission',
214                      name: 'can_login')
215
216     # delete "All users" group read permissions for this user
217     group = Group.where(name: 'All users').select do |g|
218       g[:uuid].match(/-f+$/)
219     end.first
220     Link.destroy_all(tail_uuid: self.uuid,
221                      head_uuid: group[:uuid],
222                      link_class: 'permission',
223                      name: 'can_read')
224
225     # delete any signatures by this user
226     Link.destroy_all(link_class: 'signature',
227                      tail_uuid: self.uuid)
228
229     # delete user preferences (including profile)
230     self.prefs = {}
231
232     # mark the user as inactive
233     self.is_active = false
234     self.save!
235   end
236
237   def set_initial_username(requested: false)
238     if !requested.is_a?(String) || requested.empty?
239       email_parts = email.partition("@")
240       local_parts = email_parts.first.partition("+")
241       if email_parts.any?(&:empty?)
242         return
243       elsif not local_parts.first.empty?
244         requested = local_parts.first
245       else
246         requested = email_parts.first
247       end
248     end
249     requested.sub!(/^[^A-Za-z]+/, "")
250     requested.gsub!(/[^A-Za-z0-9]/, "")
251     unless requested.empty?
252       self.username = find_usable_username_from(requested)
253     end
254   end
255
256   protected
257
258   def ensure_ownership_path_leads_to_user
259     true
260   end
261
262   def permission_to_update
263     if username_changed?
264       current_user.andand.is_admin
265     else
266       # users must be able to update themselves (even if they are
267       # inactive) in order to create sessions
268       self == current_user or super
269     end
270   end
271
272   def permission_to_create
273     current_user.andand.is_admin or
274       (self == current_user and
275        self.is_active == Rails.configuration.new_users_are_active)
276   end
277
278   def check_auto_admin
279     return if self.uuid.end_with?('anonymouspublic')
280     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
281         Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
282        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
283         Rails.configuration.auto_admin_first_user)
284       self.is_admin = true
285       self.is_active = true
286     end
287   end
288
289   def find_usable_username_from(basename)
290     # If "basename" is a usable username, return that.
291     # Otherwise, find a unique username "basenameN", where N is the
292     # smallest integer greater than 1, and return that.
293     # Return nil if a unique username can't be found after reasonable
294     # searching.
295     quoted_name = self.class.connection.quote_string(basename)
296     next_username = basename
297     next_suffix = 1
298     while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
299       next_suffix += 1
300       next_username = "%s%i" % [basename, next_suffix]
301     end
302     0.upto(6).each do |suffix_len|
303       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
304       self.class.
305           where("username like '#{pattern}'").
306           select(:username).
307           order('username asc').
308           each do |other_user|
309         if other_user.username > next_username
310           break
311         elsif other_user.username == next_username
312           next_suffix += 1
313           next_username = "%s%i" % [basename, next_suffix]
314         end
315       end
316       return next_username if (next_username.size <= pattern.size)
317     end
318     nil
319   end
320
321   def prevent_privilege_escalation
322     if current_user.andand.is_admin
323       return true
324     end
325     if self.is_active_changed?
326       if self.is_active != self.is_active_was
327         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
328         self.is_active = self.is_active_was
329       end
330     end
331     if self.is_admin_changed?
332       if self.is_admin != self.is_admin_was
333         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
334         self.is_admin = self.is_admin_was
335       end
336     end
337     true
338   end
339
340   def prevent_inactive_admin
341     if self.is_admin and not self.is_active
342       # There is no known use case for the strange set of permissions
343       # that would result from this change. It's safest to assume it's
344       # a mistake and disallow it outright.
345       raise "Admin users cannot be inactive"
346     end
347     true
348   end
349
350   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
351     nextpaths = graph[start]
352     return merged if !nextpaths
353     return merged if upstream_path.has_key? start
354     upstream_path[start] = true
355     upstream_mask ||= ALL_PERMISSIONS
356     nextpaths.each do |head, mask|
357       merged[head] ||= {}
358       mask.each do |k,v|
359         merged[head][k] ||= v if upstream_mask[k]
360       end
361       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
362     end
363     upstream_path.delete start
364     merged
365   end
366
367   def create_oid_login_perm (openid_prefix)
368     login_perm_props = { "identity_url_prefix" => openid_prefix}
369
370     # Check oid_login_perm
371     oid_login_perms = Link.where(tail_uuid: self.email,
372                                    link_class: 'permission',
373                                    name: 'can_login').where("head_uuid = ?", self.uuid)
374
375     if !oid_login_perms.any?
376       # create openid login permission
377       oid_login_perm = Link.create(link_class: 'permission',
378                                    name: 'can_login',
379                                    tail_uuid: self.email,
380                                    head_uuid: self.uuid,
381                                    properties: login_perm_props
382                                   )
383       logger.info { "openid login permission: " + oid_login_perm[:uuid] }
384     else
385       oid_login_perm = oid_login_perms.first
386     end
387
388     return oid_login_perm
389   end
390
391   def create_user_repo_link(repo_name)
392     # repo_name is optional
393     if not repo_name
394       logger.warn ("Repository name not given for #{self.uuid}.")
395       return
396     end
397
398     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
399     logger.info { "repo uuid: " + repo[:uuid] }
400     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
401                            link_class: "permission",
402                            name: "can_manage").first_or_create!
403     logger.info { "repo permission: " + repo_perm[:uuid] }
404     return repo_perm
405   end
406
407   # create login permission for the given vm_uuid, if it does not already exist
408   def create_vm_login_permission_link(vm_uuid, repo_name)
409     # vm uuid is optional
410     if vm_uuid
411       vm = VirtualMachine.where(uuid: vm_uuid).first
412
413       if not vm
414         logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
415         raise "No vm found for #{vm_uuid}"
416       end
417     else
418       return
419     end
420
421     logger.info { "vm uuid: " + vm[:uuid] }
422     login_attrs = {
423       tail_uuid: uuid, head_uuid: vm.uuid,
424       link_class: "permission", name: "can_login",
425     }
426
427     login_perm = Link.
428       where(login_attrs).
429       select { |link| link.properties["username"] == repo_name }.
430       first
431
432     login_perm ||= Link.
433       create(login_attrs.merge(properties: {"username" => repo_name}))
434
435     logger.info { "login permission: " + login_perm[:uuid] }
436     login_perm
437   end
438
439   # add the user to the 'All users' group
440   def create_user_group_link
441     return (Link.where(tail_uuid: self.uuid,
442                        head_uuid: all_users_group[:uuid],
443                        link_class: 'permission',
444                        name: 'can_read').first or
445             Link.create(tail_uuid: self.uuid,
446                         head_uuid: all_users_group[:uuid],
447                         link_class: 'permission',
448                         name: 'can_read'))
449   end
450
451   # Give the special "System group" permission to manage this user and
452   # all of this user's stuff.
453   def add_system_group_permission_link
454     return true if uuid == system_user_uuid
455     act_as_system_user do
456       Link.create(link_class: 'permission',
457                   name: 'can_manage',
458                   tail_uuid: system_group_uuid,
459                   head_uuid: self.uuid)
460     end
461   end
462
463   # Send admin notifications
464   def send_admin_notifications
465     AdminNotifier.new_user(self).deliver_now
466     if not self.is_active then
467       AdminNotifier.new_inactive_user(self).deliver_now
468     end
469   end
470
471   # Automatically setup new user during creation
472   def auto_setup_new_user
473     setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
474     if username
475       create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
476                                       username)
477       repo_name = "#{username}/#{username}"
478       if Rails.configuration.auto_setup_new_users_with_repository and
479           Repository.where(name: repo_name).first.nil?
480         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
481         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
482                      link_class: "permission", name: "can_manage")
483       end
484     end
485   end
486
487   # Send notification if the user saved profile for the first time
488   def send_profile_created_notification
489     if self.prefs_changed?
490       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
491         profile_notification_address = Rails.configuration.user_profile_notification_address
492         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address
493       end
494     end
495   end
496
497   def verify_repositories_empty
498     unless repositories.first.nil?
499       errors.add(:username, "can't be unset when the user owns repositories")
500       false
501     end
502   end
503
504   def sync_repository_names
505     old_name_re = /^#{Regexp.escape(username_was)}\//
506     name_sub = "#{username}/"
507     repositories.find_each do |repo|
508       repo.name = repo.name.sub(old_name_re, name_sub)
509       repo.save!
510     end
511   end
512 end