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