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