Add 'tools/arvbox/' from commit 'd3d368758db1f4a9fa5b89f77b5ee61d68ef5b72'
[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   validates(:username,
12             format: {
13               with: /^[A-Za-z][A-Za-z0-9]*$/,
14               message: "must begin with a letter and contain only alphanumerics",
15             },
16             uniqueness: true,
17             allow_nil: true)
18   before_update :prevent_privilege_escalation
19   before_update :prevent_inactive_admin
20   before_update :verify_repositories_empty, :if => Proc.new { |user|
21     user.username.nil? and user.username_changed?
22   }
23   before_create :check_auto_admin
24   before_create :set_initial_username, :if => Proc.new { |user|
25     user.username.nil? and user.email
26   }
27   after_create :add_system_group_permission_link
28   after_create :auto_setup_new_user, :if => Proc.new { |user|
29     Rails.configuration.auto_setup_new_users and
30     (user.uuid != system_user_uuid) and
31     (user.uuid != anonymous_user_uuid)
32   }
33   after_create :send_admin_notifications
34   after_update :send_profile_created_notification
35   after_update :sync_repository_names, :if => Proc.new { |user|
36     (user.uuid != system_user_uuid) and
37     user.username_changed? and
38     (not user.username_was.nil?)
39   }
40
41   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
42   has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
43
44   api_accessible :user, extend: :common do |t|
45     t.add :email
46     t.add :username
47     t.add :full_name
48     t.add :first_name
49     t.add :last_name
50     t.add :identity_url
51     t.add :is_active
52     t.add :is_admin
53     t.add :is_invited
54     t.add :prefs
55     t.add :writable_by
56   end
57
58   ALL_PERMISSIONS = {read: true, write: true, manage: true}
59
60   def full_name
61     "#{first_name} #{last_name}".strip
62   end
63
64   def is_invited
65     !!(self.is_active ||
66        Rails.configuration.new_users_are_active ||
67        self.groups_i_can(:read).select { |x| x.match /-f+$/ }.first)
68   end
69
70   def groups_i_can(verb)
71     my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
72     if verb == :read
73       my_groups << anonymous_group_uuid
74     end
75     my_groups
76   end
77
78   def can?(actions)
79     return true if is_admin
80     actions.each do |action, target|
81       unless target.nil?
82         if target.respond_to? :uuid
83           target_uuid = target.uuid
84         else
85           target_uuid = target
86           target = ArvadosModel.find_by_uuid(target_uuid)
87         end
88       end
89       next if target_uuid == self.uuid
90       next if (group_permissions[target_uuid] and
91                group_permissions[target_uuid][action])
92       if target.respond_to? :owner_uuid
93         next if target.owner_uuid == self.uuid
94         next if (group_permissions[target.owner_uuid] and
95                  group_permissions[target.owner_uuid][action])
96       end
97       sufficient_perms = case action
98                          when :manage
99                            ['can_manage']
100                          when :write
101                            ['can_manage', 'can_write']
102                          when :read
103                            ['can_manage', 'can_write', 'can_read']
104                          else
105                            # (Skip this kind of permission opportunity
106                            # if action is an unknown permission type)
107                          end
108       if sufficient_perms
109         # Check permission links with head_uuid pointing directly at
110         # the target object. If target is a Group, this is redundant
111         # and will fail except [a] if permission caching is broken or
112         # [b] during a race condition, where a permission link has
113         # *just* been added.
114         if Link.where(link_class: 'permission',
115                       name: sufficient_perms,
116                       tail_uuid: groups_i_can(action) + [self.uuid],
117                       head_uuid: target_uuid).any?
118           next
119         end
120       end
121       return false
122     end
123     true
124   end
125
126   def self.invalidate_permissions_cache
127     Rails.cache.delete_matched(/^groups_for_user_/)
128   end
129
130   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
131   # and perm_hash[:write] are true if this user can read and write
132   # objects owned by group_uuid.
133   #
134   # The permission graph is built by repeatedly enumerating all
135   # permission links reachable from self.uuid, and then calling
136   # search_permissions
137   def group_permissions
138     Rails.cache.fetch "groups_for_user_#{self.uuid}" do
139       permissions_from = {}
140       todo = {self.uuid => true}
141       done = {}
142       # Build the equivalence class of permissions starting with
143       # self.uuid. On each iteration of this loop, todo contains
144       # the next set of uuids in the permission equivalence class
145       # to evaluate.
146       while !todo.empty?
147         lookup_uuids = todo.keys
148         lookup_uuids.each do |uuid| done[uuid] = true end
149         todo = {}
150         newgroups = []
151         # include all groups owned by the current set of uuids.
152         Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
153           newgroups << [group.owner_uuid, group.uuid, 'can_manage']
154         end
155         # add any permission links from the current lookup_uuids to a Group.
156         Link.where('link_class = ? and tail_uuid in (?) and ' \
157                    '(head_uuid like ? or (name = ? and head_uuid like ?))',
158                    'permission',
159                    lookup_uuids,
160                    Group.uuid_like_pattern,
161                    'can_manage',
162                    User.uuid_like_pattern).each do |link|
163           newgroups << [link.tail_uuid, link.head_uuid, link.name]
164         end
165         newgroups.each do |tail_uuid, head_uuid, perm_name|
166           unless done.has_key? head_uuid
167             todo[head_uuid] = true
168           end
169           link_permissions = {}
170           case perm_name
171           when 'can_read'
172             link_permissions = {read:true}
173           when 'can_write'
174             link_permissions = {read:true,write:true}
175           when 'can_manage'
176             link_permissions = ALL_PERMISSIONS
177           end
178           permissions_from[tail_uuid] ||= {}
179           permissions_from[tail_uuid][head_uuid] ||= {}
180           link_permissions.each do |k,v|
181             permissions_from[tail_uuid][head_uuid][k] ||= v
182           end
183         end
184       end
185       search_permissions(self.uuid, permissions_from)
186     end
187   end
188
189   def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
190     return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
191   end
192
193   # create links
194   def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
195     oid_login_perm = create_oid_login_perm openid_prefix
196     repo_perm = create_user_repo_link repo_name
197     vm_login_perm = create_vm_login_permission_link vm_uuid, username
198     group_perm = create_user_group_link
199
200     return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
201   end
202
203   # delete user signatures, login, repo, and vm perms, and mark as inactive
204   def unsetup
205     # delete oid_login_perms for this user
206     Link.destroy_all(tail_uuid: self.email,
207                      link_class: 'permission',
208                      name: 'can_login')
209
210     # delete repo_perms for this user
211     Link.destroy_all(tail_uuid: self.uuid,
212                      link_class: 'permission',
213                      name: 'can_manage')
214
215     # delete vm_login_perms for this user
216     Link.destroy_all(tail_uuid: self.uuid,
217                      link_class: 'permission',
218                      name: 'can_login')
219
220     # delete "All users" group read permissions for this user
221     group = Group.where(name: 'All users').select do |g|
222       g[:uuid].match /-f+$/
223     end.first
224     Link.destroy_all(tail_uuid: self.uuid,
225                      head_uuid: group[:uuid],
226                      link_class: 'permission',
227                      name: 'can_read')
228
229     # delete any signatures by this user
230     Link.destroy_all(link_class: 'signature',
231                      tail_uuid: self.uuid)
232
233     # delete user preferences (including profile)
234     self.prefs = {}
235
236     # mark the user as inactive
237     self.is_active = false
238     self.save!
239   end
240
241   protected
242
243   def ensure_ownership_path_leads_to_user
244     true
245   end
246
247   def permission_to_update
248     if username_changed?
249       current_user.andand.is_admin
250     else
251       # users must be able to update themselves (even if they are
252       # inactive) in order to create sessions
253       self == current_user or super
254     end
255   end
256
257   def permission_to_create
258     current_user.andand.is_admin or
259       (self == current_user and
260        self.is_active == Rails.configuration.new_users_are_active)
261   end
262
263   def check_auto_admin
264     return if self.uuid.end_with?('anonymouspublic')
265     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
266         Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
267        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
268         Rails.configuration.auto_admin_first_user)
269       self.is_admin = true
270       self.is_active = true
271     end
272   end
273
274   def find_usable_username_from(basename)
275     # If "basename" is a usable username, return that.
276     # Otherwise, find a unique username "basenameN", where N is the
277     # smallest integer greater than 1, and return that.
278     # Return nil if a unique username can't be found after reasonable
279     # searching.
280     quoted_name = self.class.connection.quote_string(basename)
281     next_username = basename
282     next_suffix = 1
283     while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
284       next_suffix += 1
285       next_username = "%s%i" % [basename, next_suffix]
286     end
287     0.upto(6).each do |suffix_len|
288       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
289       self.class.
290           where("username like '#{pattern}'").
291           select(:username).
292           order(username: :asc).
293           find_each do |other_user|
294         if other_user.username > next_username
295           break
296         elsif other_user.username == next_username
297           next_suffix += 1
298           next_username = "%s%i" % [basename, next_suffix]
299         end
300       end
301       return next_username if (next_username.size <= pattern.size)
302     end
303     nil
304   end
305
306   def set_initial_username
307     email_parts = email.partition("@")
308     local_parts = email_parts.first.partition("+")
309     if email_parts.any?(&:empty?)
310       return
311     elsif not local_parts.first.empty?
312       base_username = local_parts.first
313     else
314       base_username = email_parts.first
315     end
316     base_username.sub!(/^[^A-Za-z]+/, "")
317     base_username.gsub!(/[^A-Za-z0-9]/, "")
318     unless base_username.empty?
319       self.username = find_usable_username_from(base_username)
320     end
321   end
322
323   def prevent_privilege_escalation
324     if current_user.andand.is_admin
325       return true
326     end
327     if self.is_active_changed?
328       if self.is_active != self.is_active_was
329         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
330         self.is_active = self.is_active_was
331       end
332     end
333     if self.is_admin_changed?
334       if self.is_admin != self.is_admin_was
335         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
336         self.is_admin = self.is_admin_was
337       end
338     end
339     true
340   end
341
342   def prevent_inactive_admin
343     if self.is_admin and not self.is_active
344       # There is no known use case for the strange set of permissions
345       # that would result from this change. It's safest to assume it's
346       # a mistake and disallow it outright.
347       raise "Admin users cannot be inactive"
348     end
349     true
350   end
351
352   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
353     nextpaths = graph[start]
354     return merged if !nextpaths
355     return merged if upstream_path.has_key? start
356     upstream_path[start] = true
357     upstream_mask ||= ALL_PERMISSIONS
358     nextpaths.each do |head, mask|
359       merged[head] ||= {}
360       mask.each do |k,v|
361         merged[head][k] ||= v if upstream_mask[k]
362       end
363       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
364     end
365     upstream_path.delete start
366     merged
367   end
368
369   def create_oid_login_perm (openid_prefix)
370     login_perm_props = { "identity_url_prefix" => openid_prefix}
371
372     # Check oid_login_perm
373     oid_login_perms = Link.where(tail_uuid: self.email,
374                                    link_class: 'permission',
375                                    name: 'can_login').where("head_uuid = ?", self.uuid)
376
377     if !oid_login_perms.any?
378       # create openid login permission
379       oid_login_perm = Link.create(link_class: 'permission',
380                                    name: 'can_login',
381                                    tail_uuid: self.email,
382                                    head_uuid: self.uuid,
383                                    properties: login_perm_props
384                                   )
385       logger.info { "openid login permission: " + oid_login_perm[:uuid] }
386     else
387       oid_login_perm = oid_login_perms.first
388     end
389
390     return oid_login_perm
391   end
392
393   def create_user_repo_link(repo_name)
394     # repo_name is optional
395     if not repo_name
396       logger.warn ("Repository name not given for #{self.uuid}.")
397       return
398     end
399
400     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
401     logger.info { "repo uuid: " + repo[:uuid] }
402     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
403                            link_class: "permission",
404                            name: "can_manage").first_or_create!
405     logger.info { "repo permission: " + repo_perm[:uuid] }
406     return repo_perm
407   end
408
409   # create login permission for the given vm_uuid, if it does not already exist
410   def create_vm_login_permission_link(vm_uuid, repo_name)
411     # vm uuid is optional
412     if vm_uuid
413       vm = VirtualMachine.where(uuid: vm_uuid).first
414
415       if not vm
416         logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
417         raise "No vm found for #{vm_uuid}"
418       end
419     else
420       return
421     end
422
423     logger.info { "vm uuid: " + vm[:uuid] }
424     login_attrs = {
425       tail_uuid: uuid, head_uuid: vm.uuid,
426       link_class: "permission", name: "can_login",
427     }
428
429     login_perm = Link.
430       where(login_attrs).
431       select { |link| link.properties["username"] == repo_name }.
432       first
433
434     login_perm ||= Link.
435       create(login_attrs.merge(properties: {"username" => repo_name}))
436
437     logger.info { "login permission: " + login_perm[:uuid] }
438     login_perm
439   end
440
441   # add the user to the 'All users' group
442   def create_user_group_link
443     return (Link.where(tail_uuid: self.uuid,
444                        head_uuid: all_users_group[:uuid],
445                        link_class: 'permission',
446                        name: 'can_read').first or
447             Link.create(tail_uuid: self.uuid,
448                         head_uuid: all_users_group[:uuid],
449                         link_class: 'permission',
450                         name: 'can_read'))
451   end
452
453   # Give the special "System group" permission to manage this user and
454   # all of this user's stuff.
455   def add_system_group_permission_link
456     return true if uuid == system_user_uuid
457     act_as_system_user do
458       Link.create(link_class: 'permission',
459                   name: 'can_manage',
460                   tail_uuid: system_group_uuid,
461                   head_uuid: self.uuid)
462     end
463   end
464
465   # Send admin notifications
466   def send_admin_notifications
467     AdminNotifier.new_user(self).deliver
468     if not self.is_active then
469       AdminNotifier.new_inactive_user(self).deliver
470     end
471   end
472
473   # Automatically setup new user during creation
474   def auto_setup_new_user
475     setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
476     if username
477       create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
478                                       username)
479       repo_name = "#{username}/#{username}"
480       if Rails.configuration.auto_setup_new_users_with_repository and
481           Repository.where(name: repo_name).first.nil?
482         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
483         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
484                      link_class: "permission", name: "can_manage")
485       end
486     end
487   end
488
489   # Send notification if the user saved profile for the first time
490   def send_profile_created_notification
491     if self.prefs_changed?
492       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
493         profile_notification_address = Rails.configuration.user_profile_notification_address
494         ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address
495       end
496     end
497   end
498
499   def verify_repositories_empty
500     unless repositories.first.nil?
501       errors.add(:username, "can't be unset when the user owns repositories")
502       false
503     end
504   end
505
506   def sync_repository_names
507     old_name_re = /^#{Regexp.escape(username_was)}\//
508     name_sub = "#{username}/"
509     repositories.find_each do |repo|
510       repo.name = repo.name.sub(old_name_re, name_sub)
511       repo.save!
512     end
513   end
514 end