π The fast, Pythonic way to build MCP servers and clients.
fix(auth): preserve upstream refresh error semantics (#5011)
Dreamb702804e65a2
diff --git a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.pyindex 669fa9f03..fa6666de9 100644--- a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py+++ b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py@@ -109,7 +109,7 @@ from fastmcp.server.auth.oauth_proxy.models import (_hash_token,)from fastmcp.server.auth.oauth_proxy.ui import create_error_html-from fastmcp.server.auth.oauth_proxy.upstream import AsyncOAuth2Client+from fastmcp.server.auth.oauth_proxy.upstream import AsyncOAuth2Client, OAuthErrorfrom fastmcp.server.auth.redirect_validation import (build_client_redirect,is_redirect_uri_allowed_for_application_type,@@ -1834,9 +1834,13 @@ class OAuthProxy(OAuthProvider, ConsentMixin):**self._extra_token_params,)logger.debug("Successfully refreshed upstream token")- except Exception as e:- logger.error("Upstream token refresh failed: %s", e)- raise TokenError("invalid_grant", f"Upstream refresh failed: {e}") from e+ except OAuthError as e:+ logger.warning("Upstream OAuth token refresh failed: %s", e.error)+ if e.error == "invalid_grant":+ raise TokenError(+ "invalid_grant", "Upstream refresh token was rejected"+ ) from e+ raise# A refresh response with a non-positive lifetime is equally unusable.# Reject it before mutating stored upstream state or rotating JTI mappings.diff --git a/tests/server/auth/oauth_proxy/test_tokens.py b/tests/server/auth/oauth_proxy/test_tokens.pyindex ed2545c15..1b720eec2 100644--- a/tests/server/auth/oauth_proxy/test_tokens.py+++ b/tests/server/auth/oauth_proxy/test_tokens.py@@ -9,7 +9,7 @@ import pytestfrom key_value.aio.stores.memory import MemoryStorefrom mcp.server.auth.handlers.token import TokenErrorResponsefrom mcp.server.auth.handlers.token import TokenHandler as SDKTokenHandler-from mcp.server.auth.provider import AuthorizationCode+from mcp.server.auth.provider import AuthorizationCode, TokenErrorfrom mcp.shared.auth import OAuthClientInformationFullfrom pydantic import AnyUrl@@ -31,6 +31,7 @@ from fastmcp.server.auth.oauth_proxy.models import (UpstreamTokenSet,_hash_token,)+from fastmcp.server.auth.oauth_proxy.upstream import OAuthErrorfrom fastmcp.server.auth.providers.jwt import JWTVerifier@@ -350,6 +351,123 @@ class TestOAuthProxyTokenEndpointAuth:mock_client.fetch_token.assert_not_called()+class TestOAuthProxyRefreshErrors:+ async def _make_refresh_context(self, jwt_verifier):+ proxy = OAuthProxy(+ upstream_authorization_endpoint="https://idp.example.com/authorize",+ upstream_token_endpoint="https://idp.example.com/token",+ upstream_client_id="upstream-client",+ token_verifier=jwt_verifier,+ base_url="https://proxy.example.com",+ jwt_signing_key="test-secret-key",+ client_storage=MemoryStore(),+ )+ proxy.set_mcp_path("/mcp")++ client = OAuthClientInformationFull(+ client_id="test-client",+ redirect_uris=[AnyUrl("http://localhost:12345/callback")],+ )+ refresh_jti = "refresh-jti"+ upstream_token_id = "upstream-token-id"+ refresh_value = proxy.jwt_issuer.issue_refresh_token(+ client_id=client.client_id,+ scopes=["read"],+ jti=refresh_jti,+ expires_in=3600,+ )+ now = time.time()++ await proxy._jti_mapping_store.put(+ key=refresh_jti,+ value=JTIMapping(+ jti=refresh_jti,+ upstream_token_id=upstream_token_id,+ created_at=now,+ ),+ ttl=3600,+ )+ await proxy._upstream_token_store.put(+ key=upstream_token_id,+ value=UpstreamTokenSet(+ upstream_token_id=upstream_token_id,+ access_token="old-access-token",+ refresh_token="old-refresh-token",+ refresh_token_expires_at=now + 3600,+ expires_at=now - 1,+ token_type="Bearer",+ scope="read",+ client_id=client.client_id,+ created_at=now,+ ),+ ttl=3600,+ )++ return (+ proxy,+ client,+ RefreshToken(+ token=refresh_value,+ client_id=client.client_id,+ scopes=["read"],+ expires_at=int(now) + 3600,+ ),+ )++ async def test_invalid_grant_is_sanitized(self, jwt_verifier):+ proxy, client, refresh_token = await self._make_refresh_context(jwt_verifier)+ upstream_error = OAuthError(+ error="invalid_grant", description="private-upstream-detail"+ )+ oauth_client = AsyncMock()+ oauth_client.refresh_token = AsyncMock(side_effect=upstream_error)++ with (+ patch.object(+ proxy, "_create_upstream_oauth_client", return_value=oauth_client+ ),+ pytest.raises(TokenError) as exc_info,+ ):+ await proxy.exchange_refresh_token(client, refresh_token, ["read"])++ assert exc_info.value.error == "invalid_grant"+ assert exc_info.value.error_description == "Upstream refresh token was rejected"++ async def test_temporary_upstream_error_is_preserved(self, jwt_verifier):+ proxy, client, refresh_token = await self._make_refresh_context(jwt_verifier)+ upstream_error = OAuthError(+ error="temporarily_unavailable", description="private-upstream-detail"+ )+ oauth_client = AsyncMock()+ oauth_client.refresh_token = AsyncMock(side_effect=upstream_error)++ with (+ patch.object(+ proxy, "_create_upstream_oauth_client", return_value=oauth_client+ ),+ pytest.raises(OAuthError) as exc_info,+ ):+ await proxy.exchange_refresh_token(client, refresh_token, ["read"])++ assert exc_info.value is upstream_error++ async def test_unexpected_refresh_error_is_preserved(self, jwt_verifier):+ proxy, client, refresh_token = await self._make_refresh_context(jwt_verifier)+ upstream_error = RuntimeError("private-internal-detail")+ oauth_client = AsyncMock()+ oauth_client.refresh_token = AsyncMock(side_effect=upstream_error)++ with (+ patch.object(+ proxy, "_create_upstream_oauth_client", return_value=oauth_client+ ),+ pytest.raises(RuntimeError) as exc_info,+ ):+ await proxy.exchange_refresh_token(client, refresh_token, ["read"])++ assert exc_info.value is upstream_error++class TestTokenHandlerErrorTransformation:"""Tests for TokenHandler's OAuth 2.1 compliant error transformation."""