* [Server] Add CORS, DNS rebinding and protocol version middleware Introduce three PSR-15 middleware for `StreamableHttpTransport` exposed through a public `StreamableHttpTransport::defaultMiddleware()` factory composed automatically when no middleware is passed. - `CorsMiddleware`: secure-by-default (no `Access-Control-Allow-Origin`), configurable allowlist, reflects matching origin with `Vary: Origin` to protect shared caches. - `DnsRebindingProtectionMiddleware`: validates `Origin`/`Host` against a hostname allowlist (localhost-only by default). - `ProtocolVersionMiddleware`: rejects requests carrying an unsupported `Mcp-Protocol-Version` header with `400 Bad Request`. The transport no longer applies CORS via an `instanceof + array_unshift` post-hook; the middleware parameter is nullable — `null` installs the secure defaults, `[]` disables them, and users compose by spreading `StreamableHttpTransport::defaultMiddleware()`. `SESSION_HEADER` and `PROTOCOL_VERSION_HEADER` are promoted to public constants so middleware can reuse them. BC breaks: - The `corsHeaders` constructor parameter is removed; the `middleware` parameter shifts one position. Positional callers passing the old `corsHeaders` argument must switch to named arguments or drop it. - Default `Access-Control-Allow-Origin` is no longer `*`. Addresses #260 (DNS rebinding), #277 (CORS extraction) and #306 (protocol version validation). * [Server] Address review feedback on middleware defaults - CorsMiddleware: emit Access-Control-Allow-Methods/Headers only on preflight per CORS spec; tokenize Vary header to avoid substring false-positives; add allowCredentials flag that emits Access-Control-Allow-Credentials and throws when combined with wildcard origin. - DnsRebindingProtectionMiddleware: return plain-text 403 body (HTTP-level rejection, not JSON-RPC); use parse_url(..., PHP_URL_HOST) for origin parsing; drop redundant unbracketed '::1' from default allowlist. - ProtocolVersionMiddleware: use Error::forInvalidParams instead of forInvalidRequest -- JSON-RPC -32602 fits header-value rejection better. - JsonRpcErrorResponse::create now accepts a JsonRpc\Error so callers choose the error code. - StreamableHttpTransport: emit a warning log when an explicit empty middleware list is passed, so operators can spot accidental bypass of the default security stack. * [Server] Fix CI: switch warning-log tests to PHPUnit mocks Replace the anonymous AbstractLogger fixture in StreamableHttpTransportTest with `$this->createMock(LoggerInterface::class)` so the test does not declare a `log()` signature at all. That sidesteps both the psr/log v1 LSP incompatibility (untyped parameter) and the phpstan `missingType.parameter` complaint in one move, and matches how the rest of the suite (CallToolHandlerTest etc.) fakes loggers. * Update src/Server/Transport/Http/Middleware/CorsMiddleware.php Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com> --------- Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com>
95 lines
3.2 KiB
PHP
95 lines
3.2 KiB
PHP
<?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.
|
|
*/
|
|
|
|
require_once dirname(__DIR__).'/bootstrap.php';
|
|
|
|
use Http\Discovery\Psr17Factory;
|
|
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
|
|
use Mcp\Example\Server\OAuthMicrosoft\MicrosoftJwtTokenValidator;
|
|
use Mcp\Server;
|
|
use Mcp\Server\Session\FileSessionStore;
|
|
use Mcp\Server\Transport\Http\Middleware\AuthorizationMiddleware;
|
|
use Mcp\Server\Transport\Http\Middleware\OAuthProxyMiddleware;
|
|
use Mcp\Server\Transport\Http\Middleware\OAuthRequestMetaMiddleware;
|
|
use Mcp\Server\Transport\Http\Middleware\ProtectedResourceMetadataMiddleware;
|
|
use Mcp\Server\Transport\Http\OAuth\JwksProvider;
|
|
use Mcp\Server\Transport\Http\OAuth\JwtTokenValidator;
|
|
use Mcp\Server\Transport\Http\OAuth\LenientOidcDiscoveryMetadataPolicy;
|
|
use Mcp\Server\Transport\Http\OAuth\OidcDiscovery;
|
|
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
|
|
use Mcp\Server\Transport\StreamableHttpTransport;
|
|
|
|
$tenantId = getenv('AZURE_TENANT_ID') ?: throw new RuntimeException('AZURE_TENANT_ID environment variable is required');
|
|
$clientId = getenv('AZURE_CLIENT_ID') ?: throw new RuntimeException('AZURE_CLIENT_ID environment variable is required');
|
|
|
|
$issuerV2 = "https://login.microsoftonline.com/{$tenantId}/v2.0";
|
|
$issuerV1 = "https://sts.windows.net/{$tenantId}/";
|
|
$localBaseUrl = 'http://localhost:8000';
|
|
|
|
$discovery = new OidcDiscovery(
|
|
metadataPolicy: new LenientOidcDiscoveryMetadataPolicy(),
|
|
);
|
|
|
|
$jwtTokenValidator = new JwtTokenValidator(
|
|
issuer: [$issuerV2, $issuerV1],
|
|
audience: $clientId,
|
|
jwksProvider: new JwksProvider($discovery),
|
|
jwksUri: 'https://login.microsoftonline.com/common/discovery/v2.0/keys',
|
|
scopeClaim: 'scp',
|
|
);
|
|
|
|
$validator = new MicrosoftJwtTokenValidator($jwtTokenValidator);
|
|
|
|
$protectedResourceMetadata = new ProtectedResourceMetadata(
|
|
authorizationServers: [$localBaseUrl],
|
|
scopesSupported: ['openid', 'profile', 'email'],
|
|
resourceName: 'OAuth Microsoft Example MCP Server',
|
|
resourceDocumentation: $localBaseUrl,
|
|
);
|
|
|
|
$metadataMiddleware = new ProtectedResourceMetadataMiddleware($protectedResourceMetadata);
|
|
|
|
$clientSecret = getenv('AZURE_CLIENT_SECRET') ?: null;
|
|
|
|
$oauthProxyMiddleware = new OAuthProxyMiddleware(
|
|
upstreamIssuer: $issuerV2,
|
|
localBaseUrl: $localBaseUrl,
|
|
discovery: $discovery,
|
|
clientSecret: $clientSecret,
|
|
);
|
|
|
|
$authMiddleware = new AuthorizationMiddleware(
|
|
$validator,
|
|
$protectedResourceMetadata,
|
|
);
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('OAuth Microsoft Example', '1.0.0')
|
|
->setLogger(logger())
|
|
->setSession(new FileSessionStore(__DIR__.'/sessions'))
|
|
->setDiscovery(__DIR__)
|
|
->build();
|
|
|
|
$transport = new StreamableHttpTransport(
|
|
(new Psr17Factory())->createServerRequestFromGlobals(),
|
|
logger: logger(),
|
|
middleware: [
|
|
...StreamableHttpTransport::defaultMiddleware(),
|
|
$oauthProxyMiddleware,
|
|
$metadataMiddleware,
|
|
$authMiddleware,
|
|
new OAuthRequestMetaMiddleware(),
|
|
],
|
|
);
|
|
|
|
$response = $server->run($transport);
|
|
|
|
(new SapiEmitter())->emit($response);
|