Merge branch '21635-banner-test-fix' into main. Closes #21635
[arvados.git] / services / api / test / unit / user_test.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'test_helper'
6
7 class UserTest < ActiveSupport::TestCase
8   include CurrentApiClient
9
10   # The fixture services/api/test/fixtures/users.yml serves as the input for this test case
11   setup do
12     # Make sure system_user exists before making "pre-test users" list
13     system_user
14   end
15
16   %w(a aa a0 aA Aa AA A0).each do |username|
17     test "#{username.inspect} is a valid username" do
18       user = User.new(username: username)
19       assert(user.valid?)
20     end
21   end
22
23   test "username is not required" do
24     user = User.new(username: nil)
25     assert(user.valid?)
26   end
27
28   test "username beginning with numeral is invalid" do
29     user = User.new(username: "0a")
30     refute(user.valid?)
31   end
32
33   "\\.-_/!@#$%^&*()[]{}".each_char do |bad_char|
34     test "username containing #{bad_char.inspect} is invalid" do
35       user = User.new(username: "bad#{bad_char}username")
36       refute(user.valid?)
37     end
38   end
39
40   test "username must be unique" do
41     user = User.new(username: users(:active).username)
42     refute(user.valid?)
43   end
44
45   test "non-admin can't update username" do
46     set_user_from_auth :rominiadmin
47     user = User.find_by_uuid(users(:rominiadmin).uuid)
48     user.username = "selfupdate"
49     assert_not_allowed { user.save }
50   end
51
52   def check_admin_username_change(fixture_name)
53     set_user_from_auth :admin_trustedclient
54     user = User.find_by_uuid(users(fixture_name).uuid)
55     user.username = "newnamefromtest"
56     assert(user.save)
57   end
58
59   test "admin can set username" do
60     check_admin_username_change(:active_no_prefs)
61   end
62
63   test "admin can update username" do
64     check_admin_username_change(:active)
65   end
66
67   test "admin can update own username" do
68     check_admin_username_change(:admin)
69   end
70
71   def check_new_username_setting(email_name, expect_name)
72     set_user_from_auth :admin
73     user = User.create!(email: "#{email_name}@example.org")
74     assert_equal(expect_name, user.username)
75   end
76
77   test "new username set from e-mail" do
78     check_new_username_setting("dakota", "dakota")
79   end
80
81   test "new username set from e-mail with leading digits" do
82     check_new_username_setting("1dakota9", "dakota9")
83   end
84
85   test "new username set from e-mail with punctuation" do
86     check_new_username_setting("dakota.9", "dakota9")
87   end
88
89   test "new username set from e-mail with leading digits and punctuation" do
90     check_new_username_setting("1.dakota.z", "dakotaz")
91   end
92
93   test "new username set from e-mail with extra part" do
94     check_new_username_setting("dakota+arvados", "dakota")
95   end
96
97   test "new username set with deduplication" do
98     name = users(:active).username
99     check_new_username_setting(name, "#{name}2")
100     check_new_username_setting(name, "#{name}3")
101     # Insert some out-of-order conflicts, to ensure our "sort by
102     # username, stop when we see a hole" strategy doesn't depend on
103     # insert order.
104     check_new_username_setting("#{name}13", "#{name}13")
105     check_new_username_setting("#{name}5", "#{name}5")
106     check_new_username_setting(name, "#{name}4")
107     6.upto(12).each do |n|
108       check_new_username_setting(name, "#{name}#{n}")
109     end
110   end
111
112   test "new username set avoiding blacklist" do
113     Rails.configuration.Users.AutoSetupUsernameBlacklist = ConfigLoader.to_OrderedOptions({"root"=>{}})
114     check_new_username_setting("root", "root2")
115   end
116
117   test "no username set when no base available" do
118     check_new_username_setting("_", nil)
119   end
120
121   test "admin can clear username" do
122     set_user_from_auth :admin
123     user = users(:spectator)
124     user.username = nil
125     assert(user.save)
126     assert_nil(user.username)
127   end
128
129   [[false, 'foo@example.com', true, false],
130    [false, 'bar@example.com', false, true],
131    [true, 'foo@example.com', true, false],
132    [true, 'bar@example.com', true, true],
133    [false, '', false, false],
134    [true, '', true, false]
135   ].each do |auto_admin_first_user_config, auto_admin_user_config, foo_should_be_admin, bar_should_be_admin|
136     # In each case, 'foo' is created first, then 'bar', then 'bar2', then 'baz'.
137     test "auto admin with auto_admin_first=#{auto_admin_first_user_config} auto_admin=#{auto_admin_user_config}" do
138
139       if auto_admin_first_user_config
140         # This test requires no admin users exist (except for the system user)
141         act_as_system_user do
142           users(:admin).update!(is_admin: false)
143         end
144         @all_users = User.where("uuid not like '%-000000000000000'").where(:is_admin => true)
145         assert_equal 0, @all_users.count, "No admin users should exist (except for the system user)"
146       end
147
148       Rails.configuration.Users.AutoAdminFirstUser = auto_admin_first_user_config
149       Rails.configuration.Users.AutoAdminUserWithEmail = auto_admin_user_config
150
151       # See if the foo user has is_admin
152       foo = User.new
153       foo.first_name = 'foo'
154       foo.email = 'foo@example.com'
155
156       act_as_system_user do
157         foo.save!
158       end
159
160       foo = User.find(foo.id)   # get the user back
161       assert_equal foo_should_be_admin, foo.is_admin, "is_admin is wrong for user foo"
162       assert_equal 'foo', foo.first_name
163
164       # See if the bar user has is_admin
165       bar = User.new
166       bar.first_name = 'bar'
167       bar.email = 'bar@example.com'
168
169       act_as_system_user do
170         bar.save!
171       end
172
173       bar = User.find(bar.id)   # get the user back
174       assert_equal bar_should_be_admin, bar.is_admin, "is_admin is wrong for user bar"
175       assert_equal 'bar', bar.first_name
176
177       # A subsequent user with the bar@example.com address should never be
178       # elevated to admin
179       bar2 = User.new
180       bar2.first_name = 'bar2'
181       bar2.email = 'bar@example.com'
182
183       act_as_system_user do
184         bar2.save!
185       end
186
187       bar2 = User.find(bar2.id)   # get the user back
188       assert !bar2.is_admin, "is_admin is wrong for user bar2"
189       assert_equal 'bar2', bar2.first_name
190
191       # An ordinary new user should not be elevated to admin
192       baz = User.new
193       baz.first_name = 'baz'
194       baz.email = 'baz@example.com'
195
196       act_as_system_user do
197         baz.save!
198       end
199
200       baz = User.find(baz.id)   # get the user back
201       assert !baz.is_admin
202       assert_equal 'baz', baz.first_name
203
204     end
205   end
206
207   test "check non-admin active user properties" do
208     @active_user = users(:active)     # get the active user
209     assert !@active_user.is_admin, 'is_admin should not be set for a non-admin user'
210     assert @active_user.is_active, 'user should be active'
211     assert @active_user.is_invited, 'is_invited should be set'
212     assert_not_nil @active_user.prefs, "user's preferences should be non-null, but may be size zero"
213     assert (@active_user.can? :read=>"#{@active_user.uuid}"), "user should be able to read own object"
214     assert (@active_user.can? :write=>"#{@active_user.uuid}"), "user should be able to write own object"
215     assert (@active_user.can? :manage=>"#{@active_user.uuid}"), "user should be able to manage own object"
216
217     assert @active_user.groups_i_can(:read).size > 0, "active user should be able read at least one group"
218
219     # non-admin user cannot manage or write other user objects
220     @uninvited_user = users(:inactive_uninvited)     # get the uninvited user
221     assert !(@active_user.can? :read=>"#{@uninvited_user.uuid}")
222     assert !(@active_user.can? :write=>"#{@uninvited_user.uuid}")
223     assert !(@active_user.can? :manage=>"#{@uninvited_user.uuid}")
224   end
225
226   test "check admin user properties" do
227     @admin_user = users(:admin)     # get the admin user
228     assert @admin_user.is_admin, 'is_admin should be set for admin user'
229     assert @admin_user.is_active, 'admin user cannot be inactive'
230     assert @admin_user.is_invited, 'is_invited should be set'
231     assert_not_nil @admin_user.uuid.size, "user's uuid should be non-null"
232     assert_not_nil @admin_user.prefs, "user's preferences should be non-null, but may be size zero"
233     assert @admin_user.identity_url.size > 0, "user's identity url is expected"
234     assert @admin_user.can? :read=>"#{@admin_user.uuid}"
235     assert @admin_user.can? :write=>"#{@admin_user.uuid}"
236     assert @admin_user.can? :manage=>"#{@admin_user.uuid}"
237
238     assert @admin_user.groups_i_can(:read).size > 0, "admin active user should be able read at least one group"
239     assert @admin_user.groups_i_can(:write).size > 0, "admin active user should be able write to at least one group"
240     assert @admin_user.groups_i_can(:manage).size > 0, "admin active user should be able manage at least one group"
241
242     # admin user can also write or manage other users
243     @uninvited_user = users(:inactive_uninvited)     # get the uninvited user
244     assert @admin_user.can? :read=>"#{@uninvited_user.uuid}"
245     assert @admin_user.can? :write=>"#{@uninvited_user.uuid}"
246     assert @admin_user.can? :manage=>"#{@uninvited_user.uuid}"
247   end
248
249   test "check inactive and uninvited user properties" do
250     @uninvited_user = users(:inactive_uninvited)     # get the uninvited user
251     assert !@uninvited_user.is_admin, 'is_admin should not be set for a non-admin user'
252     assert !@uninvited_user.is_active, 'user should be inactive'
253     assert !@uninvited_user.is_invited, 'is_invited should not be set'
254     assert @uninvited_user.can? :read=>"#{@uninvited_user.uuid}"
255     assert @uninvited_user.can? :write=>"#{@uninvited_user.uuid}"
256     assert @uninvited_user.can? :manage=>"#{@uninvited_user.uuid}"
257
258     assert_equal(@uninvited_user.groups_i_can(:read).sort,
259                  [@uninvited_user.uuid, groups(:anonymous_group).uuid].sort)
260     assert_equal(@uninvited_user.groups_i_can(:write),
261                  [@uninvited_user.uuid])
262     assert_equal(@uninvited_user.groups_i_can(:manage),
263                  [@uninvited_user.uuid])
264   end
265
266   test "find user method checks" do
267     User.all.each do |user|
268       assert_not_nil user.uuid, "non-null uuid expected for " + user.full_name
269     end
270
271     user = users(:active)     # get the active user
272
273     found_user = User.find(user.id)   # find a user by the row id
274
275     assert_equal found_user.full_name, user.first_name + ' ' + user.last_name
276     assert_equal found_user.identity_url, user.identity_url
277   end
278
279   test "full name should not contain spurious whitespace" do
280     set_user_from_auth :admin
281
282     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: 'foo@example.com' })
283
284     assert_equal '', user.full_name
285
286     user.first_name = 'John'
287     user.last_name = 'Smith'
288
289     assert_equal user.first_name + ' ' + user.last_name, user.full_name
290   end
291
292   test "create new user" do
293     set_user_from_auth :admin
294
295     @all_users = User.all.to_a
296
297     user = User.new
298     user.first_name = "first_name_for_newly_created_user"
299     user.save
300
301     # verify there is one extra user in the db now
302     assert_equal @all_users.size+1, User.all.count
303
304     user = User.find(user.id)   # get the user back
305     assert_equal(user.first_name, 'first_name_for_newly_created_user')
306     assert_not_nil user.uuid, 'uuid should be set for newly created user'
307     assert_nil user.email, 'email should be null for newly created user, because it was not passed in'
308     assert_nil user.identity_url, 'identity_url should be null for newly created user, because it was not passed in'
309
310     user.first_name = 'first_name_for_newly_created_user_updated'
311     user.save
312     user = User.find(user.id)   # get the user back
313     assert_equal(user.first_name, 'first_name_for_newly_created_user_updated')
314   end
315
316   active_notify_list = ConfigLoader.to_OrderedOptions({"active-notify@example.com"=>{}})
317   inactive_notify_list = ConfigLoader.to_OrderedOptions({"inactive-notify@example.com"=>{}})
318   empty_notify_list = ConfigLoader.to_OrderedOptions({})
319
320   test "create new user with notifications" do
321     set_user_from_auth :admin
322
323     Rails.configuration.Users.AutoSetupNewUsers = false
324
325     create_user_and_verify_setup_and_notifications true, active_notify_list, inactive_notify_list, nil, nil
326     create_user_and_verify_setup_and_notifications true, active_notify_list, empty_notify_list, nil, nil
327     create_user_and_verify_setup_and_notifications true, empty_notify_list, empty_notify_list, nil, nil
328     create_user_and_verify_setup_and_notifications false, empty_notify_list, inactive_notify_list, nil, nil
329     create_user_and_verify_setup_and_notifications false, empty_notify_list, inactive_notify_list, nil, nil
330     create_user_and_verify_setup_and_notifications false, empty_notify_list, empty_notify_list, nil, nil
331   end
332
333   [
334     # Easy inactive user tests.
335     [false, empty_notify_list, empty_notify_list, "inactive-none@example.com", false, "inactivenone"],
336     [false, empty_notify_list, empty_notify_list, "inactive-vm@example.com", true, "inactivevm"],
337
338     # Easy active user tests.
339     [true, active_notify_list, inactive_notify_list, "active-none@example.com", false, "activenone"],
340     [true, active_notify_list, inactive_notify_list, "active-vm@example.com", true, "activevm"],
341
342     # Test users with malformed e-mail addresses.
343     [false, empty_notify_list, empty_notify_list, nil, true, nil],
344     [false, empty_notify_list, empty_notify_list, "arvados", true, nil],
345     [false, empty_notify_list, empty_notify_list, "@example.com", true, nil],
346     [true, active_notify_list, inactive_notify_list, "*!*@example.com", true, nil],
347     [true, active_notify_list, inactive_notify_list, "*!*@example.com", false, nil],
348
349     # Test users with various username transformations.
350     [false, empty_notify_list, empty_notify_list, "arvados@example.com", false, "arvados2"],
351     [true, active_notify_list, inactive_notify_list, "arvados@example.com", false, "arvados2"],
352     [true, active_notify_list, inactive_notify_list, "root@example.com", true, "root2"],
353     [false, active_notify_list, empty_notify_list, "root@example.com", true, "root2"],
354     [true, active_notify_list, inactive_notify_list, "roo_t@example.com", false, "root2"],
355     [false, empty_notify_list, empty_notify_list, "^^incorrect_format@example.com", true, "incorrectformat"],
356     [true, active_notify_list, inactive_notify_list, "&4a_d9.@example.com", true, "ad9"],
357     [true, active_notify_list, inactive_notify_list, "&4a_d9.@example.com", false, "ad9"],
358     [false, active_notify_list, empty_notify_list, "&4a_d9.@example.com", true, "ad9"],
359     [false, active_notify_list, empty_notify_list, "&4a_d9.@example.com", false, "ad9"],
360   ].each do |active, new_user_recipients, inactive_recipients, email, auto_setup_vm, expect_username|
361     test "create new user with auto setup active=#{active} email=#{email} vm=#{auto_setup_vm}" do
362       set_user_from_auth :admin
363
364       Rails.configuration.Users.AutoSetupNewUsers = true
365
366       if auto_setup_vm
367         Rails.configuration.Users.AutoSetupNewUsersWithVmUUID = virtual_machines(:testvm)['uuid']
368       else
369         Rails.configuration.Users.AutoSetupNewUsersWithVmUUID = ""
370       end
371
372       create_user_and_verify_setup_and_notifications active, new_user_recipients, inactive_recipients, email, expect_username
373     end
374   end
375
376   test "update existing user" do
377     set_user_from_auth :active    # set active user as current user
378
379     @active_user = users(:active)     # get the active user
380
381     @active_user.first_name = "first_name_changed"
382     @active_user.save
383
384     @active_user = User.find(@active_user.id)   # get the user back
385     assert_equal(@active_user.first_name, 'first_name_changed')
386
387     # admin user also should be able to update the "active" user info
388     set_user_from_auth :admin # set admin user as current user
389     @active_user.first_name = "first_name_changed_by_admin_for_active_user"
390     @active_user.save
391
392     @active_user = User.find(@active_user.id)   # get the user back
393     assert_equal(@active_user.first_name, 'first_name_changed_by_admin_for_active_user')
394   end
395
396   test "delete a user and verify" do
397     @active_user = users(:active)     # get the active user
398     active_user_uuid = @active_user.uuid
399
400     set_user_from_auth :admin
401     @active_user.delete
402
403     found_deleted_user = false
404     User.all.each do |user|
405       if user.uuid == active_user_uuid
406         found_deleted_user = true
407         break
408       end
409     end
410     assert !found_deleted_user, "found deleted user: "+active_user_uuid
411
412   end
413
414   test "create new user as non-admin user" do
415     set_user_from_auth :active
416     assert_not_allowed { User.new.save }
417   end
418
419   [true, false].each do |visible|
420     test "setup new user with ActivatedUsersAreVisibleToOthers=#{visible}" do
421       Rails.configuration.Users.ActivatedUsersAreVisibleToOthers = visible
422       set_user_from_auth :admin
423
424       email = 'foo@example.com'
425
426       user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: email})
427
428       vm = VirtualMachine.create
429
430       response = user.setup(vm_uuid: vm.uuid)
431
432       resp_user = find_obj_in_resp response, 'User'
433       verify_user resp_user, email
434
435       group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
436       verify_link group_perm, 'permission', 'can_write', resp_user[:uuid], groups(:all_users).uuid
437
438       group_perm2 = find_obj_in_resp response, 'Link', 'arvados#user'
439       if visible
440         verify_link group_perm2, 'permission', 'can_read', groups(:all_users).uuid, nil
441       else
442         assert_nil group_perm2
443       end
444
445       vm_perm = find_obj_in_resp response, 'Link', 'arvados#virtualMachine'
446       verify_link vm_perm, 'permission', 'can_login', resp_user[:uuid], vm.uuid
447       assert_equal("foo", vm_perm.properties["username"])
448     end
449   end
450
451   test "setup new user with junk in database" do
452     set_user_from_auth :admin
453
454     email = 'foo@example.com'
455
456     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: email})
457
458     vm = VirtualMachine.create
459
460     response = user.setup(vm_uuid: vm.uuid)
461
462     resp_user = find_obj_in_resp response, 'User'
463     verify_user resp_user, email
464
465     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
466     verify_link group_perm, 'permission', 'can_write', resp_user[:uuid], groups(:all_users).uuid
467
468     vm_perm = find_obj_in_resp response, 'Link', 'arvados#virtualMachine'
469     verify_link vm_perm, 'permission', 'can_login', resp_user[:uuid], vm.uuid
470     assert_equal("foo", vm_perm.properties["username"])
471   end
472
473   test "setup new user in multiple steps" do
474     set_user_from_auth :admin
475
476     email = 'foo@example.com'
477
478     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: email})
479
480     response = user.setup()
481
482     resp_user = find_obj_in_resp response, 'User'
483     verify_user resp_user, email
484
485     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
486     verify_link group_perm, 'permission', 'can_write', resp_user[:uuid], groups(:all_users).uuid
487
488     group_perm2 = find_obj_in_resp response, 'Link', 'arvados#user'
489     verify_link group_perm2, 'permission', 'can_read', groups(:all_users).uuid, nil
490
491     # invoke setup again with a vm_uuid
492     vm = VirtualMachine.create
493
494     response = user.setup(vm_uuid: vm.uuid)
495
496     resp_user = find_obj_in_resp response, 'User', nil
497     verify_user resp_user, email
498     assert_equal user.uuid, resp_user[:uuid], 'expected uuid not found'
499
500     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
501     verify_link group_perm, 'permission', 'can_write', resp_user[:uuid], groups(:all_users).uuid
502
503     vm_perm = find_obj_in_resp response, 'Link', 'arvados#virtualMachine'
504     verify_link vm_perm, 'permission', 'can_login', resp_user[:uuid], vm.uuid
505     assert_equal("foo", vm_perm.properties["username"])
506   end
507
508   def find_obj_in_resp (response_items, object_type, head_kind=nil)
509     return_obj = nil
510     response_items.each { |x|
511       if !x
512         next
513       end
514
515       if object_type == 'User'
516         if ArvadosModel::resource_class_for_uuid(x['uuid']) == User
517           return_obj = x
518           break
519         end
520       else  # looking for a link
521         if ArvadosModel::resource_class_for_uuid(x['head_uuid']).andand.kind == head_kind
522           return_obj = x
523           break
524         end
525       end
526     }
527     return return_obj
528   end
529
530   def verify_user (resp_user, email)
531     assert_not_nil resp_user, 'expected user object'
532     assert_not_nil resp_user['uuid'], 'expected user object'
533     assert_equal email, resp_user['email'], 'expected email not found'
534   end
535
536   def verify_link (link_object, link_class, link_name, tail_uuid, head_uuid)
537     assert_not_nil link_object, "expected link for #{link_class} #{link_name}"
538     assert_not_nil link_object[:uuid],
539         "expected non-nil uuid for link for #{link_class} #{link_name}"
540     assert_equal link_class, link_object[:link_class],
541         "expected link_class not found for #{link_class} #{link_name}"
542     assert_equal link_name, link_object[:name],
543         "expected link_name not found for #{link_class} #{link_name}"
544     assert_equal tail_uuid, link_object[:tail_uuid],
545         "expected tail_uuid not found for #{link_class} #{link_name}"
546     if head_uuid
547       assert_equal head_uuid, link_object[:head_uuid],
548           "expected head_uuid not found for #{link_class} #{link_name}"
549     end
550   end
551
552   def create_user_and_verify_setup_and_notifications (active, new_user_recipients, inactive_recipients, email, expect_username)
553     Rails.configuration.Users.NewUserNotificationRecipients = new_user_recipients
554     Rails.configuration.Users.NewInactiveUserNotificationRecipients = inactive_recipients
555
556     ActionMailer::Base.deliveries = []
557
558     can_setup = (Rails.configuration.Users.AutoSetupNewUsers and
559                  (not expect_username.nil?))
560
561     user = User.new
562     user.first_name = "first_name_for_newly_created_user"
563     user.email = email
564     user.is_active = active
565     user.save!
566     assert_equal(expect_username, user.username)
567
568     # check user setup
569     verify_link_exists(Rails.configuration.Users.AutoSetupNewUsers || active,
570                        groups(:all_users).uuid, user.uuid,
571                        "permission", "can_write")
572
573     # Check for VM login.
574     if (auto_vm_uuid = Rails.configuration.Users.AutoSetupNewUsersWithVmUUID) != ""
575       verify_link_exists(can_setup, auto_vm_uuid, user.uuid,
576                          "permission", "can_login", "username", expect_username)
577     end
578
579     # check email notifications
580     new_user_email = nil
581     new_inactive_user_email = nil
582
583     new_user_email_subject = "#{Rails.configuration.Users.EmailSubjectPrefix}New user created notification"
584     if Rails.configuration.Users.AutoSetupNewUsers
585       new_user_email_subject = (expect_username or active) ?
586                                  "#{Rails.configuration.Users.EmailSubjectPrefix}New user created and setup notification" :
587                                  "#{Rails.configuration.Users.EmailSubjectPrefix}New user created, but not setup notification"
588     end
589
590     ActionMailer::Base.deliveries.each do |d|
591       if d.subject == new_user_email_subject then
592         new_user_email = d
593       elsif d.subject == "#{Rails.configuration.Users.EmailSubjectPrefix}New inactive user notification" then
594         new_inactive_user_email = d
595       end
596     end
597
598     # both active and inactive user creations should result in new user creation notification mails,
599     # if the new user email recipients config parameter is set
600     if not new_user_recipients.empty? then
601       assert_not_nil new_user_email, 'Expected new user email after setup'
602       assert_equal Rails.configuration.Users.UserNotifierEmailFrom, new_user_email.from[0]
603       assert_equal new_user_recipients.stringify_keys.keys.first, new_user_email.to[0]
604       assert_equal new_user_email_subject, new_user_email.subject
605     else
606       assert_nil new_user_email, 'Did not expect new user email after setup'
607     end
608
609     if not active
610       if not inactive_recipients.empty? then
611         assert_not_nil new_inactive_user_email, 'Expected new inactive user email after setup'
612         assert_equal Rails.configuration.Users.UserNotifierEmailFrom, new_inactive_user_email.from[0]
613         assert_equal inactive_recipients.stringify_keys.keys.first, new_inactive_user_email.to[0]
614         assert_equal "#{Rails.configuration.Users.EmailSubjectPrefix}New inactive user notification", new_inactive_user_email.subject
615       else
616         assert_nil new_inactive_user_email, 'Did not expect new inactive user email after setup'
617       end
618     else
619       assert_nil new_inactive_user_email, 'Expected no inactive user email after setting up active user'
620     end
621     ActionMailer::Base.deliveries = []
622   end
623
624   def verify_link_exists link_exists, head_uuid, tail_uuid, link_class, link_name, property_name=nil, property_value=nil
625     all_links = Link.where(head_uuid: head_uuid,
626                            tail_uuid: tail_uuid,
627                            link_class: link_class,
628                            name: link_name)
629     assert_equal link_exists, all_links.any?, "Link#{' not' if link_exists} found for #{link_name} #{link_class} #{property_value}"
630     if link_exists && property_name && property_value
631       all_links.each do |link|
632         assert_equal true, all_links.first.properties[property_name].start_with?(property_value), 'Property not found in link'
633       end
634     end
635   end
636
637   def assert_update_success(old_uuid:, new_uuid:, expect_owned_objects: true)
638     [[User, :uuid],
639      [Link, :head_uuid],
640      [Link, :tail_uuid],
641      [Group, :owner_uuid],
642      [Collection, :owner_uuid],
643     ].each do |klass, attr|
644       assert_empty klass.where(attr => old_uuid)
645       if klass == User || expect_owned_objects
646         assert_not_empty klass.where(attr => new_uuid)
647       end
648     end
649   end
650
651   test "lookup user by email" do
652     u = User.register({"email" => "active-user@arvados.local", "identity_url" => "different-identity-url"})
653     active = User.find_by_uuid(users(:active).uuid)
654     assert_equal active.uuid, u.uuid
655     assert_equal "active-user@arvados.local", active.email
656     # identity_url is not updated
657     assert_equal "https://active-user.openid.local", active.identity_url
658   end
659
660   test "lookup user by alternate email" do
661     # register method will find that active-user@arvados.local already
662     # exists and return existing 'active' user.
663     u = User.register({"email" => "user@parent-company.com",
664                        "alternate_emails" => ["active-user@arvados.local"],
665                        "identity_url" => "different-identity-url"})
666     active = User.find_by_uuid(users(:active).uuid)
667     assert_equal active.uuid, u.uuid
668
669     # email should be updated
670     assert_equal "user@parent-company.com", active.email
671
672     # identity_url is not updated
673     assert_equal "https://active-user.openid.local", active.identity_url
674   end
675
676   test "register new user" do
677     u = User.register({"email" => "never-before-seen-user@arvados.local",
678                        "identity_url" => "different-identity-url",
679                        "first_name" => "Robert",
680                        "last_name" => "Baratheon",
681                        "username" => "bobby"})
682     nbs = User.find_by_uuid(u.uuid)
683     assert_equal nbs.uuid, u.uuid
684     assert_equal "different-identity-url", nbs.identity_url
685     assert_equal "never-before-seen-user@arvados.local", nbs.email
686     assert_equal false, nbs.is_admin
687     assert_equal false , nbs.is_active
688     assert_equal "bobby", nbs.username
689     assert_equal "Robert", nbs.first_name
690     assert_equal "Baratheon", nbs.last_name
691   end
692
693   test "fail when email address is ambiguous" do
694     User.register({"email" => "active-user@arvados.local"})
695     u = User.register({"email" => "never-before-seen-user@arvados.local"})
696     u.email = "active-user@arvados.local"
697     act_as_system_user do
698       u.save!
699     end
700     assert_raises do
701       User.register({"email" => "active-user@arvados.local"})
702     end
703   end
704
705   test "fail lookup without identifiers" do
706     assert_raises do
707       User.register({"first_name" => "Robert", "last_name" => "Baratheon"})
708     end
709     assert_raises do
710       User.register({"first_name" => "Robert", "last_name" => "Baratheon", "identity_url" => "", "email" => ""})
711     end
712   end
713
714   test "user can update name" do
715     set_user_from_auth :active
716     user = users(:active)
717     user.first_name = "MyNewName"
718     assert user.save
719   end
720
721   test "user cannot update email" do
722     set_user_from_auth :active
723     user = users(:active)
724     user.email = "new-name@example.com"
725     assert_not_allowed { user.save }
726   end
727
728   test "admin can update email" do
729     set_user_from_auth :admin
730     user = users(:active)
731     user.email = "new-name@example.com"
732     assert user.save
733   end
734
735   test "empty identity_url saves as null" do
736     set_user_from_auth :admin
737     user = users(:active)
738     assert user.update(identity_url: '')
739     user.reload
740     assert_nil user.identity_url
741   end
742
743   test "id overflows int32" do
744     uuid = users(:active).uuid
745     ActiveRecord::Base.connection.execute "update users set id=333222111000 where uuid='#{uuid}'"
746     u = User.find_by_uuid(uuid)
747     assert_equal 333222111000, u.id
748   end
749 end