-
Notifications
You must be signed in to change notification settings - Fork 127
[Server] feat: relax StrictOidcDiscoveryMetadataPolicy and add Dynamic Client Registration middleware (RFC 7591) #269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
04e25df
feat: relax OIDC discovery policy and add Dynamic Client Registration…
simonchrz 5308f43
fix: move metadata policy note under server.php in Files section
simonchrz bafac06
fix: address Copilot review comments on ClientRegistrationMiddleware
simonchrz 51dce3f
fix: harden ClientRegistrationMiddleware and improve test coverage
simonchrz d0e3077
fix: reject JSON array bodies in metadata enrichment
simonchrz 3097949
fix: add RFC 7591 error codes, Content-Type validation, and docblock …
chr-hertel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 0 additions & 38 deletions
38
examples/server/oauth-microsoft/MicrosoftOidcMetadataPolicy.php
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 0 additions & 64 deletions
64
examples/server/oauth-microsoft/tests/Unit/MicrosoftOidcMetadataPolicyTest.php
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the official PHP MCP SDK. | ||
| * | ||
| * A collaboration between Symfony and the PHP Foundation. | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Mcp\Exception; | ||
|
|
||
| final class ClientRegistrationException extends \RuntimeException implements ExceptionInterface | ||
| { | ||
| public function __construct( | ||
| string $message, | ||
| public readonly string $errorCode = 'invalid_client_metadata', | ||
| ?\Throwable $previous = null, | ||
| ) { | ||
| parent::__construct($message, 0, $previous); | ||
| } | ||
| } |
177 changes: 177 additions & 0 deletions
177
src/Server/Transport/Http/Middleware/ClientRegistrationMiddleware.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,177 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the official PHP MCP SDK. | ||
| * | ||
| * A collaboration between Symfony and the PHP Foundation. | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Mcp\Server\Transport\Http\Middleware; | ||
|
|
||
| use Http\Discovery\Psr17FactoryDiscovery; | ||
| use Mcp\Exception\ClientRegistrationException; | ||
| use Mcp\Exception\InvalidArgumentException; | ||
| use Mcp\Server\Transport\Http\OAuth\ClientRegistrarInterface; | ||
| use Psr\Http\Message\ResponseFactoryInterface; | ||
| use Psr\Http\Message\ResponseInterface; | ||
| use Psr\Http\Message\ServerRequestInterface; | ||
| use Psr\Http\Message\StreamFactoryInterface; | ||
| use Psr\Http\Server\MiddlewareInterface; | ||
| use Psr\Http\Server\RequestHandlerInterface; | ||
|
|
||
| /** | ||
| * OAuth 2.0 Dynamic Client Registration (RFC 7591) middleware. | ||
| * | ||
| * Handles POST /register requests by delegating to a ClientRegistrarInterface | ||
| * and enriches /.well-known/oauth-authorization-server responses with the | ||
| * registration_endpoint. | ||
| */ | ||
| final class ClientRegistrationMiddleware implements MiddlewareInterface | ||
| { | ||
| private const REGISTRATION_PATH = '/register'; | ||
|
|
||
| private ResponseFactoryInterface $responseFactory; | ||
| private StreamFactoryInterface $streamFactory; | ||
|
|
||
| public function __construct( | ||
| private readonly ClientRegistrarInterface $registrar, | ||
| private readonly string $localBaseUrl, | ||
| ?ResponseFactoryInterface $responseFactory = null, | ||
| ?StreamFactoryInterface $streamFactory = null, | ||
| ) { | ||
| if ('' === trim($localBaseUrl)) { | ||
| throw new InvalidArgumentException('The $localBaseUrl must not be empty.'); | ||
| } | ||
|
|
||
| $this->responseFactory = $responseFactory ?? Psr17FactoryDiscovery::findResponseFactory(); | ||
| $this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory(); | ||
| } | ||
|
|
||
| public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | ||
| { | ||
| $path = $request->getUri()->getPath(); | ||
|
|
||
| if ('POST' === $request->getMethod() && self::REGISTRATION_PATH === $path) { | ||
| return $this->handleRegistration($request); | ||
| } | ||
|
|
||
| $response = $handler->handle($request); | ||
|
|
||
| if ('GET' === $request->getMethod() && '/.well-known/oauth-authorization-server' === $path) { | ||
| return $this->enrichAuthServerMetadata($response); | ||
| } | ||
|
|
||
| return $response; | ||
| } | ||
|
|
||
| private function handleRegistration(ServerRequestInterface $request): ResponseInterface | ||
| { | ||
| $contentType = $request->getHeaderLine('Content-Type'); | ||
| if (!str_starts_with($contentType, 'application/json')) { | ||
| return $this->jsonResponse(400, [ | ||
| 'error' => 'invalid_client_metadata', | ||
| 'error_description' => 'Content-Type must be application/json.', | ||
| ], ['Cache-Control' => 'no-store']); | ||
| } | ||
|
|
||
| $body = $request->getBody()->__toString(); | ||
|
|
||
| try { | ||
| $decoded = json_decode($body, false, 512, \JSON_THROW_ON_ERROR); | ||
| } catch (\JsonException) { | ||
| return $this->jsonResponse(400, [ | ||
| 'error' => 'invalid_client_metadata', | ||
| 'error_description' => 'Request body must be valid JSON.', | ||
| ], ['Cache-Control' => 'no-store']); | ||
| } | ||
|
|
||
| if (!$decoded instanceof \stdClass) { | ||
| return $this->jsonResponse(400, [ | ||
| 'error' => 'invalid_client_metadata', | ||
| 'error_description' => 'Request body must be a JSON object.', | ||
| ], ['Cache-Control' => 'no-store']); | ||
| } | ||
|
|
||
| // Re-decode with assoc=true so nested objects become arrays (safe — already validated above) | ||
| /** @var array<string, mixed> $data */ | ||
| $data = json_decode($body, true, 512, \JSON_THROW_ON_ERROR); | ||
|
|
||
| try { | ||
| $result = $this->registrar->register($data); | ||
| } catch (ClientRegistrationException $e) { | ||
| return $this->jsonResponse(400, [ | ||
| 'error' => $e->errorCode, | ||
| 'error_description' => $e->getMessage(), | ||
| ], ['Cache-Control' => 'no-store']); | ||
| } | ||
simonchrz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return $this->jsonResponse(201, $result, [ | ||
| 'Cache-Control' => 'no-store', | ||
| ]); | ||
| } | ||
|
|
||
| private function enrichAuthServerMetadata(ResponseInterface $response): ResponseInterface | ||
| { | ||
| if (200 !== $response->getStatusCode()) { | ||
| return $response; | ||
| } | ||
|
|
||
| $stream = $response->getBody(); | ||
|
|
||
| if ($stream->isSeekable()) { | ||
| $stream->rewind(); | ||
| } | ||
|
|
||
| try { | ||
| $metadata = json_decode($stream->__toString(), true, 512, \JSON_THROW_ON_ERROR); | ||
| } catch (\JsonException) { | ||
| if ($stream->isSeekable()) { | ||
| $stream->rewind(); | ||
| } | ||
|
|
||
| return $response; | ||
| } | ||
|
|
||
| if (!\is_array($metadata) || ([] !== $metadata && array_is_list($metadata))) { | ||
| if ($stream->isSeekable()) { | ||
| $stream->rewind(); | ||
| } | ||
|
|
||
| return $response; | ||
| } | ||
|
|
||
| $metadata['registration_endpoint'] = rtrim($this->localBaseUrl, '/').self::REGISTRATION_PATH; | ||
|
|
||
| return $response | ||
| ->withBody($this->streamFactory->createStream( | ||
| json_encode($metadata, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES), | ||
| )) | ||
| ->withHeader('Content-Type', 'application/json') | ||
| ->withoutHeader('Content-Length'); | ||
| } | ||
simonchrz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * @param array<string, mixed> $data | ||
| * @param array<string, string> $extraHeaders | ||
| */ | ||
| private function jsonResponse(int $status, array $data, array $extraHeaders = []): ResponseInterface | ||
| { | ||
| $response = $this->responseFactory | ||
| ->createResponse($status) | ||
| ->withHeader('Content-Type', 'application/json') | ||
| ->withBody($this->streamFactory->createStream( | ||
| json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES), | ||
| )); | ||
|
|
||
| foreach ($extraHeaders as $name => $value) { | ||
| if ('' !== $value) { | ||
| $response = $response->withHeader($name, $value); | ||
| } | ||
| } | ||
|
|
||
| return $response; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.