]> BookStack Code Mirror - bookstack/blob - tests/Auth/LdapTest.php
Updated tests to use ssddanbrown/asserthtml package
[bookstack] / tests / Auth / LdapTest.php
1 <?php
2
3 namespace Tests\Auth;
4
5 use BookStack\Auth\Access\Ldap;
6 use BookStack\Auth\Access\LdapService;
7 use BookStack\Auth\Role;
8 use BookStack\Auth\User;
9 use Illuminate\Testing\TestResponse;
10 use Mockery\MockInterface;
11 use Tests\TestCase;
12
13 class LdapTest extends TestCase
14 {
15     /**
16      * @var MockInterface
17      */
18     protected $mockLdap;
19
20     protected $mockUser;
21     protected $resourceId = 'resource-test';
22
23     protected function setUp(): void
24     {
25         parent::setUp();
26         if (!defined('LDAP_OPT_REFERRALS')) {
27             define('LDAP_OPT_REFERRALS', 1);
28         }
29         config()->set([
30             'auth.method'                          => 'ldap',
31             'auth.defaults.guard'                  => 'ldap',
32             'services.ldap.base_dn'                => 'dc=ldap,dc=local',
33             'services.ldap.email_attribute'        => 'mail',
34             'services.ldap.display_name_attribute' => 'cn',
35             'services.ldap.id_attribute'           => 'uid',
36             'services.ldap.user_to_groups'         => false,
37             'services.ldap.version'                => '3',
38             'services.ldap.user_filter'            => '(&(uid=${user}))',
39             'services.ldap.follow_referrals'       => false,
40             'services.ldap.tls_insecure'           => false,
41             'services.ldap.thumbnail_attribute'    => null,
42         ]);
43         $this->mockLdap = \Mockery::mock(Ldap::class);
44         $this->app[Ldap::class] = $this->mockLdap;
45         $this->mockUser = User::factory()->make();
46     }
47
48     protected function runFailedAuthLogin()
49     {
50         $this->commonLdapMocks(1, 1, 1, 1, 1);
51         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
52             ->andReturn(['count' => 0]);
53         $this->post('/login', ['username' => 'timmyjenkins', 'password' => 'cattreedog']);
54     }
55
56     protected function mockEscapes($times = 1)
57     {
58         $this->mockLdap->shouldReceive('escape')->times($times)->andReturnUsing(function ($val) {
59             return ldap_escape($val);
60         });
61     }
62
63     protected function mockExplodes($times = 1)
64     {
65         $this->mockLdap->shouldReceive('explodeDn')->times($times)->andReturnUsing(function ($dn, $withAttrib) {
66             return ldap_explode_dn($dn, $withAttrib);
67         });
68     }
69
70     protected function mockUserLogin(?string $email = null): TestResponse
71     {
72         return $this->post('/login', [
73             'username' => $this->mockUser->name,
74             'password' => $this->mockUser->password,
75         ] + ($email ? ['email' => $email] : []));
76     }
77
78     /**
79      * Set LDAP method mocks for things we commonly call without altering.
80      */
81     protected function commonLdapMocks(int $connects = 1, int $versions = 1, int $options = 2, int $binds = 4, int $escapes = 2, int $explodes = 0)
82     {
83         $this->mockLdap->shouldReceive('connect')->times($connects)->andReturn($this->resourceId);
84         $this->mockLdap->shouldReceive('setVersion')->times($versions);
85         $this->mockLdap->shouldReceive('setOption')->times($options);
86         $this->mockLdap->shouldReceive('bind')->times($binds)->andReturn(true);
87         $this->mockEscapes($escapes);
88         $this->mockExplodes($explodes);
89     }
90
91     public function test_login()
92     {
93         $this->commonLdapMocks(1, 1, 2, 4, 2);
94         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2)
95             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
96             ->andReturn(['count' => 1, 0 => [
97                 'uid' => [$this->mockUser->name],
98                 'cn'  => [$this->mockUser->name],
99                 'dn'  => ['dc=test' . config('services.ldap.base_dn')],
100             ]]);
101
102         $resp = $this->mockUserLogin();
103         $resp->assertRedirect('/login');
104         $resp = $this->followRedirects($resp);
105         $resp->assertSee('Please enter an email to use for this account.');
106         $resp->assertSee($this->mockUser->name);
107
108         $resp = $this->followingRedirects()->mockUserLogin($this->mockUser->email);
109         $this->withHtml($resp)->assertElementExists('#home-default');
110         $resp->assertSee($this->mockUser->name);
111         $this->assertDatabaseHas('users', [
112             'email'            => $this->mockUser->email,
113             'email_confirmed'  => false,
114             'external_auth_id' => $this->mockUser->name,
115         ]);
116     }
117
118     public function test_email_domain_restriction_active_on_new_ldap_login()
119     {
120         $this->setSettings([
121             'registration-restrict' => 'testing.com',
122         ]);
123
124         $this->commonLdapMocks(1, 1, 2, 4, 2);
125         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2)
126             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
127             ->andReturn(['count' => 1, 0 => [
128                 'uid' => [$this->mockUser->name],
129                 'cn'  => [$this->mockUser->name],
130                 'dn'  => ['dc=test' . config('services.ldap.base_dn')],
131             ]]);
132
133         $resp = $this->mockUserLogin();
134         $resp->assertRedirect('/login');
135         $this->followRedirects($resp)->assertSee('Please enter an email to use for this account.');
136
137         $email = '[email protected]';
138         $resp = $this->mockUserLogin($email);
139         $resp->assertRedirect('/login');
140         $this->followRedirects($resp)->assertSee('That email domain does not have access to this application');
141
142         $this->assertDatabaseMissing('users', ['email' => $email]);
143     }
144
145     public function test_login_works_when_no_uid_provided_by_ldap_server()
146     {
147         $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn');
148
149         $this->commonLdapMocks(1, 1, 1, 2, 1);
150         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
151             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
152             ->andReturn(['count' => 1, 0 => [
153                 'cn'   => [$this->mockUser->name],
154                 'dn'   => $ldapDn,
155                 'mail' => [$this->mockUser->email],
156             ]]);
157
158         $resp = $this->mockUserLogin();
159         $resp->assertRedirect('/');
160         $this->followRedirects($resp)->assertSee($this->mockUser->name);
161         $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => $ldapDn]);
162     }
163
164     public function test_a_custom_uid_attribute_can_be_specified_and_is_used_properly()
165     {
166         config()->set(['services.ldap.id_attribute' => 'my_custom_id']);
167
168         $this->commonLdapMocks(1, 1, 1, 2, 1);
169         $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn');
170         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
171             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
172             ->andReturn(['count' => 1, 0 => [
173                 'cn'           => [$this->mockUser->name],
174                 'dn'           => $ldapDn,
175                 'my_custom_id' => ['cooluser456'],
176                 'mail'         => [$this->mockUser->email],
177             ]]);
178
179         $resp = $this->mockUserLogin();
180         $resp->assertRedirect('/');
181         $this->followRedirects($resp)->assertSee($this->mockUser->name);
182         $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => 'cooluser456']);
183     }
184
185     public function test_initial_incorrect_credentials()
186     {
187         $this->commonLdapMocks(1, 1, 1, 0, 1);
188         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
189             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
190             ->andReturn(['count' => 1, 0 => [
191                 'uid' => [$this->mockUser->name],
192                 'cn'  => [$this->mockUser->name],
193                 'dn'  => ['dc=test' . config('services.ldap.base_dn')],
194             ]]);
195         $this->mockLdap->shouldReceive('bind')->times(2)->andReturn(true, false);
196
197         $resp = $this->mockUserLogin();
198         $resp->assertRedirect('/login');
199         $this->followRedirects($resp)->assertSee('These credentials do not match our records.');
200         $this->assertDatabaseMissing('users', ['external_auth_id' => $this->mockUser->name]);
201     }
202
203     public function test_login_not_found_username()
204     {
205         $this->commonLdapMocks(1, 1, 1, 1, 1);
206         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
207             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
208             ->andReturn(['count' => 0]);
209
210         $resp = $this->mockUserLogin();
211         $resp->assertRedirect('/login');
212         $this->followRedirects($resp)->assertSee('These credentials do not match our records.');
213         $this->assertDatabaseMissing('users', ['external_auth_id' => $this->mockUser->name]);
214     }
215
216     public function test_create_user_form()
217     {
218         $userForm = $this->asAdmin()->get('/settings/users/create');
219         $userForm->assertDontSee('Password');
220
221         $save = $this->post('/settings/users/create', [
222             'name'  => $this->mockUser->name,
223             'email' => $this->mockUser->email,
224         ]);
225         $save->assertSessionHasErrors(['external_auth_id' => 'The external auth id field is required.']);
226
227         $save = $this->post('/settings/users/create', [
228             'name'             => $this->mockUser->name,
229             'email'            => $this->mockUser->email,
230             'external_auth_id' => $this->mockUser->name,
231         ]);
232         $save->assertRedirect('/settings/users');
233         $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'external_auth_id' => $this->mockUser->name, 'email_confirmed' => true]);
234     }
235
236     public function test_user_edit_form()
237     {
238         $editUser = $this->getNormalUser();
239         $editPage = $this->asAdmin()->get("/settings/users/{$editUser->id}");
240         $editPage->assertSee('Edit User');
241         $editPage->assertDontSee('Password');
242
243         $update = $this->put("/settings/users/{$editUser->id}", [
244             'name'             => $editUser->name,
245             'email'            => $editUser->email,
246             'external_auth_id' => 'test_auth_id',
247         ]);
248         $update->assertRedirect('/settings/users');
249         $this->assertDatabaseHas('users', ['email' => $editUser->email, 'external_auth_id' => 'test_auth_id']);
250     }
251
252     public function test_registration_disabled()
253     {
254         $resp = $this->followingRedirects()->get('/register');
255         $this->withHtml($resp)->assertElementContains('#content', 'Log In');
256     }
257
258     public function test_non_admins_cannot_change_auth_id()
259     {
260         $testUser = $this->getNormalUser();
261         $this->actingAs($testUser)
262             ->get('/settings/users/' . $testUser->id)
263             ->assertDontSee('External Authentication');
264     }
265
266     public function test_login_maps_roles_and_retains_existing_roles()
267     {
268         $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']);
269         $roleToReceive2 = Role::factory()->create(['display_name' => 'LdapTester Second']);
270         $existingRole = Role::factory()->create(['display_name' => 'ldaptester-existing']);
271         $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save();
272         $this->mockUser->attachRole($existingRole);
273
274         app('config')->set([
275             'services.ldap.user_to_groups'     => true,
276             'services.ldap.group_attribute'    => 'memberOf',
277             'services.ldap.remove_from_groups' => false,
278         ]);
279
280         $this->commonLdapMocks(1, 1, 4, 5, 4, 6);
281         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(4)
282             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
283             ->andReturn(['count' => 1, 0 => [
284                 'uid'      => [$this->mockUser->name],
285                 'cn'       => [$this->mockUser->name],
286                 'dn'       => ['dc=test' . config('services.ldap.base_dn')],
287                 'mail'     => [$this->mockUser->email],
288                 'memberof' => [
289                     'count' => 2,
290                     0       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
291                     1       => 'cn=ldaptester-second,ou=groups,dc=example,dc=com',
292                 ],
293             ]]);
294
295         $this->mockUserLogin()->assertRedirect('/');
296
297         $user = User::where('email', $this->mockUser->email)->first();
298         $this->assertDatabaseHas('role_user', [
299             'user_id' => $user->id,
300             'role_id' => $roleToReceive->id,
301         ]);
302         $this->assertDatabaseHas('role_user', [
303             'user_id' => $user->id,
304             'role_id' => $roleToReceive2->id,
305         ]);
306         $this->assertDatabaseHas('role_user', [
307             'user_id' => $user->id,
308             'role_id' => $existingRole->id,
309         ]);
310     }
311
312     public function test_login_maps_roles_and_removes_old_roles_if_set()
313     {
314         $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']);
315         $existingRole = Role::factory()->create(['display_name' => 'ldaptester-existing']);
316         $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save();
317         $this->mockUser->attachRole($existingRole);
318
319         app('config')->set([
320             'services.ldap.user_to_groups'     => true,
321             'services.ldap.group_attribute'    => 'memberOf',
322             'services.ldap.remove_from_groups' => true,
323         ]);
324
325         $this->commonLdapMocks(1, 1, 3, 4, 3, 2);
326         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(3)
327             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
328             ->andReturn(['count' => 1, 0 => [
329                 'uid'      => [$this->mockUser->name],
330                 'cn'       => [$this->mockUser->name],
331                 'dn'       => ['dc=test' . config('services.ldap.base_dn')],
332                 'mail'     => [$this->mockUser->email],
333                 'memberof' => [
334                     'count' => 1,
335                     0       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
336                 ],
337             ]]);
338
339         $this->mockUserLogin()->assertRedirect('/');
340
341         $user = User::query()->where('email', $this->mockUser->email)->first();
342         $this->assertDatabaseHas('role_user', [
343             'user_id' => $user->id,
344             'role_id' => $roleToReceive->id,
345         ]);
346         $this->assertDatabaseMissing('role_user', [
347             'user_id' => $user->id,
348             'role_id' => $existingRole->id,
349         ]);
350     }
351
352     public function test_dump_user_groups_shows_group_related_details_as_json()
353     {
354         app('config')->set([
355             'services.ldap.user_to_groups'     => true,
356             'services.ldap.group_attribute'    => 'memberOf',
357             'services.ldap.remove_from_groups' => true,
358             'services.ldap.dump_user_groups'   => true,
359         ]);
360
361         $userResp = ['count' => 1, 0 => [
362             'uid'      => [$this->mockUser->name],
363             'cn'       => [$this->mockUser->name],
364             'dn'       => 'dc=test,' . config('services.ldap.base_dn'),
365             'mail'     => [$this->mockUser->email],
366         ]];
367         $this->commonLdapMocks(1, 1, 4, 5, 4, 2);
368         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(4)
369             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
370             ->andReturn($userResp, ['count' => 1,
371                 0                           => [
372                     'dn'       => 'dc=test,' . config('services.ldap.base_dn'),
373                     'memberof' => [
374                         'count' => 1,
375                         0       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
376                     ],
377                 ],
378             ], [
379                 'count' => 1,
380                 0       => [
381                     'dn'       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
382                     'memberof' => [
383                         'count' => 1,
384                         0       => 'cn=monsters,ou=groups,dc=example,dc=com',
385                     ],
386                 ],
387             ], ['count' => 0]);
388
389         $resp = $this->mockUserLogin();
390         $resp->assertJson([
391             'details_from_ldap' => [
392                 'dn'       => 'dc=test,' . config('services.ldap.base_dn'),
393                 'memberof' => [
394                     0       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
395                     'count' => 1,
396                 ],
397             ],
398             'parsed_direct_user_groups' => [
399                 'ldaptester',
400             ],
401             'parsed_recursive_user_groups' => [
402                 'ldaptester',
403                 'monsters',
404             ],
405         ]);
406     }
407
408     public function test_external_auth_id_visible_in_roles_page_when_ldap_active()
409     {
410         $role = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'ex-auth-a, test-second-param']);
411         $this->asAdmin()->get('/settings/roles/' . $role->id)
412             ->assertSee('ex-auth-a');
413     }
414
415     public function test_login_maps_roles_using_external_auth_ids_if_set()
416     {
417         $roleToReceive = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'test-second-param, ex-auth-a']);
418         $roleToNotReceive = Role::factory()->create(['display_name' => 'ex-auth-a', 'external_auth_id' => 'test-second-param']);
419
420         app('config')->set([
421             'services.ldap.user_to_groups'     => true,
422             'services.ldap.group_attribute'    => 'memberOf',
423             'services.ldap.remove_from_groups' => true,
424         ]);
425
426         $this->commonLdapMocks(1, 1, 3, 4, 3, 2);
427         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(3)
428             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
429             ->andReturn(['count' => 1, 0 => [
430                 'uid'      => [$this->mockUser->name],
431                 'cn'       => [$this->mockUser->name],
432                 'dn'       => ['dc=test' . config('services.ldap.base_dn')],
433                 'mail'     => [$this->mockUser->email],
434                 'memberof' => [
435                     'count' => 1,
436                     0       => 'cn=ex-auth-a,ou=groups,dc=example,dc=com',
437                 ],
438             ]]);
439
440         $this->mockUserLogin()->assertRedirect('/');
441
442         $user = User::query()->where('email', $this->mockUser->email)->first();
443         $this->assertDatabaseHas('role_user', [
444             'user_id' => $user->id,
445             'role_id' => $roleToReceive->id,
446         ]);
447         $this->assertDatabaseMissing('role_user', [
448             'user_id' => $user->id,
449             'role_id' => $roleToNotReceive->id,
450         ]);
451     }
452
453     public function test_login_group_mapping_does_not_conflict_with_default_role()
454     {
455         $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']);
456         $roleToReceive2 = Role::factory()->create(['display_name' => 'LdapTester Second']);
457         $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save();
458
459         setting()->put('registration-role', $roleToReceive->id);
460
461         app('config')->set([
462             'services.ldap.user_to_groups'     => true,
463             'services.ldap.group_attribute'    => 'memberOf',
464             'services.ldap.remove_from_groups' => true,
465         ]);
466
467         $this->commonLdapMocks(1, 1, 4, 5, 4, 6);
468         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(4)
469             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
470             ->andReturn(['count' => 1, 0 => [
471                 'uid'      => [$this->mockUser->name],
472                 'cn'       => [$this->mockUser->name],
473                 'dn'       => ['dc=test' . config('services.ldap.base_dn')],
474                 'mail'     => [$this->mockUser->email],
475                 'memberof' => [
476                     'count' => 2,
477                     0       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
478                     1       => 'cn=ldaptester-second,ou=groups,dc=example,dc=com',
479                 ],
480             ]]);
481
482         $this->mockUserLogin()->assertRedirect('/');
483
484         $user = User::query()->where('email', $this->mockUser->email)->first();
485         $this->assertDatabaseHas('role_user', [
486             'user_id' => $user->id,
487             'role_id' => $roleToReceive->id,
488         ]);
489         $this->assertDatabaseHas('role_user', [
490             'user_id' => $user->id,
491             'role_id' => $roleToReceive2->id,
492         ]);
493     }
494
495     public function test_login_uses_specified_display_name_attribute()
496     {
497         app('config')->set([
498             'services.ldap.display_name_attribute' => 'displayName',
499         ]);
500
501         $this->commonLdapMocks(1, 1, 2, 4, 2);
502         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2)
503             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
504             ->andReturn(['count' => 1, 0 => [
505                 'uid'         => [$this->mockUser->name],
506                 'cn'          => [$this->mockUser->name],
507                 'dn'          => ['dc=test' . config('services.ldap.base_dn')],
508                 'displayname' => 'displayNameAttribute',
509             ]]);
510
511         $this->mockUserLogin()->assertRedirect('/login');
512         $this->get('/login')->assertSee('Please enter an email to use for this account.');
513
514         $resp = $this->mockUserLogin($this->mockUser->email);
515         $resp->assertRedirect('/');
516         $this->get('/')->assertSee('displayNameAttribute');
517         $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => $this->mockUser->name, 'name' => 'displayNameAttribute']);
518     }
519
520     public function test_login_uses_default_display_name_attribute_if_specified_not_present()
521     {
522         app('config')->set([
523             'services.ldap.display_name_attribute' => 'displayName',
524         ]);
525
526         $this->commonLdapMocks(1, 1, 2, 4, 2);
527         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2)
528             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
529             ->andReturn(['count' => 1, 0 => [
530                 'uid' => [$this->mockUser->name],
531                 'cn'  => [$this->mockUser->name],
532                 'dn'  => ['dc=test' . config('services.ldap.base_dn')],
533             ]]);
534
535         $this->mockUserLogin()->assertRedirect('/login');
536         $this->get('/login')->assertSee('Please enter an email to use for this account.');
537
538         $resp = $this->mockUserLogin($this->mockUser->email);
539         $resp->assertRedirect('/');
540         $this->get('/')->assertSee($this->mockUser->name);
541         $this->assertDatabaseHas('users', [
542             'email'            => $this->mockUser->email,
543             'email_confirmed'  => false,
544             'external_auth_id' => $this->mockUser->name,
545             'name'             => $this->mockUser->name,
546         ]);
547     }
548
549     protected function checkLdapReceivesCorrectDetails($serverString, $expectedHost, $expectedPort)
550     {
551         app('config')->set([
552             'services.ldap.server' => $serverString,
553         ]);
554
555         // Standard mocks
556         $this->commonLdapMocks(0, 1, 1, 2, 1);
557         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)->andReturn(['count' => 1, 0 => [
558             'uid' => [$this->mockUser->name],
559             'cn'  => [$this->mockUser->name],
560             'dn'  => ['dc=test' . config('services.ldap.base_dn')],
561         ]]);
562
563         $this->mockLdap->shouldReceive('connect')->once()
564             ->with($expectedHost, $expectedPort)->andReturn($this->resourceId);
565         $this->mockUserLogin();
566     }
567
568     public function test_ldap_port_provided_on_host_if_host_is_full_uri()
569     {
570         $hostName = 'ldaps://bookstack:8080';
571         $this->checkLdapReceivesCorrectDetails($hostName, $hostName, 389);
572     }
573
574     public function test_ldap_port_parsed_from_server_if_host_is_not_full_uri()
575     {
576         $this->checkLdapReceivesCorrectDetails('ldap.bookstack.com:8080', 'ldap.bookstack.com', 8080);
577     }
578
579     public function test_default_ldap_port_used_if_not_in_server_string_and_not_uri()
580     {
581         $this->checkLdapReceivesCorrectDetails('ldap.bookstack.com', 'ldap.bookstack.com', 389);
582     }
583
584     public function test_forgot_password_routes_inaccessible()
585     {
586         $resp = $this->get('/password/email');
587         $this->assertPermissionError($resp);
588
589         $resp = $this->post('/password/email');
590         $this->assertPermissionError($resp);
591
592         $resp = $this->get('/password/reset/abc123');
593         $this->assertPermissionError($resp);
594
595         $resp = $this->post('/password/reset');
596         $this->assertPermissionError($resp);
597     }
598
599     public function test_user_invite_routes_inaccessible()
600     {
601         $resp = $this->get('/register/invite/abc123');
602         $this->assertPermissionError($resp);
603
604         $resp = $this->post('/register/invite/abc123');
605         $this->assertPermissionError($resp);
606     }
607
608     public function test_user_register_routes_inaccessible()
609     {
610         $resp = $this->get('/register');
611         $this->assertPermissionError($resp);
612
613         $resp = $this->post('/register');
614         $this->assertPermissionError($resp);
615     }
616
617     public function test_dump_user_details_option_works()
618     {
619         config()->set(['services.ldap.dump_user_details' => true, 'services.ldap.thumbnail_attribute' => 'jpegphoto']);
620
621         $this->commonLdapMocks(1, 1, 1, 1, 1);
622         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
623             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
624             ->andReturn(['count' => 1, 0 => [
625                 'uid' => [$this->mockUser->name],
626                 'cn'  => [$this->mockUser->name],
627                 // Test dumping binary data for avatar responses
628                 'jpegphoto' => base64_decode('/9j/4AAQSkZJRg=='),
629                 'dn'        => ['dc=test' . config('services.ldap.base_dn')],
630             ]]);
631
632         $resp = $this->post('/login', [
633             'username' => $this->mockUser->name,
634             'password' => $this->mockUser->password,
635         ]);
636         $resp->assertJsonStructure([
637             'details_from_ldap'        => [],
638             'details_bookstack_parsed' => [],
639         ]);
640     }
641
642     public function test_start_tls_called_if_option_set()
643     {
644         config()->set(['services.ldap.start_tls' => true]);
645         $this->mockLdap->shouldReceive('startTls')->once()->andReturn(true);
646         $this->runFailedAuthLogin();
647     }
648
649     public function test_connection_fails_if_tls_fails()
650     {
651         config()->set(['services.ldap.start_tls' => true]);
652         $this->mockLdap->shouldReceive('startTls')->once()->andReturn(false);
653         $this->commonLdapMocks(1, 1, 0, 0, 0);
654         $resp = $this->post('/login', ['username' => 'timmyjenkins', 'password' => 'cattreedog']);
655         $resp->assertStatus(500);
656     }
657
658     public function test_ldap_attributes_can_be_binary_decoded_if_marked()
659     {
660         config()->set(['services.ldap.id_attribute' => 'BIN;uid']);
661         $ldapService = app()->make(LdapService::class);
662         $this->commonLdapMocks(1, 1, 1, 1, 1);
663         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
664             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), ['cn', 'dn', 'uid', 'mail', 'cn'])
665             ->andReturn(['count' => 1, 0 => [
666                 'uid' => [hex2bin('FFF8F7')],
667                 'cn'  => [$this->mockUser->name],
668                 'dn'  => ['dc=test' . config('services.ldap.base_dn')],
669             ]]);
670
671         $details = $ldapService->getUserDetails('test');
672         $this->assertEquals('fff8f7', $details['uid']);
673     }
674
675     public function test_new_ldap_user_login_with_already_used_email_address_shows_error_message_to_user()
676     {
677         $this->commonLdapMocks(1, 1, 2, 4, 2);
678         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2)
679             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
680             ->andReturn(['count' => 1, 0 => [
681                 'uid'  => [$this->mockUser->name],
682                 'cn'   => [$this->mockUser->name],
683                 'dn'   => ['dc=test' . config('services.ldap.base_dn')],
684                 'mail' => '[email protected]',
685             ]], ['count' => 1, 0 => [
686                 'uid'  => ['Barry'],
687                 'cn'   => ['Scott'],
688                 'dn'   => ['dc=bscott' . config('services.ldap.base_dn')],
689                 'mail' => '[email protected]',
690             ]]);
691
692         // First user login
693         $this->mockUserLogin()->assertRedirect('/');
694
695         // Second user login
696         auth()->logout();
697         $resp = $this->followingRedirects()->post('/login', ['username' => 'bscott', 'password' => 'pass']);
698         $resp->assertSee('A user with the email [email protected] already exists but with different credentials');
699     }
700
701     public function test_login_with_email_confirmation_required_maps_groups_but_shows_confirmation_screen()
702     {
703         $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']);
704         $user = User::factory()->make();
705         setting()->put('registration-confirmation', 'true');
706
707         app('config')->set([
708             'services.ldap.user_to_groups'     => true,
709             'services.ldap.group_attribute'    => 'memberOf',
710             'services.ldap.remove_from_groups' => true,
711         ]);
712
713         $this->commonLdapMocks(1, 1, 6, 8, 6, 4);
714         $this->mockLdap->shouldReceive('searchAndGetEntries')
715             ->times(6)
716             ->andReturn(['count' => 1, 0 => [
717                 'uid'      => [$user->name],
718                 'cn'       => [$user->name],
719                 'dn'       => ['dc=test' . config('services.ldap.base_dn')],
720                 'mail'     => [$user->email],
721                 'memberof' => [
722                     'count' => 1,
723                     0       => 'cn=ldaptester,ou=groups,dc=example,dc=com',
724                 ],
725             ]]);
726
727         $login = $this->followingRedirects()->mockUserLogin();
728         $login->assertSee('Thanks for registering!');
729         $this->assertDatabaseHas('users', [
730             'email'           => $user->email,
731             'email_confirmed' => false,
732         ]);
733
734         $user = User::query()->where('email', '=', $user->email)->first();
735         $this->assertDatabaseHas('role_user', [
736             'user_id' => $user->id,
737             'role_id' => $roleToReceive->id,
738         ]);
739
740         $this->assertNull(auth()->user());
741
742         $homePage = $this->get('/');
743         $homePage->assertRedirect('/login');
744
745         $login = $this->followingRedirects()->mockUserLogin();
746         $login->assertSee('Email Address Not Confirmed');
747     }
748
749     public function test_failed_logins_are_logged_when_message_configured()
750     {
751         $log = $this->withTestLogger();
752         config()->set(['logging.failed_login.message' => 'Failed login for %u']);
753         $this->runFailedAuthLogin();
754         $this->assertTrue($log->hasWarningThatContains('Failed login for timmyjenkins'));
755     }
756
757     public function test_thumbnail_attribute_used_as_user_avatar_if_configured()
758     {
759         config()->set(['services.ldap.thumbnail_attribute' => 'jpegPhoto']);
760
761         $this->commonLdapMocks(1, 1, 1, 2, 1);
762         $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn');
763         $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1)
764             ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array'))
765             ->andReturn(['count' => 1, 0 => [
766                 'cn'        => [$this->mockUser->name],
767                 'dn'        => $ldapDn,
768                 'jpegphoto' => [base64_decode('/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8Q
769 EBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k=')],
770                 'mail' => [$this->mockUser->email],
771             ]]);
772
773         $this->mockUserLogin()
774             ->assertRedirect('/');
775
776         $user = User::query()->where('email', '=', $this->mockUser->email)->first();
777         $this->assertNotNull($user->avatar);
778         $this->assertEquals('8c90748342f19b195b9c6b4eff742ded', md5_file(public_path($user->avatar->path)));
779     }
780 }