[Server] Oauth2 based on middleware (#221)

* Add Middleware handlers to StreamableHttpTransport

* OAuth Implementation based on middleware

* OAuth Implementation based on middleware

* Add Middleware handlers to StreamableHttpTransport

* OAuth Implementation based on middleware

* OAuth Implementation based on middleware

Signed-off-by: Volodymyr Panivko <sveneld300@gmail.com>

* Address PR review feedback for OAuth middleware

* Apply php-cs-fixer to satisfy QA

* Use Mcp exception classes in OAuth middleware

* Refactor OAuth HTTP stack and add Microsoft example policies

* Fix QA PHPStan findings in OAuth examples and auth middleware

* Require OIDC discovery in JWKS provider and refine OAuth proxy behavior

* Remove local development docker artifacts from VCS

* Revert .gitignore changes for local docker files

* Fix body retrieval in OAuthRequestMetaMiddleware for proper string conversion

Signed-off-by: Volodymyr Panivko <sveneld300@gmail.com>

* Address OAuth PR review feedback and align example configs

* Fix QA style issues and add authorization docs

* Fix PHPStan typing issues in OAuth middleware

* Remove duplicate Middleware namespace, consolidate under Http\Middleware

Remove old Mcp\Server\Transport\Middleware\ classes that were duplicated
in Mcp\Server\Transport\Http\Middleware\ and Http\OAuth\. Update docs
to reference the correct namespaces.

* Address PR review: replace Throwable catch with specific exceptions, add JSON_THROW_ON_ERROR

- JwtTokenValidator: replace catch(\Throwable) with explicit
  \InvalidArgumentException|\UnexpectedValueException|\DomainException,
  letting RuntimeException from JwksProvider propagate as infrastructure errors
- OAuthProxyMiddleware: add \JSON_THROW_ON_ERROR to json_encode for metadata response
- Update tests to expect RuntimeException for JWKS infrastructure failures

---------

Signed-off-by: Volodymyr Panivko <sveneld300@gmail.com>
Co-authored-by: Volodymyr Panivko <volodymyr.panivko@togethernetworks.com>
This commit is contained in:
Volodymyr Panivko 2026-03-10 17:10:07 +01:00 • committed by GitHub
commit e3f4b88768
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 6038 additions and 0 deletions

View file

@ -0,0 +1,284 @@
<?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\RuntimeException;
use Mcp\Server\Transport\Http\Middleware\AuthorizationMiddleware;
use Mcp\Server\Transport\Http\OAuth\AuthorizationResult;
use Mcp\Server\Transport\Http\OAuth\AuthorizationTokenValidatorInterface;
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Tests AuthorizationMiddleware behavior for token validation and challenges.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class AuthorizationMiddlewareTest extends TestCase
{
#[TestDox('missing Authorization header returns 401 with metadata and scope guidance')]
public function testMissingAuthorizationReturns401(): void
{
$factory = new Psr17Factory();
$resourceMetadata = new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
scopesSupported: ['mcp:read'],
);
$validator = new class implements AuthorizationTokenValidatorInterface {
public function validate(string $accessToken): AuthorizationResult
{
throw new RuntimeException('Validator should not be called without a token.');
}
};
$middleware = new AuthorizationMiddleware(
validator: $validator,
resourceMetadata: $resourceMetadata,
responseFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(200);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(401, $response->getStatusCode());
$header = $response->getHeaderLine('WWW-Authenticate');
$this->assertStringContainsString('Bearer', $header);
$this->assertStringContainsString(
'resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"',
$header,
);
$this->assertStringContainsString('scope="mcp:read"', $header);
}
#[TestDox('malformed Authorization header returns 400 with invalid_request')]
public function testMalformedAuthorizationReturns400(): void
{
$factory = new Psr17Factory();
$resourceMetadata = new ProtectedResourceMetadata(['https://auth.example.com']);
$validator = new class implements AuthorizationTokenValidatorInterface {
public function validate(string $accessToken): AuthorizationResult
{
return AuthorizationResult::allow();
}
};
$middleware = new AuthorizationMiddleware(
validator: $validator,
resourceMetadata: $resourceMetadata,
responseFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp')
->withHeader('Authorization', 'Basic abc');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(200);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(400, $response->getStatusCode());
$this->assertStringContainsString('error="invalid_request"', $response->getHeaderLine('WWW-Authenticate'));
}
#[TestDox('insufficient scopes return 403 with scope challenge')]
public function testInsufficientScopeReturns403(): void
{
$factory = new Psr17Factory();
$resourceMetadata = new ProtectedResourceMetadata(['https://auth.example.com']);
$validator = new class implements AuthorizationTokenValidatorInterface {
public function validate(string $accessToken): AuthorizationResult
{
return AuthorizationResult::forbidden('insufficient_scope', 'Need more scopes.', ['mcp:write']);
}
};
$middleware = new AuthorizationMiddleware(
validator: $validator,
resourceMetadata: $resourceMetadata,
responseFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp')
->withHeader('Authorization', 'Bearer token');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(200);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(403, $response->getStatusCode());
$header = $response->getHeaderLine('WWW-Authenticate');
$this->assertStringContainsString('error="insufficient_scope"', $header);
$this->assertStringContainsString('scope="mcp:write"', $header);
}
#[TestDox('metadata scopes are used in challenge when result has no scopes')]
public function testMetadataScopesAreUsedWhenResultHasNoScopes(): void
{
$factory = new Psr17Factory();
$resourceMetadata = new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
scopesSupported: ['openid', 'profile'],
);
$validator = new class implements AuthorizationTokenValidatorInterface {
public function validate(string $accessToken): AuthorizationResult
{
throw new RuntimeException('Validator should not be called without a token.');
}
};
$middleware = new AuthorizationMiddleware(
validator: $validator,
resourceMetadata: $resourceMetadata,
responseFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(200);
}
};
$response = $middleware->process($request, $handler);
$header = $response->getHeaderLine('WWW-Authenticate');
$this->assertStringContainsString(
'resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"',
$header,
);
$this->assertStringContainsString('scope="openid profile"', $header);
}
#[TestDox('resource metadata object path and scopes are reflected in challenge')]
public function testResourceMetadataObjectProvidesMetadataAndScopes(): void
{
$factory = new Psr17Factory();
$validator = new class implements AuthorizationTokenValidatorInterface {
public function validate(string $accessToken): AuthorizationResult
{
throw new RuntimeException('Validator should not be called without a token.');
}
};
$resourceMetadata = new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
scopesSupported: ['openid', 'profile'],
metadataPaths: ['/oauth/resource-meta'],
);
$middleware = new AuthorizationMiddleware(
validator: $validator,
responseFactory: $factory,
resourceMetadata: $resourceMetadata,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(200);
}
};
$response = $middleware->process($request, $handler);
$header = $response->getHeaderLine('WWW-Authenticate');
$this->assertSame(401, $response->getStatusCode());
$this->assertStringContainsString(
'resource_metadata="https://mcp.example.com/oauth/resource-meta"',
$header,
);
$this->assertStringContainsString('scope="openid profile"', $header);
}
#[TestDox('authorized requests reach the handler with attributes applied')]
public function testAllowedRequestPassesAttributes(): void
{
$factory = new Psr17Factory();
$resourceMetadata = new ProtectedResourceMetadata(['https://auth.example.com']);
$validator = new class implements AuthorizationTokenValidatorInterface {
public function validate(string $accessToken): AuthorizationResult
{
return AuthorizationResult::allow(['subject' => 'user-1']);
}
};
$middleware = new AuthorizationMiddleware(
validator: $validator,
resourceMetadata: $resourceMetadata,
responseFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp')
->withHeader('Authorization', 'Bearer token');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(200)
->withHeader('X-Subject', (string) $request->getAttribute('subject'));
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('user-1', $response->getHeaderLine('X-Subject'));
}
}

