]> BookStack Code Mirror - bookstack/blobdiff - tests/Auth/OidcTest.php
Add optional OIDC avatar fetching from the “picture” claim
[bookstack] / tests / Auth / OidcTest.php
index 204a3bb5f960243e99ff30cc3f1427759b6a9470..205f75a4d62c159c2fefde68712567981c73c693 100644 (file)
@@ -37,6 +37,7 @@ class OidcTest extends TestCase
             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
             'oidc.authorization_endpoint' => 'https://oidc.local/auth',
             'oidc.token_endpoint'         => 'https://oidc.local/token',
+            'oidc.userinfo_endpoint'      => 'https://oidc.local/userinfo',
             'oidc.discover'               => false,
             'oidc.dump_user_details'      => false,
             'oidc.additional_scopes'      => '',
@@ -44,6 +45,7 @@ class OidcTest extends TestCase
             'oidc.groups_claim'           => 'group',
             'oidc.remove_from_groups'     => false,
             'oidc.external_id_claim'      => 'sub',
+            'oidc.end_session_endpoint'   => false,
         ]);
     }
 
@@ -207,6 +209,8 @@ class OidcTest extends TestCase
 
     public function test_auth_fails_if_no_email_exists_in_user_data()
     {
+        config()->set('oidc.userinfo_endpoint', null);
+
         $this->runLogin([
             'email' => '',
             'sub'   => 'benny505',
@@ -269,10 +273,38 @@ class OidcTest extends TestCase
         ]);
         $resp = $this->followRedirects($resp);
 
-        $resp->assertSeeText('ID token validate failed with error: Missing token subject value');
+        $resp->assertSeeText('ID token validation failed with error: Missing token subject value');
         $this->assertFalse(auth()->check());
     }
 
+    public function test_auth_fails_if_endpoints_start_with_https()
+    {
+        $endpointConfigKeys = [
+            'oidc.token_endpoint' => 'tokenEndpoint',
+            'oidc.authorization_endpoint' => 'authorizationEndpoint',
+            'oidc.userinfo_endpoint' => 'userinfoEndpoint',
+        ];
+
+        foreach ($endpointConfigKeys as $endpointConfigKey => $endpointName) {
+            $logger = $this->withTestLogger();
+            $original = config()->get($endpointConfigKey);
+            $new = str_replace('https://', 'http://', $original);
+            config()->set($endpointConfigKey, $new);
+
+            $this->withoutExceptionHandling();
+            $err = null;
+            try {
+                $resp = $this->runLogin();
+                $resp->assertRedirect('/login');
+            } catch (\Exception $exception) {
+                $err = $exception;
+            }
+            $this->assertEquals("Endpoint value for \"{$endpointName}\" must start with https://", $err->getMessage());
+
+            config()->set($endpointConfigKey, $original);
+        }
+    }
+
     public function test_auth_login_with_autodiscovery()
     {
         $this->withAutodiscovery();
@@ -478,6 +510,134 @@ class OidcTest extends TestCase
         $this->assertTrue($user->hasRole($roleA->id));
     }
 
