π The fast, Pythonic way to build MCP servers and clients.
fix(auth): accept private-use scheme redirect URIs in CIMD documents (#6335)
Bryan Cole8f363e0fd4bf
diff --git a/docs/servers/auth/oauth-proxy.mdx b/docs/servers/auth/oauth-proxy.mdxindex e85f0c055..c882f3fb4 100644--- a/docs/servers/auth/oauth-proxy.mdx+++ b/docs/servers/auth/oauth-proxy.mdx@@ -711,7 +711,7 @@ CIMD provides several security advantages over DCR:- **Verified identity**: The domain in the `client_id` URL is verified by HTTPS, so users know which organization is requesting access- **No registration required**: Clients don't need to store or manage dynamically-issued credentials-- **Redirect URI enforcement**: CIMD documents must declare `redirect_uris`, which are enforced by the proxy (wildcard patterns supported)+- **Redirect URI enforcement**: CIMD documents must declare `redirect_uris`, which are enforced by the proxy (wildcard patterns supported). `http` and `https` redirects must name a host; native apps may also declare private-use schemes such as `com.example.app:/callback`- **SSRF protection**: The OAuth proxy blocks fetches to localhost, private IPs, and reserved addresses- **Replay prevention**: For `private_key_jwt` clients, JTI claims are tracked to prevent assertion replay- **Cache-aware fetching**: CIMD documents are cached according to HTTP cache headers and revalidated when requireddiff --git a/fastmcp_slim/fastmcp/server/auth/cimd.py b/fastmcp_slim/fastmcp/server/auth/cimd.pyindex b5a80c454..56c535769 100644--- a/fastmcp_slim/fastmcp/server/auth/cimd.py+++ b/fastmcp_slim/fastmcp/server/auth/cimd.py@@ -165,7 +165,9 @@ class CIMDDocument(BaseModel):raise ValueError(f"CIMD redirect_uri must have a scheme (e.g. http:// or https://): {uri!r}")- if not parsed.netloc and not uri.startswith("urn:"):+ # Private-use schemes (RFC 8252 section 7.1, e.g. com.example.app:/cb)+ # have no host, so only http(s) redirects must name one.+ if parsed.scheme in ("http", "https") and not parsed.netloc:raise ValueError(f"CIMD redirect_uri must have a host: {uri!r}")return vdiff --git a/tests/server/auth/oauth_proxy/test_authorization.py b/tests/server/auth/oauth_proxy/test_authorization.pyindex 7b67ae934..814c5f276 100644--- a/tests/server/auth/oauth_proxy/test_authorization.py+++ b/tests/server/auth/oauth_proxy/test_authorization.py@@ -1,5 +1,6 @@"""Tests for OAuth proxy authorization flow."""+from unittest.mock import patchfrom urllib.parse import parse_qs, urlparseimport pytest@@ -7,6 +8,8 @@ from key_value.aio.stores.memory import MemoryStorefrom mcp.server.auth.provider import AuthorizationParamsfrom mcp.shared.auth import OAuthClientInformationFullfrom pydantic import AnyUrl+from starlette.applications import Starlette+from starlette.testclient import TestClientfrom fastmcp.server.auth.oauth_proxy import OAuthProxy@@ -261,3 +264,72 @@ class TestParameterForwarding:# Should succeed (no resource check needed)redirect_url = await proxy.authorize(client, params)assert "/consent" in redirect_url+++class TestCIMDPrivateUseSchemeAuthorize:+ """/authorize for a CIMD client whose redirect_uris use private-use schemes."""++ CLIENT_ID = "https://example.com/client.json"++ @pytest.fixture(autouse=True)+ def mock_dns(self):+ with patch(+ "fastmcp.server.auth.ssrf.resolve_hostname",+ return_value=["93.184.216.34"],+ ):+ yield++ @pytest.fixture+ def declare_client(self, httpx_mock):+ httpx_mock.add_response(+ json={+ "client_id": self.CLIENT_ID,+ "client_name": "Native App",+ "redirect_uris": ["com.example.app:/oauth", "myapp://callback"],+ "token_endpoint_auth_method": "none",+ },+ headers={"content-length": "200"},+ )++ def _authorize(self, oauth_proxy: OAuthProxy, redirect_uri: str):+ app = Starlette(routes=oauth_proxy.get_routes(mcp_path="/mcp"))+ with TestClient(+ app, base_url="https://myserver.com", follow_redirects=False+ ) as client:+ return client.get(+ "/authorize",+ params={+ "response_type": "code",+ "client_id": self.CLIENT_ID,+ "redirect_uri": redirect_uri,+ "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",+ "code_challenge_method": "S256",+ "state": "client-state",+ },+ )++ @pytest.mark.parametrize(+ "redirect_uri", ["com.example.app:/oauth", "myapp://callback"]+ )+ def test_declared_private_use_redirect_reaches_consent(+ self, oauth_proxy, declare_client, redirect_uri+ ):+ response = self._authorize(oauth_proxy, redirect_uri)++ assert response.status_code == 302+ assert urlparse(response.headers["location"]).path == "/consent"++ @pytest.mark.parametrize(+ "redirect_uri",+ ["com.evil.app:/oauth", "com.example.app://evil.example/oauth"],+ )+ def test_undeclared_private_use_redirect_is_rejected(+ self, oauth_proxy, declare_client, redirect_uri+ ):+ response = self._authorize(oauth_proxy, redirect_uri)++ assert response.status_code == 400+ assert response.json()["error"] == "invalid_request"+ assert (+ "does not match CIMD redirect_uris" in response.json()["error_description"]+ )diff --git a/tests/server/auth/test_cimd.py b/tests/server/auth/test_cimd.pyindex b88f23bf6..a07dc223b 100644--- a/tests/server/auth/test_cimd.py+++ b/tests/server/auth/test_cimd.py@@ -125,6 +125,27 @@ class TestCIMDDocument:redirect_uris=["http://"],)+ @pytest.mark.parametrize("uri", ["http://", "https:///callback"])+ def test_http_redirect_uri_without_host_rejected(self, uri):+ """http(s) redirect_uris must still name a host."""+ with pytest.raises(ValidationError, match="must have a host"):+ CIMDDocument(+ client_id=AnyHttpUrl("https://example.com/client.json"),+ redirect_uris=[uri],+ )++ @pytest.mark.parametrize(+ "uri",+ ["com.example.app:/oauth", "myapp://callback", "urn:ietf:wg:oauth:2.0:oob"],+ )+ def test_non_http_redirect_uri_accepted(self, uri):+ """Private-use schemes (RFC 8252 section 7.1) have no host."""+ doc = CIMDDocument(+ client_id=AnyHttpUrl("https://example.com/client.json"),+ redirect_uris=[uri],+ )+ assert doc.redirect_uris == [uri]+def test_redirect_uri_whitespace_only_rejected(self):"""Test that whitespace-only redirect_uris are rejected."""with pytest.raises(ValidationError, match="non-empty"):diff --git a/tests/server/auth/test_cimd_validators.py b/tests/server/auth/test_cimd_validators.pyindex 70d57d0a0..36c4c0ac0 100644--- a/tests/server/auth/test_cimd_validators.py+++ b/tests/server/auth/test_cimd_validators.py@@ -821,3 +821,36 @@ class TestCIMDRedirectUriEnforcement:# 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"))++ async def test_private_use_scheme_redirect_uris(self, httpx_mock, mock_dns):+ """A native client's private-use scheme redirect resolves and is enforced.++ RFC 8252 section 7.1 schemes have no host, and unsafe schemes in the+ document are never usable.+ """+ from mcp.shared.auth import InvalidRedirectUriError+ from pydantic import AnyUrl++ url = "https://example.com/client.json"+ httpx_mock.add_response(+ json={+ "client_id": url,+ "client_name": "Native App",+ "redirect_uris": [+ "com.example.app:/oauth",+ "javascript:alert(1)",+ ],+ "token_endpoint_auth_method": "none",+ },+ headers={"content-length": "200"},+ )++ client = await CIMDClientManager(enable_cimd=True).get_client(url)+ assert client is not None++ validated = client.validate_redirect_uri(AnyUrl("com.example.app:/oauth"))+ assert str(validated) == "com.example.app:/oauth"++ for rejected in ("com.evil.app:/oauth", "javascript:alert(1)"):+ with pytest.raises(InvalidRedirectUriError):+ client.validate_redirect_uri(AnyUrl(rejected))