View file

@ -0,0 +1,299 @@
<?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\OAuthProxyMiddleware;
use Mcp\Server\Transport\Http\OAuth\OidcDiscoveryInterface;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Tests OAuthProxyMiddleware behavior for metadata, authorize, and token routes.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class OAuthProxyMiddlewareTest extends TestCase
{
#[TestDox('metadata endpoint returns local oauth metadata with upstream capabilities')]
public function testMetadataEndpointReturnsLocalMetadata(): void
{
$factory = new Psr17Factory();
$discovery = $this->createMock(OidcDiscoveryInterface::class);
$discovery->expects($this->once())
->method('discover')
->with('https://login.example.com/tenant')
->willReturn([
'authorization_endpoint' => 'https://login.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://login.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://login.example.com/discovery/v2.0/keys',
'response_types_supported' => ['code'],
'grant_types_supported' => ['authorization_code', 'refresh_token'],
'code_challenge_methods_supported' => ['S256'],
'scopes_supported' => ['openid', 'profile'],
'token_endpoint_auth_methods_supported' => ['client_secret_post'],
]);
$middleware = new OAuthProxyMiddleware(
upstreamIssuer: 'https://login.example.com/tenant',
localBaseUrl: 'http://localhost:8000',
discovery: $discovery,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'http://localhost:8000/.well-known/oauth-authorization-server');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(404);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(200, $response->getStatusCode());
$payload = json_decode($response->getBody()->__toString(), true, 512, \JSON_THROW_ON_ERROR);
$this->assertSame('http://localhost:8000', $payload['issuer']);
$this->assertSame('http://localhost:8000/authorize', $payload['authorization_endpoint']);
$this->assertSame('http://localhost:8000/token', $payload['token_endpoint']);
$this->assertSame(['openid', 'profile'], $payload['scopes_supported']);
$this->assertSame('https://login.example.com/discovery/v2.0/keys', $payload['jwks_uri']);
}
#[TestDox('authorize endpoint redirects to upstream authorization endpoint preserving query')]
public function testAuthorizeEndpointRedirectsToUpstream(): void
{
$factory = new Psr17Factory();
$discovery = $this->createMock(OidcDiscoveryInterface::class);
$discovery->expects($this->once())
->method('getAuthorizationEndpoint')
->with('https://login.example.com/tenant')
->willReturn('https://login.example.com/oauth2/v2.0/authorize');
$middleware = new OAuthProxyMiddleware(
upstreamIssuer: 'https://login.example.com/tenant',
localBaseUrl: 'http://localhost:8000',
discovery: $discovery,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest(
'GET',
'http://localhost:8000/authorize?client_id=test-client&scope=openid%20profile&code_challenge=abc',
);
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(404);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(302, $response->getStatusCode());
$this->assertSame(
'https://login.example.com/oauth2/v2.0/authorize?client_id=test-client&scope=openid%20profile&code_challenge=abc',
$response->getHeaderLine('Location'),
);
}
#[TestDox('token endpoint proxies request and injects client secret')]
public function testTokenEndpointProxiesRequestAndInjectsClientSecret(): void
{
$factory = new Psr17Factory();
$discovery = $this->createMock(OidcDiscoveryInterface::class);
$discovery->expects($this->once())
->method('getTokenEndpoint')
->with('https://login.example.com/tenant')
->willReturn('https://login.example.com/oauth2/v2.0/token');
$discovery->expects($this->once())
->method('discover')
->with('https://login.example.com/tenant')
->willReturn([
'authorization_endpoint' => 'https://login.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://login.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://login.example.com/discovery/v2.0/keys',
'token_endpoint_auth_methods_supported' => ['client_secret_post'],
]);
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())
->method('sendRequest')
->willReturnCallback(function (RequestInterface $request) use ($factory): ResponseInterface {
$this->assertSame('POST', $request->getMethod());
$this->assertSame('https://login.example.com/oauth2/v2.0/token', (string) $request->getUri());
$this->assertSame('', $request->getHeaderLine('Authorization'));
$this->assertSame('application/x-www-form-urlencoded', $request->getHeaderLine('Content-Type'));
parse_str($request->getBody()->__toString(), $params);
$this->assertSame('authorization_code', $params['grant_type'] ?? null);
$this->assertSame('abc123', $params['code'] ?? null);
$this->assertSame('secret-value', $params['client_secret'] ?? null);
return $factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream('{"access_token":"token-1"}'));
});
$middleware = new OAuthProxyMiddleware(
upstreamIssuer: 'https://login.example.com/tenant',
localBaseUrl: 'http://localhost:8000',
clientSecret: 'secret-value',
discovery: $discovery,
httpClient: $httpClient,
requestFactory: $factory,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest('POST', 'http://localhost:8000/token')
->withHeader('Content-Type', 'application/x-www-form-urlencoded')
->withBody($factory->createStream('grant_type=authorization_code&code=abc123'));
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(404);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
$this->assertSame('{"access_token":"token-1"}', $response->getBody()->__toString());
}
#[TestDox('token endpoint uses client_secret_basic when supported by upstream metadata')]
public function testTokenEndpointUsesClientSecretBasicWhenSupported(): void
{
$factory = new Psr17Factory();
$discovery = $this->createMock(OidcDiscoveryInterface::class);
$discovery->expects($this->once())
->method('getTokenEndpoint')
->with('https://login.example.com/tenant')
->willReturn('https://login.example.com/oauth2/v2.0/token');
$discovery->expects($this->once())
->method('discover')
->with('https://login.example.com/tenant')
->willReturn([
'authorization_endpoint' => 'https://login.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://login.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://login.example.com/discovery/v2.0/keys',
'token_endpoint_auth_methods_supported' => ['client_secret_basic'],
]);
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())
->method('sendRequest')
->willReturnCallback(function (RequestInterface $request) use ($factory): ResponseInterface {
$this->assertSame('POST', $request->getMethod());
$this->assertSame('https://login.example.com/oauth2/v2.0/token', (string) $request->getUri());
$this->assertSame('Basic ZGVtby1jbGllbnQ6c2VjcmV0LXZhbHVl', $request->getHeaderLine('Authorization'));
$this->assertSame('application/x-www-form-urlencoded', $request->getHeaderLine('Content-Type'));
parse_str($request->getBody()->__toString(), $params);
$this->assertSame('authorization_code', $params['grant_type'] ?? null);
$this->assertSame('abc123', $params['code'] ?? null);
$this->assertArrayNotHasKey('client_secret', $params);
return $factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream('{"access_token":"token-1"}'));
});
$middleware = new OAuthProxyMiddleware(
upstreamIssuer: 'https://login.example.com/tenant',
localBaseUrl: 'http://localhost:8000',
clientSecret: 'secret-value',
discovery: $discovery,
httpClient: $httpClient,
requestFactory: $factory,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest('POST', 'http://localhost:8000/token')
->withHeader('Content-Type', 'application/x-www-form-urlencoded')
->withBody($factory->createStream('grant_type=authorization_code&client_id=demo-client&code=abc123'));
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(404);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
$this->assertSame('{"access_token":"token-1"}', $response->getBody()->__toString());
}
#[TestDox('non oauth proxy requests are delegated to next middleware')]
public function testNonOAuthRequestPassesThrough(): void
{
$factory = new Psr17Factory();
$discovery = $this->createMock(OidcDiscoveryInterface::class);
$discovery->expects($this->never())->method('discover');
$middleware = new OAuthProxyMiddleware(
upstreamIssuer: 'https://login.example.com/tenant',
localBaseUrl: 'http://localhost:8000',
discovery: $discovery,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'http://localhost:8000/mcp');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(204);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(204, $response->getStatusCode());
}
}