+    public function test_oidc_logout_form_active_when_oidc_active()
+    {
+        $this->runLogin();
+
+        $resp = $this->get('/');
+        $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
+    }
+    public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
+    {
+        config()->set(['oidc.end_session_endpoint' => true]);
+        $this->withAutodiscovery();
+
+        $transactions = $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
+
+        $this->assertEquals(2, $transactions->requestCount());
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
+    {
+        $this->withAutodiscovery();
+        config()->set(['oidc.end_session_endpoint' => false]);
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('/');
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_without_autodiscovery_but_with_endpoint_configured()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
+    {
+        $this->withAutodiscovery();
+        config()->set([
+            'auth.auto_initiate' => true,
+            'services.google.client_id' => false,
+            'services.github.client_id' => false,
+            'oidc.end_session_endpoint' => true,
+        ]);
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+
+        $redirectUrl = url('/login?prevent_auto_init=true');
+        $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
+        $this->withAutodiscovery();
+
+        $transactions = $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
+
+        $this->assertEquals(2, $transactions->requestCount());
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
+    {
+        config()->set(['oidc.end_session_endpoint' => true]);
+        $this->withAutodiscovery();
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('/');
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_redirect_contains_id_token_hint_if_existing()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
+
+        // Fix times so our token is predictable
+        $claimOverrides = [
+            'iat' => time(),
+            'exp' => time() + 720,
+            'auth_time' => time()
+        ];
+        $this->runLogin($claimOverrides);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) .  '&post_logout_redirect_uri=' . urlencode(url('/'));
+        $resp->assertRedirect('https://example.com/logout?' . $query);
+    }
+
     public function test_oidc_id_token_pre_validate_theme_event_without_return()
     {
         $args = [];
@@ -532,22 +692,214 @@ class OidcTest extends TestCase
         ]);
     }
 
