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