View file

@ -0,0 +1,179 @@
<?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\OAuthRequestMetaMiddleware;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Tests OAuthRequestMetaMiddleware propagation of OAuth attributes to JSON-RPC meta.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class OAuthRequestMetaMiddlewareTest extends TestCase
{
#[TestDox('oauth request attributes are copied to json-rpc params _meta')]
public function testInjectsOauthAttributesIntoSingleRequest(): void
{
$factory = new Psr17Factory();
$middleware = new OAuthRequestMetaMiddleware($factory);
$payload = [
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'initialize',
'params' => [
'protocolVersion' => '2024-11-05',
],
];
$request = $factory
->createServerRequest('POST', 'https://mcp.example.com/mcp')
->withBody($factory->createStream(json_encode($payload, \JSON_THROW_ON_ERROR)))
->withAttribute('oauth.claims', ['sub' => 'user-1'])
->withAttribute('oauth.scopes', ['openid', 'profile'])
->withAttribute('oauth.subject', 'user-1')
->withAttribute('not_oauth', 'ignored');
$response = $middleware->process($request, $this->createEchoHandler($factory));
$decoded = json_decode($response->getBody()->__toString(), true, 512, \JSON_THROW_ON_ERROR);
$this->assertSame(['sub' => 'user-1'], $decoded['params']['_meta']['oauth']['oauth.claims']);
$this->assertSame(['openid', 'profile'], $decoded['params']['_meta']['oauth']['oauth.scopes']);
$this->assertSame('user-1', $decoded['params']['_meta']['oauth']['oauth.subject']);
$this->assertArrayNotHasKey('not_oauth', $decoded['params']['_meta']['oauth']);
}
#[TestDox('existing _meta is preserved and oauth keys are merged')]
public function testMergesWithExistingMeta(): void
{
$factory = new Psr17Factory();
$middleware = new OAuthRequestMetaMiddleware($factory);
$payload = [
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'tools/list',
'params' => [
'_meta' => [
'trace_id' => 'trace-1',
'oauth' => [
'client_hint' => 'web',
'oauth.subject' => 'spoofed',
],
],
],
];
$request = $factory
->createServerRequest('POST', 'https://mcp.example.com/mcp')
->withBody($factory->createStream(json_encode($payload, \JSON_THROW_ON_ERROR)))
->withAttribute('oauth.subject', 'trusted-user')
->withAttribute('oauth.scopes', ['mcp.read']);
$response = $middleware->process($request, $this->createEchoHandler($factory));
$decoded = json_decode($response->getBody()->__toString(), true, 512, \JSON_THROW_ON_ERROR);
$this->assertSame('trace-1', $decoded['params']['_meta']['trace_id']);
$this->assertSame('web', $decoded['params']['_meta']['oauth']['client_hint']);
$this->assertSame('trusted-user', $decoded['params']['_meta']['oauth']['oauth.subject']);
$this->assertSame(['mcp.read'], $decoded['params']['_meta']['oauth']['oauth.scopes']);
}
#[TestDox('oauth request attributes are copied for each batch entry')]
public function testInjectsOauthAttributesIntoBatchRequest(): void
{
$factory = new Psr17Factory();
$middleware = new OAuthRequestMetaMiddleware($factory);
$payload = [
[
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'initialize',
'params' => [],
],
[
'jsonrpc' => '2.0',
'id' => 2,
'method' => 'tools/list',
],
];
$request = $factory
->createServerRequest('POST', 'https://mcp.example.com/mcp')
->withBody($factory->createStream(json_encode($payload, \JSON_THROW_ON_ERROR)))
->withAttribute('oauth.subject', 'batch-user');
$response = $middleware->process($request, $this->createEchoHandler($factory));
$decoded = json_decode($response->getBody()->__toString(), true, 512, \JSON_THROW_ON_ERROR);
$this->assertSame('batch-user', $decoded[0]['params']['_meta']['oauth']['oauth.subject']);
$this->assertSame('batch-user', $decoded[1]['params']['_meta']['oauth']['oauth.subject']);
}
#[TestDox('request without oauth attributes passes through unchanged')]
public function testNoOauthAttributesPassThrough(): void
{
$factory = new Psr17Factory();
$middleware = new OAuthRequestMetaMiddleware($factory);
$body = '{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}';
$request = $factory
->createServerRequest('POST', 'https://mcp.example.com/mcp')
->withBody($factory->createStream($body));
$response = $middleware->process($request, $this->createEchoHandler($factory));
$this->assertSame($body, $response->getBody()->__toString());
}
#[TestDox('non post requests pass through unchanged')]
public function testNonPostPassesThrough(): void
{
$factory = new Psr17Factory();
$middleware = new OAuthRequestMetaMiddleware($factory);
$body = '{"jsonrpc":"2.0","id":1,"method":"ping"}';
$request = $factory
->createServerRequest('GET', 'https://mcp.example.com/mcp')
->withBody($factory->createStream($body))
->withAttribute('oauth.subject', 'user-1');
$response = $middleware->process($request, $this->createEchoHandler($factory));
$this->assertSame($body, $response->getBody()->__toString());
}
private function createEchoHandler(Psr17Factory $factory): RequestHandlerInterface
{
return new class($factory) implements RequestHandlerInterface {
public function __construct(private readonly Psr17Factory $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory
->createResponse(200)
->withBody($this->factory->createStream($request->getBody()->__toString()));
}
};
}
}