-    protected function withAutodiscovery()
+    public function test_pkce_used_on_authorize_and_access()
+    {
+        // Start auth
+        $resp = $this->post('/oidc/login');
+        $state = session()->get('oidc_state');
+
+        $pkceCode = session()->get('oidc_pkce_code');
+        $this->assertGreaterThan(30, strlen($pkceCode));
+
+        $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
+        $redirect = $resp->headers->get('Location');
+        $redirectParams = [];
+        parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
+        $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
+        $this->assertEquals('S256', $redirectParams['code_challenge_method']);
+
+        $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
+            'email' => '[email protected]',
+            'sub'   => 'benny1010101',
+        ])]);
+
+        $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
+        $tokenRequest = $transactions->latestRequest();
+        $bodyParams = [];
+        parse_str($tokenRequest->getBody(), $bodyParams);
+        $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
+    }
+
+    public function test_userinfo_endpoint_used_if_missing_claims_in_id_token()
+    {
+        config()->set('oidc.display_name_claims', 'first_name|last_name');
+        $this->post('/oidc/login');
+        $state = session()->get('oidc_state');
+
+        $client = $this->mockHttpClient([
+            $this->getMockAuthorizationResponse(['name' => null]),
+            new Response(200, [
+                'Content-Type'  => 'application/json',
+            ], json_encode([
+                'sub' => OidcJwtHelper::defaultPayload()['sub'],
+                'first_name' => 'Barry',
+                'last_name' => 'Userinfo',
+            ]))
+        ]);
+
+        $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
+        $resp->assertRedirect('/');
+        $this->assertEquals(2, $client->requestCount());
+
+        $userinfoRequest = $client->requestAt(1);
+        $this->assertEquals('GET', $userinfoRequest->getMethod());
+        $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri());
+
+        $this->assertEquals('Barry Userinfo', user()->name);
+    }
+
+    public function test_userinfo_endpoint_fetch_with_different_sub_throws_error()
+    {
+        $userinfoResponseData = ['sub' => 'dcba4321'];
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
+    }
+
+    public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error()
+    {
+        $userinfoResponseData = ['name' => 'testing'];
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
+    }
+
+    public function test_userinfo_endpoint_fetch_can_parsed_nested_groups()
+    {
+        config()->set([
+            'oidc.user_to_groups'     => true,
+            'oidc.groups_claim'       => 'my.nested.groups.attr',
+            'oidc.remove_from_groups' => false,
+        ]);
+
+        $roleA = Role::factory()->create(['display_name' => 'Ducks']);
+        $userinfoResponseData = [
+            'sub' => OidcJwtHelper::defaultPayload()['sub'],
+            'my' => ['nested' => ['groups' => ['attr' => ['Ducks', 'Donkeys']]]]
+        ];
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
+        $resp = $this->runLogin(['groups' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/');
+
+        $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
+        $this->assertTrue($user->hasRole($roleA->id));
+    }
+
+    public function test_userinfo_endpoint_response_with_complex_json_content_type_handled()
+    {
+        $userinfoResponseData = [
+            'sub' => OidcJwtHelper::defaultPayload()['sub'],
+            'name' => 'Barry',
+        ];
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'Application/Json ; charset=utf-8'], json_encode($userinfoResponseData));
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/');
+
+        $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
+        $this->assertEquals('Barry', $user->name);
+    }
+
+    public function test_userinfo_endpoint_jwks_response_handled()
+    {
+        $userinfoResponseData = OidcJwtHelper::idToken(['name' => 'Barry Jwks']);
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
+
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/');
+
+        $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
+        $this->assertEquals('Barry Jwks', $user->name);
+    }
+
+    public function test_userinfo_endpoint_jwks_response_returning_no_sub_throws()
+    {
+        $userinfoResponseData = OidcJwtHelper::idToken(['sub' => null]);
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
+
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
+    }
+
+    public function test_userinfo_endpoint_jwks_response_returning_non_matching_sub_throws()
+    {
+        $userinfoResponseData = OidcJwtHelper::idToken(['sub' => 'zzz123']);
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
+
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
+    }
+
+    public function test_userinfo_endpoint_jwks_response_with_invalid_signature_throws()
+    {
+        $userinfoResponseData = OidcJwtHelper::idToken();
+        $exploded = explode('.', $userinfoResponseData);
+        $exploded[2] = base64_encode(base64_decode($exploded[2]) . 'ABC');
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], implode('.', $exploded));
+
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: Token signature could not be validated using the provided keys');
+    }
+
+    public function test_userinfo_endpoint_jwks_response_with_invalid_signature_alg_throws()
+    {
+        $userinfoResponseData = OidcJwtHelper::idToken([], ['alg' => 'ZZ512']);
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
+
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: Only RS256 signature validation is supported. Token reports using ZZ512');
+    }
+
+    public function test_userinfo_endpoint_response_with_invalid_content_type_throws()
+    {
+        $userinfoResponse = new Response(200, ['Content-Type'  => 'application/beans'], json_encode(OidcJwtHelper::defaultPayload()));
+        $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
+        $resp->assertRedirect('/login');
+        $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
+    }
+
+    public function test_userinfo_endpoint_not_called_if_empty_groups_array_provided_in_id_token()
+    {
+        config()->set([
+            'oidc.user_to_groups'     => true,
+            'oidc.groups_claim'       => 'groups',
+            'oidc.remove_from_groups' => false,
+        ]);
+
+        $this->post('/oidc/login');
+        $state = session()->get('oidc_state');
+        $client = $this->mockHttpClient([$this->getMockAuthorizationResponse([
+            'groups' => [],
+        ])]);
+
+        $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
+        $resp->assertRedirect('/');
+        $this->assertEquals(1, $client->requestCount());
+        $this->assertTrue(auth()->check());
+    }
+
+    protected function withAutodiscovery(): void
     {
         config()->set([
             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
             'oidc.discover'               => true,
             'oidc.authorization_endpoint' => null,
             'oidc.token_endpoint'         => null,
+            'oidc.userinfo_endpoint'      => null,
             'oidc.jwt_public_key'         => null,
         ]);
     }
 
-    protected function runLogin($claimOverrides = []): TestResponse
+    protected function runLogin($claimOverrides = [], $additionalHttpResponses = []): TestResponse
     {
         $this->post('/oidc/login');
         $state = session()->get('oidc_state');
-        $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]);
+        $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides), ...$additionalHttpResponses]);
 
         return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
     }
@@ -561,8 +913,10 @@ class OidcTest extends TestCase
         ], json_encode(array_merge([
             'token_endpoint'         => OidcJwtHelper::defaultIssuer() . '/oidc/token',
             'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
+            'userinfo_endpoint'      => OidcJwtHelper::defaultIssuer() . '/oidc/userinfo',
             'jwks_uri'               => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
             'issuer'                 => OidcJwtHelper::defaultIssuer(),
+            'end_session_endpoint'   => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
         ], $responseOverrides)));
     }