Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix(auth): preserve GitHub sessions across transient verification failures (#4881)

sui-ni23c6fbf7a2cb4
diff --git a/fastmcp_slim/fastmcp/server/auth/__init__.py b/fastmcp_slim/fastmcp/server/auth/__init__.py
index 8c1e2631d..2c556c81a 100644
--- a/fastmcp_slim/fastmcp/server/auth/__init__.py
+++ b/fastmcp_slim/fastmcp/server/auth/__init__.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING
from .auth import (
OAuthProvider,
TokenVerifier,
+ TokenVerificationError,
RemoteAuthProvider,
MultiAuth,
AccessToken,
@@ -75,6 +76,7 @@ __all__ = [
"OIDCProxy",
"RemoteAuthProvider",
"StaticTokenVerifier",
+ "TokenVerificationError",
"TokenVerifier",
"require_roles",
"require_scopes",
diff --git a/fastmcp_slim/fastmcp/server/auth/auth.py b/fastmcp_slim/fastmcp/server/auth/auth.py
index 214cd8222..66128ea41 100644
--- a/fastmcp_slim/fastmcp/server/auth/auth.py
+++ b/fastmcp_slim/fastmcp/server/auth/auth.py
@@ -509,6 +509,15 @@ class AuthProvider(TokenVerifierProtocol):
return resource_base_url
+class TokenVerificationError(RuntimeError):
+ """Token validity could not be determined because verification was unavailable.
+
+ Verifiers should raise this for operational failures such as an upstream
+ service outage or transport error. Returning ``None`` remains reserved for
+ credentials that were actually determined to be invalid or unacceptable.
+ """
+
+
class TokenVerifier(AuthProvider):
"""Base class for token verifiers (Resource Servers).
@@ -871,10 +880,11 @@ class MultiAuth(AuthProvider):
async def verify_token(self, token: str) -> AccessToken | None:
"""Verify a token by trying the server, then each verifier in order.
- Each source is tried independently. If a source raises an exception,
- it is logged and treated as a non-match so that remaining sources
- still get a chance to verify the token.
+ Each source is tried independently. Operational verification failures
+ do not prevent later sources from validating the token, but are
+ re-raised if no source ultimately succeeds.
"""
+ verification_error: TokenVerificationError | None = None
for source_id, source in zip(self._source_ids, self._sources, strict=True):
try:
result = await source.verify_token(token)
@@ -902,6 +912,14 @@ class MultiAuth(AuthProvider):
"original_client_id": original_client_id,
}
)
+ except TokenVerificationError as error:
+ if verification_error is None:
+ verification_error = error
+ logger.debug(
+ "Token verification unavailable for %s, trying next source",
+ type(source).__name__,
+ exc_info=True,
+ )
except Exception:
logger.debug(
"Token verification failed for %s, trying next source",
@@ -909,6 +927,9 @@ class MultiAuth(AuthProvider):
exc_info=True,
)
+ if verification_error is not None:
+ raise verification_error
+
return None
def set_mcp_path(self, mcp_path: str | None) -> None:
diff --git a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py
index fbc8a7bab..14ab210ba 100644
--- a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py
+++ b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py
@@ -77,6 +77,7 @@ from fastmcp.server.auth.auth import (
OAuthProvider,
PrivateKeyJWTClientAuthenticator,
TokenHandler,
+ TokenVerificationError,
TokenVerifier,
)
from fastmcp.server.auth.cimd import CIMDClientManager
@@ -2340,6 +2341,8 @@ class OAuthProxy(OAuthProvider, ConsentMixin):
validated = await self._token_validator.verify_token(
verification_token
)
+ except TokenVerificationError:
+ raise
except Exception as e:
logger.debug("Transparent upstream refresh failed: %s", e)
# In a distributed deployment, another worker may have
@@ -2357,6 +2360,8 @@ class OAuthProxy(OAuthProvider, ConsentMixin):
)
if validated:
upstream_token_set = reloaded
+ except TokenVerificationError:
+ raise
except Exception as reload_error:
logger.debug(
"Re-read of upstream token after refresh failure also failed: %s",
@@ -2401,6 +2406,8 @@ class OAuthProxy(OAuthProvider, ConsentMixin):
)
return validated
+ except TokenVerificationError:
+ raise
except Exception as e:
logger.debug("Token swap validation failed: %s", e)
return None
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/github.py b/fastmcp_slim/fastmcp/server/auth/providers/github.py
index b958f274b..5a6b427db 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/github.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/github.py
@@ -28,7 +28,7 @@ import httpx2
from key_value.aio.protocols import AsyncKeyValue
from pydantic import AnyHttpUrl
-from fastmcp.server.auth import TokenVerifier
+from fastmcp.server.auth import TokenVerificationError, TokenVerifier
from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.auth.identity_assertion import IdentityAssertion
from fastmcp.server.auth.oauth_proxy import OAuthProxy
@@ -39,6 +39,35 @@ from fastmcp.utilities.token_cache import TokenCache
logger = get_logger(__name__)
+def _is_transient(response: httpx2.Response) -> bool:
+ """Whether a GitHub API error response is temporary rather than a verdict on the token.
+
+ Server errors and rate limits are temporary. GitHub reports rate limits as
+ 429, or as 403 with exhausted quota, a retry header, or a secondary
+ rate-limit message. Other 4xx responses reject the token.
+ """
+ status = response.status_code
+ if status >= 500 or status == 429:
+ return True
+ if status == 403:
+ headers = response.headers
+ if (
+ headers.get("x-ratelimit-remaining") == "0"
+ or headers.get("retry-after") is not None
+ ):
+ return True
+ try:
+ error = response.json()
+ except ValueError:
+ return False
+ return (
+ isinstance(error, dict)
+ and isinstance(error.get("message"), str)
+ and "secondary rate limit" in error["message"].casefold()
+ )
+ return False
+
+
class GitHubTokenVerifier(TokenVerifier):
"""Token verifier for GitHub OAuth tokens.
@@ -102,7 +131,6 @@ class GitHubTokenVerifier(TokenVerifier):
if self._http_client is not None
else httpx2.AsyncClient(timeout=self.timeout_seconds)
) as client:
- # Get token info from GitHub API
response = await client.get(
"https://api.github.com/user",
headers={
@@ -112,7 +140,7 @@ class GitHubTokenVerifier(TokenVerifier):
},
)
- if response.status_code != 200:
+ if response.status_code != 200 and not _is_transient(response):
logger.debug(
"GitHub token verification failed: %d - %s",
response.status_code,
@@ -120,37 +148,104 @@ class GitHubTokenVerifier(TokenVerifier):
)
return None
- user_data = response.json()
+ if response.status_code != 200:
+ logger.warning(
+ "GitHub token verification unavailable: %d - %s",
+ response.status_code,
+ response.text[:200],
+ )
+ raise TokenVerificationError(
+ "GitHub token verification unavailable: "
+ f"HTTP {response.status_code}"
+ )
- # Get token scopes from GitHub API
- # GitHub includes scopes in the X-OAuth-Scopes header
- scopes_response = await client.get(
- "https://api.github.com/user/repos", # Any authenticated endpoint
- headers={
- "Authorization": f"Bearer {token}",
- "Accept": "application/vnd.github.v3+json",
- "User-Agent": "FastMCP-GitHub-OAuth",
- },
- )
+ try:
+ user_data = response.json()
+ user_id = user_data["id"]
+ except (ValueError, TypeError, KeyError) as e:
+ logger.warning(
+ "GitHub token verification returned invalid user data: %s", e
+ )
+ raise TokenVerificationError(
+ "GitHub token verification returned an invalid user response"
+ ) from e
+
+ # Identity is verified by /user, but that does not establish
+ # which OAuth scopes were granted. If scope discovery is
+ # temporarily unavailable, do not infer scopes; required scopes
+ # must wait for a successful check.
+ scope_discovery_unavailable = False
+ scope_discovery_error: str | None = None
+ try:
+ scopes_response = await client.get(
+ "https://api.github.com/user/repos",
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/vnd.github.v3+json",
+ "User-Agent": "FastMCP-GitHub-OAuth",
+ },
+ )
+ except httpx2.RequestError as e:
+ logger.warning("GitHub scope verification unavailable: %s", e)
+ scope_discovery_unavailable = True
+ scope_discovery_error = "transport error"
+ oauth_scopes_header = ""
+ else:
+ if 500 <= scopes_response.status_code < 600:
+ logger.warning(
+ "GitHub scope verification unavailable: %d - %s",
+ scopes_response.status_code,
+ scopes_response.text[:200],
+ )
+ scope_discovery_unavailable = True
+ scope_discovery_error = f"HTTP {scopes_response.status_code}"
+ oauth_scopes_header = ""
+ elif _is_transient(scopes_response):
+ logger.warning(
+ "GitHub scope verification unavailable: %d - %s",
+ scopes_response.status_code,
+ scopes_response.text[:200],
+ )
+ raise TokenVerificationError(
+ "GitHub scope verification unavailable: "
+ f"HTTP {scopes_response.status_code}"
+ )
+ elif scopes_response.status_code != 200:
+ logger.debug(
+ "GitHub scope verification rejected credentials: %d - %s",
+ scopes_response.status_code,
+ scopes_response.text[:200],
+ )
+ return None
+ else:
+ oauth_scopes_header = scopes_response.headers.get(
+ "x-oauth-scopes", ""
+ )
+ # GitHub App user tokens carry no X-OAuth-Scopes header.
+ # A successful /user call already proves the "user"
+ # grant those tokens act with.
+ if not oauth_scopes_header.strip():
+ oauth_scopes_header = "user"
- # Extract scopes from X-OAuth-Scopes header if available
- scopes_verified = scopes_response.status_code == 200
- oauth_scopes_header = scopes_response.headers.get("x-oauth-scopes", "")
token_scopes = [
scope.strip()
for scope in oauth_scopes_header.split(",")
if scope.strip()
]
-
- # If no scopes in header, assume basic scopes based on successful user API call
- if not token_scopes:
- token_scopes = ["user"] # Basic scope if we can access user info
-
- # Check required scopes
if self.required_scopes:
token_scopes_set = set(token_scopes)
required_scopes_set = set(self.required_scopes)
if not required_scopes_set.issubset(token_scopes_set):
+ if scope_discovery_unavailable:
+ detail = (
+ f" ({scope_discovery_error})"
+ if scope_discovery_error is not None
+ else ""
+ )
+ raise TokenVerificationError(
+ "GitHub scope verification unavailable"
+ f"{detail}; required scopes could not be verified"
+ )
logger.debug(
"GitHub token missing required scopes. Has %d, needs %d",
len(token_scopes_set),
@@ -158,15 +253,14 @@ class GitHubTokenVerifier(TokenVerifier):
)
return None
- # Create AccessToken with GitHub user info
result = AccessToken(
token=token,
- client_id=str(user_data.get("id", "unknown")), # Use GitHub user ID
+ client_id=str(user_id),
scopes=token_scopes,
- expires_at=None, # GitHub tokens don't typically expire
- subject=str(user_data["id"]),
+ expires_at=None,
+ subject=str(user_id),
claims={
- "sub": str(user_data["id"]),
+ "sub": str(user_id),
"login": user_data.get("login"),
"name": user_data.get("name"),
"email": user_data.get("email"),
@@ -174,13 +268,16 @@ class GitHubTokenVerifier(TokenVerifier):
"github_user_data": user_data,
},
)
- if scopes_verified:
- self._cache.set(token, result)
+ self._cache.set(token, result)
return result
+ except TokenVerificationError:
+ raise
except httpx2.RequestError as e:
- logger.debug("Failed to verify GitHub token: %s", e)
- return None
+ logger.warning("GitHub token verification unavailable: %s", e)
+ raise TokenVerificationError(
+ "GitHub token verification unavailable due to a transport error"
+ ) from e
except Exception as e:
logger.debug("GitHub token verification error: %s", e)
return None
@@ -291,12 +388,10 @@ class GitHubProvider(OAuthProxy):
identity_assertion: Optional SEP-990 ID-JAG configuration for
identity-bound token exchange. Disabled by default.
"""
- # Parse scopes if provided as string
required_scopes_final = (
parse_scopes(required_scopes) if required_scopes is not None else ["user"]
)
- # Create GitHub token verifier
token_verifier = GitHubTokenVerifier(
required_scopes=required_scopes_final,
timeout_seconds=timeout_seconds,
@@ -305,7 +400,6 @@ class GitHubProvider(OAuthProxy):
http_client=http_client,
)
- # Initialize OAuth proxy with GitHub endpoints
super().__init__(
upstream_authorization_endpoint="https://github.com/login/oauth/authorize",
upstream_token_endpoint="https://github.com/login/oauth/access_token",
@@ -315,7 +409,7 @@ class GitHubProvider(OAuthProxy):
base_url=base_url,
resource_base_url=resource_base_url,
redirect_path=redirect_path,
- issuer_url=issuer_url or base_url, # Default to base_url if not specified
+ issuer_url=issuer_url or base_url,
allowed_client_redirect_uris=allowed_client_redirect_uris,
client_storage=client_storage,
jwt_signing_key=jwt_signing_key,
diff --git a/tests/server/auth/providers/test_github.py b/tests/server/auth/providers/test_github.py
index 29c2f7ba2..2d5734a3f 100644
--- a/tests/server/auth/providers/test_github.py
+++ b/tests/server/auth/providers/test_github.py
@@ -135,6 +135,7 @@ class TestGitHubTokenVerifier:
# Mock successful scopes API response
scopes_response = MagicMock()
+ scopes_response.status_code = 200
scopes_response.headers = {"x-oauth-scopes": "user,repo"}
# Set up the mock client to return our responses
@@ -278,8 +279,8 @@ class TestGitHubTokenVerifierCaching:
assert result2 is not None
assert result2.claims["login"] == "testuser"
- async def test_scope_failure_skips_cache(self):
- """Token verified with fallback scopes (scope API failed) should not be cached."""
+ async def test_scope_failure_keeps_identity_without_inventing_scopes(self):
+ """A scope-endpoint outage may verify identity, but must not invent scopes."""
verifier = GitHubTokenVerifier(cache_ttl_seconds=300)
mock_client = AsyncMock()
@@ -296,6 +297,7 @@ class TestGitHubTokenVerifierCaching:
scopes_response = MagicMock()
scopes_response.status_code = 500
+ scopes_response.text = "simulated outage"
scopes_response.headers = {}
with patch(
@@ -304,10 +306,16 @@ class TestGitHubTokenVerifierCaching:
mock_cls.return_value.__aenter__.return_value = mock_client
mock_client.get.side_effect = [user_response, scopes_response]
- result = await verifier.verify_token("tok-1")
- assert result is not None
- # Should NOT be cached because scope response was not 200
- assert not verifier._cache.enabled or len(verifier._cache._entries) == 0
+ first = await verifier.verify_token("tok-1")
+ second = await verifier.verify_token("tok-1")
+
+ assert first is not None
+ assert first.scopes == []
+ assert second is not None
+ assert second.scopes == []
+ assert second.client_id == first.client_id
+ assert second is not first
+ assert mock_client.get.call_count == 2
def test_provider_passes_cache_params(self, memory_storage: MemoryStore):
provider = GitHubProvider(
diff --git a/tests/server/auth/providers/test_github_transient_failures.py b/tests/server/auth/providers/test_github_transient_failures.py
new file mode 100644
index 000000000..d59973e05
--- /dev/null
+++ b/tests/server/auth/providers/test_github_transient_failures.py
@@ -0,0 +1,410 @@
+"""Regression coverage for operational GitHub token verification failures."""
+
+import time
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx2
+import pytest
+from key_value.aio.stores.memory import MemoryStore
+
+from fastmcp.server.auth import TokenVerificationError, TokenVerifier
+from fastmcp.server.auth.oauth_proxy import OAuthProxy
+from fastmcp.server.auth.oauth_proxy.models import JTIMapping, UpstreamTokenSet
+from fastmcp.server.auth.providers.github import GitHubProvider, GitHubTokenVerifier
+
+
+def _response(
+ status_code: int,
+ text: str = "simulated",
+ *,
+ headers: dict[str, str] | None = None,
+ json_data: dict | None = None,
+) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.text = text
+ response.headers = headers or {}
+ response.json.return_value = json_data or {}
+ return response
+
+
+def _github_user_response() -> MagicMock:
+ return _response(
+ 200,
+ json_data={
+ "id": 12345,
+ "login": "testuser",
+ "name": "Test User",
+ "email": "[email protected]",
+ "avatar_url": "https://github.com/testuser.png",
+ },
+ )
+
+
+async def _store_proxy_access_token(
+ proxy: OAuthProxy,
+ *,
+ upstream_scope: str,
+) -> str:
+ proxy.set_mcp_path("/mcp")
+ now = time.time()
+ upstream_token_id = "upstream-token-id"
+ jti = "access-jti"
+ await proxy._upstream_token_store.put(
+ key=upstream_token_id,
+ value=UpstreamTokenSet(
+ upstream_token_id=upstream_token_id,
+ access_token="upstream-access-token",
+ refresh_token=None,
+ refresh_token_expires_at=None,
+ expires_at=now + 3600,
+ token_type="Bearer",
+ scope=upstream_scope,
+ client_id="mcp-client",
+ created_at=now,
+ raw_token_data={"access_token": "upstream-access-token"},
+ ),
+ ttl=3600,
+ )
+ await proxy._jti_mapping_store.put(
+ key=jti,
+ value=JTIMapping(
+ jti=jti,
+ upstream_token_id=upstream_token_id,
+ created_at=now,
+ ),
+ ttl=3600,
+ )
+ return proxy.jwt_issuer.issue_access_token(
+ client_id="mcp-client",
+ scopes=upstream_scope.split(),
+ jti=jti,
+ expires_in=3600,
+ )
+
+
+_RATE_LIMITED = [
+ (403, {"x-ratelimit-remaining": "0"}),
+ (403, {"retry-after": "60"}),
+ (429, {}),
+]
+
+
+async def test_github_401_is_still_an_invalid_token():
+ client = AsyncMock()
+ client.get.return_value = _response(401, "Bad credentials")
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ assert await verifier.verify_token("bad-token") is None
+
+
[email protected]("status_code, headers", [*_RATE_LIMITED, (500, {}), (503, {})])
+async def test_github_operational_http_failure_raises_typed_error(status_code, headers):
+ client = AsyncMock()
+ client.get.return_value = _response(status_code, headers=headers)
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ with pytest.raises(TokenVerificationError, match=str(status_code)):
+ await verifier.verify_token("still-valid-token")
+
+
[email protected]("headers", [{}, {"x-ratelimit-remaining": "42"}])
+async def test_secondary_rate_limit_message_is_operational_error(
+ headers: dict[str, str],
+):
+ client = AsyncMock()
+ client.get.return_value = _response(
+ 403,
+ headers=headers,
+ json_data={"message": "You have exceeded a secondary rate limit."},
+ )
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ with pytest.raises(TokenVerificationError, match="HTTP 403"):
+ await verifier.verify_token("still-valid-token")
+
+
+async def test_github_transport_failure_raises_typed_error():
+ client = AsyncMock()
+ client.get.side_effect = httpx2.ConnectError(
+ "simulated transport failure",
+ request=httpx2.Request("GET", "https://api.github.com/user"),
+ )
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ with pytest.raises(TokenVerificationError, match="transport"):
+ await verifier.verify_token("still-valid-token")
+
+
+async def test_github_malformed_user_json_raises_typed_error():
+ client = AsyncMock()
+ response = _response(200)
+ response.json.side_effect = ValueError("malformed json")
+ client.get.return_value = response
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ with pytest.raises(TokenVerificationError, match="invalid user response"):
+ await verifier.verify_token("still-valid-token")
+
+
+async def test_github_missing_user_id_raises_typed_error():
+ client = AsyncMock()
+ client.get.return_value = _response(200, json_data={"login": "testuser"})
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ with pytest.raises(TokenVerificationError, match="invalid user response"):
+ await verifier.verify_token("still-valid-token")
+
+
+async def test_non_rate_limited_403_message_still_rejects_token():
+ client = AsyncMock()
+ client.get.return_value = _response(
+ 403,
+ headers={"x-ratelimit-remaining": "42"},
+ json_data={"message": "Resource not accessible by integration"},
+ )
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ assert await verifier.verify_token("rejected-token") is None
+
+
[email protected]("status_code", [403, 404])
+async def test_github_permanent_client_error_is_an_invalid_token(status_code):
+ """A forbidden or missing user is a final answer, so the client re-authenticates."""
+ client = AsyncMock()
+ client.get.return_value = _response(status_code)
+ verifier = GitHubTokenVerifier(http_client=client)
+
+ assert await verifier.verify_token("rejected-token") is None
+
+
[email protected]("status_code, headers", _RATE_LIMITED)
+async def test_scope_rate_limit_raises_typed_error(status_code, headers):
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ _response(status_code, headers=headers),
+ ]
+ verifier = GitHubTokenVerifier(required_scopes=["user"], http_client=client)
+
+ with pytest.raises(TokenVerificationError, match=str(status_code)):
+ await verifier.verify_token("still-valid-token")
+
+
+async def test_scope_secondary_rate_limit_message_is_operational_error():
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ _response(
+ 403,
+ headers={"x-ratelimit-remaining": "42"},
+ json_data={"message": "You have exceeded a secondary rate limit."},
+ ),
+ ]
+ verifier = GitHubTokenVerifier(required_scopes=["user"], http_client=client)
+
+ with pytest.raises(TokenVerificationError, match="HTTP 403"):
+ await verifier.verify_token("still-valid-token")
+
+
[email protected]("status_code", [500, 503])
+async def test_scope_server_failure_does_not_grant_required_user_scope_and_recovers(
+ status_code,
+):
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ _response(status_code),
+ _github_user_response(),
+ _response(200, headers={"x-oauth-scopes": "user"}),
+ ]
+ verifier = GitHubTokenVerifier(
+ required_scopes=["user"],
+ cache_ttl_seconds=300,
+ http_client=client,
+ )
+
+ with pytest.raises(TokenVerificationError, match="scope verification unavailable"):
+ await verifier.verify_token("still-valid-token")
+
+ assert len(verifier._cache._entries) == 0
+
+ recovered = await verifier.verify_token("still-valid-token")
+ assert recovered is not None
+ assert recovered.scopes == ["user"]
+ assert client.get.call_count == 4
+
+
+async def test_scope_transport_failure_does_not_grant_user_scope_and_recovers():
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ httpx2.ConnectError(
+ "simulated scope transport failure",
+ request=httpx2.Request("GET", "https://api.github.com/user/repos"),
+ ),
+ _github_user_response(),
+ _response(200, headers={"x-oauth-scopes": "user"}),
+ ]
+ verifier = GitHubTokenVerifier(
+ required_scopes=["user"],
+ cache_ttl_seconds=300,
+ http_client=client,
+ )
+
+ with pytest.raises(TokenVerificationError, match="scope verification unavailable"):
+ await verifier.verify_token("still-valid-token")
+
+ assert len(verifier._cache._entries) == 0
+
+ recovered = await verifier.verify_token("still-valid-token")
+ assert recovered is not None
+ assert recovered.scopes == ["user"]
+ assert client.get.call_count == 4
+
+
+async def test_scope_401_is_still_an_invalid_token():
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ _response(401, "Bad credentials"),
+ ]
+ verifier = GitHubTokenVerifier(required_scopes=["user"], http_client=client)
+
+ assert await verifier.verify_token("revoked-token") is None
+
+
[email protected]("status_code", [403, 404])
+async def test_scope_permanent_client_error_is_an_invalid_token(status_code):
+ client = AsyncMock()
+ client.get.side_effect = [_github_user_response(), _response(status_code)]
+ verifier = GitHubTokenVerifier(required_scopes=["user"], http_client=client)
+
+ assert await verifier.verify_token("rejected-token") is None
+
+
+async def test_github_app_token_without_scope_header_has_user_scope():
+ """GitHub App user tokens send no X-OAuth-Scopes; the default required scope still passes."""
+ client = AsyncMock()
+ client.get.side_effect = [_github_user_response(), _response(200, headers={})]
+ verifier = GitHubTokenVerifier(required_scopes=["user"], http_client=client)
+
+ result = await verifier.verify_token("github-app-user-token")
+
+ assert result is not None
+ assert result.scopes == ["user"]
+ assert result.subject == "12345"
+
+
+async def test_successful_scope_verification_is_cached():
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ _response(200, headers={"x-oauth-scopes": "user"}),
+ ]
+ verifier = GitHubTokenVerifier(
+ required_scopes=["user"],
+ cache_ttl_seconds=300,
+ http_client=client,
+ )
+
+ first = await verifier.verify_token("valid-token")
+ second = await verifier.verify_token("valid-token")
+
+ assert first is not None
+ assert first.scopes == ["user"]
+ assert second is not None
+ assert second.scopes == ["user"]
+ assert second.client_id == first.client_id
+ assert second is not first
+ assert client.get.call_count == 2
+
+
+class UnavailableVerifier(TokenVerifier):
+ async def verify_token(self, token: str):
+ raise TokenVerificationError("upstream verifier unavailable")
+
+
+async def test_oauth_proxy_propagates_operational_verification_error():
+ proxy = OAuthProxy(
+ upstream_authorization_endpoint="https://idp.example.com/authorize",
+ upstream_token_endpoint="https://idp.example.com/token",
+ upstream_client_id="upstream-client",
+ upstream_client_secret="upstream-secret",
+ token_verifier=UnavailableVerifier(),
+ base_url="https://proxy.example.com",
+ jwt_signing_key="test-signing-key",
+ client_storage=MemoryStore(),
+ )
+ fastmcp_token = await _store_proxy_access_token(proxy, upstream_scope="user")
+
+ with pytest.raises(TokenVerificationError, match="upstream verifier unavailable"):
+ await proxy.load_access_token(fastmcp_token)
+
+
+async def test_github_provider_scope_outage_propagates_operational_error():
+ client = AsyncMock()
+ client.get.side_effect = [_github_user_response(), _response(503)]
+ provider = GitHubProvider(
+ client_id="github-client",
+ client_secret="github-secret",
+ base_url="https://proxy.example.com",
+ required_scopes=["repo"],
+ http_client=client,
+ jwt_signing_key="test-signing-key",
+ client_storage=MemoryStore(),
+ )
+ fastmcp_token = await _store_proxy_access_token(provider, upstream_scope="repo")
+
+ with pytest.raises(TokenVerificationError, match="503"):
+ await provider.load_access_token(fastmcp_token)
+
+
+async def test_github_provider_secondary_rate_limit_recovers():
+ client = AsyncMock()
+ client.get.side_effect = [
+ _response(
+ 403,
+ headers={"x-ratelimit-remaining": "42"},
+ json_data={"message": "You have exceeded a secondary rate limit."},
+ ),
+ _github_user_response(),
+ _response(200, headers={"x-oauth-scopes": "user"}),
+ ]
+ provider = GitHubProvider(
+ client_id="github-client",
+ client_secret="github-secret",
+ base_url="https://proxy.example.com",
+ required_scopes=["user"],
+ http_client=client,
+ jwt_signing_key="test-signing-key",
+ client_storage=MemoryStore(),
+ )
+ fastmcp_token = await _store_proxy_access_token(provider, upstream_scope="user")
+
+ with pytest.raises(TokenVerificationError, match="HTTP 403"):
+ await provider.load_access_token(fastmcp_token)
+
+ recovered = await provider.load_access_token(fastmcp_token)
+ assert recovered is not None
+ assert client.get.call_count == 3
+
+
+async def test_github_provider_scope_401_stays_invalid():
+ client = AsyncMock()
+ client.get.side_effect = [
+ _github_user_response(),
+ _response(401, "Bad credentials"),
+ ]
+ provider = GitHubProvider(
+ client_id="github-client",
+ client_secret="github-secret",
+ base_url="https://proxy.example.com",
+ required_scopes=["repo"],
+ http_client=client,
+ jwt_signing_key="test-signing-key",
+ client_storage=MemoryStore(),
+ )
+ fastmcp_token = await _store_proxy_access_token(provider, upstream_scope="repo")
+
+ assert await provider.load_access_token(fastmcp_token) is None
diff --git a/tests/server/auth/test_multi_auth.py b/tests/server/auth/test_multi_auth.py
index ab6a7fa17..d7b646bad 100644
--- a/tests/server/auth/test_multi_auth.py
+++ b/tests/server/auth/test_multi_auth.py
@@ -4,7 +4,12 @@ from key_value.aio.stores.memory import MemoryStore
from pydantic import AnyHttpUrl
from fastmcp import FastMCP
-from fastmcp.server.auth import MultiAuth, RemoteAuthProvider, TokenVerifier
+from fastmcp.server.auth import (
+ MultiAuth,
+ RemoteAuthProvider,
+ TokenVerificationError,
+ TokenVerifier,
+)
from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.providers.azure import AzureJWTVerifier
@@ -18,6 +23,13 @@ class RaisingVerifier(TokenVerifier):
raise RuntimeError("simulated failure")
+class UnavailableVerifier(TokenVerifier):
+ """A verifier whose upstream dependency is temporarily unavailable."""
+
+ async def verify_token(self, token: str) -> AccessToken | None:
+ raise TokenVerificationError("simulated verifier unavailable")
+
+
class UnderScopedVerifier(TokenVerifier):
"""A verifier that returns a token missing its required scopes."""
@@ -339,6 +351,28 @@ class TestMultiAuthVerifyToken:
assert result is not None
assert result.original_client_id == "fallback"
+ async def test_operational_failure_raises_without_successful_fallback(self):
+ """Operational failure is re-raised if no later source validates."""
+ rejecting = StaticTokenVerifier(tokens={})
+ auth = MultiAuth(verifiers=[UnavailableVerifier(), rejecting])
+
+ with pytest.raises(
+ TokenVerificationError, match="simulated verifier unavailable"
+ ):
+ await auth.verify_token("anything")
+
+ async def test_operational_failure_allows_successful_fallback(self):
+ """A later successful verifier still wins after an operational failure."""
+ good = StaticTokenVerifier(
+ tokens={"valid": {"client_id": "fallback", "scopes": []}}
+ )
+ auth = MultiAuth(verifiers=[UnavailableVerifier(), good])
+
+ result = await auth.verify_token("valid")
+
+ assert result is not None
+ assert result.original_client_id == "fallback"
+
async def test_all_raising_returns_none(self):
"""If every source raises, verify_token returns None."""
auth = MultiAuth(