View file

@ -0,0 +1,125 @@
<?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\ProtectedResourceMetadataMiddleware;
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Tests ProtectedResourceMetadataMiddleware responses for metadata endpoints.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class ProtectedResourceMetadataMiddlewareTest extends TestCase
{
#[TestDox('default metadata endpoint returns protected resource metadata JSON')]
public function testDefaultMetadataEndpointReturnsJson(): void
{
$factory = new Psr17Factory();
$metadata = new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
scopesSupported: ['mcp:read', 'mcp:write'],
resource: 'https://mcp.example.com/mcp',
resourceName: 'Example MCP API',
resourceDocumentation: 'https://mcp.example.com/docs',
localizedHumanReadable: [
'resource_name#uk' => 'Pryklad MCP API',
],
);
$middleware = new ProtectedResourceMetadataMiddleware(
metadata: $metadata,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest(
'GET',
'https://mcp.example.com/.well-known/oauth-protected-resource',
);
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(404);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
$payload = json_decode($response->getBody()->__toString(), true, 512, \JSON_THROW_ON_ERROR);
$this->assertSame(['https://auth.example.com'], $payload['authorization_servers']);
$this->assertSame(['mcp:read', 'mcp:write'], $payload['scopes_supported']);
$this->assertSame('https://mcp.example.com/mcp', $payload['resource']);
$this->assertSame('Example MCP API', $payload['resource_name']);
$this->assertSame('https://mcp.example.com/docs', $payload['resource_documentation']);
$this->assertSame('Pryklad MCP API', $payload['resource_name#uk']);
}
#[TestDox('non metadata request passes to next middleware')]
public function testNonMetadataRequestPassesThrough(): void
{
$factory = new Psr17Factory();
$metadata = new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
);
$middleware = new ProtectedResourceMetadataMiddleware(
metadata: $metadata,
responseFactory: $factory,
streamFactory: $factory,
);
$request = $factory->createServerRequest('GET', 'https://mcp.example.com/mcp');
$handler = new class($factory) implements RequestHandlerInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->factory->createResponse(204);
}
};
$response = $middleware->process($request, $handler);
$this->assertSame(204, $response->getStatusCode());
}
#[TestDox('empty authorization servers are rejected')]
public function testEmptyAuthorizationServersThrows(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('requires at least one authorization server');
new ProtectedResourceMetadata([]);
}
}

View file

