Merge branch '2498-group-admin'
[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 any signatures by this user
179     signed_uuids = Link.where(link_class: 'signature',
180                               tail_kind: 'arvados#user',
181                               tail_uuid: self.uuid)
182     signed_uuids.each do |sign|
183       Link.delete sign
184     end
185
186     # mark the user as inactive
187     self.is_active = false
188     self.save!
189   end
190
191   protected
192
193   def permission_to_update
194     # users must be able to update themselves (even if they are
195     # inactive) in order to create sessions
196     self == current_user or super
197   end
198
199   def permission_to_create
200     current_user.andand.is_admin or
201       (self == current_user and
202        self.is_active == Rails.configuration.new_users_are_active)
203   end
204
205   def check_auto_admin
206     if User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and Rails.configuration.auto_admin_user
207       if current_user.email == Rails.configuration.auto_admin_user
208         self.is_admin = true
209         self.is_active = true
210       end
211     end
212   end
213
214   def prevent_privilege_escalation
215     if current_user.andand.is_admin
216       return true
217     end
218     if self.is_active_changed?
219       if self.is_active != self.is_active_was
220         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
221         self.is_active = self.is_active_was
222       end
223     end
224     if self.is_admin_changed?
225       if self.is_admin != self.is_admin_was
226         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
227         self.is_admin = self.is_admin_was
228       end
229     end
230     true
231   end
232
233   def prevent_inactive_admin
234     if self.is_admin and not self.is_active
235       # There is no known use case for the strange set of permissions
236       # that would result from this change. It's safest to assume it's
237       # a mistake and disallow it outright.
238       raise "Admin users cannot be inactive"
239     end
240     true
241   end
242
243   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
244     nextpaths = graph[start]
245     return merged if !nextpaths
246     return merged if upstream_path.has_key? start
247     upstream_path[start] = true
248     upstream_mask ||= ALL_PERMISSIONS
249     nextpaths.each do |head, mask|
250       merged[head] ||= {}
251       mask.each do |k,v|
252         merged[head][k] ||= v if upstream_mask[k]
253       end
254       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
255     end
256     upstream_path.delete start
257     merged
258   end
259
260   def create_user_repo_link(repo_name)
261     # repo_name is optional
262     if not repo_name
263       logger.warn ("Repository name not given for #{self.uuid}.")
264       return
265     end
266
267     # Check for an existing repository with the same name we're about to use.
268     repo = Repository.where(name: repo_name).first
269
270     if repo
271       logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
272
273       # Look for existing repository access for this repo
274       repo_perms = Link.where(tail_uuid: self.uuid,
275                               head_kind: 'arvados#repository',
276                               head_uuid: repo[:uuid],
277                               link_class: 'permission',
278                               name: 'can_write')
279       if repo_perms.any?
280         logger.warn "User already has repository access " +
281             repo_perms.collect { |p| p[:uuid] }.inspect
282         return repo_perms.first
283       end
284     end
285
286     # create repo, if does not already exist
287     repo ||= Repository.create(name: repo_name)
288     logger.info { "repo uuid: " + repo[:uuid] }
289
290     repo_perm = Link.create(tail_kind: 'arvados#user',
291                             tail_uuid: self.uuid,
292                             head_kind: 'arvados#repository',
293                             head_uuid: repo[:uuid],
294                             link_class: 'permission',
295                             name: 'can_write')
296     logger.info { "repo permission: " + repo_perm[:uuid] }
297     return repo_perm
298   end
299
300   # create login permission for the given vm_uuid, if it does not already exist
301   def create_vm_login_permission_link(vm_uuid, repo_name)
302     begin
303
304       # vm uuid is optional
305       if vm_uuid
306         vm = VirtualMachine.where(uuid: vm_uuid).first
307
308         if not vm
309           logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
310           raise "No vm found for #{vm_uuid}"
311         end
312       else
313         return
314       end
315
316       logger.info { "vm uuid: " + vm[:uuid] }
317
318       login_perms = Link.where(tail_uuid: self.uuid,
319                               head_uuid: vm[:uuid],
320                               head_kind: 'arvados#virtualMachine',
321                               link_class: 'permission',
322                               name: 'can_login')
323       if !login_perms.any?
324         login_perm = Link.create(tail_kind: 'arvados#user',
325                                  tail_uuid: self.uuid,
326                                  head_kind: 'arvados#virtualMachine',
327                                  head_uuid: vm[:uuid],
328                                  link_class: 'permission',
329                                  name: 'can_login',
330                                  properties: {username: repo_name})
331         logger.info { "login permission: " + login_perm[:uuid] }
332       else
333         login_perm = login_perms.first
334       end
335
336       return login_perm
337     end
338   end
339
340   # add the user to the 'All users' group
341   def create_user_group_link
342     # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
343     group = Group.where(name: 'All users').select do |g|
344       g[:uuid].match /-f+$/
345     end.first
346
347     if not group
348       logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
349       raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
350     else
351       logger.info { "\"All users\" group uuid: " + group[:uuid] }
352
353       group_perms = Link.where(tail_uuid: self.uuid,
354                               head_uuid: group[:uuid],
355                               head_kind: 'arvados#group',
356                               link_class: 'permission',
357                               name: 'can_read')
358
359       if !group_perms.any?
360         group_perm = Link.create(tail_kind: 'arvados#user',
361                                  tail_uuid: self.uuid,
362                                  head_kind: 'arvados#group',
363                                  head_uuid: group[:uuid],
364                                  link_class: 'permission',
365                                  name: 'can_read')
366         logger.info { "group permission: " + group_perm[:uuid] }
367       else
368         group_perm = group_perms.first
369       end
370
371       return group_perm
372     end
373   end
374
375   # Give the special "System group" permission to manage this user and
376   # all of this user's stuff.
377   #
378   def add_system_group_permission_link
379     Link.create(link_class: 'permission',
380                 name: 'can_manage',
381                 tail_kind: 'arvados#group',
382                 tail_uuid: system_group_uuid,
383                 head_kind: 'arvados#user',
384                 head_uuid: self.uuid)
385   end
386 end