5 use BookStack\Activity\ActivityType;
6 use BookStack\Facades\Theme;
7 use BookStack\Theming\ThemeEvents;
8 use BookStack\Users\Models\Role;
9 use BookStack\Users\Models\User;
10 use GuzzleHttp\Psr7\Response;
11 use Illuminate\Testing\TestResponse;
12 use Tests\Helpers\OidcJwtHelper;
15 class OidcTest extends TestCase
17 protected string $keyFilePath;
20 protected function setUp(): void
23 // Set default config for OpenID Connect
25 $this->keyFile = tmpfile();
26 $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri'];
27 file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey());
30 'auth.method' => 'oidc',
31 'auth.defaults.guard' => 'oidc',
32 'oidc.name' => 'SingleSignOn-Testing',
33 'oidc.display_name_claims' => 'name',
34 'oidc.client_id' => OidcJwtHelper::defaultClientId(),
35 'oidc.client_secret' => 'testpass',
36 'oidc.jwt_public_key' => $this->keyFilePath,
37 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
38 'oidc.authorization_endpoint' => 'https://oidc.local/auth',
39 'oidc.token_endpoint' => 'https://oidc.local/token',
40 'oidc.discover' => false,
41 'oidc.dump_user_details' => false,
42 'oidc.additional_scopes' => '',
43 'oidc.user_to_groups' => false,
44 'oidc.groups_claim' => 'group',
45 'oidc.remove_from_groups' => false,
46 'oidc.external_id_claim' => 'sub',
47 'oidc.end_session_endpoint' => null,
51 protected function tearDown(): void
54 if (file_exists($this->keyFilePath)) {
55 unlink($this->keyFilePath);
59 public function test_login_option_shows_on_login_page()
61 $req = $this->get('/login');
62 $req->assertSeeText('SingleSignOn-Testing');
63 $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST] button');
66 public function test_oidc_routes_are_only_active_if_oidc_enabled()
68 config()->set(['auth.method' => 'standard']);
69 $routes = ['/login' => 'post', '/callback' => 'get'];
70 foreach ($routes as $uri => $method) {
71 $req = $this->call($method, '/oidc' . $uri);
72 $this->assertPermissionError($req);
76 public function test_forgot_password_routes_inaccessible()
78 $resp = $this->get('/password/email');
79 $this->assertPermissionError($resp);
81 $resp = $this->post('/password/email');
82 $this->assertPermissionError($resp);
84 $resp = $this->get('/password/reset/abc123');
85 $this->assertPermissionError($resp);
87 $resp = $this->post('/password/reset');
88 $this->assertPermissionError($resp);
91 public function test_standard_login_routes_inaccessible()
93 $resp = $this->post('/login');
94 $this->assertPermissionError($resp);
97 public function test_logout_route_functions()
99 $this->actingAs($this->users->editor());
100 $this->post('/logout');
101 $this->assertFalse(auth()->check());
104 public function test_user_invite_routes_inaccessible()
106 $resp = $this->get('/register/invite/abc123');
107 $this->assertPermissionError($resp);
109 $resp = $this->post('/register/invite/abc123');
110 $this->assertPermissionError($resp);
113 public function test_user_register_routes_inaccessible()
115 $resp = $this->get('/register');
116 $this->assertPermissionError($resp);
118 $resp = $this->post('/register');
119 $this->assertPermissionError($resp);
122 public function test_login()
124 $req = $this->post('/oidc/login');
125 $redirect = $req->headers->get('location');
127 $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
128 $this->assertFalse($this->isAuthenticated());
129 $this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
130 $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
131 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
134 public function test_login_success_flow()
137 $this->post('/oidc/login');
138 $state = session()->get('oidc_state');
140 $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
142 'sub' => 'benny1010101',
145 // Callback from auth provider
146 // App calls token endpoint to get id token
147 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
148 $resp->assertRedirect('/');
149 $this->assertEquals(1, $transactions->requestCount());
150 $tokenRequest = $transactions->latestRequest();
151 $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
152 $this->assertEquals('POST', $tokenRequest->getMethod());
153 $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
154 $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
155 $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
156 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
158 $this->assertTrue(auth()->check());
159 $this->assertDatabaseHas('users', [
161 'external_auth_id' => 'benny1010101',
162 'email_confirmed' => false,
166 $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
169 public function test_login_uses_custom_additional_scopes_if_defined()
172 'oidc.additional_scopes' => 'groups, badgers',
175 $redirect = $this->post('/oidc/login')->headers->get('location');
177 $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect);
180 public function test_callback_fails_if_no_state_present_or_matching()
182 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
183 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
185 $this->post('/oidc/login');
186 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
187 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
190 public function test_dump_user_details_option_outputs_as_expected()
192 config()->set('oidc.dump_user_details', true);
194 $resp = $this->runLogin([
199 $resp->assertStatus(200);
203 'iss' => OidcJwtHelper::defaultIssuer(),
204 'aud' => OidcJwtHelper::defaultClientId(),
206 $this->assertFalse(auth()->check());
209 public function test_auth_fails_if_no_email_exists_in_user_data()
216 $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
219 public function test_auth_fails_if_already_logged_in()
228 $this->assertSessionError('Already logged in');
231 public function test_auth_login_as_existing_user()
233 $editor = $this->users->editor();
234 $editor->external_auth_id = 'benny505';
237 $this->assertFalse(auth()->check());
244 $this->assertTrue(auth()->check());
245 $this->assertEquals($editor->id, auth()->user()->id);
248 public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
250 $editor = $this->users->editor();
251 $editor->external_auth_id = 'editor101';
254 $this->assertFalse(auth()->check());
256 $resp = $this->runLogin([
257 'email' => $editor->email,
260 $resp = $this->followRedirects($resp);
262 $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.');
263 $this->assertFalse(auth()->check());
266 public function test_auth_login_with_invalid_token_fails()
268 $resp = $this->runLogin([
271 $resp = $this->followRedirects($resp);
273 $resp->assertSeeText('ID token validate failed with error: Missing token subject value');
274 $this->assertFalse(auth()->check());
277 public function test_auth_login_with_autodiscovery()
279 $this->withAutodiscovery();
281 $transactions = $this->mockHttpClient([
282 $this->getAutoDiscoveryResponse(),
283 $this->getJwksResponse(),
286 $this->assertFalse(auth()->check());
290 $this->assertTrue(auth()->check());
292 $discoverRequest = $transactions->requestAt(0);
293 $keysRequest = $transactions->requestAt(1);
294 $this->assertEquals('GET', $keysRequest->getMethod());
295 $this->assertEquals('GET', $discoverRequest->getMethod());
296 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
297 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
300 public function test_auth_fails_if_autodiscovery_fails()
302 $this->withAutodiscovery();
303 $this->mockHttpClient([
304 new Response(404, [], 'Not found'),
307 $resp = $this->followRedirects($this->runLogin());
308 $this->assertFalse(auth()->check());
309 $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
312 public function test_autodiscovery_calls_are_cached()
314 $this->withAutodiscovery();
316 $transactions = $this->mockHttpClient([
317 $this->getAutoDiscoveryResponse(),
318 $this->getJwksResponse(),
319 $this->getAutoDiscoveryResponse([
320 'issuer' => 'https://auto.example.com',
322 $this->getJwksResponse(),
326 $this->post('/oidc/login');
327 $this->assertEquals(2, $transactions->requestCount());
328 // Second run, hits cache
329 $this->post('/oidc/login');
330 $this->assertEquals(2, $transactions->requestCount());
332 // Third run, different issuer, new cache key
333 config()->set(['oidc.issuer' => 'https://auto.example.com']);
334 $this->post('/oidc/login');
335 $this->assertEquals(4, $transactions->requestCount());
338 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
340 $this->withAutodiscovery();
342 $keyArray = OidcJwtHelper::publicJwkKeyArray();
343 unset($keyArray['alg']);
345 $this->mockHttpClient([
346 $this->getAutoDiscoveryResponse(),
348 'Content-Type' => 'application/json',
349 'Cache-Control' => 'no-cache, no-store',
350 'Pragma' => 'no-cache',
358 $this->assertFalse(auth()->check());
360 $this->assertTrue(auth()->check());
363 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_use_property()
365 // Based on reading the OIDC discovery spec:
366 // > This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also
367 // > contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When
368 // > both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all
369 // > keys in the referenced JWK Set to indicate each key's intended usage.
370 // We can assume that keys without use are intended for signing.
371 $this->withAutodiscovery();
373 $keyArray = OidcJwtHelper::publicJwkKeyArray();
374 unset($keyArray['use']);
376 $this->mockHttpClient([
377 $this->getAutoDiscoveryResponse(),
379 'Content-Type' => 'application/json',
380 'Cache-Control' => 'no-cache, no-store',
381 'Pragma' => 'no-cache',
389 $this->assertFalse(auth()->check());
391 $this->assertTrue(auth()->check());
394 public function test_auth_uses_configured_external_id_claim_option()
397 'oidc.external_id_claim' => 'super_awesome_id',
400 $resp = $this->runLogin([
402 'sub' => 'benny1010101',
403 'super_awesome_id' => 'xXBennyTheGeezXx',
405 $resp->assertRedirect('/');
407 /** @var User $user */
409 $this->assertEquals('xXBennyTheGeezXx', $user->external_auth_id);
412 public function test_auth_uses_mulitple_display_name_claims_if_configured()
414 config()->set(['oidc.display_name_claims' => 'first_name|last_name']);
418 'sub' => 'benny1010101',
419 'first_name' => 'Benny',
420 'last_name' => 'Jenkins'
423 $this->assertDatabaseHas('users', [
424 'name' => 'Benny Jenkins',
429 public function test_login_group_sync()
432 'oidc.user_to_groups' => true,
433 'oidc.groups_claim' => 'groups',
434 'oidc.remove_from_groups' => false,
436 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
437 $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
438 $roleC = Role::factory()->create(['display_name' => 'Another Role']);
440 $resp = $this->runLogin([
442 'sub' => 'benny1010101',
443 'groups' => ['Wizards', 'Zookeepers'],
445 $resp->assertRedirect('/');
447 /** @var User $user */
450 $this->assertTrue($user->hasRole($roleA->id));
451 $this->assertTrue($user->hasRole($roleB->id));
452 $this->assertFalse($user->hasRole($roleC->id));
455 public function test_login_group_sync_with_nested_groups_in_token()
458 'oidc.user_to_groups' => true,
459 'oidc.groups_claim' => 'my.custom.groups.attr',
460 'oidc.remove_from_groups' => false,
462 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
464 $resp = $this->runLogin([
466 'sub' => 'benny1010101',
470 'attr' => ['Wizards'],
475 $resp->assertRedirect('/');
477 /** @var User $user */
479 $this->assertTrue($user->hasRole($roleA->id));
482 public function test_oidc_logout_form_active_when_oidc_active()
486 $resp = $this->get('/');
487 $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
489 public function test_logout_with_autodiscovery()
491 $this->withAutodiscovery();
493 $transactions = $this->mockHttpClient([
494 $this->getAutoDiscoveryResponse(),
495 $this->getJwksResponse(),
498 $resp = $this->asEditor()->post('/oidc/logout');
499 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
501 $this->assertEquals(2, $transactions->requestCount());
504 public function test_logout_with_autodiscovery_but_oidc_logout_disabled()
506 $this->withAutodiscovery();
507 config()->set(['oidc.end_session_endpoint' => false]);
509 $this->mockHttpClient([
510 $this->getAutoDiscoveryResponse(),
511 $this->getJwksResponse(),
514 $resp = $this->asEditor()->post('/oidc/logout');
515 $resp->assertRedirect('/');
518 public function test_logout_without_autodiscovery_but_with_endpoint_configured()
520 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
522 $resp = $this->asEditor()->post('/oidc/logout');
523 $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
526 public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
528 $this->withAutodiscovery();
530 'auth.auto_initiate' => true,
531 'services.google.client_id' => false,
532 'services.github.client_id' => false,
535 $this->mockHttpClient([
536 $this->getAutoDiscoveryResponse(),
537 $this->getJwksResponse(),
540 $resp = $this->asEditor()->post('/oidc/logout');
542 $redirectUrl = url('/login?prevent_auto_init=true');
543 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
546 public function test_logout_redirect_contains_id_token_hint_if_existing()
548 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
552 $resp = $this->asEditor()->post('/oidc/logout');
553 $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken()) . '&post_logout_redirect_uri=' . urlencode(url('/'));
554 $resp->assertRedirect('https://example.com/logout?' . $query);
557 public function test_oidc_id_token_pre_validate_theme_event_without_return()
560 $callback = function (...$eventArgs) use (&$args) {
563 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
565 $resp = $this->runLogin([
567 'sub' => 'benny1010101',
570 $resp->assertRedirect('/');
572 $this->assertDatabaseHas('users', [
573 'external_auth_id' => 'benny1010101',
576 $this->assertArrayHasKey('iss', $args[0]);
577 $this->assertArrayHasKey('sub', $args[0]);
578 $this->assertEquals('Benny', $args[0]['name']);
579 $this->assertEquals('benny1010101', $args[0]['sub']);
581 $this->assertArrayHasKey('access_token', $args[1]);
582 $this->assertArrayHasKey('expires_in', $args[1]);
583 $this->assertArrayHasKey('refresh_token', $args[1]);
586 public function test_oidc_id_token_pre_validate_theme_event_with_return()
588 $callback = function (...$eventArgs) {
589 return array_merge($eventArgs[0], [
591 'sub' => 'lenny1010101',
595 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
597 $resp = $this->runLogin([
599 'sub' => 'benny1010101',
602 $resp->assertRedirect('/');
604 $this->assertDatabaseHas('users', [
606 'external_auth_id' => 'lenny1010101',
611 protected function withAutodiscovery()
614 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
615 'oidc.discover' => true,
616 'oidc.authorization_endpoint' => null,
617 'oidc.token_endpoint' => null,
618 'oidc.jwt_public_key' => null,
622 protected function runLogin($claimOverrides = []): TestResponse
624 $this->post('/oidc/login');
625 $state = session()->get('oidc_state');
626 $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]);
628 return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
631 protected function getAutoDiscoveryResponse($responseOverrides = []): Response
633 return new Response(200, [
634 'Content-Type' => 'application/json',
635 'Cache-Control' => 'no-cache, no-store',
636 'Pragma' => 'no-cache',
637 ], json_encode(array_merge([
638 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
639 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
640 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
641 'issuer' => OidcJwtHelper::defaultIssuer(),
642 'end_session_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
643 ], $responseOverrides)));
646 protected function getJwksResponse(): Response
648 return new Response(200, [
649 'Content-Type' => 'application/json',
650 'Cache-Control' => 'no-cache, no-store',
651 'Pragma' => 'no-cache',
654 OidcJwtHelper::publicJwkKeyArray(),
659 protected function getMockAuthorizationResponse($claimOverrides = []): Response
661 return new Response(200, [
662 'Content-Type' => 'application/json',
663 'Cache-Control' => 'no-cache, no-store',
664 'Pragma' => 'no-cache',
666 'access_token' => 'abc123',
667 'token_type' => 'Bearer',
668 'expires_in' => 3600,
669 'id_token' => OidcJwtHelper::idToken($claimOverrides),