From bbdb534a117e7d2f5b8f1f90ed52992c5780367f Mon Sep 17 00:00:00 2001 From: Yong Xiang Zhan Date: Fri, 4 Dec 2026 01:45:34 +0000 Subject: [PATCH 1/2] feat(oauth2): add PKCE support to the authorization code flow OAuth 2.1 and the MCP authorization spec require clients to send a PKCE code challenge and expect the server to verify it. Nextcloud ignored these parameters, so an intercepted authorization code could still be exchanged without the code verifier, and clients that check the server for PKCE support refused to connect. The authorization endpoint now accepts a code challenge with the S256 method and the token endpoint verifies the code verifier against it. The plain method is rejected because it gives no protection against an attacker who can read the authorization request. Clients that send no challenge keep working as before. Error redirects now keep the query string and fragment of the redirect URI and honour the legacy localhost redirect of ownCloud clients, so the new PKCE errors reach the client on the URL it registered. This continues #59930 by Julien Veyssier on top of current master, where the OAuth2 entities moved to ORM attributes. Co-authored-by: Julien Veyssier Assisted-by: ClaudeCode:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Signed-off-by: Yong Xiang Zhan --- apps/oauth2/appinfo/info.xml | 2 +- .../composer/composer/autoload_classmap.php | 1 + .../composer/composer/autoload_static.php | 1 + .../Controller/LoginRedirectorController.php | 70 +++++- .../lib/Controller/OauthApiController.php | 42 ++++ apps/oauth2/lib/Db/AccessToken.php | 6 + .../Version030000Date20261202224022.php | 48 ++++ apps/oauth2/openapi.json | 24 ++ .../LoginRedirectorControllerTest.php | 173 ++++++++++++++- .../Controller/OauthApiControllerTest.php | 207 +++++++++++++++++- core/Controller/ClientFlowLoginController.php | 19 ++ openapi.json | 24 ++ .../ClientFlowLoginControllerTest.php | 114 ++++++++++ 13 files changed, 714 insertions(+), 17 deletions(-) create mode 100644 apps/oauth2/lib/Migration/Version030000Date20261202224022.php diff --git a/apps/oauth2/appinfo/info.xml b/apps/oauth2/appinfo/info.xml index f9efd562ddc50..40b9534d881c7 100644 --- a/apps/oauth2/appinfo/info.xml +++ b/apps/oauth2/appinfo/info.xml @@ -9,7 +9,7 @@ OAuth 2.0 Allows OAuth2 compatible authentication from other web applications. The OAuth2 app allows administrators to configure the built-in authentication workflow to also allow OAuth2 compatible authentication from other web applications. - 3.0.0-dev.0 + 3.0.0-dev.1 agpl Lukas Reschke OAuth2 diff --git a/apps/oauth2/composer/composer/autoload_classmap.php b/apps/oauth2/composer/composer/autoload_classmap.php index 2b685da748d02..52811f00bed40 100644 --- a/apps/oauth2/composer/composer/autoload_classmap.php +++ b/apps/oauth2/composer/composer/autoload_classmap.php @@ -27,6 +27,7 @@ 'OCA\\OAuth2\\Migration\\Version011602Date20230613160650' => $baseDir . '/../lib/Migration/Version011602Date20230613160650.php', 'OCA\\OAuth2\\Migration\\Version011603Date20230620111039' => $baseDir . '/../lib/Migration/Version011603Date20230620111039.php', 'OCA\\OAuth2\\Migration\\Version011901Date20240829164356' => $baseDir . '/../lib/Migration/Version011901Date20240829164356.php', + 'OCA\\OAuth2\\Migration\\Version030000Date20261202224022' => $baseDir . '/../lib/Migration/Version030000Date20261202224022.php', 'OCA\\OAuth2\\Service\\ClientService' => $baseDir . '/../lib/Service/ClientService.php', 'OCA\\OAuth2\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php', ); diff --git a/apps/oauth2/composer/composer/autoload_static.php b/apps/oauth2/composer/composer/autoload_static.php index 952ed942bfa5b..151ab0c9b5d1c 100644 --- a/apps/oauth2/composer/composer/autoload_static.php +++ b/apps/oauth2/composer/composer/autoload_static.php @@ -42,6 +42,7 @@ class ComposerStaticInitOAuth2 'OCA\\OAuth2\\Migration\\Version011602Date20230613160650' => __DIR__ . '/..' . '/../lib/Migration/Version011602Date20230613160650.php', 'OCA\\OAuth2\\Migration\\Version011603Date20230620111039' => __DIR__ . '/..' . '/../lib/Migration/Version011603Date20230620111039.php', 'OCA\\OAuth2\\Migration\\Version011901Date20240829164356' => __DIR__ . '/..' . '/../lib/Migration/Version011901Date20240829164356.php', + 'OCA\\OAuth2\\Migration\\Version030000Date20261202224022' => __DIR__ . '/..' . '/../lib/Migration/Version030000Date20261202224022.php', 'OCA\\OAuth2\\Service\\ClientService' => __DIR__ . '/..' . '/../lib/Service/ClientService.php', 'OCA\\OAuth2\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php', ); diff --git a/apps/oauth2/lib/Controller/LoginRedirectorController.php b/apps/oauth2/lib/Controller/LoginRedirectorController.php index d91a44a4bf617..881414b9d6da7 100644 --- a/apps/oauth2/lib/Controller/LoginRedirectorController.php +++ b/apps/oauth2/lib/Controller/LoginRedirectorController.php @@ -30,6 +30,10 @@ #[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)] final class LoginRedirectorController extends Controller { + private const string PKCE_STRING_PATTERN = '/^[A-Za-z0-9._~-]{43,128}$/'; + + private const string LEGACY_LOCALHOST_REDIRECT_PATTERN = '/^http:\/\/localhost:[0-9]+$/'; + public function __construct( string $appName, IRequest $request, @@ -44,6 +48,42 @@ public function __construct( parent::__construct($appName, $request); } + /** + * @return RedirectResponse + */ + private function buildErrorRedirectResponse( + string $registeredRedirectUri, + string $providedRedirectUri, + string $error, + string $state, + ?string $errorDescription = null, + ): RedirectResponse { + $redirectUri = $registeredRedirectUri; + $enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false); + if ($enableOcClients && $redirectUri === 'http://localhost:*' && preg_match(self::LEGACY_LOCALHOST_REDIRECT_PATTERN, $providedRedirectUri) === 1) { + $redirectUri = $providedRedirectUri; + } + + $fragment = ''; + $fragmentPosition = strpos($redirectUri, '#'); + if ($fragmentPosition !== false) { + $fragment = substr($redirectUri, $fragmentPosition); + $redirectUri = substr($redirectUri, 0, $fragmentPosition); + } + + $params = [ + 'error' => $error, + ]; + if ($errorDescription !== null) { + $params['error_description'] = $errorDescription; + } + + $params['state'] = $state; + + $separator = str_contains($redirectUri, '?') ? '&' : '?'; + return new RedirectResponse($redirectUri . $separator . http_build_query($params) . $fragment); + } + /** * Authorize the user * @@ -51,6 +91,8 @@ public function __construct( * @param string $state State of the flow * @param string $response_type Response type for the flow * @param string $redirect_uri URI to redirect to after the flow (is only used for legacy ownCloud clients) + * @param string $code_challenge PKCE code challenge (optional, RFC 7636 format) + * @param string $code_challenge_method PKCE code challenge method. Only "S256" is supported. If omitted, RFC 7636 defaults to "plain", which is rejected. * @return TemplateResponse|RedirectResponse * * 200: Client not found @@ -60,7 +102,12 @@ public function __construct( #[NoCSRFRequired] #[UseSession] public function authorize( - string $client_id, string $state, string $response_type, string $redirect_uri = '', + string $client_id, + string $state, + string $response_type, + string $redirect_uri = '', + string $code_challenge = '', + string $code_challenge_method = '', ): TemplateResponse|RedirectResponse { try { $client = $this->clientMapper->getByIdentifier($client_id); @@ -72,9 +119,22 @@ public function authorize( } if ($response_type !== 'code') { - //Fail - $url = $client->redirectUri . '?error=unsupported_response_type&state=' . \urlencode($state); - return new RedirectResponse($url); + return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'unsupported_response_type', $state); + } + + if ($code_challenge === '' && $code_challenge_method !== '') { + return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'code_challenge required'); + } + + if ($code_challenge !== '' && preg_match(self::PKCE_STRING_PATTERN, $code_challenge) !== 1) { + return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'Invalid code_challenge'); + } + + $effectiveCodeChallengeMethod = $code_challenge_method === '' && $code_challenge !== '' + ? 'plain' + : $code_challenge_method; + if ($effectiveCodeChallengeMethod !== '' && $effectiveCodeChallengeMethod !== 'S256') { + return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'Transform algorithm not supported'); } $enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false); @@ -88,6 +148,8 @@ public function authorize( 'clientIdentifier' => $client->clientIdentifier, 'state' => $state, ]); + $this->session->set('oauth.code_challenge', $code_challenge); + $this->session->set('oauth.code_challenge_method', $effectiveCodeChallengeMethod); if (in_array($client->name, $this->appConfig->getValueArray('oauth2', 'skipAuthPickerApplications', []), true)) { /** @see ClientFlowLoginController::showAuthPickerPage **/ diff --git a/apps/oauth2/lib/Controller/OauthApiController.php b/apps/oauth2/lib/Controller/OauthApiController.php index 25c78f65fb6ea..9123b5c4f017d 100644 --- a/apps/oauth2/lib/Controller/OauthApiController.php +++ b/apps/oauth2/lib/Controller/OauthApiController.php @@ -44,6 +44,8 @@ final class OauthApiController extends Controller { // the authorization code expires after 10 minutes public const int AUTHORIZATION_CODE_EXPIRES_AFTER = 10 * 60; + private const string PKCE_STRING_PATTERN = '/^[A-Za-z0-9._~-]{43,128}$/'; + public function __construct( string $appName, IRequest $request, @@ -72,6 +74,7 @@ public function __construct( * @param ?string $refresh_token Refresh token * @param ?string $client_id Client ID * @param ?string $client_secret Client secret + * @param ?string $code_verifier PKCE code verifier in RFC 7636 format (required if code_challenge was provided) * @throws Exception * @return JSONResponse|JSONResponse * @@ -84,6 +87,7 @@ public function __construct( public function getToken( string $grant_type, ?string $code, ?string $refresh_token, ?string $client_id, ?string $client_secret, + ?string $code_verifier = null, ): JSONResponse { // We only handle two types @@ -144,6 +148,44 @@ public function getToken( $response->throttle(['invalid_request' => 'authorization_code_expired', 'expired_since' => $expiredSince]); return $response; } + + // verify PKCE code_verifier if code_challenge was provided + $hashedCodeChallenge = $accessToken->hashedCodeChallenge; + if ($hashedCodeChallenge !== null && $hashedCodeChallenge !== '') { + if ($code_verifier === null || $code_verifier === '') { + $response = new JSONResponse([ + 'error' => 'invalid_request', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_request' => 'code_verifier_required']); + return $response; + } + + if (preg_match(self::PKCE_STRING_PATTERN, $code_verifier) !== 1) { + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'invalid_code_verifier']); + return $response; + } + + $codeChallengeMethod = $accessToken->codeChallengeMethod; + if ($codeChallengeMethod !== 'S256') { + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'unsupported_code_challenge_method']); + return $response; + } + + $expectedHash = rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '='); + if (!hash_equals($hashedCodeChallenge, $expectedHash)) { + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'pkce_verification_failed']); + return $response; + } + } } try { diff --git a/apps/oauth2/lib/Db/AccessToken.php b/apps/oauth2/lib/Db/AccessToken.php index 445e86d74214e..1de2b4747b905 100644 --- a/apps/oauth2/lib/Db/AccessToken.php +++ b/apps/oauth2/lib/Db/AccessToken.php @@ -39,4 +39,10 @@ final class AccessToken { #[Column(name: 'token_count', type: ColumnType::Bigint, default: 0)] public int $tokenCount = 0; + + #[Column(name: 'hashed_code_challenge', type: ColumnType::String, length: 128, nullable: true)] + public ?string $hashedCodeChallenge = null; + + #[Column(name: 'code_challenge_method', type: ColumnType::String, length: 10, nullable: true)] + public ?string $codeChallengeMethod = null; } diff --git a/apps/oauth2/lib/Migration/Version030000Date20261202224022.php b/apps/oauth2/lib/Migration/Version030000Date20261202224022.php new file mode 100644 index 0000000000000..761ff7b3ce43c --- /dev/null +++ b/apps/oauth2/lib/Migration/Version030000Date20261202224022.php @@ -0,0 +1,48 @@ +getTable('oauth2_access_tokens'); + if (!$table->hasColumn('hashed_code_challenge')) { + $table->addColumn('hashed_code_challenge', Types::STRING, [ + 'notnull' => false, + 'length' => 128, + ]); + $modified = true; + } + + if (!$table->hasColumn('code_challenge_method')) { + $table->addColumn('code_challenge_method', Types::STRING, [ + 'notnull' => false, + 'length' => 10, + ]); + $modified = true; + } + + return $modified ? $schema : null; + } +} diff --git a/apps/oauth2/openapi.json b/apps/oauth2/openapi.json index 6710c39b2552b..774b8255d1740 100644 --- a/apps/oauth2/openapi.json +++ b/apps/oauth2/openapi.json @@ -74,6 +74,24 @@ "type": "string", "default": "" } + }, + { + "name": "code_challenge", + "in": "query", + "description": "PKCE code challenge (optional, RFC 7636 format)", + "schema": { + "type": "string", + "default": "" + } + }, + { + "name": "code_challenge_method", + "in": "query", + "description": "PKCE code challenge method. Only \"S256\" is supported. If omitted, RFC 7636 defaults to \"plain\", which is rejected.", + "schema": { + "type": "string", + "default": "" + } } ], "responses": { @@ -153,6 +171,12 @@ "type": "string", "nullable": true, "description": "Client secret" + }, + "code_verifier": { + "type": "string", + "nullable": true, + "default": null, + "description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided)" } } } diff --git a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php index 30394f8558c0b..e8ee8e396aa14 100644 --- a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php +++ b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php @@ -82,9 +82,18 @@ public function testAuthorize(): void { ->with('MyClientId') ->willReturn($client); $this->session - ->expects($this->once()) + ->expects($this->exactly(3)) ->method('set') - ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']); + ->willReturnCallback(function (string $key, string|array $value): void { + switch ([$key, $value]) { + case ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']]: + case ['oauth.code_challenge', '']: + case ['oauth.code_challenge_method', '']: + break; + default: + throw new \LogicException(); + } + }); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') @@ -116,11 +125,13 @@ public function testAuthorizeSkipPicker(): void { ->with('MyClientId') ->willReturn($client); $this->session - ->expects(static::exactly(2)) + ->expects(static::exactly(4)) ->method('set') ->willReturnCallback(function (string $key, string|array $value): void { switch ([$key, $value]) { case ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']]: + case ['oauth.code_challenge', '']: + case ['oauth.code_challenge_method', '']: case [ClientFlowLoginController::STATE_NAME, 'MyStateToken']: /* Expected */ break; @@ -176,6 +187,136 @@ public function testAuthorizeWrongResponseType(): void { $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'wrongcode')); } + public function testAuthorizeWrongResponseTypePreservesExistingQuery(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar?hello=world'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + + $expected = new RedirectResponse('http://foo.bar?hello=world&error=unsupported_response_type&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'wrongcode')); + } + + public function testAuthorizeRejectsCodeChallengeMethodWithoutChallenge(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + + $expected = new RedirectResponse('http://foo.bar?error=invalid_request&error_description=code_challenge+required&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', '', 'S256')); + } + + public function testAuthorizeRejectsPkceWithoutMethodBecausePlainIsUnsupported(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + + $codeChallenge = str_repeat('a', 43); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + $expected = new RedirectResponse('http://foo.bar?error=invalid_request&error_description=Transform+algorithm+not+supported&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', $codeChallenge)); + } + + public function testAuthorizeRejectsPkceWithoutMethodForLegacyOcClientUsingProvidedRedirectUri(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://localhost:*'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(true); + + $codeChallenge = str_repeat('a', 43); + $expected = new RedirectResponse('http://localhost:30000?error=invalid_request&error_description=Transform+algorithm+not+supported&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', 'http://localhost:30000', $codeChallenge)); + } + + public function testAuthorizeRejectsUnsupportedCodeChallengeMethod(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + + $codeChallenge = str_repeat('a', 43); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + $expected = new RedirectResponse('http://foo.bar?error=invalid_request&error_description=Transform+algorithm+not+supported&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', $codeChallenge, 'plain')); + } + + public function testAuthorizeRejectsInvalidCodeChallengeFormat(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + + $expected = new RedirectResponse('http://foo.bar?error=invalid_request&error_description=Invalid+code_challenge&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', 'short', 'S256')); + } + public function testAuthorizeWithLegacyOcClient(): void { $client = new Client(); $client->name = 'MyClientName'; @@ -187,9 +328,18 @@ public function testAuthorizeWithLegacyOcClient(): void { ->with('MyClientId') ->willReturn($client); $this->session - ->expects($this->once()) + ->expects($this->exactly(3)) ->method('set') - ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']); + ->willReturnCallback(function (string $key, string|array $value): void { + switch ([$key, $value]) { + case ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']]: + case ['oauth.code_challenge', '']: + case ['oauth.code_challenge_method', '']: + break; + default: + throw new \LogicException(); + } + }); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') @@ -221,9 +371,18 @@ public function testAuthorizeNotForwardingUntrustedURIs(): void { ->with('MyClientId') ->willReturn($client); $this->session - ->expects($this->once()) + ->expects($this->exactly(3)) ->method('set') - ->with('oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']); + ->willReturnCallback(function (string $key, string|array $value): void { + switch ([$key, $value]) { + case ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState']]: + case ['oauth.code_challenge', '']: + case ['oauth.code_challenge_method', '']: + break; + default: + throw new \LogicException(); + } + }); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') diff --git a/apps/oauth2/tests/Controller/OauthApiControllerTest.php b/apps/oauth2/tests/Controller/OauthApiControllerTest.php index 56db86bf2b5b4..f05c4537fe85c 100644 --- a/apps/oauth2/tests/Controller/OauthApiControllerTest.php +++ b/apps/oauth2/tests/Controller/OauthApiControllerTest.php @@ -219,6 +219,203 @@ public function testGetTokenClientDoesNotExist(): void { $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null)); } + public function testGetTokenPkceRequiresVerifier(): void { + $expected = new JSONResponse([ + 'error' => 'invalid_request', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_request' => 'code_verifier_required']); + + $codeChallenge = str_repeat('a', 43); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = $codeChallenge; + $accessToken->codeChallengeMethod = 'S256'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null)); + } + + public function testGetTokenPkceRejectsInvalidVerifierFormat(): void { + $expected = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_grant' => 'invalid_code_verifier']); + + $codeChallenge = str_repeat('a', 43); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = $codeChallenge; + $accessToken->codeChallengeMethod = 'S256'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null, 'short')); + } + + public function testGetTokenPkceS256VerifierMismatch(): void { + $expected = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_grant' => 'pkce_verification_failed']); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = 'expected-challenge'; + $accessToken->codeChallengeMethod = 'S256'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null, str_repeat('b', 43))); + } + + public function testGetTokenPkceRejectsUnsupportedStoredMethod(): void { + $expected = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_grant' => 'unsupported_code_challenge_method']); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = str_repeat('a', 43); + $accessToken->codeChallengeMethod = 'plain'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null, str_repeat('a', 43))); + } + + public function testGetTokenPkceS256VerifierMatch(): void { + $codeVerifier = str_repeat('a', 43); + $codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '='); + + $accessToken = new AccessToken(); + $accessToken->id = 21; + $accessToken->clientId = 42; + $accessToken->tokenId = 1337; + $accessToken->encryptedToken = 'encryptedToken'; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = $codeChallenge; + $accessToken->codeChallengeMethod = 'S256'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $client = new Client(); + $client->clientIdentifier = 'clientId'; + $client->secret = bin2hex('hashedClientSecret'); + $this->clientMapper->method('getByUid') + ->with(42) + ->willReturn($client); + + $this->db->expects($this->once()) + ->method('beginTransaction'); + + $this->db->expects($this->once()) + ->method('commit'); + + $this->db->expects($this->never()) + ->method('rollBack'); + + $this->tokenProvider->expects($this->never()) + ->method('invalidateToken'); + + $this->crypto + ->method('decrypt') + ->with('encryptedToken', 'validcode') + ->willReturn('decryptedToken'); + + $this->crypto + ->method('calculateHMAC') + ->with('clientSecret') + ->willReturn('hashedClientSecret'); + + $appToken = new PublicKeyToken(); + $appToken->setUid('userId'); + $this->tokenProvider->method('getTokenById') + ->with(1337) + ->willThrowException(new ExpiredTokenException($appToken)); + + $this->secureRandom->method('generate') + ->willReturnCallback(fn (int $len): string => 'random' . $len); + + $this->tokenProvider->expects($this->once()) + ->method('rotate') + ->with( + $appToken, + 'decryptedToken', + 'random72' + )->willReturn($appToken); + + $this->time->method('getTime') + ->willReturn(1000); + + $this->tokenProvider->expects($this->once()) + ->method('updateToken') + ->with( + $this->callback(fn (PublicKeyToken $token): bool => $token->getExpires() === 4600) + ); + + $this->crypto->method('encrypt') + ->with('random72', 'random128') + ->willReturn('newEncryptedToken'); + + $this->accessTokenMapper->expects($this->once()) + ->method('rotateToken') + ->with( + 21, + 'validcode', + 'random128', + 'newEncryptedToken', + 'authorization_code', + )->willReturn(1); + + $expected = new JSONResponse([ + 'access_token' => 'random72', + 'token_type' => 'Bearer', + 'expires_in' => 3600, + 'refresh_token' => 'random128', + 'user_id' => 'userId', + ]); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret', $codeVerifier)); + } + public function testRefreshTokenInvalidRefreshToken(): void { $expected = new JSONResponse([ 'error' => 'invalid_request', @@ -323,7 +520,7 @@ public function testRefreshTokenInvalidAppToken(): void { $this->crypto ->method('decrypt') - ->with('encryptedToken') + ->with('encryptedToken', 'validrefresh') ->willReturn('decryptedToken'); $this->crypto @@ -363,7 +560,7 @@ public function testRefreshTokenValidAppToken(): void { $this->crypto ->method('decrypt') - ->with('encryptedToken') + ->with('encryptedToken', 'validrefresh') ->willReturn('decryptedToken'); $this->crypto @@ -459,7 +656,7 @@ public function testRefreshTokenValidAppTokenBasicAuth(): void { $this->crypto ->method('decrypt') - ->with('encryptedToken') + ->with('encryptedToken', 'validrefresh') ->willReturn('decryptedToken'); $this->crypto @@ -558,7 +755,7 @@ public function testRefreshTokenExpiredAppToken(): void { $this->crypto ->method('decrypt') - ->with('encryptedToken') + ->with('encryptedToken', 'validrefresh') ->willReturn('decryptedToken'); $this->crypto @@ -659,7 +856,7 @@ public function testRefreshTokenRedeemedConcurrently(): void { $this->crypto ->method('decrypt') - ->with('encryptedToken') + ->with('encryptedToken', 'validrefresh') ->willReturn('decryptedToken'); $this->crypto diff --git a/core/Controller/ClientFlowLoginController.php b/core/Controller/ClientFlowLoginController.php index 798f104e1ab09..232f4f29742f5 100644 --- a/core/Controller/ClientFlowLoginController.php +++ b/core/Controller/ClientFlowLoginController.php @@ -312,8 +312,19 @@ public function generateAppPassword( $accessToken->hashedCode = hash('sha512', $code); $accessToken->tokenId = $generatedToken->getId(); $accessToken->codeCreatedAt = $this->timeFactory->now()->getTimestamp(); + + $codeChallenge = $this->session->get('oauth.code_challenge'); + $codeChallengeMethod = $this->session->get('oauth.code_challenge_method'); + if ($codeChallenge !== null && $codeChallenge !== '') { + $accessToken->hashedCodeChallenge = $codeChallenge; + $accessToken->codeChallengeMethod = $codeChallengeMethod; + } + $this->accessTokenMapper->insert($accessToken); + $this->session->remove('oauth.code_challenge'); + $this->session->remove('oauth.code_challenge_method'); + $enableOcClients = $this->config->getSystemValueBool('oauth2.enable_oc_clients', false); $redirectUri = $client->redirectUri; @@ -328,6 +339,13 @@ public function generateAppPassword( $redirectUri = $providedRedirectUri; } + $fragment = ''; + $fragmentPosition = strpos($redirectUri, '#'); + if ($fragmentPosition !== false) { + $fragment = substr($redirectUri, $fragmentPosition); + $redirectUri = substr($redirectUri, 0, $fragmentPosition); + } + if (parse_url($redirectUri, PHP_URL_QUERY)) { $redirectUri .= '&'; } else { @@ -339,6 +357,7 @@ public function generateAppPassword( urlencode($this->getOAuthState($clientIdentifier) ?? ''), urlencode($code) ); + $redirectUri .= $fragment; $this->session->remove('oauth.state'); } else { $redirectUri = 'nc://login/server:' . $this->getServerPath() . '&user:' . urlencode($loginName) . '&password:' . urlencode($token); diff --git a/openapi.json b/openapi.json index 51b24b1822ca6..a284f637e5e02 100644 --- a/openapi.json +++ b/openapi.json @@ -30988,6 +30988,24 @@ "type": "string", "default": "" } + }, + { + "name": "code_challenge", + "in": "query", + "description": "PKCE code challenge (optional, RFC 7636 format)", + "schema": { + "type": "string", + "default": "" + } + }, + { + "name": "code_challenge_method", + "in": "query", + "description": "PKCE code challenge method. Only \"S256\" is supported. If omitted, RFC 7636 defaults to \"plain\", which is rejected.", + "schema": { + "type": "string", + "default": "" + } } ], "responses": { @@ -31067,6 +31085,12 @@ "type": "string", "nullable": true, "description": "Client secret" + }, + "code_verifier": { + "type": "string", + "nullable": true, + "default": null, + "description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided)" } } } diff --git a/tests/Core/Controller/ClientFlowLoginControllerTest.php b/tests/Core/Controller/ClientFlowLoginControllerTest.php index b224ce1e71efd..a28cf3de0abb8 100644 --- a/tests/Core/Controller/ClientFlowLoginControllerTest.php +++ b/tests/Core/Controller/ClientFlowLoginControllerTest.php @@ -15,6 +15,7 @@ use OC\Authentication\Token\IProvider; use OC\Authentication\Token\IToken; use OC\Core\Controller\ClientFlowLoginController; +use OCA\OAuth2\Db\AccessToken; use OCA\OAuth2\Db\AccessTokenMapper; use OCA\OAuth2\Db\Client; use OCA\OAuth2\Db\ClientMapper; @@ -426,6 +427,8 @@ public function testGeneratePasswordWithPassword(): void { * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode", "MyClientIdentifier"] * ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode", "MyClientIdentifier"] * ["https://example.com/redirect.php", "https://example.com/redirect.php?state=&code=MyAccessCode", "OtherClientIdentifier"] + * ["https://example.com/redirect.php#target", "https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode#target", "MyClientIdentifier"] + * ["https://example.com/redirect.php?hello=world#target", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode#target", "MyClientIdentifier"] * */ public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl, string $stateClientIdentifier): void { @@ -437,6 +440,8 @@ public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $re ]); $calls = [ 'client.flow.state.token', + 'oauth.code_challenge', + 'oauth.code_challenge_method', 'oauth.state', ]; $this->session @@ -509,6 +514,115 @@ public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $re $this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken', 'MyClientIdentifier')); } + public function testGeneratePasswordWithPasswordForOauthClientStoresPkceChallenge(): void { + $codeChallenge = str_repeat('a', 43); + $this->session + ->method('get') + ->willReturnMap([ + ['client.flow.state.token', 'MyStateToken'], + ['oauth.state', ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyOauthState']], + ['oauth.code_challenge', $codeChallenge], + ['oauth.code_challenge_method', 'S256'], + ]); + $calls = [ + 'client.flow.state.token', + 'oauth.code_challenge', + 'oauth.code_challenge_method', + 'oauth.state', + ]; + $this->session + ->method('remove') + ->willReturnCallback(function ($key) use (&$calls): void { + $expected = array_shift($calls); + $this->assertEquals($expected, $key); + }); + $this->session + ->expects($this->once()) + ->method('getId') + ->willReturn('SessionId'); + $myToken = $this->createMock(IToken::class); + $myToken + ->expects($this->once()) + ->method('getLoginName') + ->willReturn('MyLoginName'); + $this->tokenProvider + ->expects($this->once()) + ->method('getToken') + ->with('SessionId') + ->willReturn($myToken); + $this->tokenProvider + ->expects($this->once()) + ->method('getPassword') + ->with($myToken, 'SessionId') + ->willReturn('MyPassword'); + $this->random + ->method('generate') + ->willReturnMap([ + [72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS, 'MyGeneratedToken'], + [128, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS, 'MyAccessCode'], + ]); + $user = $this->createMock(IUser::class); + $user + ->expects($this->once()) + ->method('getUID') + ->willReturn('MyUid'); + $this->userSession + ->expects($this->once()) + ->method('getUser') + ->willReturn($user); + $token = $this->createMock(IToken::class); + $token->method('getId')->willReturn(123); + $this->tokenProvider + ->expects($this->once()) + ->method('generateToken') + ->with( + 'MyGeneratedToken', + 'MyUid', + 'MyLoginName', + 'MyPassword', + 'My OAuth client', + IToken::PERMANENT_TOKEN, + IToken::DO_NOT_REMEMBER + ) + ->willReturn($token); + $client = new Client(); + $client->id = 42; + $client->name = 'My OAuth client'; + $client->redirectUri = 'https://example.com/redirect.php'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientIdentifier') + ->willReturn($client); + $this->crypto + ->expects($this->once()) + ->method('encrypt') + ->with('MyGeneratedToken', 'MyAccessCode') + ->willReturn('EncryptedToken'); + $this->timeFactory + ->expects($this->once()) + ->method('now') + ->willReturn((new \DateTimeImmutable())->setTimestamp(100)); + $this->accessTokenMapper + ->expects($this->once()) + ->method('insert') + ->with($this->callback(function (AccessToken $accessToken) { + return $accessToken->hashedCodeChallenge === str_repeat('a', 43) + && $accessToken->codeChallengeMethod === 'S256' + && $accessToken->hashedCode === hash('sha512', 'MyAccessCode'); + })); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + + $this->expectAppPasswordCreatedEvents(); + + $expected = new RedirectResponse('https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode'); + $this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken', 'MyClientIdentifier')); + } + public function testGeneratePasswordWithoutPassword(): void { $this->session ->expects($this->once()) From ab1180a57512f39709e52374393d8a48cd0a87aa Mon Sep 17 00:00:00 2001 From: Yong Xiang Zhan Date: Fri, 4 Dec 2026 01:45:34 +0000 Subject: [PATCH 2/2] feat(oauth2): harden PKCE against downgrade and probing PKCE only helps if a code can never lose the challenge its client sent. Three gaps remained after the port: - The token endpoint accepted a code verifier for a code that has no challenge. RFC 9700 section 2.1.1 forbids that, because it hides a challenge that was stripped from the authorization request. - The challenge lives in the session, so a second authorization request in the same session replaced it while the consent page of the first request could still be approved. A new request now invalidates the consent page that is still open. - The verifier was checked before the client was authenticated, so anybody holding a code could find out whether it is bound to a challenge and test verifiers without the client secret. A challenge must now be exactly 43 base64url characters, the only shape an S256 challenge can have, and the patterns no longer match a trailing newline. Error redirects use a literal "&" so the PHP setting arg_separator.output cannot change them. Assisted-by: ClaudeCode:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Signed-off-by: Yong Xiang Zhan --- .../Controller/LoginRedirectorController.php | 12 +- .../lib/Controller/OauthApiController.php | 90 +++++++------- apps/oauth2/openapi.json | 2 +- .../LoginRedirectorControllerTest.php | 94 +++++++++++++++ .../Controller/OauthApiControllerTest.php | 113 +++++++++++++++++- openapi.json | 2 +- 6 files changed, 263 insertions(+), 50 deletions(-) diff --git a/apps/oauth2/lib/Controller/LoginRedirectorController.php b/apps/oauth2/lib/Controller/LoginRedirectorController.php index 881414b9d6da7..4c1a5007f7741 100644 --- a/apps/oauth2/lib/Controller/LoginRedirectorController.php +++ b/apps/oauth2/lib/Controller/LoginRedirectorController.php @@ -30,9 +30,10 @@ #[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)] final class LoginRedirectorController extends Controller { - private const string PKCE_STRING_PATTERN = '/^[A-Za-z0-9._~-]{43,128}$/'; + // An S256 code challenge is the unpadded base64url encoding of a SHA-256 hash, which is always 43 characters + private const string CODE_CHALLENGE_PATTERN = '/^[A-Za-z0-9_-]{43}$/D'; - private const string LEGACY_LOCALHOST_REDIRECT_PATTERN = '/^http:\/\/localhost:[0-9]+$/'; + private const string LEGACY_LOCALHOST_REDIRECT_PATTERN = '/^http:\/\/localhost:[0-9]+$/D'; public function __construct( string $appName, @@ -81,7 +82,7 @@ private function buildErrorRedirectResponse( $params['state'] = $state; $separator = str_contains($redirectUri, '?') ? '&' : '?'; - return new RedirectResponse($redirectUri . $separator . http_build_query($params) . $fragment); + return new RedirectResponse($redirectUri . $separator . http_build_query($params, '', '&') . $fragment); } /** @@ -126,7 +127,7 @@ public function authorize( return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'code_challenge required'); } - if ($code_challenge !== '' && preg_match(self::PKCE_STRING_PATTERN, $code_challenge) !== 1) { + if ($code_challenge !== '' && preg_match(self::CODE_CHALLENGE_PATTERN, $code_challenge) !== 1) { return $this->buildErrorRedirectResponse($client->redirectUri, $redirect_uri, 'invalid_request', $state, 'Invalid code_challenge'); } @@ -144,6 +145,9 @@ public function authorize( $providedRedirectUri = $redirect_uri; } + // The values below are stored once per session. A consent page that is still open from an + // earlier request must not be able to complete with them, so its flow token is dropped here. + $this->session->remove(ClientFlowLoginController::STATE_NAME); $this->session->set('oauth.state', [ 'clientIdentifier' => $client->clientIdentifier, 'state' => $state, diff --git a/apps/oauth2/lib/Controller/OauthApiController.php b/apps/oauth2/lib/Controller/OauthApiController.php index 9123b5c4f017d..c13c4a94cbed7 100644 --- a/apps/oauth2/lib/Controller/OauthApiController.php +++ b/apps/oauth2/lib/Controller/OauthApiController.php @@ -44,7 +44,7 @@ final class OauthApiController extends Controller { // the authorization code expires after 10 minutes public const int AUTHORIZATION_CODE_EXPIRES_AFTER = 10 * 60; - private const string PKCE_STRING_PATTERN = '/^[A-Za-z0-9._~-]{43,128}$/'; + private const string PKCE_STRING_PATTERN = '/^[A-Za-z0-9._~-]{43,128}$/D'; public function __construct( string $appName, @@ -74,7 +74,7 @@ public function __construct( * @param ?string $refresh_token Refresh token * @param ?string $client_id Client ID * @param ?string $client_secret Client secret - * @param ?string $code_verifier PKCE code verifier in RFC 7636 format (required if code_challenge was provided) + * @param ?string $code_verifier PKCE code verifier in RFC 7636 format (required if code_challenge was provided, rejected otherwise) * @throws Exception * @return JSONResponse|JSONResponse * @@ -148,44 +148,6 @@ public function getToken( $response->throttle(['invalid_request' => 'authorization_code_expired', 'expired_since' => $expiredSince]); return $response; } - - // verify PKCE code_verifier if code_challenge was provided - $hashedCodeChallenge = $accessToken->hashedCodeChallenge; - if ($hashedCodeChallenge !== null && $hashedCodeChallenge !== '') { - if ($code_verifier === null || $code_verifier === '') { - $response = new JSONResponse([ - 'error' => 'invalid_request', - ], Http::STATUS_BAD_REQUEST); - $response->throttle(['invalid_request' => 'code_verifier_required']); - return $response; - } - - if (preg_match(self::PKCE_STRING_PATTERN, $code_verifier) !== 1) { - $response = new JSONResponse([ - 'error' => 'invalid_grant', - ], Http::STATUS_BAD_REQUEST); - $response->throttle(['invalid_grant' => 'invalid_code_verifier']); - return $response; - } - - $codeChallengeMethod = $accessToken->codeChallengeMethod; - if ($codeChallengeMethod !== 'S256') { - $response = new JSONResponse([ - 'error' => 'invalid_grant', - ], Http::STATUS_BAD_REQUEST); - $response->throttle(['invalid_grant' => 'unsupported_code_challenge_method']); - return $response; - } - - $expectedHash = rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '='); - if (!hash_equals($hashedCodeChallenge, $expectedHash)) { - $response = new JSONResponse([ - 'error' => 'invalid_grant', - ], Http::STATUS_BAD_REQUEST); - $response->throttle(['invalid_grant' => 'pkce_verification_failed']); - return $response; - } - } } try { @@ -235,6 +197,54 @@ public function getToken( return $response; } + if ($grant_type === 'authorization_code') { + // Verify the PKCE code verifier only for an authenticated client, so the answer says nothing to anybody else + $hashedCodeChallenge = $accessToken->hashedCodeChallenge; + if ($hashedCodeChallenge !== null && $hashedCodeChallenge !== '') { + if ($code_verifier === null || $code_verifier === '') { + $response = new JSONResponse([ + 'error' => 'invalid_request', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_request' => 'code_verifier_required']); + return $response; + } + + if (preg_match(self::PKCE_STRING_PATTERN, $code_verifier) !== 1) { + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'invalid_code_verifier']); + return $response; + } + + $codeChallengeMethod = $accessToken->codeChallengeMethod; + if ($codeChallengeMethod !== 'S256') { + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'unsupported_code_challenge_method']); + return $response; + } + + $expectedHash = rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '='); + if (!hash_equals($hashedCodeChallenge, $expectedHash)) { + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'pkce_verification_failed']); + return $response; + } + } elseif ($code_verifier !== null && $code_verifier !== '') { + // A code verifier is only valid for a code that was requested with a code challenge (RFC 9700 section 2.1.1). + // Accepting it here would hide that the challenge was stripped from the authorization request. + $response = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $response->throttle(['invalid_grant' => 'unexpected_code_verifier']); + return $response; + } + } + $decryptedToken = $this->crypto->decrypt($accessToken->encryptedToken, $code); // Obtain the appToken associated diff --git a/apps/oauth2/openapi.json b/apps/oauth2/openapi.json index 774b8255d1740..088cb5bfcb845 100644 --- a/apps/oauth2/openapi.json +++ b/apps/oauth2/openapi.json @@ -176,7 +176,7 @@ "type": "string", "nullable": true, "default": null, - "description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided)" + "description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided, rejected otherwise)" } } } diff --git a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php index e8ee8e396aa14..2209c50af33a8 100644 --- a/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php +++ b/apps/oauth2/tests/Controller/LoginRedirectorControllerTest.php @@ -317,6 +317,100 @@ public function testAuthorizeRejectsInvalidCodeChallengeFormat(): void { $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', 'short', 'S256')); } + public function testAuthorizeRejectsCodeChallengeWithTrailingNewline(): void { + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + + $expected = new RedirectResponse('http://foo.bar?error=invalid_request&error_description=Invalid+code_challenge&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', str_repeat('a', 43) . "\n", 'S256')); + } + + public function testAuthorizeRejectsCodeChallengeThatIsNotASha256Hash(): void { + // 44 characters of the right alphabet can never be the S256 transform of a verifier + $client = new Client(); + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $this->session + ->expects($this->never()) + ->method('set'); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + + $expected = new RedirectResponse('http://foo.bar?error=invalid_request&error_description=Invalid+code_challenge&state=MyState'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', str_repeat('a', 44), 'S256')); + } + + public function testAuthorizeStoresChallengeAndDropsPendingFlowToken(): void { + $codeChallenge = str_repeat('a', 43); + $client = new Client(); + $client->name = 'MyClientName'; + $client->clientIdentifier = 'MyClientIdentifier'; + $client->redirectUri = 'http://foo.bar'; + $this->clientMapper + ->expects($this->once()) + ->method('getByIdentifier') + ->with('MyClientId') + ->willReturn($client); + $stored = []; + $this->session + ->expects($this->exactly(3)) + ->method('set') + ->willReturnCallback(function (string $key, string|array $value) use (&$stored): void { + $stored[$key] = $value; + }); + // A consent page of an earlier request must not complete with the values of this one + $this->session + ->expects($this->once()) + ->method('remove') + ->with(ClientFlowLoginController::STATE_NAME); + $this->urlGenerator + ->expects($this->once()) + ->method('linkToRouteAbsolute') + ->with( + 'core.ClientFlowLogin.showAuthPickerPage', + [ + 'clientIdentifier' => 'MyClientIdentifier', + 'providedRedirectUri' => '', + ] + ) + ->willReturn('https://example.com/?clientIdentifier=foo'); + $this->config + ->expects($this->once()) + ->method('getSystemValueBool') + ->with('oauth2.enable_oc_clients', false) + ->willReturn(false); + + $expected = new RedirectResponse('https://example.com/?clientIdentifier=foo'); + $this->assertEquals($expected, $this->loginRedirectorController->authorize('MyClientId', 'MyState', 'code', '', $codeChallenge, 'S256')); + $this->assertSame([ + 'oauth.state' => ['clientIdentifier' => 'MyClientIdentifier', 'state' => 'MyState'], + 'oauth.code_challenge' => $codeChallenge, + 'oauth.code_challenge_method' => 'S256', + ], $stored); + } + public function testAuthorizeWithLegacyOcClient(): void { $client = new Client(); $client->name = 'MyClientName'; diff --git a/apps/oauth2/tests/Controller/OauthApiControllerTest.php b/apps/oauth2/tests/Controller/OauthApiControllerTest.php index f05c4537fe85c..bf528073bb6ac 100644 --- a/apps/oauth2/tests/Controller/OauthApiControllerTest.php +++ b/apps/oauth2/tests/Controller/OauthApiControllerTest.php @@ -241,7 +241,9 @@ public function testGetTokenPkceRequiresVerifier(): void { $this->timeFactory->method('now') ->willReturn($dateNow); - $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null)); + $this->arrangeAuthenticatedClient(); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret')); } public function testGetTokenPkceRejectsInvalidVerifierFormat(): void { @@ -266,7 +268,93 @@ public function testGetTokenPkceRejectsInvalidVerifierFormat(): void { $this->timeFactory->method('now') ->willReturn($dateNow); - $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null, 'short')); + $this->arrangeAuthenticatedClient(); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret', 'short')); + } + + public function testGetTokenPkceRejectsVerifierWithTrailingNewline(): void { + $expected = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_grant' => 'invalid_code_verifier']); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = str_repeat('a', 43); + $accessToken->codeChallengeMethod = 'S256'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $this->arrangeAuthenticatedClient(); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret', str_repeat('a', 43) . "\n")); + } + + public function testGetTokenRejectsVerifierWithoutChallenge(): void { + // The authorization request had no code challenge, so a code verifier must not be accepted + $expected = new JSONResponse([ + 'error' => 'invalid_grant', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_grant' => 'unexpected_code_verifier']); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $this->arrangeAuthenticatedClient(); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret', str_repeat('a', 43))); + } + + public function testGetTokenChecksClientBeforePkce(): void { + // A caller that cannot authenticate as the client must not learn whether the verifier matches + $expected = new JSONResponse([ + 'error' => 'invalid_client', + ], Http::STATUS_BAD_REQUEST); + $expected->throttle(['invalid_client' => 'client ID or secret does not match']); + + $accessToken = new AccessToken(); + $accessToken->clientId = 42; + $accessToken->codeCreatedAt = 100; + $accessToken->hashedCodeChallenge = str_repeat('a', 43); + $accessToken->codeChallengeMethod = 'S256'; + + $this->accessTokenMapper->method('getByCode') + ->with('validcode') + ->willReturn($accessToken); + + $dateNow = (new \DateTimeImmutable())->setTimestamp(101); + $this->timeFactory->method('now') + ->willReturn($dateNow); + + $client = new Client(); + $client->clientIdentifier = 'clientId'; + $client->secret = bin2hex('hashedClientSecret'); + $this->clientMapper->method('getByUid') + ->with(42) + ->willReturn($client); + $this->crypto + ->method('calculateHMAC') + ->with('wrongSecret') + ->willReturn('otherHash'); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'wrongSecret', str_repeat('b', 43))); } public function testGetTokenPkceS256VerifierMismatch(): void { @@ -289,7 +377,9 @@ public function testGetTokenPkceS256VerifierMismatch(): void { $this->timeFactory->method('now') ->willReturn($dateNow); - $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null, str_repeat('b', 43))); + $this->arrangeAuthenticatedClient(); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret', str_repeat('b', 43))); } public function testGetTokenPkceRejectsUnsupportedStoredMethod(): void { @@ -312,7 +402,9 @@ public function testGetTokenPkceRejectsUnsupportedStoredMethod(): void { $this->timeFactory->method('now') ->willReturn($dateNow); - $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null, str_repeat('a', 43))); + $this->arrangeAuthenticatedClient(); + + $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, 'clientId', 'clientSecret', str_repeat('a', 43))); } public function testGetTokenPkceS256VerifierMatch(): void { @@ -915,6 +1007,19 @@ public function testRefreshTokenRedeemedConcurrently(): void { * arrange a successful "refresh_token" exchange, shared by the secondary-push tests below. * returns the resulting app token, so tests can further configure push-related mocks. */ + private function arrangeAuthenticatedClient(): void { + $client = new Client(); + $client->clientIdentifier = 'clientId'; + $client->secret = bin2hex('hashedClientSecret'); + $this->clientMapper->method('getByUid') + ->with(42) + ->willReturn($client); + $this->crypto + ->method('calculateHMAC') + ->with('clientSecret') + ->willReturn('hashedClientSecret'); + } + private function arrangeSuccessfulTokenExchange(): PublicKeyToken { $accessToken = new AccessToken(); $accessToken->id = 21; diff --git a/openapi.json b/openapi.json index a284f637e5e02..f2622d2d02310 100644 --- a/openapi.json +++ b/openapi.json @@ -31090,7 +31090,7 @@ "type": "string", "nullable": true, "default": null, - "description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided)" + "description": "PKCE code verifier in RFC 7636 format (required if code_challenge was provided, rejected otherwise)" } } }