π The fast, Pythonic way to build MCP servers and clients.
Accept ES256 and other RSA/EC algorithms for CIMD private_key_jwt assertions (#5695)
Asem ahmedddfcf200a137
diff --git a/docs/servers/auth/oauth-proxy.mdx b/docs/servers/auth/oauth-proxy.mdxindex d2a2a2e5c..1071b8a6d 100644--- a/docs/servers/auth/oauth-proxy.mdx+++ b/docs/servers/auth/oauth-proxy.mdx@@ -702,6 +702,8 @@ To use `private_key_jwt`, the CIMD document must include either a `jwks_uri` (URThe OAuth proxy validates JWT assertions according to RFC 7523, checking the signature, issuer, audience, subject claims, and preventing replay attacks via JTI tracking.+Assertions may be signed with an RSA or EC key using `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384`, or `ES512`. Other algorithms, including symmetric ones such as `HS256`, are rejected.+### Security ConsiderationsCIMD provides several security advantages over DCR:diff --git a/fastmcp_slim/fastmcp/server/auth/cimd.py b/fastmcp_slim/fastmcp/server/auth/cimd.pyindex c55287f49..b5a80c454 100644--- a/fastmcp_slim/fastmcp/server/auth/cimd.py+++ b/fastmcp_slim/fastmcp/server/auth/cimd.py@@ -37,6 +37,7 @@ from fastmcp.server.auth.ssrf import (ssrf_safe_fetch_response,validate_url,)+from fastmcp.utilities.auth import decode_jwt_headerfrom fastmcp.utilities.logging import get_loggerif TYPE_CHECKING:@@ -44,6 +45,12 @@ if TYPE_CHECKING:logger = get_logger(__name__)+# Signing algorithms accepted for private_key_jwt assertions: the RSA and EC+# families whose public keys can be published in a client's JWKS.+ASSERTION_ALGORITHMS = frozenset(+ {"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"}+)+def _jwk_to_pem(key_data: dict[str, Any]) -> str:key_type = key_data.get("kty")@@ -550,16 +557,27 @@ class CIMDAssertionValidator:# Periodic cleanup of expired JTIsself._maybe_cleanup()- # 1. Validate CIMD document has key material and get/create verifier+ # 1. Validate CIMD document has key material and get/create verifier.+ # The verifier only accepts keys of the type its algorithm needs, so+ # taking the algorithm from the header cannot widen what the client's+ # own JWKS permits.+ try:+ algorithm = decode_jwt_header(assertion).get("alg")+ except (ValueError, AttributeError) as e:+ raise ValueError(f"Invalid JWT assertion: {e}") from e+ if not isinstance(algorithm, str) or algorithm not in ASSERTION_ALGORITHMS:+ raise ValueError(f"Unsupported assertion algorithm: {algorithm!r}")+if cimd_doc.jwks_uri:jwks_uri_str = str(cimd_doc.jwks_uri)- cache_key = f"{jwks_uri_str}|{client_id}|{token_endpoint}"+ cache_key = f"{jwks_uri_str}|{client_id}|{token_endpoint}|{algorithm}"verifier = self._verifier_cache.get(cache_key)if verifier is None:verifier = _JWTVerifier(jwks_uri=jwks_uri_str,issuer=client_id,audience=token_endpoint,+ algorithm=algorithm,ssrf_safe=True,)if len(self._verifier_cache) >= self._verifier_cache_max_size:@@ -573,6 +591,7 @@ class CIMDAssertionValidator:public_key=public_key,issuer=client_id,audience=token_endpoint,+ algorithm=algorithm,)else:raise ValueError(diff --git a/tests/server/auth/test_cimd_validators.py b/tests/server/auth/test_cimd_validators.pyindex eefabf0bc..70d57d0a0 100644--- a/tests/server/auth/test_cimd_validators.py+++ b/tests/server/auth/test_cimd_validators.py@@ -355,6 +355,116 @@ class TestCIMDAssertionValidator:)assert "Invalid JWT assertion" in str(exc_info.value)+ @staticmethod+ def _ec_assertion(client_id: str, token_endpoint: str, jti: str):+ """Sign an ES256 assertion, returning it with the matching public JWK."""+ from joserfc import jwk, jwt++ key = jwk.ECKey.generate_key(+ "P-256", {"kid": "ec-key-1", "use": "sig", "alg": "ES256"}+ )+ now = int(time.time())+ assertion = jwt.encode(+ {"alg": "ES256", "kid": "ec-key-1"},+ {+ "iss": client_id,+ "sub": client_id,+ "aud": token_endpoint,+ "iat": now,+ "exp": now + 60,+ "jti": jti,+ },+ key,+ )+ return assertion, key.as_dict(private=False)++ async def test_valid_es256_assertion_with_inline_jwks(self, validator):+ """An assertion signed with an EC key validates against an EC JWKS."""+ client_id = "https://example.com/client.json"+ token_endpoint = "https://oauth.example.com/token"+ assertion, public_jwk = self._ec_assertion(+ client_id, token_endpoint, "ec-inline-jti"+ )+ doc = CIMDDocument(+ client_id=AnyHttpUrl(client_id),+ redirect_uris=["http://localhost:3000/callback"],+ token_endpoint_auth_method="private_key_jwt",+ jwks={"keys": [public_jwk]},+ )++ assert await validator.validate_assertion(+ assertion, client_id, token_endpoint, doc+ )++ async def test_valid_es256_assertion_with_jwks_uri(+ self, validator, cimd_doc_with_jwks_uri, httpx_mock+ ):+ """An assertion signed with an EC key validates against a fetched EC JWKS."""+ client_id = "https://example.com/client.json"+ token_endpoint = "https://oauth.example.com/token"+ assertion, public_jwk = self._ec_assertion(+ client_id, token_endpoint, "ec-uri-jti"+ )++ with patch(+ "fastmcp.server.auth.ssrf.resolve_hostname",+ return_value=[TEST_PUBLIC_IP],+ ):+ httpx_mock.add_response(json={"keys": [public_jwk]})++ assert await validator.validate_assertion(+ assertion, client_id, token_endpoint, cimd_doc_with_jwks_uri+ )++ async def test_rejects_unsupported_assertion_algorithm(+ self, validator, cimd_doc_with_inline_jwks+ ):+ """Symmetric and unsigned assertion algorithms are rejected up front."""+ from joserfc import jwk, jwt++ client_id = "https://example.com/client.json"+ token_endpoint = "https://oauth.example.com/token"+ now = int(time.time())+ assertion = jwt.encode(+ {"alg": "HS256", "kid": "test-key-1"},+ {+ "iss": client_id,+ "sub": client_id,+ "aud": token_endpoint,+ "iat": now,+ "exp": now + 60,+ "jti": "hs256-jti",+ },+ jwk.OctKey.import_key("a-shared-secret-that-is-long-enough-32b"),+ )++ with pytest.raises(ValueError, match="Unsupported assertion algorithm"):+ await validator.validate_assertion(+ assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks+ )++ @pytest.mark.parametrize("alg", [[], {}, None, 256])+ async def test_rejects_non_string_assertion_algorithm(+ self, validator, cimd_doc_with_inline_jwks, alg+ ):+ """A header whose alg is not a string is an invalid assertion, not a crash."""+ import base64+ import json++ def segment(data: dict) -> str:+ raw = json.dumps(data).encode()+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()++ assertion = f"{segment({'alg': alg, 'typ': 'JWT'})}.{segment({})}.c2ln"++ with pytest.raises(ValueError, match="Unsupported assertion algorithm"):+ await validator.validate_assertion(+ assertion,+ "https://example.com/client.json",+ "https://oauth.example.com/token",+ cimd_doc_with_inline_jwks,+ )+class TestCIMDClientManager:"""Tests for CIMDClientManager."""