@ -0,0 +1,168 @@
<?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\OAuth;
use Mcp\Exception\RuntimeException;
use Mcp\Server\Transport\Http\OAuth\JwksProvider;
use Mcp\Server\Transport\Http\OAuth\OidcDiscoveryInterface;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\SimpleCache\CacheInterface;
/**
* Tests JwksProvider loading, validation, and caching behavior.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class JwksProviderTest extends TestCase
{
#[TestDox('JWKS are loaded from explicit URI')]
public function testGetJwksFromExplicitUri(): void
{
$factory = new Psr17Factory();
$jwksUri = 'https://auth.example.com/jwks';
$jwks = [
'keys' => [
['kty' => 'RSA', 'kid' => 'kid-1', 'n' => 'abc', 'e' => 'AQAB'],
],
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())
->method('sendRequest')
->willReturn(
$factory->createResponse(200)->withBody(
$factory->createStream(json_encode($jwks, \JSON_THROW_ON_ERROR)),
),
);
$provider = new JwksProvider(
discovery: $this->createDiscoveryStub(),
httpClient: $httpClient,
requestFactory: $factory,
);
$result = $provider->getJwks('https://auth.example.com', $jwksUri);
$this->assertSame($jwks, $result);
}
#[TestDox('invalid cached JWKS are ignored and replaced by fetched values')]
public function testInvalidCachedJwksAreIgnored(): void
{
$factory = new Psr17Factory();
$jwksUri = 'https://auth.example.com/jwks';
$jwks = [
'keys' => [
['kty' => 'RSA', 'kid' => 'kid-1', 'n' => 'abc', 'e' => 'AQAB'],
],
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())
->method('sendRequest')
->willReturn(
$factory->createResponse(200)->withBody(
$factory->createStream(json_encode($jwks, \JSON_THROW_ON_ERROR)),
),
);
$cache = $this->createMock(CacheInterface::class);
$cache->expects($this->once())
->method('get')
->willReturn(['keys' => []]);
$cache->expects($this->once())
->method('set');
$provider = new JwksProvider(
discovery: $this->createDiscoveryStub(),
httpClient: $httpClient,
requestFactory: $factory,
cache: $cache,
);
$result = $provider->getJwks('https://auth.example.com', $jwksUri);
$this->assertSame($jwks, $result);
}
#[TestDox('discovery is used when explicit JWKS URI is not provided')]
public function testDiscoveryIsUsedWhenUriIsMissing(): void
{
$factory = new Psr17Factory();
$jwksUri = 'https://auth.example.com/jwks';
$jwks = [
'keys' => [
['kty' => 'RSA', 'kid' => 'kid-1', 'n' => 'abc', 'e' => 'AQAB'],
],
];
$discovery = $this->createMock(OidcDiscoveryInterface::class);
$discovery->expects($this->once())
->method('getJwksUri')
->with('https://auth.example.com')
->willReturn($jwksUri);
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())
->method('sendRequest')
->willReturn(
$factory->createResponse(200)->withBody(
$factory->createStream(json_encode($jwks, \JSON_THROW_ON_ERROR)),
),
);
$provider = new JwksProvider(
httpClient: $httpClient,
requestFactory: $factory,
discovery: $discovery,
);
$result = $provider->getJwks('https://auth.example.com');
$this->assertSame($jwks, $result);
}
#[TestDox('empty keys in fetched JWKS throw RuntimeException')]
public function testEmptyKeysThrow(): void
{
$factory = new Psr17Factory();
$jwksUri = 'https://auth.example.com/jwks';
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->once())
->method('sendRequest')
->willReturn(
$factory->createResponse(200)->withBody(
$factory->createStream(json_encode(['keys' => []], \JSON_THROW_ON_ERROR)),
),
);
$provider = new JwksProvider(
discovery: $this->createDiscoveryStub(),
httpClient: $httpClient,
requestFactory: $factory,
);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('expected non-empty "keys" array');
$provider->getJwks('https://auth.example.com', $jwksUri);
}
private function createDiscoveryStub(): OidcDiscoveryInterface
{
return $this->createStub(OidcDiscoveryInterface::class);
}
}

View file

@ -0,0 +1,589 @@
<?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\OAuth;
use Firebase\JWT\JWT;
use Mcp\Exception\RuntimeException;
use Mcp\Server\Transport\Http\OAuth\JwksProvider;
use Mcp\Server\Transport\Http\OAuth\JwtTokenValidator;
use Mcp\Server\Transport\Http\OAuth\OidcDiscoveryInterface;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Tests JwtTokenValidator for signature, claims, and scope extraction.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class JwtTokenValidatorTest extends TestCase
{
#[TestDox('valid JWT is allowed and claims/scopes are exposed as request attributes')]
public function testValidJwtAllowsAndExposesAttributes(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$jwksUri = 'https://auth.example.com/.well-known/jwks.json';
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: $jwksUri,
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'client_id' => 'client-abc',
'azp' => 'client-abc',
'scope' => 'mcp:read mcp:write',
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertTrue($result->isAllowed());
$attributes = $result->getAttributes();
$this->assertArrayHasKey('oauth.claims', $attributes);
$this->assertArrayHasKey('oauth.scopes', $attributes);
$this->assertSame(['mcp:read', 'mcp:write'], $attributes['oauth.scopes']);
$this->assertSame('user-123', $attributes['oauth.subject']);
$this->assertSame('client-abc', $attributes['oauth.client_id']);
$this->assertSame('client-abc', $attributes['oauth.authorized_party']);
}
#[TestDox('issuer mismatch yields unauthorized result')]
public function testIssuerMismatchIsUnauthorized(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$jwksUri = 'https://auth.example.com/.well-known/jwks.json';
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: $jwksUri,
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://other-issuer.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'scope' => 'mcp:read',
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertFalse($result->isAllowed());
$this->assertSame(401, $result->getStatusCode());
$this->assertSame('invalid_token', $result->getError());
$this->assertSame('Token issuer mismatch.', $result->getErrorDescription());
}
#[TestDox('audience mismatch yields unauthorized result')]
public function testAudienceMismatchIsUnauthorized(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$jwksUri = 'https://auth.example.com/.well-known/jwks.json';
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: ['mcp-api'],
jwksUri: $jwksUri,
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'different-aud',
'sub' => 'user-123',
'scope' => 'mcp:read',
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertFalse($result->isAllowed());
$this->assertSame(401, $result->getStatusCode());
$this->assertSame('invalid_token', $result->getError());
$this->assertSame('Token audience mismatch.', $result->getErrorDescription());
}
#[TestDox('expired token yields unauthorized invalid_token with expired message')]
public function testExpiredTokenIsUnauthorized(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'iat' => time() - 7200,
'exp' => time() - 10,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertFalse($result->isAllowed());
$this->assertSame(401, $result->getStatusCode());
$this->assertSame('invalid_token', $result->getError());
$this->assertSame('Token has expired.', $result->getErrorDescription());
}
#[TestDox('token with future nbf yields unauthorized invalid_token with not-yet-valid message')]
public function testBeforeValidTokenIsUnauthorized(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'iat' => time(),
'nbf' => time() + 3600,
'exp' => time() + 7200,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertFalse($result->isAllowed());
$this->assertSame(401, $result->getStatusCode());
$this->assertSame('invalid_token', $result->getError());
$this->assertSame('Token is not yet valid.', $result->getErrorDescription());
}
#[TestDox('signature verification failure yields unauthorized invalid_token with signature message')]
public function testSignatureInvalidIsUnauthorized(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
// Create a mismatched JWK with the same kid so the key lookup succeeds but signature verification fails.
[, $mismatchedJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$mismatchedJwk['kid'] = $publicJwk['kid'];
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$mismatchedJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertFalse($result->isAllowed());
$this->assertSame(401, $result->getStatusCode());
$this->assertSame('invalid_token', $result->getError());
$this->assertSame('Token signature verification failed.', $result->getErrorDescription());
}
#[TestDox('JWKS HTTP error results in RuntimeException')]
public function testJwksHttpErrorThrowsRuntimeException(): void
{
$factory = new Psr17Factory();
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $this->createHttpClientMock([$factory->createResponse(500)]), requestFactory: $factory),
);
$token = $this->unsignedJwt(['iss' => 'https://auth.example.com', 'aud' => 'mcp-api']);
$this->expectException(RuntimeException::class);
$validator->validate($token);
}
#[TestDox('Invalid JWKS JSON results in RuntimeException')]
public function testInvalidJwksJsonThrowsRuntimeException(): void
{
$factory = new Psr17Factory();
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream('{not-json')),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = $this->unsignedJwt(['iss' => 'https://auth.example.com', 'aud' => 'mcp-api']);
$this->expectException(RuntimeException::class);
$validator->validate($token);
}
#[TestDox('JWKS without keys array results in RuntimeException')]
public function testJwksMissingKeysThrowsRuntimeException(): void
{
$factory = new Psr17Factory();
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['nope' => []], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = $this->unsignedJwt(['iss' => 'https://auth.example.com', 'aud' => 'mcp-api']);
$this->expectException(RuntimeException::class);
$validator->validate($token);
}
#[TestDox('requireScopes returns forbidden when any required scope is missing')]
public function testRequireScopesForbiddenWhenMissing(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'scope' => 'mcp:read',
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertTrue($result->isAllowed());
$scoped = $validator->requireScopes($result, ['mcp:read', 'mcp:write']);
$this->assertFalse($scoped->isAllowed());
$this->assertSame(403, $scoped->getStatusCode());
$this->assertSame('insufficient_scope', $scoped->getError());
$this->assertSame(['mcp:read', 'mcp:write'], $scoped->getScopes());
}
#[TestDox('requireScopes passes through when all required scopes are present')]
public function testRequireScopesPassesWhenPresent(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$httpClient = $this->createHttpClientMock([
$factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR))),
]);
$validator = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$token = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'scope' => ['mcp:read', 'mcp:write'],
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$result = $validator->validate($token);
$this->assertTrue($result->isAllowed());
$scoped = $validator->requireScopes($result, ['mcp:read']);
$this->assertTrue($scoped->isAllowed());
}
#[TestDox('extractScopes returns empty array when scope claim is missing or invalid type')]
public function testExtractScopesEdgeCases(): void
{
$factory = new Psr17Factory();
[$privateKeyPem, $publicJwk] = $this->generateRsaKeypairAsJwk('test-kid');
$jwksResponse = $factory->createResponse(200)
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream(json_encode(['keys' => [$publicJwk]], \JSON_THROW_ON_ERROR)));
$httpClient = $this->createHttpClientMock([$jwksResponse]);
// missing scope
$validatorMissing = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient, requestFactory: $factory),
);
$tokenMissing = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$resultMissing = $validatorMissing->validate($tokenMissing);
$this->assertTrue($resultMissing->isAllowed());
$this->assertSame([], $resultMissing->getAttributes()['oauth.scopes']);
// invalid scope type
$httpClient2 = $this->createHttpClientMock([$jwksResponse]);
$validatorInvalid = new JwtTokenValidator(
issuer: 'https://auth.example.com',
audience: 'mcp-api',
jwksUri: 'https://auth.example.com/jwks',
jwksProvider: new JwksProvider(discovery: $this->createDiscoveryStub(), httpClient: $httpClient2, requestFactory: $factory),
);
$tokenInvalid = JWT::encode(
[
'iss' => 'https://auth.example.com',
'aud' => 'mcp-api',
'sub' => 'user-123',
'scope' => 123,
'iat' => time() - 10,
'exp' => time() + 600,
],
$privateKeyPem,
'RS256',
keyId: 'test-kid',
);
$resultInvalid = $validatorInvalid->validate($tokenInvalid);
$this->assertTrue($resultInvalid->isAllowed());
$this->assertSame([], $resultInvalid->getAttributes()['oauth.scopes']);
}
private function unsignedJwt(array $claims): string
{
$header = $this->b64urlEncode(json_encode(['alg' => 'none', 'typ' => 'JWT'], \JSON_THROW_ON_ERROR));
$payload = $this->b64urlEncode(json_encode($claims, \JSON_THROW_ON_ERROR));
return $header.'.'.$payload.'.';
}
/**
* @return array{0: string, 1: array<string, mixed>}
*/
private function generateRsaKeypairAsJwk(string $kid): array
{
$key = openssl_pkey_new([
'private_key_type' => \OPENSSL_KEYTYPE_RSA,
'private_key_bits' => 2048,
]);
if (false === $key) {
$this->fail('Failed to generate RSA keypair via OpenSSL.');
}
$privateKeyPem = '';
if (!openssl_pkey_export($key, $privateKeyPem)) {
$this->fail('Failed to export RSA private key.');
}
$details = openssl_pkey_get_details($key);
if (false === $details || !isset($details['rsa']['n'], $details['rsa']['e'])) {
$this->fail('Failed to read RSA key details.');
}
$n = $this->b64urlEncode($details['rsa']['n']);
$e = $this->b64urlEncode($details['rsa']['e']);
$publicJwk = [
'kty' => 'RSA',
'kid' => $kid,
'use' => 'sig',
'alg' => 'RS256',
'n' => $n,
'e' => $e,
];
return [$privateKeyPem, $publicJwk];
}
private function b64urlEncode(string $data): string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
private function createDiscoveryStub(): OidcDiscoveryInterface
{
return $this->createStub(OidcDiscoveryInterface::class);
}
/**
* @param list<ResponseInterface> $responses
*/
private function createHttpClientMock(array $responses, ?int $expectedCalls = null): ClientInterface
{
$expectedCalls ??= \count($responses);
$httpClient = $this->createMock(ClientInterface::class);
$expectation = $httpClient
->expects($this->exactly($expectedCalls))
->method('sendRequest')
->with($this->isInstanceOf(RequestInterface::class));
if (1 === $expectedCalls) {
$expectation->willReturn($responses[0]);
} else {
// If expectedCalls > count(responses), keep returning the last response.
$sequence = $responses;
while (\count($sequence) < $expectedCalls) {
$sequence[] = $responses[array_key_last($responses)];
}
$expectation->willReturnOnConsecutiveCalls(...$sequence);
}
return $httpClient;
}
}

