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