Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683"""Unit tests for CIMD assertion validators, client manager, and redirect URI enforcement."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytestfrom pydantic import AnyHttpUrl
from fastmcp.server.auth.cimd import ( CIMDAssertionValidator, CIMDClientManager, CIMDDocument,)from fastmcp.server.auth.oauth_proxy.models import ProxyDCRClient
# Standard public IP used for DNS mocking in testsTEST_PUBLIC_IP = "93.184.216.34"
class TestCIMDAssertionValidator: """Tests for CIMDAssertionValidator (private_key_jwt support)."""
@pytest.fixture def validator(self): """Create a CIMDAssertionValidator for testing.""" return CIMDAssertionValidator()
@pytest.fixture def key_pair(self): """Generate RSA key pair for testing.""" from fastmcp.server.auth.providers.jwt import RSAKeyPair
return RSAKeyPair.generate()
@pytest.fixture def jwks(self, key_pair): """Create JWKS from key pair.""" import base64
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization
# Load public key public_key = serialization.load_pem_public_key( key_pair.public_key.encode(), backend=default_backend() )
# Get RSA public numbers from cryptography.hazmat.primitives.asymmetric import rsa
if isinstance(public_key, rsa.RSAPublicKey): numbers = public_key.public_numbers()
# Convert to JWK format return { "keys": [ { "kty": "RSA", "kid": "test-key-1", "use": "sig", "alg": "RS256", "n": base64.urlsafe_b64encode( numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), "e": base64.urlsafe_b64encode( numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), } ] }
@pytest.fixture def cimd_doc_with_jwks_uri(self): """Create CIMD document with jwks_uri.""" return CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks_uri=AnyHttpUrl("https://example.com/.well-known/jwks.json"), )
@pytest.fixture def cimd_doc_with_inline_jwks(self, jwks): """Create CIMD document with inline JWKS.""" return CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks=jwks, )
async def test_valid_assertion_with_jwks_uri( self, validator, key_pair, cimd_doc_with_jwks_uri, httpx_mock ): """Test that valid JWT assertion passes validation (jwks_uri).""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Mock JWKS endpoint import base64
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization
public_key = serialization.load_pem_public_key( key_pair.public_key.encode(), backend=default_backend() ) from cryptography.hazmat.primitives.asymmetric import rsa
assert isinstance(public_key, rsa.RSAPublicKey) numbers = public_key.public_numbers()
jwks = { "keys": [ { "kty": "RSA", "kid": "test-key-1", "use": "sig", "alg": "RS256", "n": base64.urlsafe_b64encode( numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), "e": base64.urlsafe_b64encode( numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), } ] }
# Mock DNS resolution for SSRF-safe fetch with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): httpx_mock.add_response(json=jwks)
# Create valid assertion (use short lifetime for security compliance) assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "unique-jti-123"}, expires_in_seconds=60, # 1 minute (max allowed is 300s) kid="test-key-1", )
# Should validate successfully assert await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_jwks_uri )
async def test_valid_assertion_with_inline_jwks( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that valid JWT assertion passes validation (inline JWKS).""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create valid assertion (use short lifetime for security compliance) assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "unique-jti-456"}, expires_in_seconds=60, # 1 minute (max allowed is 300s) kid="test-key-1", )
# Should validate successfully assert await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks )
async def test_rejects_wrong_issuer( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that wrong issuer is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create assertion with wrong issuer assertion = key_pair.create_token( subject=client_id, issuer="https://attacker.com", # Wrong! audience=token_endpoint, additional_claims={"jti": "unique-jti-789"}, expires_in_seconds=60, kid="test-key-1", )
with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "Invalid JWT assertion" in str(exc_info.value)
async def test_rejects_wrong_audience( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that wrong audience is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create assertion with wrong audience assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience="https://wrong-endpoint.com/token", # Wrong! additional_claims={"jti": "unique-jti-abc"}, expires_in_seconds=60, kid="test-key-1", )
with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "Invalid JWT assertion" in str(exc_info.value)
async def test_rejects_wrong_subject( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that wrong subject claim is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create assertion with wrong subject assertion = key_pair.create_token( subject="https://different-client.com", # Wrong! issuer=client_id, audience=token_endpoint, additional_claims={"jti": "unique-jti-def"}, expires_in_seconds=60, kid="test-key-1", )
with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "sub claim must be" in str(exc_info.value)
async def test_rejects_missing_jti( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that missing jti claim is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create assertion without jti assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, # No jti! expires_in_seconds=60, kid="test-key-1", )
with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "jti claim" in str(exc_info.value)
async def test_rejects_replayed_jti( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that replayed JTI is detected and rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create assertion assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "replayed-jti"}, expires_in_seconds=60, kid="test-key-1", )
# First use should succeed assert await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks )
# Second use with same jti should fail (replay attack) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "replay" in str(exc_info.value).lower()
async def test_rejects_expired_token( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that expired tokens are rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token"
# Create expired assertion (expired 1 hour ago) assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "expired-jti"}, expires_in_seconds=-3600, # Negative = expired kid="test-key-1", )
with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "Invalid JWT assertion" in str(exc_info.value)
class TestCIMDClientManager: """Tests for CIMDClientManager."""
@pytest.fixture def manager(self): """Create a CIMDClientManager for testing.""" return CIMDClientManager(enable_cimd=True)
@pytest.fixture def disabled_manager(self): """Create a disabled CIMDClientManager for testing.""" return CIMDClientManager(enable_cimd=False)
@pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield
def test_is_cimd_client_id_enabled(self, manager): """Test CIMD URL detection when enabled.""" assert manager.is_cimd_client_id("https://example.com/client.json") assert not manager.is_cimd_client_id("regular-client-id")
def test_is_cimd_client_id_disabled(self, disabled_manager): """Test CIMD URL detection when disabled.""" assert not disabled_manager.is_cimd_client_id("https://example.com/client.json") assert not disabled_manager.is_cimd_client_id("regular-client-id")
async def test_get_client_success(self, manager, httpx_mock, mock_dns): """Test successful CIMD client creation.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
client = await manager.get_client(url) assert client is not None assert client.client_id == url assert client.client_name == "Test App" # Verify it uses proxy's patterns (None by default), not document's redirect_uris assert client.allowed_redirect_uri_patterns is None
async def test_get_client_disabled(self, disabled_manager): """Test that get_client returns None when disabled.""" client = await disabled_manager.get_client("https://example.com/client.json") assert client is None
async def test_get_client_fetch_failure(self, manager, httpx_mock, mock_dns): """Test that get_client returns None on fetch failure.""" url = "https://example.com/client.json" httpx_mock.add_response(status_code=404)
client = await manager.get_client(url) assert client is None
# Trust policy and consent bypass tests removed - functionality removed from CIMD
class TestCIMDClientManagerGetClientOptions: """Tests for CIMDClientManager.get_client with default_scope and allowed patterns."""
@pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield
async def test_default_scope_applied_when_doc_has_no_scope( self, httpx_mock, mock_dns ): """When the CIMD document omits scope, the manager's default_scope is used."""
url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", # No scope field } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
manager = CIMDClientManager( enable_cimd=True, default_scope="read write admin", ) client = await manager.get_client(url) assert client is not None assert client.scope == "read write admin"
async def test_doc_scope_takes_precedence_over_default(self, httpx_mock, mock_dns): """When the CIMD document specifies scope, it wins over the default."""
url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", "scope": "custom-scope", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
manager = CIMDClientManager( enable_cimd=True, default_scope="default-scope", ) client = await manager.get_client(url) assert client is not None assert client.scope == "custom-scope"
async def test_allowed_redirect_uri_patterns_stored_on_client( self, httpx_mock, mock_dns ): """Proxy's allowed_redirect_uri_patterns are forwarded to the created client."""
url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:*/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
patterns = ["http://localhost:*", "https://app.example.com/*"] manager = CIMDClientManager( enable_cimd=True, allowed_redirect_uri_patterns=patterns, ) client = await manager.get_client(url) assert client is not None assert client.allowed_redirect_uri_patterns == patterns
async def test_cimd_document_attached_to_client(self, httpx_mock, mock_dns): """The fetched CIMDDocument is attached to the created client."""
url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Attached Doc App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
manager = CIMDClientManager(enable_cimd=True) client = await manager.get_client(url) assert client is not None assert client.cimd_document is not None assert client.cimd_document.client_name == "Attached Doc App" assert str(client.cimd_document.client_id) == url
class TestCIMDClientManagerValidatePrivateKeyJwt: """Tests for CIMDClientManager.validate_private_key_jwt wrapper."""
@pytest.fixture def manager(self): return CIMDClientManager(enable_cimd=True)
async def test_missing_cimd_document_raises(self, manager): """validate_private_key_jwt raises ValueError if client has no cimd_document."""
client = ProxyDCRClient( client_id="https://example.com/client.json", client_secret=None, redirect_uris=None, cimd_document=None, ) with pytest.raises(ValueError, match="must have CIMD document"): await manager.validate_private_key_jwt( "fake.jwt.token", client, "https://oauth.example.com/token", )
async def test_wrong_auth_method_raises(self, manager): """validate_private_key_jwt raises ValueError if auth method is not private_key_jwt."""
cimd_doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="none", # Not private_key_jwt ) client = ProxyDCRClient( client_id="https://example.com/client.json", client_secret=None, redirect_uris=None, cimd_document=cimd_doc, ) with pytest.raises(ValueError, match="private_key_jwt"): await manager.validate_private_key_jwt( "fake.jwt.token", client, "https://oauth.example.com/token", )
async def test_success_delegates_to_assertion_validator(self, manager): """On success, validate_private_key_jwt delegates to the assertion validator."""
cimd_doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks_uri=AnyHttpUrl("https://example.com/.well-known/jwks.json"), ) client = ProxyDCRClient( client_id="https://example.com/client.json", client_secret=None, redirect_uris=None, cimd_document=cimd_doc, )
manager._assertion_validator.validate_assertion = AsyncMock(return_value=True)
result = await manager.validate_private_key_jwt( "test.jwt.assertion", client, "https://oauth.example.com/token", ) assert result is True manager._assertion_validator.validate_assertion.assert_awaited_once_with( "test.jwt.assertion", "https://example.com/client.json", "https://oauth.example.com/token", cimd_doc, )
class TestCIMDRedirectUriEnforcement: """Tests for CIMD redirect_uri validation security.
Verifies that CIMD clients enforce BOTH: 1. CIMD document's redirect_uris 2. Proxy's allowed_redirect_uri_patterns """
@pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield
async def test_cimd_redirect_uris_enforced(self, httpx_mock, mock_dns): """Test that CIMD document redirect_uris are enforced.
Even if proxy patterns allow http://localhost:*, a CIMD client should only accept URIs declared in its document. """ from mcp.shared.auth import InvalidRedirectUriError from pydantic import AnyUrl
url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", # CIMD only declares port 3000 "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
# Proxy allows any localhost port manager = CIMDClientManager( enable_cimd=True, allowed_redirect_uri_patterns=["http://localhost:*"], ) client = await manager.get_client(url) assert client is not None
# Declared URI should work validated = client.validate_redirect_uri( AnyUrl("http://localhost:3000/callback") ) assert str(validated) == "http://localhost:3000/callback"
# Different port should fail (not in CIMD redirect_uris) with pytest.raises(InvalidRedirectUriError): client.validate_redirect_uri(AnyUrl("http://localhost:4000/callback"))
async def test_proxy_patterns_also_checked(self, httpx_mock, mock_dns): """Test that proxy patterns are checked even for CIMD clients.
A CIMD client should not be able to use a redirect_uri that's in its document but not allowed by proxy patterns. """ from mcp.shared.auth import InvalidRedirectUriError from pydantic import AnyUrl
url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", # CIMD declares both localhost and external URI "redirect_uris": [ "http://localhost:3000/callback", "https://evil.com/callback", ], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, )
# Proxy only allows localhost manager = CIMDClientManager( enable_cimd=True, allowed_redirect_uri_patterns=["http://localhost:*"], ) client = await manager.get_client(url) assert client is not None
# Localhost should work (in CIMD and matches pattern) validated = client.validate_redirect_uri( AnyUrl("http://localhost:3000/callback") ) assert str(validated) == "http://localhost:3000/callback"
# Evil.com should fail (in CIMD but doesn't match proxy patterns) with pytest.raises(InvalidRedirectUriError): client.validate_redirect_uri(AnyUrl("https://evil.com/callback"))