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