]> BookStack Code Mirror - bookstack/blob - tests/Auth/AuthTest.php
Merge branch 'modernize-3rd-party-service-logos' of https://github.com/na3shkw/BookSt...
[bookstack] / tests / Auth / AuthTest.php
1 <?php
2
3 namespace Tests\Auth;
4
5 use BookStack\Auth\Access\Mfa\MfaSession;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Notifications\ConfirmEmail;
9 use BookStack\Notifications\ResetPassword;
10 use Illuminate\Support\Facades\DB;
11 use Illuminate\Support\Facades\Notification;
12 use Tests\TestCase;
13 use Tests\TestResponse;
14
15 class AuthTest extends TestCase
16 {
17     public function test_auth_working()
18     {
19         $this->get('/')->assertRedirect('/login');
20     }
21
22     public function test_login()
23     {
24         $this->login('[email protected]', 'password')->assertRedirect('/');
25     }
26
27     public function test_public_viewing()
28     {
29         $this->setSettings(['app-public' => 'true']);
30         $this->get('/')
31             ->assertOk()
32             ->assertSee('Log in');
33     }
34
35     public function test_registration_showing()
36     {
37         // Ensure registration form is showing
38         $this->setSettings(['registration-enabled' => 'true']);
39         $this->get('/login')
40             ->assertElementContains('a[href="' . url('/register') . '"]', 'Sign up');
41     }
42
43     public function test_normal_registration()
44     {
45         // Set settings and get user instance
46         $this->setSettings(['registration-enabled' => 'true']);
47         $user = User::factory()->make();
48
49         // Test form and ensure user is created
50         $this->get('/register')
51             ->assertSee('Sign Up')
52             ->assertElementContains('form[action="' . url('/register') . '"]', 'Create Account');
53
54         $resp = $this->post('/register', $user->only('password', 'name', 'email'));
55         $resp->assertRedirect('/');
56
57         $resp = $this->get('/');
58         $resp->assertOk();
59         $resp->assertSee($user->name);
60         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email]);
61     }
62
63     public function test_empty_registration_redirects_back_with_errors()
64     {
65         // Set settings and get user instance
66         $this->setSettings(['registration-enabled' => 'true']);
67
68         // Test form and ensure user is created
69         $this->get('/register');
70         $this->post('/register', [])->assertRedirect('/register');
71         $this->get('/register')->assertSee('The name field is required');
72     }
73
74     public function test_registration_validation()
75     {
76         $this->setSettings(['registration-enabled' => 'true']);
77
78         $this->get('/register');
79         $resp = $this->followingRedirects()->post('/register', [
80             'name'     => '1',
81             'email'    => '1',
82             'password' => '1',
83         ]);
84         $resp->assertSee('The name must be at least 2 characters.');
85         $resp->assertSee('The email must be a valid email address.');
86         $resp->assertSee('The password must be at least 8 characters.');
87     }
88
89     public function test_sign_up_link_on_login()
90     {
91         $this->get('/login')->assertDontSee('Sign up');
92
93         $this->setSettings(['registration-enabled' => 'true']);
94
95         $this->get('/login')->assertSee('Sign up');
96     }
97
98     public function test_confirmed_registration()
99     {
100         // Fake notifications
101         Notification::fake();
102
103         // Set settings and get user instance
104         $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']);
105         $user = User::factory()->make();
106
107         // Go through registration process
108         $resp = $this->post('/register', $user->only('name', 'email', 'password'));
109         $resp->assertRedirect('/register/confirm');
110         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);
111
112         // Ensure notification sent
113         /** @var User $dbUser */
114         $dbUser = User::query()->where('email', '=', $user->email)->first();
115         Notification::assertSentTo($dbUser, ConfirmEmail::class);
116
117         // Test access and resend confirmation email
118         $resp = $this->login($user->email, $user->password);
119         $resp->assertRedirect('/register/confirm/awaiting');
120
121         $resp = $this->get('/register/confirm/awaiting');
122         $resp->assertElementContains('form[action="' . url('/register/confirm/resend') . '"]', 'Resend');
123
124         $this->get('/books')->assertRedirect('/login');
125         $this->post('/register/confirm/resend', $user->only('email'));
126
127         // Get confirmation and confirm notification matches
128         $emailConfirmation = DB::table('email_confirmations')->where('user_id', '=', $dbUser->id)->first();
129         Notification::assertSentTo($dbUser, ConfirmEmail::class, function ($notification, $channels) use ($emailConfirmation) {
130             return $notification->token === $emailConfirmation->token;
131         });
132
133         // Check confirmation email confirmation activation.
134         $this->get('/register/confirm/' . $emailConfirmation->token)->assertRedirect('/');
135         $this->get('/')->assertSee($user->name);
136         $this->assertDatabaseMissing('email_confirmations', ['token' => $emailConfirmation->token]);
137         $this->assertDatabaseHas('users', ['name' => $dbUser->name, 'email' => $dbUser->email, 'email_confirmed' => true]);
138     }
139
140     public function test_restricted_registration()
141     {
142         $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true', 'registration-restrict' => 'example.com']);
143         $user = User::factory()->make();
144
145         // Go through registration process
146         $this->post('/register', $user->only('name', 'email', 'password'))
147             ->assertRedirect('/register');
148         $resp = $this->get('/register');
149         $resp->assertSee('That email domain does not have access to this application');
150         $this->assertDatabaseMissing('users', $user->only('email'));
151
152         $user->email = '[email protected]';
153
154         $this->post('/register', $user->only('name', 'email', 'password'))
155             ->assertRedirect('/register/confirm');
156         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);
157
158         $this->assertNull(auth()->user());
159
160         $this->get('/')->assertRedirect('/login');
161         $resp = $this->followingRedirects()->post('/login', $user->only('email', 'password'));
162         $resp->assertSee('Email Address Not Confirmed');
163         $this->assertNull(auth()->user());
164     }
165
166     public function test_restricted_registration_with_confirmation_disabled()
167     {
168         $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'false', 'registration-restrict' => 'example.com']);
169         $user = User::factory()->make();
170
171         // Go through registration process
172         $this->post('/register', $user->only('name', 'email', 'password'))
173             ->assertRedirect('/register');
174         $this->assertDatabaseMissing('users', $user->only('email'));
175         $this->get('/register')->assertSee('That email domain does not have access to this application');
176
177         $user->email = '[email protected]';
178
179         $this->post('/register', $user->only('name', 'email', 'password'))
180             ->assertRedirect('/register/confirm');
181         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);
182
183         $this->assertNull(auth()->user());
184
185         $this->get('/')->assertRedirect('/login');
186         $resp = $this->post('/login', $user->only('email', 'password'));
187         $resp->assertRedirect('/register/confirm/awaiting');
188         $this->get('/register/confirm/awaiting')->assertSee('Email Address Not Confirmed');
189         $this->assertNull(auth()->user());
190     }
191
192     public function test_logout()
193     {
194         $this->asAdmin()->get('/')->assertOk();
195         $this->get('/logout')->assertRedirect('/');
196         $this->get('/')->assertRedirect('/login');
197     }
198
199     public function test_mfa_session_cleared_on_logout()
200     {
201         $user = $this->getEditor();
202         $mfaSession = $this->app->make(MfaSession::class);
203
204         $mfaSession->markVerifiedForUser($user);
205         $this->assertTrue($mfaSession->isVerifiedForUser($user));
206
207         $this->asAdmin()->get('/logout');
208         $this->assertFalse($mfaSession->isVerifiedForUser($user));
209     }
210
211     public function test_reset_password_flow()
212     {
213         Notification::fake();
214
215         $this->get('/login')
216             ->assertElementContains('a[href="' . url('/password/email') . '"]', 'Forgot Password?');
217
218         $this->get('/password/email')
219             ->assertElementContains('form[action="' . url('/password/email') . '"]', 'Send Reset Link');
220
221         $resp = $this->post('/password/email', [
222             'email' => '[email protected]',
223         ]);
224         $resp->assertRedirect('/password/email');
225
226         $resp = $this->get('/password/email');
227         $resp->assertSee('A password reset link will be sent to [email protected] if that email address is found in the system.');
228
229         $this->assertDatabaseHas('password_resets', [
230             'email' => '[email protected]',
231         ]);
232
233         /** @var User $user */
234         $user = User::query()->where('email', '=', '[email protected]')->first();
235
236         Notification::assertSentTo($user, ResetPassword::class);
237         $n = Notification::sent($user, ResetPassword::class);
238
239         $this->get('/password/reset/' . $n->first()->token)
240             ->assertOk()
241             ->assertSee('Reset Password');
242
243         $resp = $this->post('/password/reset', [
244             'email'                 => '[email protected]',
245             'password'              => 'randompass',
246             'password_confirmation' => 'randompass',
247             'token'                 => $n->first()->token,
248         ]);
249         $resp->assertRedirect('/');
250
251         $this->get('/')->assertSee('Your password has been successfully reset');
252     }
253
254     public function test_reset_password_flow_shows_success_message_even_if_wrong_password_to_prevent_user_discovery()
255     {
256         $this->get('/password/email');
257         $resp = $this->followingRedirects()->post('/password/email', [
258             'email' => '[email protected]',
259         ]);
260         $resp->assertSee('A password reset link will be sent to [email protected] if that email address is found in the system.');
261         $resp->assertDontSee('We can\'t find a user');
262
263         $this->get('/password/reset/arandometokenvalue')->assertSee('Reset Password');
264         $resp = $this->post('/password/reset', [
265             'email'                 => '[email protected]',
266             'password'              => 'randompass',
267             'password_confirmation' => 'randompass',
268             'token'                 => 'arandometokenvalue',
269         ]);
270         $resp->assertRedirect('/password/reset/arandometokenvalue');
271
272         $this->get('/password/reset/arandometokenvalue')
273             ->assertDontSee('We can\'t find a user')
274             ->assertSee('The password reset token is invalid for this email address.');
275     }
276
277     public function test_reset_password_page_shows_sign_links()
278     {
279         $this->setSettings(['registration-enabled' => 'true']);
280         $this->get('/password/email')
281             ->assertElementContains('a', 'Log in')
282             ->assertElementContains('a', 'Sign up');
283     }
284
285     public function test_reset_password_request_is_throttled()
286     {
287         $editor = $this->getEditor();
288         Notification::fake();
289         $this->get('/password/email');
290         $this->followingRedirects()->post('/password/email', [
291             'email' => $editor->email,
292         ]);
293
294         $resp = $this->followingRedirects()->post('/password/email', [
295             'email' => $editor->email,
296         ]);
297         Notification::assertTimesSent(1, ResetPassword::class);
298         $resp->assertSee('A password reset link will be sent to ' . $editor->email . ' if that email address is found in the system.');
299     }
300
301     public function test_login_redirects_to_initially_requested_url_correctly()
302     {
303         config()->set('app.url', 'http://localhost');
304         /** @var Page $page */
305         $page = Page::query()->first();
306
307         $this->get($page->getUrl())->assertRedirect(url('/login'));
308         $this->login('[email protected]', 'password')
309             ->assertRedirect($page->getUrl());
310     }
311
312     public function test_login_intended_redirect_does_not_redirect_to_external_pages()
313     {
314         config()->set('app.url', 'http://localhost');
315         $this->setSettings(['app-public' => true]);
316
317         $this->get('/login', ['referer' => 'https://example.com']);
318         $login = $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
319
320         $login->assertRedirect('http://localhost');
321     }
322
323     public function test_login_intended_redirect_does_not_factor_mfa_routes()
324     {
325         $this->get('/books')->assertRedirect('/login');
326         $this->get('/mfa/setup')->assertRedirect('/login');
327         $login = $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
328         $login->assertRedirect('/books');
329     }
330
331     public function test_login_authenticates_admins_on_all_guards()
332     {
333         $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
334         $this->assertTrue(auth()->check());
335         $this->assertTrue(auth('ldap')->check());
336         $this->assertTrue(auth('saml2')->check());
337         $this->assertTrue(auth('oidc')->check());
338     }
339
340     public function test_login_authenticates_nonadmins_on_default_guard_only()
341     {
342         $editor = $this->getEditor();
343         $editor->password = bcrypt('password');
344         $editor->save();
345
346         $this->post('/login', ['email' => $editor->email, 'password' => 'password']);
347         $this->assertTrue(auth()->check());
348         $this->assertFalse(auth('ldap')->check());
349         $this->assertFalse(auth('saml2')->check());
350         $this->assertFalse(auth('oidc')->check());
351     }
352
353     public function test_failed_logins_are_logged_when_message_configured()
354     {
355         $log = $this->withTestLogger();
356         config()->set(['logging.failed_login.message' => 'Failed login for %u']);
357
358         $this->post('/login', ['email' => '[email protected]', 'password' => 'cattreedog']);
359         $this->assertTrue($log->hasWarningThatContains('Failed login for [email protected]'));
360
361         $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
362         $this->assertFalse($log->hasWarningThatContains('Failed login for [email protected]'));
363     }
364
365     public function test_logged_in_user_with_unconfirmed_email_is_logged_out()
366     {
367         $this->setSettings(['registration-confirmation' => 'true']);
368         $user = $this->getEditor();
369         $user->email_confirmed = false;
370         $user->save();
371
372         auth()->login($user);
373         $this->assertTrue(auth()->check());
374
375         $this->get('/books')->assertRedirect('/');
376         $this->assertFalse(auth()->check());
377     }
378
379     /**
380      * Perform a login.
381      */
382     protected function login(string $email, string $password): TestResponse
383     {
384         return $this->post('/login', compact('email', 'password'));
385     }
386 }