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