[Server] Compose StreamableHttpTransport security middleware via defaultMiddleware() factory (#307)
* [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>
This commit is contained in:
parent
ee40ff523f
commit
293a5880e4
5 changed files with 1340 additions and 154 deletions
|
|
@ -0,0 +1,269 @@
|
|||
<?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\Tests\Unit\Server\Transport\Http\Middleware;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
|
||||
final class CorsMiddlewareTest extends MiddlewareTestCase
|
||||
{
|
||||
#[TestDox('default configuration does not advertise an allowed origin')]
|
||||
public function testDefaultDoesNotSetAllowOrigin(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware();
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||
$this->assertTrue($response->hasHeader('Access-Control-Expose-Headers'));
|
||||
// Non-preflight: Methods/Headers must NOT be emitted per CORS spec.
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Methods'));
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('preflight request receives Access-Control-Allow-Methods and Access-Control-Allow-Headers')]
|
||||
public function testPreflightReceivesMethodAndHeaderAdvertisements(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->preflightRequest('https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame('GET, POST, DELETE', $response->getHeaderLine('Access-Control-Allow-Methods'));
|
||||
$this->assertNotSame('', $response->getHeaderLine('Access-Control-Allow-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('non-preflight OPTIONS request does not receive Methods/Headers advertisements')]
|
||||
public function testPlainOptionsIsNotTreatedAsPreflight(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['*']);
|
||||
// OPTIONS without `Access-Control-Request-Method` is not a CORS preflight.
|
||||
$request = $this->factory->createServerRequest('OPTIONS', 'https://example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Methods'));
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('wildcard allowedOrigins sets Access-Control-Allow-Origin to *')]
|
||||
public function testWildcardOrigin(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['*']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame('*', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
}
|
||||
|
||||
#[TestDox('matching Origin is reflected back')]
|
||||
public function testMatchingOriginIsReflected(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(
|
||||
allowedOrigins: ['https://app.example.com', 'https://staging.example.com'],
|
||||
);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame('https://app.example.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
}
|
||||
|
||||
#[TestDox('non-matching Origin is not echoed')]
|
||||
public function testNonMatchingOriginIsBlocked(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||
}
|
||||
|
||||
#[TestDox('does not overwrite headers set by inner middleware')]
|
||||
public function testPreExistingHeadersAreNotOverwritten(): void
|
||||
{
|
||||
$inner = $this->handlerReturning(200, [
|
||||
'Access-Control-Allow-Origin' => 'https://override.example.com',
|
||||
'Access-Control-Allow-Methods' => 'POST',
|
||||
]);
|
||||
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['*']);
|
||||
$request = $this->preflightRequest();
|
||||
|
||||
$response = $middleware->process($request, $inner);
|
||||
|
||||
$this->assertSame('https://override.example.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
$this->assertSame('POST', $response->getHeaderLine('Access-Control-Allow-Methods'));
|
||||
}
|
||||
|
||||
#[TestDox('exposed headers can be omitted')]
|
||||
public function testEmptyExposedHeadersAreNotSet(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['*'], exposedHeaders: []);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Expose-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('adds Vary: Origin when reflecting a specific origin to protect caches')]
|
||||
public function testVaryOriginIsAddedForReflectedOrigin(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame('Origin', $response->getHeaderLine('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('adds Vary: Origin even when origin is rejected so caches do not poison')]
|
||||
public function testVaryOriginIsAddedEvenWhenOriginDoesNotMatch(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||
$this->assertSame('Origin', $response->getHeaderLine('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('does not add Vary when Access-Control-Allow-Origin is wildcard')]
|
||||
public function testVaryOriginIsNotAddedForWildcard(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['*']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame('*', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
$this->assertFalse($response->hasHeader('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('does not add Vary when no allowed origins are configured')]
|
||||
public function testVaryOriginIsNotAddedWhenAllowedOriginsEmpty(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware();
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('preserves existing Vary value when appending Origin')]
|
||||
public function testVaryOriginAppendsToExistingVary(): void
|
||||
{
|
||||
$inner = $this->handlerReturning(200, ['Vary' => 'Accept-Encoding']);
|
||||
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $inner);
|
||||
|
||||
$this->assertSame('Accept-Encoding, Origin', $response->getHeaderLine('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('does not duplicate Origin in existing Vary header')]
|
||||
public function testVaryOriginIsNotDuplicated(): void
|
||||
{
|
||||
$inner = $this->handlerReturning(200, ['Vary' => 'Accept-Encoding, Origin']);
|
||||
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $inner);
|
||||
|
||||
$this->assertSame('Accept-Encoding, Origin', $response->getHeaderLine('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('does not treat a substring match like Origin-Other as the Origin token')]
|
||||
public function testVarySubstringDoesNotPreventAppending(): void
|
||||
{
|
||||
// `Origin-Resource-Policy` contains the substring "origin" but is a different token —
|
||||
// tokenized comparison must still treat the response as missing the `Origin` value.
|
||||
$inner = $this->handlerReturning(200, ['Vary' => 'Origin-Resource-Policy']);
|
||||
|
||||
$middleware = new CorsMiddleware(allowedOrigins: ['https://app.example.com']);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $inner);
|
||||
|
||||
$this->assertSame('Origin-Resource-Policy, Origin', $response->getHeaderLine('Vary'));
|
||||
}
|
||||
|
||||
#[TestDox('allowCredentials emits Access-Control-Allow-Credentials when an origin matches')]
|
||||
public function testAllowCredentialsHeaderEmitted(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(
|
||||
allowedOrigins: ['https://app.example.com'],
|
||||
allowCredentials: true,
|
||||
);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://app.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame('https://app.example.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
$this->assertSame('true', $response->getHeaderLine('Access-Control-Allow-Credentials'));
|
||||
}
|
||||
|
||||
#[TestDox('allowCredentials does not emit credentials header when no origin matches')]
|
||||
public function testAllowCredentialsSkippedWhenOriginUnmatched(): void
|
||||
{
|
||||
$middleware = new CorsMiddleware(
|
||||
allowedOrigins: ['https://app.example.com'],
|
||||
allowCredentials: true,
|
||||
);
|
||||
$request = $this->factory->createServerRequest('POST', 'https://example.com')
|
||||
->withHeader('Origin', 'https://evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Credentials'));
|
||||
}
|
||||
|
||||
#[TestDox('combining wildcard origin with allowCredentials throws')]
|
||||
public function testWildcardWithCredentialsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
new CorsMiddleware(allowedOrigins: ['*'], allowCredentials: true);
|
||||
}
|
||||
|
||||
private function preflightRequest(string $origin = 'https://app.example.com'): ServerRequestInterface
|
||||
{
|
||||
return $this->factory
|
||||
->createServerRequest('OPTIONS', 'https://example.com')
|
||||
->withHeader('Origin', $origin)
|
||||
->withHeader('Access-Control-Request-Method', 'POST')
|
||||
->withHeader('Access-Control-Request-Headers', 'Content-Type');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
<?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\Tests\Unit\Server\Transport\Http\Middleware;
|
||||
|
||||
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
|
||||
final class DnsRebindingProtectionMiddlewareTest extends MiddlewareTestCase
|
||||
{
|
||||
public static function allowedOriginProvider(): iterable
|
||||
{
|
||||
yield 'localhost' => ['http://localhost:8000'];
|
||||
yield 'IPv4 loopback' => ['http://127.0.0.1:3000'];
|
||||
yield 'IPv6 loopback (bracketed)' => ['http://[::1]:8000'];
|
||||
}
|
||||
|
||||
#[DataProvider('allowedOriginProvider')]
|
||||
#[TestDox('allows request with localhost Origin variant: $origin')]
|
||||
public function testAllowsLocalhostOrigin(string $origin): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Origin', $origin);
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('rejects non-allowed Origin with 403')]
|
||||
public function testRejectsForeignOrigin(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Origin', 'http://evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(403, $response->getStatusCode());
|
||||
$this->assertSame('text/plain', $response->getHeaderLine('Content-Type'));
|
||||
$this->assertStringContainsString('Origin', (string) $response->getBody());
|
||||
}
|
||||
|
||||
#[TestDox('Origin header takes precedence over Host')]
|
||||
public function testOriginPrecedenceOverHost(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Origin', 'http://localhost:8000')
|
||||
->withHeader('Host', 'evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('validates Host header when Origin is absent')]
|
||||
public function testFallbackToHostValidation(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://evil/')
|
||||
->withHeader('Host', 'evil.example.com');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(403, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('strips port from Host header when validating')]
|
||||
public function testHostPortIsStripped(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost:8000');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('IPv6 Host with port is parsed correctly')]
|
||||
public function testIpv6HostWithPort(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', '[::1]:8080');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('custom allowed hosts permit non-localhost names')]
|
||||
public function testCustomAllowedHosts(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(
|
||||
allowedHosts: ['myapp.local'],
|
||||
responseFactory: $this->factory,
|
||||
streamFactory: $this->factory,
|
||||
);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://myapp.local/')
|
||||
->withHeader('Origin', 'http://myapp.local:3000');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('host comparison is case-insensitive')]
|
||||
public function testCaseInsensitive(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(
|
||||
allowedHosts: ['MyApp.Local'],
|
||||
responseFactory: $this->factory,
|
||||
streamFactory: $this->factory,
|
||||
);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://myapp.local/')
|
||||
->withHeader('Origin', 'http://MYAPP.LOCAL:80');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('request without Origin or Host is allowed')]
|
||||
public function testNoOriginNoHostPasses(): void
|
||||
{
|
||||
$middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')->withoutHeader('Host');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
<?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\Tests\Unit\Server\Transport\Http\Middleware;
|
||||
|
||||
use Nyholm\Psr7\Factory\Psr17Factory;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
abstract class MiddlewareTestCase extends TestCase
|
||||
{
|
||||
protected Psr17Factory $factory;
|
||||
protected RequestHandlerInterface $passthroughHandler;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->factory = new Psr17Factory();
|
||||
$this->passthroughHandler = $this->handlerReturning(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $headers extra headers to set on the response (already-set CORS headers etc.)
|
||||
*/
|
||||
protected function handlerReturning(int $status, array $headers = []): RequestHandlerInterface
|
||||
{
|
||||
return new class($this->factory, $status, $headers) implements RequestHandlerInterface {
|
||||
/** @param array<string, string> $headers */
|
||||
public function __construct(
|
||||
private ResponseFactoryInterface $factory,
|
||||
private int $status,
|
||||
private array $headers,
|
||||
) {
|
||||
}
|
||||
|
||||
public function handle(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$response = $this->factory->createResponse($this->status);
|
||||
foreach ($this->headers as $name => $value) {
|
||||
$response = $response->withHeader($name, $value);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
<?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\Tests\Unit\Server\Transport\Http\Middleware;
|
||||
|
||||
use Mcp\Schema\Enum\ProtocolVersion;
|
||||
use Mcp\Server\Transport\Http\Middleware\ProtocolVersionMiddleware;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
|
||||
final class ProtocolVersionMiddlewareTest extends MiddlewareTestCase
|
||||
{
|
||||
#[TestDox('passes request through when header is absent and 2025-03-26 backwards-compat default is supported')]
|
||||
public function testMissingHeaderAcceptedWhenBackwardsCompatVersionIsSupported(): void
|
||||
{
|
||||
$middleware = new ProtocolVersionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('rejects missing header when 2025-03-26 backwards-compat default is not in supportedVersions')]
|
||||
public function testMissingHeaderRejectedByStrictServer(): void
|
||||
{
|
||||
$middleware = new ProtocolVersionMiddleware(
|
||||
supportedVersions: [ProtocolVersion::V2025_11_25],
|
||||
responseFactory: $this->factory,
|
||||
streamFactory: $this->factory,
|
||||
);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(400, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('accepts every version declared in the ProtocolVersion enum')]
|
||||
public function testAcceptsSupportedVersions(): void
|
||||
{
|
||||
$middleware = new ProtocolVersionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
|
||||
foreach (ProtocolVersion::cases() as $version) {
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, $version->value);
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode(), 'Expected '.$version->value.' to be accepted.');
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('rejects unsupported well-formed version with 400')]
|
||||
public function testRejectsUnsupportedVersion(): void
|
||||
{
|
||||
$middleware = new ProtocolVersionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, '1900-01-01');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(400, $response->getStatusCode());
|
||||
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
|
||||
}
|
||||
|
||||
#[TestDox('rejects malformed version with 400')]
|
||||
public function testRejectsMalformedVersion(): void
|
||||
{
|
||||
$middleware = new ProtocolVersionMiddleware(responseFactory: $this->factory, streamFactory: $this->factory);
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, 'not-a-version');
|
||||
|
||||
$response = $middleware->process($request, $this->passthroughHandler);
|
||||
|
||||
$this->assertSame(400, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('accepts only the supportedVersions whitelist when provided')]
|
||||
public function testRestrictedSupportedVersions(): void
|
||||
{
|
||||
$middleware = new ProtocolVersionMiddleware(
|
||||
supportedVersions: [ProtocolVersion::V2025_11_25],
|
||||
responseFactory: $this->factory,
|
||||
streamFactory: $this->factory,
|
||||
);
|
||||
|
||||
$accepted = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, ProtocolVersion::V2025_11_25->value);
|
||||
$rejected = $this->factory->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, ProtocolVersion::V2024_11_05->value);
|
||||
|
||||
$this->assertSame(200, $middleware->process($accepted, $this->passthroughHandler)->getStatusCode());
|
||||
$this->assertSame(400, $middleware->process($rejected, $this->passthroughHandler)->getStatusCode());
|
||||
}
|
||||
}
|
||||
|
|
@ -11,9 +11,12 @@
|
|||
|
||||
namespace Mcp\Tests\Unit\Server\Transport;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
|
||||
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
|
||||
use Mcp\Server\Transport\Http\Middleware\ProtocolVersionMiddleware;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
use Nyholm\Psr7\Factory\Psr17Factory;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
|
|
@ -21,120 +24,201 @@ use Psr\Http\Message\ResponseInterface;
|
|||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
final class StreamableHttpTransportTest extends TestCase
|
||||
{
|
||||
public static function corsHeaderProvider(): iterable
|
||||
private Psr17Factory $factory;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
yield 'GET (middleware returns 401)' => ['GET', false, 401];
|
||||
yield 'POST (middleware returns 401)' => ['POST', false, 401];
|
||||
yield 'DELETE (middleware returns 401)' => ['DELETE', false, 401];
|
||||
yield 'OPTIONS (middleware delegates -> transport handles preflight)' => ['OPTIONS', true, 204];
|
||||
yield 'GET (middleware delegates -> transport handles preflight)' => ['GET', true, 405];
|
||||
yield 'POST (middleware delegates -> transport handles preflight)' => ['POST', true, 202];
|
||||
yield 'DELETE (middleware delegates -> transport handles preflight)' => ['DELETE', true, 400];
|
||||
$this->factory = new Psr17Factory();
|
||||
}
|
||||
|
||||
#[DataProvider('corsHeaderProvider')]
|
||||
#[TestDox('CORS headers are always applied')]
|
||||
public function testCorsHeader(string $method, bool $middlewareDelegatesToTransport, int $expectedStatusCode): void
|
||||
#[TestDox('default middleware is applied when none is passed')]
|
||||
public function testDefaultMiddlewareIsAppliedWhenOmitted(): void
|
||||
{
|
||||
$factory = new Psr17Factory();
|
||||
$request = $factory->createServerRequest($method, 'https://example.com');
|
||||
// Preflight: OPTIONS + Access-Control-Request-Method — CorsMiddleware advertises Methods/Headers only on preflight.
|
||||
$request = $this->factory
|
||||
->createServerRequest('OPTIONS', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost')
|
||||
->withHeader('Access-Control-Request-Method', 'POST');
|
||||
|
||||
$middleware = new class($factory, $expectedStatusCode, $middlewareDelegatesToTransport) implements MiddlewareInterface {
|
||||
public function __construct(
|
||||
private ResponseFactoryInterface $responseFactory,
|
||||
private int $expectedStatusCode,
|
||||
private bool $middlewareDelegatesToTransport,
|
||||
) {
|
||||
}
|
||||
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
|
||||
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
if ($this->middlewareDelegatesToTransport) {
|
||||
return $handler->handle($request);
|
||||
}
|
||||
$response = $transport->listen();
|
||||
|
||||
return $this->responseFactory->createResponse($this->expectedStatusCode);
|
||||
}
|
||||
};
|
||||
$this->assertSame(204, $response->getStatusCode());
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin')); // secure-by-default
|
||||
$this->assertSame('GET, POST, DELETE', $response->getHeaderLine('Access-Control-Allow-Methods'));
|
||||
$this->assertNotSame('', $response->getHeaderLine('Access-Control-Allow-Headers'));
|
||||
$this->assertNotSame('', $response->getHeaderLine('Access-Control-Expose-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('default middleware blocks non-localhost Origin')]
|
||||
public function testDefaultMiddlewareBlocksRebindingAttempt(): void
|
||||
{
|
||||
$request = $this->factory
|
||||
->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost')
|
||||
->withHeader('Origin', 'http://evil.example.com');
|
||||
|
||||
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
||||
$this->assertSame(403, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('default middleware rejects unsupported MCP-Protocol-Version')]
|
||||
public function testDefaultMiddlewareRejectsUnsupportedProtocolVersion(): void
|
||||
{
|
||||
$request = $this->factory
|
||||
->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost')
|
||||
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, '1900-01-01');
|
||||
|
||||
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
||||
$this->assertSame(400, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('explicit empty middleware list disables defaults and emits a warning log')]
|
||||
public function testEmptyMiddlewareListDisablesDefaultsAndWarns(): void
|
||||
{
|
||||
$request = $this->factory
|
||||
->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', 'evil.example.com')
|
||||
->withHeader('Origin', 'http://evil.example.com');
|
||||
|
||||
$logger = $this->createMock(LoggerInterface::class);
|
||||
$logger->expects($this->once())
|
||||
->method('warning')
|
||||
->with($this->stringContains('empty middleware list'));
|
||||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
$factory,
|
||||
$factory,
|
||||
$this->factory,
|
||||
$this->factory,
|
||||
$logger,
|
||||
[],
|
||||
null,
|
||||
[$middleware],
|
||||
);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
||||
$this->assertSame($expectedStatusCode, $response->getStatusCode(), $response->getBody()->getContents());
|
||||
$this->assertTrue($response->hasHeader('Access-Control-Allow-Origin'));
|
||||
$this->assertTrue($response->hasHeader('Access-Control-Allow-Methods'));
|
||||
$this->assertTrue($response->hasHeader('Access-Control-Allow-Headers'));
|
||||
$this->assertTrue($response->hasHeader('Access-Control-Expose-Headers'));
|
||||
|
||||
$this->assertSame('*', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
$this->assertSame('GET, POST, DELETE, OPTIONS', $response->getHeaderLine('Access-Control-Allow-Methods'));
|
||||
$this->assertSame(
|
||||
'Accept,Authorization,Content-Type,Last-Event-ID,Mcp-Protocol-Version,Mcp-Session-Id',
|
||||
$response->getHeaderLine('Access-Control-Allow-Headers')
|
||||
);
|
||||
$this->assertSame('Mcp-Session-Id', $response->getHeaderLine('Access-Control-Expose-Headers'));
|
||||
// No CORS, no DNS rebinding check — transport just answers.
|
||||
$this->assertNotSame(403, $response->getStatusCode());
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||
$this->assertFalse($response->hasHeader('Access-Control-Allow-Methods'));
|
||||
}
|
||||
|
||||
#[TestDox('transport replaces existing CORS headers on the response')]
|
||||
public function testCorsHeadersAreReplacedWhenAlreadyPresent(): void
|
||||
#[TestDox('null middleware does not trigger the empty-list warning')]
|
||||
public function testNullMiddlewareDoesNotWarn(): void
|
||||
{
|
||||
$factory = new Psr17Factory();
|
||||
$request = $factory->createServerRequest('GET', 'https://example.com');
|
||||
$request = $this->factory
|
||||
->createServerRequest('OPTIONS', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost');
|
||||
|
||||
$middleware = new class($factory) implements MiddlewareInterface {
|
||||
public function __construct(private ResponseFactoryInterface $responses)
|
||||
{
|
||||
}
|
||||
$logger = $this->createMock(LoggerInterface::class);
|
||||
$logger->expects($this->never())->method('warning');
|
||||
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
return $this->responses->createResponse(200)
|
||||
->withHeader('Access-Control-Allow-Origin', 'https://another.com');
|
||||
}
|
||||
};
|
||||
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory, $logger);
|
||||
$transport->listen();
|
||||
}
|
||||
|
||||
#[TestDox('custom middleware composes with default stack via spread')]
|
||||
public function testDefaultsCanBeSpreadAndExtended(): void
|
||||
{
|
||||
$request = $this->factory
|
||||
->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost');
|
||||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
$factory,
|
||||
$factory,
|
||||
[],
|
||||
$this->factory,
|
||||
$this->factory,
|
||||
null,
|
||||
[$middleware],
|
||||
[
|
||||
...StreamableHttpTransport::defaultMiddleware(),
|
||||
$this->stubAuth401(),
|
||||
],
|
||||
);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
|
||||
$this->assertSame('https://another.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
$this->assertSame('GET, POST, DELETE, OPTIONS', $response->getHeaderLine('Access-Control-Allow-Methods'));
|
||||
$this->assertSame(
|
||||
'Accept,Authorization,Content-Type,Last-Event-ID,Mcp-Protocol-Version,Mcp-Session-Id',
|
||||
$response->getHeaderLine('Access-Control-Allow-Headers')
|
||||
);
|
||||
$this->assertSame(401, $response->getStatusCode());
|
||||
// CORS middleware is outermost — Expose-Headers is emitted on all responses, including 401.
|
||||
$this->assertSame('Mcp-Session-Id', $response->getHeaderLine('Access-Control-Expose-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('defaults can be filtered to drop DNS rebinding for proxy deployments')]
|
||||
public function testDefaultsCanBeFilteredToDropDnsRebinding(): void
|
||||
{
|
||||
// Behind a reverse proxy: real Host is api.myapp.com, browser Origin is myapp.com.
|
||||
// DnsRebindingProtectionMiddleware default (localhost-only) would 403 this — drop it.
|
||||
$request = $this->factory
|
||||
->createServerRequest('POST', 'http://api.myapp.com/')
|
||||
->withHeader('Host', 'api.myapp.com')
|
||||
->withHeader('Origin', 'https://myapp.com');
|
||||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
$this->factory,
|
||||
$this->factory,
|
||||
null,
|
||||
[
|
||||
...array_filter(
|
||||
StreamableHttpTransport::defaultMiddleware(),
|
||||
static fn (MiddlewareInterface $m): bool => !$m instanceof DnsRebindingProtectionMiddleware,
|
||||
),
|
||||
$this->stubAuth401(),
|
||||
],
|
||||
);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
||||
// Auth short-circuits with 401 — proves DNS rebinding didn't reject the request first.
|
||||
$this->assertSame(401, $response->getStatusCode());
|
||||
// CORS middleware is still in the chain — Expose-Headers attached to the 401.
|
||||
$this->assertSame('Mcp-Session-Id', $response->getHeaderLine('Access-Control-Expose-Headers'));
|
||||
}
|
||||
|
||||
#[TestDox('configured CorsMiddleware reflects matching Origin')]
|
||||
public function testConfiguredCorsReflectsMatchingOrigin(): void
|
||||
{
|
||||
$request = $this->factory
|
||||
->createServerRequest('POST', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost')
|
||||
->withHeader('Origin', 'https://myapp.example.com');
|
||||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
$this->factory,
|
||||
$this->factory,
|
||||
null,
|
||||
[
|
||||
new CorsMiddleware(allowedOrigins: ['https://myapp.example.com']),
|
||||
new DnsRebindingProtectionMiddleware(allowedHosts: ['localhost']),
|
||||
new ProtocolVersionMiddleware(),
|
||||
],
|
||||
);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
||||
$this->assertSame('https://myapp.example.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
|
||||
}
|
||||
|
||||
#[TestDox('middleware runs before transport handles the request')]
|
||||
public function testMiddlewareRunsBeforeTransportHandlesRequest(): void
|
||||
{
|
||||
$factory = new Psr17Factory();
|
||||
$request = $factory->createServerRequest('OPTIONS', 'https://example.com');
|
||||
$request = $this->factory->createServerRequest('OPTIONS', 'http://localhost/')
|
||||
->withHeader('Host', 'localhost');
|
||||
|
||||
$state = new \stdClass();
|
||||
$state->called = false;
|
||||
$middleware = new class($state) implements MiddlewareInterface {
|
||||
$spy = new class($state) implements MiddlewareInterface {
|
||||
public function __construct(private \stdClass $state)
|
||||
{
|
||||
}
|
||||
|
|
@ -149,11 +233,10 @@ final class StreamableHttpTransportTest extends TestCase
|
|||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
$factory,
|
||||
$factory,
|
||||
[],
|
||||
$this->factory,
|
||||
$this->factory,
|
||||
null,
|
||||
[$middleware],
|
||||
[$spy],
|
||||
);
|
||||
|
||||
$response = $transport->listen();
|
||||
|
|
@ -161,4 +244,34 @@ final class StreamableHttpTransportTest extends TestCase
|
|||
$this->assertTrue($state->called);
|
||||
$this->assertSame(204, $response->getStatusCode());
|
||||
}
|
||||
|
||||
#[TestDox('non-middleware entries are rejected')]
|
||||
public function testInvalidMiddlewareEntryThrows(): void
|
||||
{
|
||||
$request = $this->factory->createServerRequest('POST', 'http://localhost/');
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
new StreamableHttpTransport(
|
||||
$request,
|
||||
$this->factory,
|
||||
$this->factory,
|
||||
null,
|
||||
[new \stdClass()], // @phpstan-ignore-line argument.type
|
||||
);
|
||||
}
|
||||
|
||||
private function stubAuth401(): MiddlewareInterface
|
||||
{
|
||||
return new class($this->factory) implements MiddlewareInterface {
|
||||
public function __construct(private ResponseFactoryInterface $factory)
|
||||
{
|
||||
}
|
||||
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
return $this->factory->createResponse(401);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue