Merge branch 'master' of git.curoverse.com:arvados
[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}".strip
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_uuid like ? or head_uuid like ?)',
84                    lookup_uuids,
85                    'permission',
86                    Group.uuid_like_pattern,
87                    User.uuid_like_pattern).each do |link|
88           newgroups << [link.tail_uuid, link.head_uuid, link.name]
89         end
90         newgroups.each do |tail_uuid, head_uuid, perm_name|
91           unless done.has_key? head_uuid
92             todo[head_uuid] = true
93           end
94           link_permissions = {}
95           case perm_name
96           when 'can_read'
97             link_permissions = {read:true}
98           when 'can_write'
99             link_permissions = {read:true,write:true}
100           when 'can_manage'
101             link_permissions = ALL_PERMISSIONS
102           end
103           permissions_from[tail_uuid] ||= {}
104           permissions_from[tail_uuid][head_uuid] ||= {}
105           link_permissions.each do |k,v|
106             permissions_from[tail_uuid][head_uuid][k] ||= v
107           end
108         end
109       end
110       search_permissions(self.uuid, permissions_from)
111     end
112   end
113
114   def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
115     return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
116   end
117
118   # create links
119   def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
120     oid_login_perm = create_oid_login_perm openid_prefix
121     repo_perm = create_user_repo_link repo_name
122     vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
123     group_perm = create_user_group_link
124
125     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
126   end
127
128   # delete user signatures, login, repo, and vm perms, and mark as inactive
129   def unsetup
130     # delete oid_login_perms for this user
131     oid_login_perms = Link.where(tail_uuid: self.email,
132                                  link_class: 'permission',
133                                  name: 'can_login')
134     oid_login_perms.each do |perm|
135       Link.delete perm
136     end
137
138     # delete repo_perms for this user
139     repo_perms = Link.where(tail_uuid: self.uuid,
140                             link_class: 'permission',
141                             name: 'can_write')
142     repo_perms.each do |perm|
143       Link.delete perm
144     end
145
146     # delete vm_login_perms for this user
147     vm_login_perms = Link.where(tail_uuid: self.uuid,
148                                 link_class: 'permission',
149                                 name: 'can_login')
150     vm_login_perms.each do |perm|
151       Link.delete perm
152     end
153
154     # delete "All users' group read permissions for this user
155     group = Group.where(name: 'All users').select do |g|
156       g[:uuid].match /-f+$/
157     end.first
158     group_perms = Link.where(tail_uuid: self.uuid,
159                              head_uuid: group[:uuid],
160                              link_class: 'permission',
161                              name: 'can_read')
162     group_perms.each do |perm|
163       Link.delete perm
164     end
165
166     # delete any signatures by this user
167     signed_uuids = Link.where(link_class: 'signature',
168                               tail_uuid: self.uuid)
169     signed_uuids.each do |sign|
170       Link.delete sign
171     end
172
173     # mark the user as inactive
174     self.is_active = false
175     self.save!
176   end
177
178   protected
179
180   def permission_to_update
181     # users must be able to update themselves (even if they are
182     # inactive) in order to create sessions
183     self == current_user or super
184   end
185
186   def permission_to_create
187     current_user.andand.is_admin or
188       (self == current_user and
189        self.is_active == Rails.configuration.new_users_are_active)
190   end
191
192   def check_auto_admin
193     if User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and Rails.configuration.auto_admin_user
194       if current_user.email == Rails.configuration.auto_admin_user
195         self.is_admin = true
196         self.is_active = true
197       end
198     end
199   end
200
201   def prevent_privilege_escalation
202     if current_user.andand.is_admin
203       return true
204     end
205     if self.is_active_changed?
206       if self.is_active != self.is_active_was
207         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
208         self.is_active = self.is_active_was
209       end
210     end
211     if self.is_admin_changed?
212       if self.is_admin != self.is_admin_was
213         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
214         self.is_admin = self.is_admin_was
215       end
216     end
217     true
218   end
219
220   def prevent_inactive_admin
221     if self.is_admin and not self.is_active
222       # There is no known use case for the strange set of permissions
223       # that would result from this change. It's safest to assume it's
224       # a mistake and disallow it outright.
225       raise "Admin users cannot be inactive"
226     end
227     true
228   end
229
230   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
231     nextpaths = graph[start]
232     return merged if !nextpaths
233     return merged if upstream_path.has_key? start
234     upstream_path[start] = true
235     upstream_mask ||= ALL_PERMISSIONS
236     nextpaths.each do |head, mask|
237       merged[head] ||= {}
238       mask.each do |k,v|
239         merged[head][k] ||= v if upstream_mask[k]
240       end
241       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
242     end
243     upstream_path.delete start
244     merged
245   end
246
247   def create_oid_login_perm (openid_prefix)
248     login_perm_props = { "identity_url_prefix" => openid_prefix}
249
250     # Check oid_login_perm
251     oid_login_perms = Link.where(tail_uuid: self.email,
252                                    link_class: 'permission',
253                                    name: 'can_login').where("head_uuid = ?", self.uuid)
254
255     if !oid_login_perms.any?
256       # create openid login permission
257       oid_login_perm = Link.create(link_class: 'permission',
258                                    name: 'can_login',
259                                    tail_uuid: self.email,
260                                    head_uuid: self.uuid,
261                                    properties: login_perm_props
262                                   )
263       logger.info { "openid login permission: " + oid_login_perm[:uuid] }
264     else
265       oid_login_perm = oid_login_perms.first
266     end
267
268     return oid_login_perm
269   end
270
271   def create_user_repo_link(repo_name)
272     # repo_name is optional
273     if not repo_name
274       logger.warn ("Repository name not given for #{self.uuid}.")
275       return
276     end
277
278     # Check for an existing repository with the same name we're about to use.
279     repo = Repository.where(name: repo_name).first
280
281     if repo
282       logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
283
284       # Look for existing repository access for this repo
285       repo_perms = Link.where(tail_uuid: self.uuid,
286                               head_uuid: repo[:uuid],
287                               link_class: 'permission',
288                               name: 'can_write')
289       if repo_perms.any?
290         logger.warn "User already has repository access " +
291             repo_perms.collect { |p| p[:uuid] }.inspect
292         return repo_perms.first
293       end
294     end
295
296     # create repo, if does not already exist
297     repo ||= Repository.create(name: repo_name)
298     logger.info { "repo uuid: " + repo[:uuid] }
299
300     repo_perm = Link.create(tail_uuid: self.uuid,
301                             head_uuid: repo[:uuid],
302                             link_class: 'permission',
303                             name: 'can_write')
304     logger.info { "repo permission: " + repo_perm[:uuid] }
305     return repo_perm
306   end
307
308   # create login permission for the given vm_uuid, if it does not already exist
309   def create_vm_login_permission_link(vm_uuid, repo_name)
310     begin
311
312       # vm uuid is optional
313       if vm_uuid
314         vm = VirtualMachine.where(uuid: vm_uuid).first
315
316         if not vm
317           logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
318           raise "No vm found for #{vm_uuid}"
319         end
320       else
321         return
322       end
323
324       logger.info { "vm uuid: " + vm[:uuid] }
325
326       login_perms = Link.where(tail_uuid: self.uuid,
327                               head_uuid: vm[:uuid],
328                               link_class: 'permission',
329                               name: 'can_login')
330
331       perm_exists = false
332       login_perms.each do |perm|
333         if perm.properties[:username] == repo_name
334           perm_exists = true
335           break
336         end
337       end
338
339       if !perm_exists
340         login_perm = Link.create(tail_uuid: self.uuid,
341                                  head_uuid: vm[:uuid],
342                                  link_class: 'permission',
343                                  name: 'can_login',
344                                  properties: {username: repo_name})
345         logger.info { "login permission: " + login_perm[:uuid] }
346       else
347         login_perm = login_perms.first
348       end
349
350       return login_perm
351     end
352   end
353
354   # add the user to the 'All users' group
355   def create_user_group_link
356     # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
357     group = Group.where(name: 'All users').select do |g|
358       g[:uuid].match /-f+$/
359     end.first
360
361     if not group
362       logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
363       raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
364     else
365       logger.info { "\"All users\" group uuid: " + group[:uuid] }
366
367       group_perms = Link.where(tail_uuid: self.uuid,
368                               head_uuid: group[:uuid],
369                               link_class: 'permission',
370                               name: 'can_read')
371
372       if !group_perms.any?
373         group_perm = Link.create(tail_uuid: self.uuid,
374                                  head_uuid: group[:uuid],
375                                  link_class: 'permission',
376                                  name: 'can_read')
377         logger.info { "group permission: " + group_perm[:uuid] }
378       else
379         group_perm = group_perms.first
380       end
381
382       return group_perm
383     end
384   end
385
386   # Give the special "System group" permission to manage this user and
387   # all of this user's stuff.
388   #
389   def add_system_group_permission_link
390     act_as_system_user do
391       Link.create(link_class: 'permission',
392                   name: 'can_manage',
393                   tail_uuid: system_group_uuid,
394                   head_uuid: self.uuid)
395     end
396   end
397 end