View file

@ -0,0 +1,268 @@
<?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\OAuth;
use Mcp\Exception\RuntimeException;
use Mcp\Server\Transport\Http\OAuth\OidcDiscovery;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\CacheInterface;
/**
* Tests OidcDiscovery metadata resolution, validation, and caching behavior.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class OidcDiscoveryTest extends TestCase
{
#[TestDox('invalid issuer URL throws RuntimeException')]
public function testInvalidIssuerUrlThrows(): void
{
$this->skipIfPsrHttpClientIsMissing();
$factory = new Psr17Factory();
$discovery = new OidcDiscovery(
httpClient: $this->createMock(ClientInterface::class),
requestFactory: $factory,
);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Invalid issuer URL');
$discovery->discover('invalid-issuer');
}
#[TestDox('strict discovery rejects metadata without code challenge methods')]
public function testDiscoverRejectsMetadataWithoutCodeChallengeMethodsSupported(): void
{
$this->skipIfPsrHttpClientIsMissing();
$factory = new Psr17Factory();
$issuer = 'https://auth.example.com';
$metadataWithoutCodeChallengeMethods = [
'issuer' => $issuer,
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://auth.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->exactly(2))
->method('sendRequest')
->willReturn($factory->createResponse(200)->withBody(
$factory->createStream(json_encode($metadataWithoutCodeChallengeMethods, \JSON_THROW_ON_ERROR)),
));
$discovery = new OidcDiscovery(
httpClient: $httpClient,
requestFactory: $factory,
);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Failed to discover authorization server metadata');
$discovery->discover($issuer);
}
#[TestDox('discover falls back to the next metadata URL when first response is invalid')]
public function testDiscoverFallsBackOnInvalidMetadataResponse(): void
{
$this->skipIfPsrHttpClientIsMissing();
$factory = new Psr17Factory();
$requestedUrls = [];
$invalidMetadata = [
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
// token_endpoint is intentionally missing
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
];
$validMetadata = [
'issuer' => 'https://auth.example.com/tenant',
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://auth.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
'code_challenge_methods_supported' => ['S256'],
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->exactly(2))
->method('sendRequest')
->willReturnCallback(static function (RequestInterface $request) use ($factory, &$requestedUrls, $invalidMetadata, $validMetadata): ResponseInterface {
$requestedUrls[] = (string) $request->getUri();
$payload = 1 === \count($requestedUrls) ? $invalidMetadata : $validMetadata;
return $factory->createResponse(200)->withBody(
$factory->createStream(json_encode($payload, \JSON_THROW_ON_ERROR)),
);
});
$discovery = new OidcDiscovery(
httpClient: $httpClient,
requestFactory: $factory,
);
$metadata = $discovery->discover('https://auth.example.com/tenant');
$this->assertSame($validMetadata['authorization_endpoint'], $metadata['authorization_endpoint']);
$this->assertSame($validMetadata['token_endpoint'], $metadata['token_endpoint']);
$this->assertSame($validMetadata['jwks_uri'], $metadata['jwks_uri']);
$this->assertSame(
'https://auth.example.com/.well-known/oauth-authorization-server/tenant',
$requestedUrls[0],
);
$this->assertSame(
'https://auth.example.com/.well-known/openid-configuration/tenant',
$requestedUrls[1],
);
}
#[TestDox('valid metadata from cache is returned without HTTP call')]
public function testDiscoverUsesValidCacheWithoutHttpCall(): void
{
$this->skipIfPsrHttpClientIsMissing();
$factory = new Psr17Factory();
$cachedMetadata = [
'issuer' => 'https://auth.example.com/tenant',
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://auth.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
'code_challenge_methods_supported' => ['S256'],
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->never())->method('sendRequest');
$cache = $this->createMock(CacheInterface::class);
$cache->expects($this->once())
->method('get')
->willReturn($cachedMetadata);
$cache->expects($this->never())->method('set');
$discovery = new OidcDiscovery(
httpClient: $httpClient,
requestFactory: $factory,
cache: $cache,
);
$metadata = $discovery->discover('https://auth.example.com/tenant');
$this->assertSame($cachedMetadata, $metadata);
}
#[TestDox('discover skips metadata when issuer claim does not match requested issuer')]
public function testDiscoverSkipsIssuerMismatch(): void
{
$this->skipIfPsrHttpClientIsMissing();
$factory = new Psr17Factory();
$requestedUrls = [];
$issuerMismatch = [
'issuer' => 'https://auth.example.com/other-tenant',
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://auth.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
'code_challenge_methods_supported' => ['S256'],
];
$validMetadata = [
'issuer' => 'https://auth.example.com/tenant',
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://auth.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
'code_challenge_methods_supported' => ['S256'],
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->exactly(2))
->method('sendRequest')
->willReturnCallback(static function (RequestInterface $request) use ($factory, &$requestedUrls, $issuerMismatch, $validMetadata): ResponseInterface {
$requestedUrls[] = (string) $request->getUri();
$payload = 1 === \count($requestedUrls) ? $issuerMismatch : $validMetadata;
return $factory->createResponse(200)->withBody(
$factory->createStream(json_encode($payload, \JSON_THROW_ON_ERROR)),
);
});
$discovery = new OidcDiscovery(
httpClient: $httpClient,
requestFactory: $factory,
);
$metadata = $discovery->discover('https://auth.example.com/tenant');
$this->assertSame($validMetadata['issuer'], $metadata['issuer']);
$this->assertSame(
'https://auth.example.com/.well-known/oauth-authorization-server/tenant',
$requestedUrls[0],
);
$this->assertSame(
'https://auth.example.com/.well-known/openid-configuration/tenant',
$requestedUrls[1],
);
}
#[TestDox('issuer without path uses standard well-known endpoints')]
public function testIssuerWithoutPathUsesStandardWellKnownEndpoints(): void
{
$this->skipIfPsrHttpClientIsMissing();
$factory = new Psr17Factory();
$requestedUrls = [];
$validMetadata = [
'issuer' => 'https://auth.example.com',
'authorization_endpoint' => 'https://auth.example.com/oauth2/v2.0/authorize',
'token_endpoint' => 'https://auth.example.com/oauth2/v2.0/token',
'jwks_uri' => 'https://auth.example.com/discovery/v2.0/keys',
'code_challenge_methods_supported' => ['S256'],
];
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->expects($this->exactly(2))
->method('sendRequest')
->willReturnCallback(static function (RequestInterface $request) use ($factory, &$requestedUrls, $validMetadata): ResponseInterface {
$requestedUrls[] = (string) $request->getUri();
if (1 === \count($requestedUrls)) {
return $factory->createResponse(404);
}
return $factory->createResponse(200)->withBody(
$factory->createStream(json_encode($validMetadata, \JSON_THROW_ON_ERROR)),
);
});
$discovery = new OidcDiscovery(
httpClient: $httpClient,
requestFactory: $factory,
);
$metadata = $discovery->discover('https://auth.example.com');
$this->assertSame($validMetadata['jwks_uri'], $metadata['jwks_uri']);
$this->assertSame('https://auth.example.com/.well-known/oauth-authorization-server', $requestedUrls[0]);
$this->assertSame('https://auth.example.com/.well-known/openid-configuration', $requestedUrls[1]);
}
private function skipIfPsrHttpClientIsMissing(): void
{
if (!interface_exists(ClientInterface::class)) {
$this->markTestSkipped('psr/http-client is not available in this runtime.');
}
}
}

View file

@ -0,0 +1,86 @@
<?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\OAuth;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Tests ProtectedResourceMetadata serialization and input validation.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class ProtectedResourceMetadataTest extends TestCase
{
#[TestDox('serializes RFC 9728 metadata including human-readable fields')]
public function testJsonSerializeIncludesHumanReadableFields(): void
{
$metadata = new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
scopesSupported: ['openid', 'profile'],
resource: 'https://api.example.com/mcp',
resourceName: 'Example MCP API',
resourceDocumentation: 'https://api.example.com/docs',
resourcePolicyUri: 'https://api.example.com/policy',
resourceTosUri: 'https://api.example.com/tos',
localizedHumanReadable: [
'resource_name#en' => 'Example MCP API',
],
extra: [
'bearer_methods_supported' => ['header'],
],
metadataPaths: ['.well-known/oauth-protected-resource'],
);
$this->assertSame(
[
'bearer_methods_supported' => ['header'],
'authorization_servers' => ['https://auth.example.com'],
'scopes_supported' => ['openid', 'profile'],
'resource' => 'https://api.example.com/mcp',
'resource_name' => 'Example MCP API',
'resource_documentation' => 'https://api.example.com/docs',
'resource_policy_uri' => 'https://api.example.com/policy',
'resource_tos_uri' => 'https://api.example.com/tos',
'resource_name#en' => 'Example MCP API',
],
$metadata->jsonSerialize(),
);
$this->assertSame('/.well-known/oauth-protected-resource', $metadata->getPrimaryMetadataPath());
$this->assertSame(['openid', 'profile'], $metadata->getScopesSupported());
}
#[TestDox('invalid localized human-readable field is rejected')]
public function testInvalidLocalizedHumanReadableFieldThrows(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid localized human-readable field');
new ProtectedResourceMetadata(
authorizationServers: ['https://auth.example.com'],
localizedHumanReadable: [
'invalid#en' => 'value',
],
);
}
#[TestDox('empty authorization servers are rejected')]
public function testEmptyAuthorizationServersThrows(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('requires at least one authorization server');
new ProtectedResourceMetadata([]);
}
}

View file

@ -0,0 +1,79 @@
<?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\OAuth;
use Mcp\Server\Transport\Http\OAuth\StrictOidcDiscoveryMetadataPolicy;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Tests StrictOidcDiscoveryMetadataPolicy validation behavior.
*
* @author Volodymyr Panivko <sveneld300@gmail.com>
*/
class StrictOidcDiscoveryMetadataPolicyTest extends TestCase
{
#[TestDox('metadata without code challenge methods is invalid in strict mode')]
public function testMissingCodeChallengeMethodsIsInvalid(): void
{
$policy = new StrictOidcDiscoveryMetadataPolicy();
$metadata = [
'authorization_endpoint' => 'https://auth.example.com/authorize',
'token_endpoint' => 'https://auth.example.com/token',
'jwks_uri' => 'https://auth.example.com/jwks',
];
$this->assertFalse($policy->isValid($metadata));
}
#[TestDox('valid code challenge methods list is accepted in strict mode')]
public function testValidCodeChallengeMethodsIsAccepted(): void
{
$policy = new StrictOidcDiscoveryMetadataPolicy();
$metadata = [
'authorization_endpoint' => 'https://auth.example.com/authorize',
'token_endpoint' => 'https://auth.example.com/token',
'jwks_uri' => 'https://auth.example.com/jwks',
'code_challenge_methods_supported' => ['S256'],
];
$this->assertTrue($policy->isValid($metadata));
}
#[TestDox('empty code challenge methods list is invalid in strict mode')]
public function testEmptyCodeChallengeMethodsIsInvalid(): void
{
$policy = new StrictOidcDiscoveryMetadataPolicy();
$metadata = [
'authorization_endpoint' => 'https://auth.example.com/authorize',
'token_endpoint' => 'https://auth.example.com/token',
'jwks_uri' => 'https://auth.example.com/jwks',
'code_challenge_methods_supported' => [],
];
$this->assertFalse($policy->isValid($metadata));
}
#[TestDox('non string code challenge method is invalid in strict mode')]
public function testNonStringCodeChallengeMethodIsInvalid(): void
{
$policy = new StrictOidcDiscoveryMetadataPolicy();
$metadata = [
'authorization_endpoint' => 'https://auth.example.com/authorize',
'token_endpoint' => 'https://auth.example.com/token',
'jwks_uri' => 'https://auth.example.com/jwks',
'code_challenge_methods_supported' => ['S256', 123],
];
$this->assertFalse($policy->isValid($metadata));
}
}