5d25361eda4aafac1ed926fb7c72c3de9f5b835c
[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 = {"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 "updating username updates repository names" do
122     set_user_from_auth :admin
123     user = users(:active)
124     user.username = "newtestname"
125     assert(user.save, "username update failed")
126     {foo: "newtestname/foo", repository2: "newtestname/foo2"}.
127         each_pair do |repo_sym, expect_name|
128       assert_equal(expect_name, repositories(repo_sym).name)
129     end
130   end
131
132   test "admin can clear username when user owns no repositories" do
133     set_user_from_auth :admin
134     user = users(:spectator)
135     user.username = nil
136     assert(user.save)
137     assert_nil(user.username)
138   end
139
140   test "admin can't clear username when user owns repositories" do
141     set_user_from_auth :admin
142     user = users(:active)
143     user.username = nil
144     assert_not_allowed { user.save }
145     refute_empty(user.errors[:username])
146   end
147
148   test "failed username update doesn't change repository names" do
149     set_user_from_auth :admin
150     user = users(:active)
151     user.username = users(:fuse).username
152     assert_not_allowed { user.save }
153     assert_equal("active/foo", repositories(:foo).name)
154   end
155
156   [[false, 'foo@example.com', true, nil],
157    [false, 'bar@example.com', nil, true],
158    [true, 'foo@example.com', true, nil],
159    [true, 'bar@example.com', true, true],
160    [false, '', nil, nil],
161    [true, '', true, nil]
162   ].each do |auto_admin_first_user_config, auto_admin_user_config, foo_should_be_admin, bar_should_be_admin|
163     # In each case, 'foo' is created first, then 'bar', then 'bar2', then 'baz'.
164     test "auto admin with auto_admin_first=#{auto_admin_first_user_config} auto_admin=#{auto_admin_user_config}" do
165
166       if auto_admin_first_user_config
167         # This test requires no admin users exist (except for the system user)
168         act_as_system_user do
169           users(:admin).update_attributes!(is_admin: false)
170         end
171         # need to manually call clear_permissions because we used 'delete' instead of 'destory'
172         # we use delete here because 'destroy' will throw an error
173         #users(:admin).clear_permissions
174         @all_users = User.where("uuid not like '%-000000000000000'").where(:is_admin => true)
175         assert_equal 0, @all_users.count, "No admin users should exist (except for the system user)"
176       end
177
178       Rails.configuration.Users.AutoAdminFirstUser = auto_admin_first_user_config
179       Rails.configuration.Users.AutoAdminUserWithEmail = auto_admin_user_config
180
181       # See if the foo user has is_admin
182       foo = User.new
183       foo.first_name = 'foo'
184       foo.email = 'foo@example.com'
185
186       act_as_system_user do
187         foo.save!
188       end
189
190       foo = User.find(foo.id)   # get the user back
191       assert_equal foo_should_be_admin, foo.is_admin, "is_admin is wrong for user foo"
192       assert_equal 'foo', foo.first_name
193
194       # See if the bar user has is_admin
195       bar = User.new
196       bar.first_name = 'bar'
197       bar.email = 'bar@example.com'
198
199       act_as_system_user do
200         bar.save!
201       end
202
203       bar = User.find(bar.id)   # get the user back
204       assert_equal bar_should_be_admin, bar.is_admin, "is_admin is wrong for user bar"
205       assert_equal 'bar', bar.first_name
206
207       # A subsequent user with the bar@example.com address should never be
208       # elevated to admin
209       bar2 = User.new
210       bar2.first_name = 'bar2'
211       bar2.email = 'bar@example.com'
212
213       act_as_system_user do
214         bar2.save!
215       end
216
217       bar2 = User.find(bar2.id)   # get the user back
218       assert !bar2.is_admin, "is_admin is wrong for user bar2"
219       assert_equal 'bar2', bar2.first_name
220
221       # An ordinary new user should not be elevated to admin
222       baz = User.new
223       baz.first_name = 'baz'
224       baz.email = 'baz@example.com'
225
226       act_as_system_user do
227         baz.save!
228       end
229
230       baz = User.find(baz.id)   # get the user back
231       assert !baz.is_admin
232       assert_equal 'baz', baz.first_name
233
234     end
235   end
236
237   test "check non-admin active user properties" do
238     @active_user = users(:active)     # get the active user
239     assert !@active_user.is_admin, 'is_admin should not be set for a non-admin user'
240     assert @active_user.is_active, 'user should be active'
241     assert @active_user.is_invited, 'is_invited should be set'
242     assert_not_nil @active_user.prefs, "user's preferences should be non-null, but may be size zero"
243     assert (@active_user.can? :read=>"#{@active_user.uuid}"), "user should be able to read own object"
244     assert (@active_user.can? :write=>"#{@active_user.uuid}"), "user should be able to write own object"
245     assert (@active_user.can? :manage=>"#{@active_user.uuid}"), "user should be able to manage own object"
246
247     assert @active_user.groups_i_can(:read).size > 0, "active user should be able read at least one group"
248
249     # non-admin user cannot manage or write other user objects
250     @uninvited_user = users(:inactive_uninvited)     # get the uninvited user
251     assert !(@active_user.can? :read=>"#{@uninvited_user.uuid}")
252     assert !(@active_user.can? :write=>"#{@uninvited_user.uuid}")
253     assert !(@active_user.can? :manage=>"#{@uninvited_user.uuid}")
254   end
255
256   test "check admin user properties" do
257     @admin_user = users(:admin)     # get the admin user
258     assert @admin_user.is_admin, 'is_admin should be set for admin user'
259     assert @admin_user.is_active, 'admin user cannot be inactive'
260     assert @admin_user.is_invited, 'is_invited should be set'
261     assert_not_nil @admin_user.uuid.size, "user's uuid should be non-null"
262     assert_not_nil @admin_user.prefs, "user's preferences should be non-null, but may be size zero"
263     assert @admin_user.identity_url.size > 0, "user's identity url is expected"
264     assert @admin_user.can? :read=>"#{@admin_user.uuid}"
265     assert @admin_user.can? :write=>"#{@admin_user.uuid}"
266     assert @admin_user.can? :manage=>"#{@admin_user.uuid}"
267
268     assert @admin_user.groups_i_can(:read).size > 0, "admin active user should be able read at least one group"
269     assert @admin_user.groups_i_can(:write).size > 0, "admin active user should be able write to at least one group"
270     assert @admin_user.groups_i_can(:manage).size > 0, "admin active user should be able manage at least one group"
271
272     # admin user can also write or manage other users
273     @uninvited_user = users(:inactive_uninvited)     # get the uninvited user
274     assert @admin_user.can? :read=>"#{@uninvited_user.uuid}"
275     assert @admin_user.can? :write=>"#{@uninvited_user.uuid}"
276     assert @admin_user.can? :manage=>"#{@uninvited_user.uuid}"
277   end
278
279   test "check inactive and uninvited user properties" do
280     @uninvited_user = users(:inactive_uninvited)     # get the uninvited user
281     assert !@uninvited_user.is_admin, 'is_admin should not be set for a non-admin user'
282     assert !@uninvited_user.is_active, 'user should be inactive'
283     assert !@uninvited_user.is_invited, 'is_invited should not be set'
284     assert @uninvited_user.can? :read=>"#{@uninvited_user.uuid}"
285     assert @uninvited_user.can? :write=>"#{@uninvited_user.uuid}"
286     assert @uninvited_user.can? :manage=>"#{@uninvited_user.uuid}"
287
288     assert_equal(@uninvited_user.groups_i_can(:read).sort,
289                  [@uninvited_user.uuid, groups(:anonymous_group).uuid].sort)
290     assert_equal(@uninvited_user.groups_i_can(:write),
291                  [@uninvited_user.uuid])
292     assert_equal(@uninvited_user.groups_i_can(:manage),
293                  [@uninvited_user.uuid])
294   end
295
296   test "find user method checks" do
297     User.all.each do |user|
298       assert_not_nil user.uuid, "non-null uuid expected for " + user.full_name
299     end
300
301     user = users(:active)     # get the active user
302
303     found_user = User.find(user.id)   # find a user by the row id
304
305     assert_equal found_user.full_name, user.first_name + ' ' + user.last_name
306     assert_equal found_user.identity_url, user.identity_url
307   end
308
309   test "full name should not contain spurious whitespace" do
310     set_user_from_auth :admin
311
312     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: 'foo@example.com' })
313
314     assert_equal '', user.full_name
315
316     user.first_name = 'John'
317     user.last_name = 'Smith'
318
319     assert_equal user.first_name + ' ' + user.last_name, user.full_name
320   end
321
322   test "create new user" do
323     set_user_from_auth :admin
324
325     @all_users = User.all.to_a
326
327     user = User.new
328     user.first_name = "first_name_for_newly_created_user"
329     user.save
330
331     # verify there is one extra user in the db now
332     assert_equal @all_users.size+1, User.all.count
333
334     user = User.find(user.id)   # get the user back
335     assert_equal(user.first_name, 'first_name_for_newly_created_user')
336     assert_not_nil user.uuid, 'uuid should be set for newly created user'
337     assert_nil user.email, 'email should be null for newly created user, because it was not passed in'
338     assert_nil user.identity_url, 'identity_url should be null for newly created user, because it was not passed in'
339
340     user.first_name = 'first_name_for_newly_created_user_updated'
341     user.save
342     user = User.find(user.id)   # get the user back
343     assert_equal(user.first_name, 'first_name_for_newly_created_user_updated')
344   end
345
346   test "create new user with notifications" do
347     set_user_from_auth :admin
348
349     create_user_and_verify_setup_and_notifications true, {'active-notify-address@example.com'=>{}}, {'inactive-notify-address@example.com'=>{}}, nil, nil
350     create_user_and_verify_setup_and_notifications true, {'active-notify-address@example.com'=>{}}, {}, nil, nil
351     create_user_and_verify_setup_and_notifications true, {}, [], nil, nil
352     create_user_and_verify_setup_and_notifications false, {'active-notify-address@example.com'=>{}}, {'inactive-notify-address@example.com'=>{}}, nil, nil
353     create_user_and_verify_setup_and_notifications false, {}, {'inactive-notify-address@example.com'=>{}}, nil, nil
354     create_user_and_verify_setup_and_notifications false, {}, {}, nil, nil
355   end
356
357   [
358     # Easy inactive user tests.
359     [false, {}, {}, "inactive-none@example.com", false, false, "inactivenone"],
360     [false, {}, {}, "inactive-vm@example.com", true, false, "inactivevm"],
361     [false, {}, {}, "inactive-repo@example.com", false, true, "inactiverepo"],
362     [false, {}, {}, "inactive-both@example.com", true, true, "inactiveboth"],
363
364     # Easy active user tests.
365     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "active-none@example.com", false, false, "activenone"],
366     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "active-vm@example.com", true, false, "activevm"],
367     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "active-repo@example.com", false, true, "activerepo"],
368     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "active-both@example.com", true, true, "activeboth"],
369
370     # Test users with malformed e-mail addresses.
371     [false, {}, {}, nil, true, true, nil],
372     [false, {}, {}, "arvados", true, true, nil],
373     [false, {}, {}, "@example.com", true, true, nil],
374     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "*!*@example.com", true, false, nil],
375     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "*!*@example.com", false, false, nil],
376
377     # Test users with various username transformations.
378     [false, {}, {}, "arvados@example.com", false, false, "arvados2"],
379     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "arvados@example.com", false, false, "arvados2"],
380     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "root@example.com", true, false, "root2"],
381     [false, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "root@example.com", true, false, "root2"],
382     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "roo_t@example.com", false, true, "root2"],
383     [false, {}, {}, "^^incorrect_format@example.com", true, true, "incorrectformat"],
384     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "&4a_d9.@example.com", true, true, "ad9"],
385     [true, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "&4a_d9.@example.com", false, false, "ad9"],
386     [false, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "&4a_d9.@example.com", true, true, "ad9"],
387     [false, {"active-notify@example.com"=>{}}, {"inactive-notify@example.com"=>{}}, "&4a_d9.@example.com", false, false, "ad9"],
388   ].each do |active, new_user_recipients, inactive_recipients, email, auto_setup_vm, auto_setup_repo, expect_username|
389     test "create new user with auto setup #{active} #{email} #{auto_setup_vm} #{auto_setup_repo}" do
390       set_user_from_auth :admin
391
392       Rails.configuration.Users.AutoSetupNewUsers = true
393
394       if auto_setup_vm
395         Rails.configuration.Users.AutoSetupNewUsersWithVmUUID = virtual_machines(:testvm)['uuid']
396       else
397         Rails.configuration.Users.AutoSetupNewUsersWithVmUUID = ""
398       end
399
400       Rails.configuration.Users.AutoSetupNewUsersWithRepository = auto_setup_repo
401
402       create_user_and_verify_setup_and_notifications active, new_user_recipients, inactive_recipients, email, expect_username
403     end
404   end
405
406   test "update existing user" do
407     set_user_from_auth :active    # set active user as current user
408
409     @active_user = users(:active)     # get the active user
410
411     @active_user.first_name = "first_name_changed"
412     @active_user.save
413
414     @active_user = User.find(@active_user.id)   # get the user back
415     assert_equal(@active_user.first_name, 'first_name_changed')
416
417     # admin user also should be able to update the "active" user info
418     set_user_from_auth :admin # set admin user as current user
419     @active_user.first_name = "first_name_changed_by_admin_for_active_user"
420     @active_user.save
421
422     @active_user = User.find(@active_user.id)   # get the user back
423     assert_equal(@active_user.first_name, 'first_name_changed_by_admin_for_active_user')
424   end
425
426   test "delete a user and verify" do
427     @active_user = users(:active)     # get the active user
428     active_user_uuid = @active_user.uuid
429
430     set_user_from_auth :admin
431     @active_user.delete
432
433     found_deleted_user = false
434     User.all.each do |user|
435       if user.uuid == active_user_uuid
436         found_deleted_user = true
437         break
438       end
439     end
440     assert !found_deleted_user, "found deleted user: "+active_user_uuid
441
442   end
443
444   test "create new user as non-admin user" do
445     set_user_from_auth :active
446     assert_not_allowed { User.new.save }
447   end
448
449   test "setup new user" do
450     set_user_from_auth :admin
451
452     email = 'foo@example.com'
453
454     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: email})
455
456     vm = VirtualMachine.create
457
458     response = user.setup(repo_name: 'foo/testrepo',
459                           vm_uuid: vm.uuid)
460
461     resp_user = find_obj_in_resp response, 'User'
462     verify_user resp_user, email
463
464     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
465     verify_link group_perm, 'permission', 'can_read', resp_user[:uuid], nil
466
467     repo_perm = find_obj_in_resp response, 'Link', 'arvados#repository'
468     verify_link repo_perm, 'permission', 'can_manage', resp_user[:uuid], nil
469
470     vm_perm = find_obj_in_resp response, 'Link', 'arvados#virtualMachine'
471     verify_link vm_perm, 'permission', 'can_login', resp_user[:uuid], vm.uuid
472     assert_equal("foo", vm_perm.properties["username"])
473   end
474
475   test "setup new user with junk in database" do
476     set_user_from_auth :admin
477
478     email = 'foo@example.com'
479
480     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: email})
481
482     vm = VirtualMachine.create
483
484     # Set up the bogus Link
485     bad_uuid = 'zzzzz-tpzed-xyzxyzxyzxyzxyz'
486
487     resp_link = Link.create ({tail_uuid: email, link_class: 'permission',
488         name: 'can_login', head_uuid: bad_uuid})
489     resp_link.save(validate: false)
490
491     verify_link resp_link, 'permission', 'can_login', email, bad_uuid
492
493     response = user.setup(repo_name: 'foo/testrepo',
494                           vm_uuid: vm.uuid)
495
496     resp_user = find_obj_in_resp response, 'User'
497     verify_user resp_user, email
498
499     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
500     verify_link group_perm, 'permission', 'can_read', resp_user[:uuid], nil
501
502     repo_perm = find_obj_in_resp response, 'Link', 'arvados#repository'
503     verify_link repo_perm, 'permission', 'can_manage', resp_user[:uuid], nil
504
505     vm_perm = find_obj_in_resp response, 'Link', 'arvados#virtualMachine'
506     verify_link vm_perm, 'permission', 'can_login', resp_user[:uuid], vm.uuid
507     assert_equal("foo", vm_perm.properties["username"])
508   end
509
510   test "setup new user in multiple steps" do
511     set_user_from_auth :admin
512
513     email = 'foo@example.com'
514
515     user = User.create ({uuid: 'zzzzz-tpzed-abcdefghijklmno', email: email})
516
517     response = user.setup()
518
519     resp_user = find_obj_in_resp response, 'User'
520     verify_user resp_user, email
521
522     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
523     verify_link group_perm, 'permission', 'can_read', resp_user[:uuid], nil
524
525     # invoke setup again with repo_name
526     response = user.setup(repo_name: 'foo/testrepo')
527     resp_user = find_obj_in_resp response, 'User', nil
528     verify_user resp_user, email
529     assert_equal user.uuid, resp_user[:uuid], 'expected uuid not found'
530
531     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
532     verify_link group_perm, 'permission', 'can_read', resp_user[:uuid], nil
533
534     repo_perm = find_obj_in_resp response, 'Link', 'arvados#repository'
535     verify_link repo_perm, 'permission', 'can_manage', resp_user[:uuid], nil
536
537     # invoke setup again with a vm_uuid
538     vm = VirtualMachine.create
539
540     response = user.setup(repo_name: 'foo/testrepo',
541                           vm_uuid: vm.uuid)
542
543     resp_user = find_obj_in_resp response, 'User', nil
544     verify_user resp_user, email
545     assert_equal user.uuid, resp_user[:uuid], 'expected uuid not found'
546
547     group_perm = find_obj_in_resp response, 'Link', 'arvados#group'
548     verify_link group_perm, 'permission', 'can_read', resp_user[:uuid], nil
549
550     repo_perm = find_obj_in_resp response, 'Link', 'arvados#repository'
551     verify_link repo_perm, 'permission', 'can_manage', resp_user[:uuid], nil
552
553     vm_perm = find_obj_in_resp response, 'Link', 'arvados#virtualMachine'
554     verify_link vm_perm, 'permission', 'can_login', resp_user[:uuid], vm.uuid
555     assert_equal("foo", vm_perm.properties["username"])
556   end
557
558   def find_obj_in_resp (response_items, object_type, head_kind=nil)
559     return_obj = nil
560     response_items.each { |x|
561       if !x
562         next
563       end
564
565       if object_type == 'User'
566         if ArvadosModel::resource_class_for_uuid(x['uuid']) == User
567           return_obj = x
568           break
569         end
570       else  # looking for a link
571         if ArvadosModel::resource_class_for_uuid(x['head_uuid']).kind == head_kind
572           return_obj = x
573           break
574         end
575       end
576     }
577     return return_obj
578   end
579
580   def verify_user (resp_user, email)
581     assert_not_nil resp_user, 'expected user object'
582     assert_not_nil resp_user['uuid'], 'expected user object'
583     assert_equal email, resp_user['email'], 'expected email not found'
584
585   end
586
587   def verify_link (link_object, link_class, link_name, tail_uuid, head_uuid)
588     assert_not_nil link_object, "expected link for #{link_class} #{link_name}"
589     assert_not_nil link_object[:uuid],
590         "expected non-nil uuid for link for #{link_class} #{link_name}"
591     assert_equal link_class, link_object[:link_class],
592         "expected link_class not found for #{link_class} #{link_name}"
593     assert_equal link_name, link_object[:name],
594         "expected link_name not found for #{link_class} #{link_name}"
595     assert_equal tail_uuid, link_object[:tail_uuid],
596         "expected tail_uuid not found for #{link_class} #{link_name}"
597     if head_uuid
598       assert_equal head_uuid, link_object[:head_uuid],
599           "expected head_uuid not found for #{link_class} #{link_name}"
600     end
601   end
602
603   def create_user_and_verify_setup_and_notifications (active, new_user_recipients, inactive_recipients, email, expect_username)
604     Rails.configuration.Users.NewUserNotificationRecipients = new_user_recipients
605     Rails.configuration.Users.NewInactiveUserNotificationRecipients = inactive_recipients
606
607     ActionMailer::Base.deliveries = []
608
609     can_setup = (Rails.configuration.Users.AutoSetupNewUsers and
610                  (not expect_username.nil?))
611     expect_repo_name = "#{expect_username}/#{expect_username}"
612     prior_repo = Repository.where(name: expect_repo_name).first
613
614     user = User.new
615     user.first_name = "first_name_for_newly_created_user"
616     user.email = email
617     user.is_active = active
618     user.save!
619     assert_equal(expect_username, user.username)
620
621     # check user setup
622     verify_link_exists(Rails.configuration.Users.AutoSetupNewUsers || active,
623                        groups(:all_users).uuid, user.uuid,
624                        "permission", "can_read")
625
626     # Check for repository.
627     if named_repo = (prior_repo or
628                      Repository.where(name: expect_repo_name).first)
629       verify_link_exists((can_setup and prior_repo.nil? and
630                           Rails.configuration.Users.AutoSetupNewUsersWithRepository),
631                          named_repo.uuid, user.uuid, "permission", "can_manage")
632     end
633     # Check for VM login.
634     if (auto_vm_uuid = Rails.configuration.Users.AutoSetupNewUsersWithVmUUID) != ""
635       verify_link_exists(can_setup, auto_vm_uuid, user.uuid,
636                          "permission", "can_login", "username", expect_username)
637     end
638
639     # check email notifications
640     new_user_email = nil
641     new_inactive_user_email = nil
642
643     new_user_email_subject = "#{Rails.configuration.Users.EmailSubjectPrefix}New user created notification"
644     if Rails.configuration.Users.AutoSetupNewUsers
645       new_user_email_subject = (expect_username or active) ?
646                                  "#{Rails.configuration.Users.EmailSubjectPrefix}New user created and setup notification" :
647                                  "#{Rails.configuration.Users.EmailSubjectPrefix}New user created, but not setup notification"
648     end
649
650     ActionMailer::Base.deliveries.each do |d|
651       if d.subject == new_user_email_subject then
652         new_user_email = d
653       elsif d.subject == "#{Rails.configuration.Users.EmailSubjectPrefix}New inactive user notification" then
654         new_inactive_user_email = d
655       end
656     end
657
658     # both active and inactive user creations should result in new user creation notification mails,
659     # if the new user email recipients config parameter is set
660     if not new_user_recipients.empty? then
661       assert_not_nil new_user_email, 'Expected new user email after setup'
662       assert_equal Rails.configuration.Users.UserNotifierEmailFrom, new_user_email.from[0]
663       assert_equal new_user_recipients.keys.first, new_user_email.to[0]
664       assert_equal new_user_email_subject, new_user_email.subject
665     else
666       assert_nil new_user_email, 'Did not expect new user email after setup'
667     end
668
669     if not active
670       if not inactive_recipients.empty? then
671         assert_not_nil new_inactive_user_email, 'Expected new inactive user email after setup'
672         assert_equal Rails.configuration.Users.UserNotifierEmailFrom, new_inactive_user_email.from[0]
673         assert_equal inactive_recipients.keys.first, new_inactive_user_email.to[0]
674         assert_equal "#{Rails.configuration.Users.EmailSubjectPrefix}New inactive user notification", new_inactive_user_email.subject
675       else
676         assert_nil new_inactive_user_email, 'Did not expect new inactive user email after setup'
677       end
678     else
679       assert_nil new_inactive_user_email, 'Expected no inactive user email after setting up active user'
680     end
681     ActionMailer::Base.deliveries = []
682
683   end
684
685   def verify_link_exists link_exists, head_uuid, tail_uuid, link_class, link_name, property_name=nil, property_value=nil
686     all_links = Link.where(head_uuid: head_uuid,
687                            tail_uuid: tail_uuid,
688                            link_class: link_class,
689                            name: link_name)
690     assert_equal link_exists, all_links.any?, "Link #{'not' if link_exists} found for #{link_name} #{link_class} #{property_value}"
691     if link_exists && property_name && property_value
692       all_links.each do |link|
693         assert_equal true, all_links.first.properties[property_name].start_with?(property_value), 'Property not found in link'
694       end
695     end
696   end
697
698   [
699     [:active, 'zzzzz-borkd-abcde12345abcde'],
700     [:active, 'zzzzz-j7d0g-abcde12345abcde'],
701     [:active, 'zzzzz-tpzed-borkd'],
702     [:system_user, 'zzzzz-tpzed-abcde12345abcde'],
703     [:anonymous, 'zzzzz-tpzed-abcde12345abcde'],
704   ].each do |fixture, new_uuid|
705     test "disallow update_uuid #{fixture} -> #{new_uuid}" do
706       u = users(fixture)
707       orig_uuid = u.uuid
708       act_as_system_user do
709         assert_raises do
710           u.update_uuid(new_uuid: new_uuid)
711         end
712       end
713       # "Successfully aborted orig->new" outcome looks the same as
714       # "successfully updated new->orig".
715       assert_update_success(old_uuid: new_uuid,
716                             new_uuid: orig_uuid,
717                             expect_owned_objects: fixture == :active)
718     end
719   end
720
721   [:active, :spectator, :admin].each do |target|
722     test "update_uuid on #{target} as non-admin user" do
723       act_as_user users(:active) do
724         assert_raises(ArvadosModel::PermissionDeniedError) do
725           users(target).update_uuid(new_uuid: 'zzzzz-tpzed-abcde12345abcde')
726         end
727       end
728     end
729   end
730
731   test "update_uuid to existing uuid" do
732     u = users(:active)
733     orig_uuid = u.uuid
734     new_uuid = users(:admin).uuid
735     act_as_system_user do
736       assert_raises do
737         u.update_uuid(new_uuid: new_uuid)
738       end
739     end
740     u.reload
741     assert_equal u.uuid, orig_uuid
742     assert_not_empty Collection.where(owner_uuid: orig_uuid)
743     assert_not_empty Group.where(owner_uuid: orig_uuid)
744   end
745
746   [
747     [:active, 'zbbbb-tpzed-abcde12345abcde'],
748     [:active, 'zzzzz-tpzed-abcde12345abcde'],
749     [:admin, 'zbbbb-tpzed-abcde12345abcde'],
750     [:admin, 'zzzzz-tpzed-abcde12345abcde'],
751   ].each do |fixture, new_uuid|
752     test "update_uuid #{fixture} to unused uuid #{new_uuid}" do
753       u = users(fixture)
754       orig_uuid = u.uuid
755       act_as_system_user do
756         u.update_uuid(new_uuid: new_uuid)
757       end
758       assert_update_success(old_uuid: orig_uuid,
759                             new_uuid: new_uuid,
760                             expect_owned_objects: fixture == :active)
761     end
762   end
763
764   def assert_update_success(old_uuid:, new_uuid:, expect_owned_objects: true)
765     [[User, :uuid],
766      [Link, :head_uuid],
767      [Link, :tail_uuid],
768      [Group, :owner_uuid],
769      [Collection, :owner_uuid],
770     ].each do |klass, attr|
771       assert_empty klass.where(attr => old_uuid)
772       if klass == User || expect_owned_objects
773         assert_not_empty klass.where(attr => new_uuid)
774       end
775     end
776   end
777
778   test "lookup user by email" do
779     u = User.register({"email" => "active-user@arvados.local", "identity_url" => "different-identity-url"})
780     active = User.find_by_uuid(users(:active).uuid)
781     assert_equal active.uuid, u.uuid
782     assert_equal "active-user@arvados.local", active.email
783     # identity_url is not updated
784     assert_equal "https://active-user.openid.local", active.identity_url
785   end
786
787   test "lookup user by alternate email" do
788     # register method will find that active-user@arvados.local already
789     # exists and return existing 'active' user.
790     u = User.register({"email" => "user@parent-company.com",
791                        "alternate_emails" => ["active-user@arvados.local"],
792                        "identity_url" => "different-identity-url"})
793     active = User.find_by_uuid(users(:active).uuid)
794     assert_equal active.uuid, u.uuid
795
796     # email should be updated
797     assert_equal "user@parent-company.com", active.email
798
799     # identity_url is not updated
800     assert_equal "https://active-user.openid.local", active.identity_url
801   end
802
803   test "register new user" do
804     u = User.register({"email" => "never-before-seen-user@arvados.local",
805                        "identity_url" => "different-identity-url",
806                        "first_name" => "Robert",
807                        "last_name" => "Baratheon",
808                        "username" => "bobby"})
809     nbs = User.find_by_uuid(u.uuid)
810     assert_equal nbs.uuid, u.uuid
811     assert_equal "different-identity-url", nbs.identity_url
812     assert_equal "never-before-seen-user@arvados.local", nbs.email
813     assert_equal false, nbs.is_admin
814     assert_equal false , nbs.is_active
815     assert_equal "bobby", nbs.username
816     assert_equal "Robert", nbs.first_name
817     assert_equal "Baratheon", nbs.last_name
818   end
819
820   test "fail when email address is ambiguous" do
821     User.register({"email" => "active-user@arvados.local"})
822     u = User.register({"email" => "never-before-seen-user@arvados.local"})
823     u.email = "active-user@arvados.local"
824     act_as_system_user do
825       u.save!
826     end
827     assert_raises do
828       User.register({"email" => "active-user@arvados.local"})
829     end
830   end
831
832   test "fail lookup without identifiers" do
833     assert_raises do
834       User.register({"first_name" => "Robert", "last_name" => "Baratheon"})
835     end
836     assert_raises do
837       User.register({"first_name" => "Robert", "last_name" => "Baratheon", "identity_url" => "", "email" => ""})
838     end
839   end
840
841   test "user can update name" do
842     set_user_from_auth :active
843     user = users(:active)
844     user.first_name = "MyNewName"
845     assert user.save
846   end
847
848   test "user cannot update email" do
849     set_user_from_auth :active
850     user = users(:active)
851     user.email = "new-name@example.com"
852     assert_not_allowed { user.save }
853   end
854
855   test "admin can update email" do
856     set_user_from_auth :admin
857     user = users(:active)
858     user.email = "new-name@example.com"
859     assert user.save
860   end
861
862 end