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