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