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