php-sdk/tests/Unit/Server/Transport/Http/Middleware/DnsRebindingProtectionMiddlewareTest.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

145 lines
5.9 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\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());
}
}