[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:
parent
61c20f1450
commit
e3f4b88768
5 changed files with 6038 additions and 0 deletions
168
tests/Unit/Server/Transport/Http/OAuth/JwksProviderTest.php
Normal file
168
tests/Unit/Server/Transport/Http/OAuth/JwksProviderTest.php
Normal 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);
|
||||
}
|
||||
}
|
||||
589
tests/Unit/Server/Transport/Http/OAuth/JwtTokenValidatorTest.php
Normal file
589
tests/Unit/Server/Transport/Http/OAuth/JwtTokenValidatorTest.php
Normal 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;
|
||||
}
|
||||
}
|
||||
268
tests/Unit/Server/Transport/Http/OAuth/OidcDiscoveryTest.php
Normal file
268
tests/Unit/Server/Transport/Http/OAuth/OidcDiscoveryTest.php
Normal 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.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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([]);
|
||||
}
|
||||
}
|
||||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue