php-sdk/tests/Unit/Server/Transport/Http/Middleware/ProtocolVersionMiddlewareTest.php
Volodymyr Panivko 293a5880e4
[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>
2026-05-25 13:49:43 +02:00

104 lines
4.6 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.
*/
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());
}
}