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.userinfo_endpoint' => 'https://oidc.local/userinfo',
41 'oidc.discover' => false,
42 'oidc.dump_user_details' => false,
43 'oidc.additional_scopes' => '',
44 'odic.fetch_avatar' => false,
45 'oidc.user_to_groups' => false,
46 'oidc.groups_claim' => 'group',
47 'oidc.remove_from_groups' => false,
48 'oidc.external_id_claim' => 'sub',
49 'oidc.end_session_endpoint' => false,
53 protected function tearDown(): void
56 if (file_exists($this->keyFilePath)) {
57 unlink($this->keyFilePath);
61 public function test_login_option_shows_on_login_page()
63 $req = $this->get('/login');
64 $req->assertSeeText('SingleSignOn-Testing');
65 $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST] button');
68 public function test_oidc_routes_are_only_active_if_oidc_enabled()
70 config()->set(['auth.method' => 'standard']);
71 $routes = ['/login' => 'post', '/callback' => 'get'];
72 foreach ($routes as $uri => $method) {
73 $req = $this->call($method, '/oidc' . $uri);
74 $this->assertPermissionError($req);
78 public function test_forgot_password_routes_inaccessible()
80 $resp = $this->get('/password/email');
81 $this->assertPermissionError($resp);
83 $resp = $this->post('/password/email');
84 $this->assertPermissionError($resp);
86 $resp = $this->get('/password/reset/abc123');
87 $this->assertPermissionError($resp);
89 $resp = $this->post('/password/reset');
90 $this->assertPermissionError($resp);
93 public function test_standard_login_routes_inaccessible()
95 $resp = $this->post('/login');
96 $this->assertPermissionError($resp);
99 public function test_logout_route_functions()
101 $this->actingAs($this->users->editor());
102 $this->post('/logout');
103 $this->assertFalse(auth()->check());
106 public function test_user_invite_routes_inaccessible()
108 $resp = $this->get('/register/invite/abc123');
109 $this->assertPermissionError($resp);
111 $resp = $this->post('/register/invite/abc123');
112 $this->assertPermissionError($resp);
115 public function test_user_register_routes_inaccessible()
117 $resp = $this->get('/register');
118 $this->assertPermissionError($resp);
120 $resp = $this->post('/register');
121 $this->assertPermissionError($resp);
124 public function test_login()
126 $req = $this->post('/oidc/login');
127 $redirect = $req->headers->get('location');
129 $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
130 $this->assertFalse($this->isAuthenticated());
131 $this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
132 $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
133 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
136 public function test_login_success_flow()
139 $this->post('/oidc/login');
140 $state = session()->get('oidc_state');
142 $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
144 'sub' => 'benny1010101',
147 // Callback from auth provider
148 // App calls token endpoint to get id token
149 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
150 $resp->assertRedirect('/');
151 $this->assertEquals(1, $transactions->requestCount());
152 $tokenRequest = $transactions->latestRequest();
153 $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
154 $this->assertEquals('POST', $tokenRequest->getMethod());
155 $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
156 $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
157 $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
158 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
160 $this->assertTrue(auth()->check());
161 $this->assertDatabaseHas('users', [
163 'external_auth_id' => 'benny1010101',
164 'email_confirmed' => false,
168 $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
171 public function test_login_uses_custom_additional_scopes_if_defined()
174 'oidc.additional_scopes' => 'groups, badgers',
177 $redirect = $this->post('/oidc/login')->headers->get('location');
179 $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect);
182 public function test_callback_fails_if_no_state_present_or_matching()
184 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
185 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
187 $this->post('/oidc/login');
188 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
189 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
192 public function test_dump_user_details_option_outputs_as_expected()
194 config()->set('oidc.dump_user_details', true);
196 $resp = $this->runLogin([
201 $resp->assertStatus(200);
205 'iss' => OidcJwtHelper::defaultIssuer(),
206 'aud' => OidcJwtHelper::defaultClientId(),
208 $this->assertFalse(auth()->check());
211 public function test_auth_fails_if_no_email_exists_in_user_data()
213 config()->set('oidc.userinfo_endpoint', null);
220 $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
223 public function test_auth_fails_if_already_logged_in()
232 $this->assertSessionError('Already logged in');
235 public function test_auth_login_as_existing_user()
237 $editor = $this->users->editor();
238 $editor->external_auth_id = 'benny505';
241 $this->assertFalse(auth()->check());
248 $this->assertTrue(auth()->check());
249 $this->assertEquals($editor->id, auth()->user()->id);
252 public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
254 $editor = $this->users->editor();
255 $editor->external_auth_id = 'editor101';
258 $this->assertFalse(auth()->check());
260 $resp = $this->runLogin([
261 'email' => $editor->email,
264 $resp = $this->followRedirects($resp);
266 $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.');
267 $this->assertFalse(auth()->check());
270 public function test_auth_login_with_invalid_token_fails()
272 $resp = $this->runLogin([
275 $resp = $this->followRedirects($resp);
277 $resp->assertSeeText('ID token validation failed with error: Missing token subject value');
278 $this->assertFalse(auth()->check());
281 public function test_auth_fails_if_endpoints_start_with_https()
283 $endpointConfigKeys = [
284 'oidc.token_endpoint' => 'tokenEndpoint',
285 'oidc.authorization_endpoint' => 'authorizationEndpoint',
286 'oidc.userinfo_endpoint' => 'userinfoEndpoint',
289 foreach ($endpointConfigKeys as $endpointConfigKey => $endpointName) {
290 $logger = $this->withTestLogger();
291 $original = config()->get($endpointConfigKey);
292 $new = str_replace('https://', 'http://', $original);
293 config()->set($endpointConfigKey, $new);
295 $this->withoutExceptionHandling();
298 $resp = $this->runLogin();
299 $resp->assertRedirect('/login');
300 } catch (\Exception $exception) {
303 $this->assertEquals("Endpoint value for \"{$endpointName}\" must start with https://", $err->getMessage());
305 config()->set($endpointConfigKey, $original);
309 public function test_auth_login_with_autodiscovery()
311 $this->withAutodiscovery();
313 $transactions = $this->mockHttpClient([
314 $this->getAutoDiscoveryResponse(),
315 $this->getJwksResponse(),
318 $this->assertFalse(auth()->check());
322 $this->assertTrue(auth()->check());
324 $discoverRequest = $transactions->requestAt(0);
325 $keysRequest = $transactions->requestAt(1);
326 $this->assertEquals('GET', $keysRequest->getMethod());
327 $this->assertEquals('GET', $discoverRequest->getMethod());
328 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
329 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
332 public function test_auth_fails_if_autodiscovery_fails()
334 $this->withAutodiscovery();
335 $this->mockHttpClient([
336 new Response(404, [], 'Not found'),
339 $resp = $this->followRedirects($this->runLogin());
340 $this->assertFalse(auth()->check());
341 $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
344 public function test_autodiscovery_calls_are_cached()
346 $this->withAutodiscovery();
348 $transactions = $this->mockHttpClient([
349 $this->getAutoDiscoveryResponse(),
350 $this->getJwksResponse(),
351 $this->getAutoDiscoveryResponse([
352 'issuer' => 'https://auto.example.com',
354 $this->getJwksResponse(),
358 $this->post('/oidc/login');
359 $this->assertEquals(2, $transactions->requestCount());
360 // Second run, hits cache
361 $this->post('/oidc/login');
362 $this->assertEquals(2, $transactions->requestCount());
364 // Third run, different issuer, new cache key
365 config()->set(['oidc.issuer' => 'https://auto.example.com']);
366 $this->post('/oidc/login');
367 $this->assertEquals(4, $transactions->requestCount());
370 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
372 $this->withAutodiscovery();
374 $keyArray = OidcJwtHelper::publicJwkKeyArray();
375 unset($keyArray['alg']);
377 $this->mockHttpClient([
378 $this->getAutoDiscoveryResponse(),
380 'Content-Type' => 'application/json',
381 'Cache-Control' => 'no-cache, no-store',
382 'Pragma' => 'no-cache',
390 $this->assertFalse(auth()->check());
392 $this->assertTrue(auth()->check());
395 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_use_property()
397 // Based on reading the OIDC discovery spec:
398 // > This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also
399 // > contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When
400 // > both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all
401 // > keys in the referenced JWK Set to indicate each key's intended usage.
402 // We can assume that keys without use are intended for signing.
403 $this->withAutodiscovery();
405 $keyArray = OidcJwtHelper::publicJwkKeyArray();
406 unset($keyArray['use']);
408 $this->mockHttpClient([
409 $this->getAutoDiscoveryResponse(),
411 'Content-Type' => 'application/json',
412 'Cache-Control' => 'no-cache, no-store',
413 'Pragma' => 'no-cache',
421 $this->assertFalse(auth()->check());
423 $this->assertTrue(auth()->check());
426 public function test_auth_uses_configured_external_id_claim_option()
429 'oidc.external_id_claim' => 'super_awesome_id',
432 $resp = $this->runLogin([
434 'sub' => 'benny1010101',
435 'super_awesome_id' => 'xXBennyTheGeezXx',
437 $resp->assertRedirect('/');
439 /** @var User $user */
441 $this->assertEquals('xXBennyTheGeezXx', $user->external_auth_id);
444 public function test_auth_uses_mulitple_display_name_claims_if_configured()
446 config()->set(['oidc.display_name_claims' => 'first_name|last_name']);
450 'sub' => 'benny1010101',
451 'first_name' => 'Benny',
452 'last_name' => 'Jenkins'
455 $this->assertDatabaseHas('users', [
456 'name' => 'Benny Jenkins',
461 public function test_user_avatar_fetched_from_picture_on_first_login_if_enabled()
463 config()->set(['oidc.fetch_avatar' => true]);
467 'picture' => 'https://example.com/my-avatar.jpg',
469 new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
473 $this->assertNotNull($user);
475 $this->assertTrue($user->avatar()->exists());
478 public function test_user_avatar_not_fetched_if_image_data_format_unknown()
480 config()->set(['oidc.fetch_avatar' => true]);
484 'picture' => 'https://example.com/my-avatar.jpg',
486 new Response(200, ['Content-Type' => 'image/jpeg'], str_repeat('abc123', 5))
490 $this->assertNotNull($user);
492 $this->assertFalse($user->avatar()->exists());
495 public function test_user_avatar_not_fetched_when_user_already_exists()
497 config()->set(['oidc.fetch_avatar' => true]);
498 $editor = $this->users->editor();
499 $editor->external_auth_id = 'benny509';
502 'picture' => 'https://example.com/my-avatar.jpg',
505 new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
509 $this->assertFalse($editor->avatar()->exists());
512 public function test_login_group_sync()
515 'oidc.user_to_groups' => true,
516 'oidc.groups_claim' => 'groups',
517 'oidc.remove_from_groups' => false,
519 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
520 $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
521 $roleC = Role::factory()->create(['display_name' => 'Another Role']);
523 $resp = $this->runLogin([
525 'sub' => 'benny1010101',
526 'groups' => ['Wizards', 'Zookeepers'],
528 $resp->assertRedirect('/');
530 /** @var User $user */
533 $this->assertTrue($user->hasRole($roleA->id));
534 $this->assertTrue($user->hasRole($roleB->id));
535 $this->assertFalse($user->hasRole($roleC->id));
538 public function test_login_group_sync_with_nested_groups_in_token()
541 'oidc.user_to_groups' => true,
542 'oidc.groups_claim' => 'my.custom.groups.attr',
543 'oidc.remove_from_groups' => false,
545 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
547 $resp = $this->runLogin([
549 'sub' => 'benny1010101',
553 'attr' => ['Wizards'],
558 $resp->assertRedirect('/');
560 /** @var User $user */
562 $this->assertTrue($user->hasRole($roleA->id));
565 public function test_oidc_logout_form_active_when_oidc_active()
569 $resp = $this->get('/');
570 $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
572 public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
574 config()->set(['oidc.end_session_endpoint' => true]);
575 $this->withAutodiscovery();
577 $transactions = $this->mockHttpClient([
578 $this->getAutoDiscoveryResponse(),
579 $this->getJwksResponse(),
582 $resp = $this->asEditor()->post('/oidc/logout');
583 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
585 $this->assertEquals(2, $transactions->requestCount());
586 $this->assertFalse(auth()->check());
589 public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
591 $this->withAutodiscovery();
592 config()->set(['oidc.end_session_endpoint' => false]);
594 $this->mockHttpClient([
595 $this->getAutoDiscoveryResponse(),
596 $this->getJwksResponse(),
599 $resp = $this->asEditor()->post('/oidc/logout');
600 $resp->assertRedirect('/');
601 $this->assertFalse(auth()->check());
604 public function test_logout_without_autodiscovery_but_with_endpoint_configured()
606 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
608 $resp = $this->asEditor()->post('/oidc/logout');
609 $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
610 $this->assertFalse(auth()->check());
613 public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
615 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
617 $resp = $this->asEditor()->post('/oidc/logout');
618 $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
619 $this->assertFalse(auth()->check());
622 public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
624 $this->withAutodiscovery();
626 'auth.auto_initiate' => true,
627 'services.google.client_id' => false,
628 'services.github.client_id' => false,
629 'oidc.end_session_endpoint' => true,
632 $this->mockHttpClient([
633 $this->getAutoDiscoveryResponse(),
634 $this->getJwksResponse(),
637 $resp = $this->asEditor()->post('/oidc/logout');
639 $redirectUrl = url('/login?prevent_auto_init=true');
640 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
641 $this->assertFalse(auth()->check());
644 public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
646 config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
647 $this->withAutodiscovery();
649 $transactions = $this->mockHttpClient([
650 $this->getAutoDiscoveryResponse(),
651 $this->getJwksResponse(),
654 $resp = $this->asEditor()->post('/oidc/logout');
655 $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
657 $this->assertEquals(2, $transactions->requestCount());
658 $this->assertFalse(auth()->check());
661 public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
663 config()->set(['oidc.end_session_endpoint' => true]);
664 $this->withAutodiscovery();
666 $this->mockHttpClient([
667 $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
668 $this->getJwksResponse(),
671 $resp = $this->asEditor()->post('/oidc/logout');
672 $resp->assertRedirect('/');
673 $this->assertFalse(auth()->check());
676 public function test_logout_redirect_contains_id_token_hint_if_existing()
678 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
680 // Fix times so our token is predictable
683 'exp' => time() + 720,
684 'auth_time' => time()
686 $this->runLogin($claimOverrides);
688 $resp = $this->asEditor()->post('/oidc/logout');
689 $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) . '&post_logout_redirect_uri=' . urlencode(url('/'));
690 $resp->assertRedirect('https://example.com/logout?' . $query);
693 public function test_oidc_id_token_pre_validate_theme_event_without_return()
696 $callback = function (...$eventArgs) use (&$args) {
699 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
701 $resp = $this->runLogin([
703 'sub' => 'benny1010101',
706 $resp->assertRedirect('/');
708 $this->assertDatabaseHas('users', [
709 'external_auth_id' => 'benny1010101',
712 $this->assertArrayHasKey('iss', $args[0]);
713 $this->assertArrayHasKey('sub', $args[0]);
714 $this->assertEquals('Benny', $args[0]['name']);
715 $this->assertEquals('benny1010101', $args[0]['sub']);
717 $this->assertArrayHasKey('access_token', $args[1]);
718 $this->assertArrayHasKey('expires_in', $args[1]);
719 $this->assertArrayHasKey('refresh_token', $args[1]);
722 public function test_oidc_id_token_pre_validate_theme_event_with_return()
724 $callback = function (...$eventArgs) {
725 return array_merge($eventArgs[0], [
727 'sub' => 'lenny1010101',
731 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
733 $resp = $this->runLogin([
735 'sub' => 'benny1010101',
738 $resp->assertRedirect('/');
740 $this->assertDatabaseHas('users', [
742 'external_auth_id' => 'lenny1010101',
747 public function test_pkce_used_on_authorize_and_access()
750 $resp = $this->post('/oidc/login');
751 $state = session()->get('oidc_state');
753 $pkceCode = session()->get('oidc_pkce_code');
754 $this->assertGreaterThan(30, strlen($pkceCode));
756 $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
757 $redirect = $resp->headers->get('Location');
758 $redirectParams = [];
759 parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
760 $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
761 $this->assertEquals('S256', $redirectParams['code_challenge_method']);
763 $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
765 'sub' => 'benny1010101',
768 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
769 $tokenRequest = $transactions->latestRequest();
771 parse_str($tokenRequest->getBody(), $bodyParams);
772 $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
775 public function test_userinfo_endpoint_used_if_missing_claims_in_id_token()
777 config()->set('oidc.display_name_claims', 'first_name|last_name');
778 $this->post('/oidc/login');
779 $state = session()->get('oidc_state');
781 $client = $this->mockHttpClient([
782 $this->getMockAuthorizationResponse(['name' => null]),
784 'Content-Type' => 'application/json',
786 'sub' => OidcJwtHelper::defaultPayload()['sub'],
787 'first_name' => 'Barry',
788 'last_name' => 'Userinfo',
792 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
793 $resp->assertRedirect('/');
794 $this->assertEquals(2, $client->requestCount());
796 $userinfoRequest = $client->requestAt(1);
797 $this->assertEquals('GET', $userinfoRequest->getMethod());
798 $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri());
800 $this->assertEquals('Barry Userinfo', user()->name);
803 public function test_userinfo_endpoint_fetch_with_different_sub_throws_error()
805 $userinfoResponseData = ['sub' => 'dcba4321'];
806 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
807 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
808 $resp->assertRedirect('/login');
809 $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
812 public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error()
814 $userinfoResponseData = ['name' => 'testing'];
815 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
816 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
817 $resp->assertRedirect('/login');
818 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
821 public function test_userinfo_endpoint_fetch_can_parsed_nested_groups()
824 'oidc.user_to_groups' => true,
825 'oidc.groups_claim' => 'my.nested.groups.attr',
826 'oidc.remove_from_groups' => false,
829 $roleA = Role::factory()->create(['display_name' => 'Ducks']);
830 $userinfoResponseData = [
831 'sub' => OidcJwtHelper::defaultPayload()['sub'],
832 'my' => ['nested' => ['groups' => ['attr' => ['Ducks', 'Donkeys']]]]
834 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
835 $resp = $this->runLogin(['groups' => null], [$userinfoResponse]);
836 $resp->assertRedirect('/');
838 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
839 $this->assertTrue($user->hasRole($roleA->id));
842 public function test_userinfo_endpoint_response_with_complex_json_content_type_handled()
844 $userinfoResponseData = [
845 'sub' => OidcJwtHelper::defaultPayload()['sub'],
848 $userinfoResponse = new Response(200, ['Content-Type' => 'Application/Json ; charset=utf-8'], json_encode($userinfoResponseData));
849 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
850 $resp->assertRedirect('/');
852 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
853 $this->assertEquals('Barry', $user->name);
856 public function test_userinfo_endpoint_jwks_response_handled()
858 $userinfoResponseData = OidcJwtHelper::idToken(['name' => 'Barry Jwks']);
859 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
861 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
862 $resp->assertRedirect('/');
864 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
865 $this->assertEquals('Barry Jwks', $user->name);
868 public function test_userinfo_endpoint_jwks_response_returning_no_sub_throws()
870 $userinfoResponseData = OidcJwtHelper::idToken(['sub' => null]);
871 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
873 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
874 $resp->assertRedirect('/login');
875 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
878 public function test_userinfo_endpoint_jwks_response_returning_non_matching_sub_throws()
880 $userinfoResponseData = OidcJwtHelper::idToken(['sub' => 'zzz123']);
881 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
883 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
884 $resp->assertRedirect('/login');
885 $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
888 public function test_userinfo_endpoint_jwks_response_with_invalid_signature_throws()
890 $userinfoResponseData = OidcJwtHelper::idToken();
891 $exploded = explode('.', $userinfoResponseData);
892 $exploded[2] = base64_encode(base64_decode($exploded[2]) . 'ABC');
893 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], implode('.', $exploded));
895 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
896 $resp->assertRedirect('/login');
897 $this->assertSessionError('Userinfo endpoint response validation failed with error: Token signature could not be validated using the provided keys');
900 public function test_userinfo_endpoint_jwks_response_with_invalid_signature_alg_throws()
902 $userinfoResponseData = OidcJwtHelper::idToken([], ['alg' => 'ZZ512']);
903 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
905 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
906 $resp->assertRedirect('/login');
907 $this->assertSessionError('Userinfo endpoint response validation failed with error: Only RS256 signature validation is supported. Token reports using ZZ512');
910 public function test_userinfo_endpoint_response_with_invalid_content_type_throws()
912 $userinfoResponse = new Response(200, ['Content-Type' => 'application/beans'], json_encode(OidcJwtHelper::defaultPayload()));
913 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
914 $resp->assertRedirect('/login');
915 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
918 public function test_userinfo_endpoint_not_called_if_empty_groups_array_provided_in_id_token()
921 'oidc.user_to_groups' => true,
922 'oidc.groups_claim' => 'groups',
923 'oidc.remove_from_groups' => false,
926 $this->post('/oidc/login');
927 $state = session()->get('oidc_state');
928 $client = $this->mockHttpClient([$this->getMockAuthorizationResponse([
932 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
933 $resp->assertRedirect('/');
934 $this->assertEquals(1, $client->requestCount());
935 $this->assertTrue(auth()->check());
938 protected function withAutodiscovery(): void
941 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
942 'oidc.discover' => true,
943 'oidc.authorization_endpoint' => null,
944 'oidc.token_endpoint' => null,
945 'oidc.userinfo_endpoint' => null,
946 'oidc.jwt_public_key' => null,
950 protected function runLogin($claimOverrides = [], $additionalHttpResponses = []): TestResponse
952 $this->post('/oidc/login');
953 $state = session()->get('oidc_state');
954 $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides), ...$additionalHttpResponses]);
956 return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
959 protected function getAutoDiscoveryResponse($responseOverrides = []): Response
961 return new Response(200, [
962 'Content-Type' => 'application/json',
963 'Cache-Control' => 'no-cache, no-store',
964 'Pragma' => 'no-cache',
965 ], json_encode(array_merge([
966 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
967 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
968 'userinfo_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/userinfo',
969 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
970 'issuer' => OidcJwtHelper::defaultIssuer(),
971 'end_session_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
972 ], $responseOverrides)));
975 protected function getJwksResponse(): Response
977 return new Response(200, [
978 'Content-Type' => 'application/json',
979 'Cache-Control' => 'no-cache, no-store',
980 'Pragma' => 'no-cache',
983 OidcJwtHelper::publicJwkKeyArray(),
988 protected function getMockAuthorizationResponse($claimOverrides = []): Response
990 return new Response(200, [
991 'Content-Type' => 'application/json',
992 'Cache-Control' => 'no-cache, no-store',
993 'Pragma' => 'no-cache',
995 'access_token' => 'abc123',
996 'token_type' => 'Bearer',
997 'expires_in' => 3600,
998 'id_token' => OidcJwtHelper::idToken($claimOverrides),