]> BookStack Code Mirror - bookstack/blob - tests/Auth/OidcTest.php
Added 404 response for non-existing setting categories
[bookstack] / tests / Auth / OidcTest.php
1 <?php
2
3 namespace Tests\Auth;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\User;
7 use GuzzleHttp\Psr7\Request;
8 use GuzzleHttp\Psr7\Response;
9 use Tests\Helpers\OidcJwtHelper;
10 use Tests\TestCase;
11 use Tests\TestResponse;
12
13 class OidcTest extends TestCase
14 {
15     protected string $keyFilePath;
16     protected $keyFile;
17
18     protected function setUp(): void
19     {
20         parent::setUp();
21         // Set default config for OpenID Connect
22
23         $this->keyFile = tmpfile();
24         $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri'];
25         file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey());
26
27         config()->set([
28             'auth.method'                 => 'oidc',
29             'auth.defaults.guard'         => 'oidc',
30             'oidc.name'                   => 'SingleSignOn-Testing',
31             'oidc.display_name_claims'    => ['name'],
32             'oidc.client_id'              => OidcJwtHelper::defaultClientId(),
33             'oidc.client_secret'          => 'testpass',
34             'oidc.jwt_public_key'         => $this->keyFilePath,
35             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
36             'oidc.authorization_endpoint' => 'https://oidc.local/auth',
37             'oidc.token_endpoint'         => 'https://oidc.local/token',
38             'oidc.discover'               => false,
39             'oidc.dump_user_details'      => false,
40         ]);
41     }
42
43     protected function tearDown(): void
44     {
45         parent::tearDown();
46         if (file_exists($this->keyFilePath)) {
47             unlink($this->keyFilePath);
48         }
49     }
50
51     public function test_login_option_shows_on_login_page()
52     {
53         $req = $this->get('/login');
54         $req->assertSeeText('SingleSignOn-Testing');
55         $req->assertElementExists('form[action$="/oidc/login"][method=POST] button');
56     }
57
58     public function test_oidc_routes_are_only_active_if_oidc_enabled()
59     {
60         config()->set(['auth.method' => 'standard']);
61         $routes = ['/login' => 'post', '/callback' => 'get'];
62         foreach ($routes as $uri => $method) {
63             $req = $this->call($method, '/oidc' . $uri);
64             $this->assertPermissionError($req);
65         }
66     }
67
68     public function test_forgot_password_routes_inaccessible()
69     {
70         $resp = $this->get('/password/email');
71         $this->assertPermissionError($resp);
72
73         $resp = $this->post('/password/email');
74         $this->assertPermissionError($resp);
75
76         $resp = $this->get('/password/reset/abc123');
77         $this->assertPermissionError($resp);
78
79         $resp = $this->post('/password/reset');
80         $this->assertPermissionError($resp);
81     }
82
83     public function test_standard_login_routes_inaccessible()
84     {
85         $resp = $this->post('/login');
86         $this->assertPermissionError($resp);
87     }
88
89     public function test_logout_route_functions()
90     {
91         $this->actingAs($this->getEditor());
92         $this->post('/logout');
93         $this->assertFalse(auth()->check());
94     }
95
96     public function test_user_invite_routes_inaccessible()
97     {
98         $resp = $this->get('/register/invite/abc123');
99         $this->assertPermissionError($resp);
100
101         $resp = $this->post('/register/invite/abc123');
102         $this->assertPermissionError($resp);
103     }
104
105     public function test_user_register_routes_inaccessible()
106     {
107         $resp = $this->get('/register');
108         $this->assertPermissionError($resp);
109
110         $resp = $this->post('/register');
111         $this->assertPermissionError($resp);
112     }
113
114     public function test_login()
115     {
116         $req = $this->post('/oidc/login');
117         $redirect = $req->headers->get('location');
118
119         $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
120         $this->assertFalse($this->isAuthenticated());
121         $this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
122         $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
123         $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
124     }
125
126     public function test_login_success_flow()
127     {
128         // Start auth
129         $this->post('/oidc/login');
130         $state = session()->get('oidc_state');
131
132         $transactions = &$this->mockHttpClient([$this->getMockAuthorizationResponse([
133             'email' => 'benny@example.com',
134             'sub'   => 'benny1010101',
135         ])]);
136
137         // Callback from auth provider
138         // App calls token endpoint to get id token
139         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
140         $resp->assertRedirect('/');
141         $this->assertCount(1, $transactions);
142         /** @var Request $tokenRequest */
143         $tokenRequest = $transactions[0]['request'];
144         $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
145         $this->assertEquals('POST', $tokenRequest->getMethod());
146         $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
147         $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
148         $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
149         $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
150
151         $this->assertTrue(auth()->check());
152         $this->assertDatabaseHas('users', [
153             'email'            => 'benny@example.com',
154             'external_auth_id' => 'benny1010101',
155             'email_confirmed'  => false,
156         ]);
157
158         $user = User::query()->where('email', '=', 'benny@example.com')->first();
159         $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
160     }
161
162     public function test_callback_fails_if_no_state_present_or_matching()
163     {
164         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
165         $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
166
167         $this->post('/oidc/login');
168         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
169         $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
170     }
171
172     public function test_dump_user_details_option_outputs_as_expected()
173     {
174         config()->set('oidc.dump_user_details', true);
175
176         $resp = $this->runLogin([
177             'email' => 'benny@example.com',
178             'sub'   => 'benny505',
179         ]);
180
181         $resp->assertStatus(200);
182         $resp->assertJson([
183             'email' => 'benny@example.com',
184             'sub'   => 'benny505',
185             'iss'   => OidcJwtHelper::defaultIssuer(),
186             'aud'   => OidcJwtHelper::defaultClientId(),
187         ]);
188         $this->assertFalse(auth()->check());
189     }
190
191     public function test_auth_fails_if_no_email_exists_in_user_data()
192     {
193         $this->runLogin([
194             'email' => '',
195             'sub'   => 'benny505',
196         ]);
197
198         $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
199     }
200
201     public function test_auth_fails_if_already_logged_in()
202     {
203         $this->asEditor();
204
205         $this->runLogin([
206             'email' => 'benny@example.com',
207             'sub'   => 'benny505',
208         ]);
209
210         $this->assertSessionError('Already logged in');
211     }
212
213     public function test_auth_login_as_existing_user()
214     {
215         $editor = $this->getEditor();
216         $editor->external_auth_id = 'benny505';
217         $editor->save();
218
219         $this->assertFalse(auth()->check());
220
221         $this->runLogin([
222             'email' => 'benny@example.com',
223             'sub'   => 'benny505',
224         ]);
225
226         $this->assertTrue(auth()->check());
227         $this->assertEquals($editor->id, auth()->user()->id);
228     }
229
230     public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
231     {
232         $editor = $this->getEditor();
233         $editor->external_auth_id = 'editor101';
234         $editor->save();
235
236         $this->assertFalse(auth()->check());
237
238         $resp = $this->runLogin([
239             'email' => $editor->email,
240             'sub'   => 'benny505',
241         ]);
242         $resp = $this->followRedirects($resp);
243
244         $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.');
245         $this->assertFalse(auth()->check());
246     }
247
248     public function test_auth_login_with_invalid_token_fails()
249     {
250         $resp = $this->runLogin([
251             'sub' => null,
252         ]);
253         $resp = $this->followRedirects($resp);
254
255         $resp->assertSeeText('ID token validate failed with error: Missing token subject value');
256         $this->assertFalse(auth()->check());
257     }
258
259     public function test_auth_login_with_autodiscovery()
260     {
261         $this->withAutodiscovery();
262
263         $transactions = &$this->mockHttpClient([
264             $this->getAutoDiscoveryResponse(),
265             $this->getJwksResponse(),
266         ]);
267
268         $this->assertFalse(auth()->check());
269
270         $this->runLogin();
271
272         $this->assertTrue(auth()->check());
273         /** @var Request $discoverRequest */
274         $discoverRequest = $transactions[0]['request'];
275         /** @var Request $discoverRequest */
276         $keysRequest = $transactions[1]['request'];
277
278         $this->assertEquals('GET', $keysRequest->getMethod());
279         $this->assertEquals('GET', $discoverRequest->getMethod());
280         $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
281         $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
282     }
283
284     public function test_auth_fails_if_autodiscovery_fails()
285     {
286         $this->withAutodiscovery();
287         $this->mockHttpClient([
288             new Response(404, [], 'Not found'),
289         ]);
290
291         $resp = $this->followRedirects($this->runLogin());
292         $this->assertFalse(auth()->check());
293         $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
294     }
295
296     public function test_autodiscovery_calls_are_cached()
297     {
298         $this->withAutodiscovery();
299
300         $transactions = &$this->mockHttpClient([
301             $this->getAutoDiscoveryResponse(),
302             $this->getJwksResponse(),
303             $this->getAutoDiscoveryResponse([
304                 'issuer' => 'https://auto.example.com',
305             ]),
306             $this->getJwksResponse(),
307         ]);
308
309         // Initial run
310         $this->post('/oidc/login');
311         $this->assertCount(2, $transactions);
312         // Second run, hits cache
313         $this->post('/oidc/login');
314         $this->assertCount(2, $transactions);
315
316         // Third run, different issuer, new cache key
317         config()->set(['oidc.issuer' => 'https://auto.example.com']);
318         $this->post('/oidc/login');
319         $this->assertCount(4, $transactions);
320     }
321
322     public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
323     {
324         $this->withAutodiscovery();
325
326         $keyArray = OidcJwtHelper::publicJwkKeyArray();
327         unset($keyArray['alg']);
328
329         $this->mockHttpClient([
330             $this->getAutoDiscoveryResponse(),
331             new Response(200, [
332                 'Content-Type'  => 'application/json',
333                 'Cache-Control' => 'no-cache, no-store',
334                 'Pragma'        => 'no-cache',
335             ], json_encode([
336                 'keys' => [
337                     $keyArray,
338                 ],
339             ])),
340         ]);
341
342         $this->assertFalse(auth()->check());
343         $this->runLogin();
344         $this->assertTrue(auth()->check());
345     }
346
347     protected function withAutodiscovery()
348     {
349         config()->set([
350             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
351             'oidc.discover'               => true,
352             'oidc.authorization_endpoint' => null,
353             'oidc.token_endpoint'         => null,
354             'oidc.jwt_public_key'         => null,
355         ]);
356     }
357
358     protected function runLogin($claimOverrides = []): TestResponse
359     {
360         $this->post('/oidc/login');
361         $state = session()->get('oidc_state');
362         $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]);
363
364         return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
365     }
366
367     protected function getAutoDiscoveryResponse($responseOverrides = []): Response
368     {
369         return new Response(200, [
370             'Content-Type'  => 'application/json',
371             'Cache-Control' => 'no-cache, no-store',
372             'Pragma'        => 'no-cache',
373         ], json_encode(array_merge([
374             'token_endpoint'         => OidcJwtHelper::defaultIssuer() . '/oidc/token',
375             'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
376             'jwks_uri'               => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
377             'issuer'                 => OidcJwtHelper::defaultIssuer(),
378         ], $responseOverrides)));
379     }
380
381     protected function getJwksResponse(): Response
382     {
383         return new Response(200, [
384             'Content-Type'  => 'application/json',
385             'Cache-Control' => 'no-cache, no-store',
386             'Pragma'        => 'no-cache',
387         ], json_encode([
388             'keys' => [
389                 OidcJwtHelper::publicJwkKeyArray(),
390             ],
391         ]));
392     }
393
394     protected function getMockAuthorizationResponse($claimOverrides = []): Response
395     {
396         return new Response(200, [
397             'Content-Type'  => 'application/json',
398             'Cache-Control' => 'no-cache, no-store',
399             'Pragma'        => 'no-cache',
400         ], json_encode([
401             'access_token' => 'abc123',
402             'token_type'   => 'Bearer',
403             'expires_in'   => 3600,
404             'id_token'     => OidcJwtHelper::idToken($claimOverrides),
405         ]));
406     }
407 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.