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