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