π The fast, Pythonic way to build MCP servers and clients.
Add in-memory caching for token introspection results (#3298)
Jeremiah Lowin8a4c9b33e1c5
diff --git a/src/fastmcp/server/auth/providers/introspection.py b/src/fastmcp/server/auth/providers/introspection.pyindex b6f03a105..09e20abfd 100644--- a/src/fastmcp/server/auth/providers/introspection.py+++ b/src/fastmcp/server/auth/providers/introspection.py@@ -25,7 +25,9 @@ from __future__ import annotationsimport base64import contextlib+import hashlibimport time+from dataclasses import dataclassfrom typing import Any, Literal, get_argsimport httpx@@ -37,6 +39,15 @@ from fastmcp.utilities.logging import get_loggerlogger = get_logger(__name__)++@dataclass+class _IntrospectionCacheEntry:+ """Cached introspection result with expiration."""++ result: AccessToken+ expires_at: float++ClientAuthMethod = Literal["client_secret_basic", "client_secret_post"]@@ -60,6 +71,10 @@ class IntrospectionTokenVerifier(TokenVerifier):- Your tokens require real-time revocation checking- Your authorization server supports RFC 7662 introspection+ Caching is disabled by default to preserve real-time revocation semantics.+ Set ``cache_ttl_seconds`` to enable caching and reduce load on the+ introspection endpoint (e.g., ``cache_ttl_seconds=300`` for 5 minutes).+Example:```pythonverifier = IntrospectionTokenVerifier(@@ -71,6 +86,9 @@ class IntrospectionTokenVerifier(TokenVerifier):```"""+ # Default cache settings+ DEFAULT_MAX_CACHE_SIZE = 10000+def __init__(self,*,@@ -81,6 +99,8 @@ class IntrospectionTokenVerifier(TokenVerifier):timeout_seconds: int = 10,required_scopes: list[str] | None = None,base_url: AnyHttpUrl | str | None = None,+ cache_ttl_seconds: int | None = None,+ max_cache_size: int | None = None,http_client: httpx.AsyncClient | None = None,):"""@@ -95,6 +115,12 @@ class IntrospectionTokenVerifier(TokenVerifier):timeout_seconds: HTTP request timeout in seconds (default: 10)required_scopes: Required scopes for all tokens (optional)base_url: Base URL for TokenVerifier protocol+ cache_ttl_seconds: How long to cache introspection results in seconds.+ Caching is disabled by default (None) to preserve real-time+ revocation semantics. Set to a positive integer to enable caching+ (e.g., 300 for 5 minutes).+ max_cache_size: Maximum number of tokens to cache when caching is+ enabled. Default: 10000.http_client: Optional httpx.AsyncClient for connection pooling. When provided,the client is reused across calls and the caller is responsible for itslifecycle. When None (default), a fresh client is created per call.@@ -128,6 +154,98 @@ class IntrospectionTokenVerifier(TokenVerifier):self._http_client = http_clientself.logger = get_logger(__name__)+ # Cache configuration (None or 0 = disabled)+ self._cache_ttl = cache_ttl_seconds or 0+ self._max_cache_size = (+ max_cache_size+ if max_cache_size is not None+ else self.DEFAULT_MAX_CACHE_SIZE+ )+ self._cache: dict[str, _IntrospectionCacheEntry] = {}+ self._last_cleanup = time.monotonic()+ self._cleanup_interval = 60 # Cleanup every 60 seconds++ def _hash_token(self, token: str) -> str:+ """Hash token for use as cache key.++ Using SHA-256 for memory efficiency (fixed 64-char hex digest+ regardless of token length).+ """+ return hashlib.sha256(token.encode("utf-8")).hexdigest()++ def _cleanup_expired_cache(self) -> None:+ """Remove expired entries from cache."""+ now = time.time()+ expired = [key for key, entry in self._cache.items() if entry.expires_at < now]+ for key in expired:+ del self._cache[key]+ if expired:+ self.logger.debug("Cleaned up %d expired cache entries", len(expired))++ def _maybe_cleanup(self) -> None:+ """Periodically cleanup expired entries to prevent unbounded growth."""+ now = time.monotonic()+ if now - self._last_cleanup > self._cleanup_interval:+ self._cleanup_expired_cache()+ self._last_cleanup = now++ def _get_cached(self, token: str) -> tuple[bool, AccessToken | None]:+ """Get cached introspection result.++ Returns:+ Tuple of (is_cached, result):+ - (True, AccessToken) if cached valid token+ - (False, None) if not in cache or expired+ """+ if self._cache_ttl <= 0 or self._max_cache_size <= 0:+ return (False, None) # Caching disabled++ cache_key = self._hash_token(token)+ entry = self._cache.get(cache_key)++ if entry is None:+ return (False, None) # Not in cache++ if entry.expires_at < time.time():+ del self._cache[cache_key]+ return (False, None) # Expired++ # Return a copy to prevent mutations from affecting cached value+ return (True, entry.result.model_copy(deep=True))++ def _set_cached(self, token: str, result: AccessToken) -> None:+ """Cache a valid introspection result with TTL.++ Only successful validations are cached. Failures (inactive, expired,+ missing scopes, errors) are never cached to avoid sticky false negatives.+ """+ if self._cache_ttl <= 0 or self._max_cache_size <= 0:+ return # Caching disabled++ # Periodic cleanup+ self._maybe_cleanup()++ # Check cache size limit+ if len(self._cache) >= self._max_cache_size:+ self._cleanup_expired_cache()+ # If still at limit after cleanup, evict oldest entry+ if len(self._cache) >= self._max_cache_size:+ oldest_key = next(iter(self._cache))+ del self._cache[oldest_key]++ cache_key = self._hash_token(token)++ # Use token's expiration if available and sooner than TTL+ expires_at = time.time() + self._cache_ttl+ if result.expires_at:+ expires_at = min(expires_at, float(result.expires_at))++ # Store a deep copy to prevent mutations from affecting cached value+ self._cache[cache_key] = _IntrospectionCacheEntry(+ result=result.model_copy(deep=True),+ expires_at=expires_at,+ )+def _create_basic_auth_header(self) -> str:"""Create HTTP Basic Auth header value from client credentials."""credentials = f"{self.client_id}:{self.client_secret}"@@ -165,12 +283,21 @@ class IntrospectionTokenVerifier(TokenVerifier):authenticated using the configured client authentication method (client_secret_basicor client_secret_post).+ Results are cached in-memory to reduce load on the introspection endpoint.+ Cache TTL and size are configurable via constructor parameters.+Args:token: The opaque token string to validateReturns:AccessToken object if valid and active, None if invalid, inactive, or expired"""+ # Check cache first+ is_cached, cached_result = self._get_cached(token)+ if is_cached:+ self.logger.debug("Token introspection cache hit")+ return cached_result+try:async with (contextlib.nullcontext(self._http_client)@@ -203,7 +330,7 @@ class IntrospectionTokenVerifier(TokenVerifier):headers=headers,)- # Check for HTTP errors+ # Check for HTTP errors - don't cache HTTP errors (may be transient)if response.status_code != 200:self.logger.debug("Token introspection failed: HTTP %d - %s",@@ -215,6 +342,8 @@ class IntrospectionTokenVerifier(TokenVerifier):introspection_data = response.json()# Check if token is active (required field per RFC 7662)+ # Don't cache inactive tokens - they may become valid later+ # (e.g., tokens with future nbf, or propagation delays)if not introspection_data.get("active", False):self.logger.debug("Token introspection returned active=false")return None@@ -239,6 +368,7 @@ class IntrospectionTokenVerifier(TokenVerifier):scopes = self._extract_scopes(introspection_data)# Check required scopes+ # Don't cache scope failures - permissions may be updated dynamicallyif self.required_scopes:token_scopes = set(scopes)required_scopes = set(self.required_scopes)@@ -251,13 +381,15 @@ class IntrospectionTokenVerifier(TokenVerifier):return None# Create AccessToken with introspection response data- return AccessToken(+ result = AccessToken(token=token,client_id=str(client_id),scopes=scopes,expires_at=int(exp) if exp else None,claims=introspection_data, # Store full response for extensibility)+ self._set_cached(token, result)+ return resultexcept httpx.TimeoutException:self.logger.debug(diff --git a/tests/server/auth/providers/test_introspection.py b/tests/server/auth/providers/test_introspection.pyindex 901412eb9..793570987 100644--- a/tests/server/auth/providers/test_introspection.py+++ b/tests/server/auth/providers/test_introspection.py@@ -523,6 +523,438 @@ class TestIntrospectionTokenVerifier:assert "client_secret=" not in body+class TestIntrospectionCaching:+ """Test in-memory caching for token introspection."""++ @pytest.fixture+ def verifier_with_cache(self) -> IntrospectionTokenVerifier:+ """Create verifier with caching enabled."""+ return IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=300, # 5 minutes+ max_cache_size=100,+ )++ @pytest.fixture+ def verifier_no_cache(self) -> IntrospectionTokenVerifier:+ """Create verifier with caching disabled."""+ return IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=0, # Disabled+ )++ def test_default_cache_settings(self):+ """Test that caching is disabled by default."""+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ )+ assert verifier._cache_ttl == 0 # Disabled by default+ assert verifier._max_cache_size == 10000++ def test_custom_cache_settings(self):+ """Test that cache settings can be customized."""+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=60,+ max_cache_size=500,+ )+ assert verifier._cache_ttl == 60+ assert verifier._max_cache_size == 500++ def test_cache_disabled_with_zero_ttl(self):+ """Test that cache is disabled when TTL is 0 or None."""+ # Explicit 0+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=0,+ )+ assert verifier._cache_ttl == 0++ # Explicit None (same as default)+ verifier2 = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=None,+ )+ assert verifier2._cache_ttl == 0++ async def test_cache_disabled_with_zero_or_negative_max_size(+ self, httpx_mock: HTTPXMock+ ):+ """Test that cache is disabled when max_cache_size is 0 or negative."""+ # Add two responses for the two verifiers+ for _ in range(2):+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read",+ },+ )++ # Zero max_cache_size should disable caching (not raise StopIteration)+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=300,+ max_cache_size=0,+ )+ result = await verifier.verify_token("test-token")+ assert result is not None+ assert result.client_id == "user-123"++ # Negative max_cache_size should also disable caching+ verifier2 = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=300,+ max_cache_size=-1,+ )+ result2 = await verifier2.verify_token("test-token")+ assert result2 is not None++ async def test_cache_hit_returns_cached_result(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that cached valid tokens are returned without introspection call."""+ # First call - introspection endpoint called+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read write",+ "exp": int(time.time()) + 3600,+ },+ )++ # First verification+ result1 = await verifier_with_cache.verify_token("test-token")+ assert result1 is not None+ assert result1.client_id == "user-123"++ # Verify one request was made+ requests = httpx_mock.get_requests()+ assert len(requests) == 1++ # Second verification - should use cache, no new request+ result2 = await verifier_with_cache.verify_token("test-token")+ assert result2 is not None+ assert result2.client_id == "user-123"++ # Still only one request+ requests = httpx_mock.get_requests()+ assert len(requests) == 1++ async def test_cache_returns_defensive_copy(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that cached tokens are defensive copies (mutations don't leak)."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read write",+ "exp": int(time.time()) + 3600,+ "custom_claim": "original",+ },+ )++ # First verification+ result1 = await verifier_with_cache.verify_token("test-token")+ assert result1 is not None+ assert result1.claims["custom_claim"] == "original"++ # Mutate the result (simulating request-path code adding derived claims)+ result1.claims["custom_claim"] = "mutated"+ result1.claims["new_claim"] = "injected"+ result1.scopes.append("admin")++ # Second verification - should get clean copy, not mutated one+ result2 = await verifier_with_cache.verify_token("test-token")+ assert result2 is not None+ assert result2.claims["custom_claim"] == "original"+ assert "new_claim" not in result2.claims+ assert "admin" not in result2.scopes++ # Verify they are different object instances+ assert result1 is not result2++ async def test_inactive_tokens_not_cached(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that inactive tokens are NOT cached (may become valid later)."""+ # Add two responses - inactive tokens should trigger re-introspection+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": False},+ )+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": False},+ )++ # First verification+ result1 = await verifier_with_cache.verify_token("inactive-token")+ assert result1 is None++ # Verify one request was made+ requests = httpx_mock.get_requests()+ assert len(requests) == 1++ # Second verification - should NOT use cache, makes another request+ result2 = await verifier_with_cache.verify_token("inactive-token")+ assert result2 is None++ # Two requests made (inactive tokens not cached)+ requests = httpx_mock.get_requests()+ assert len(requests) == 2++ async def test_cache_disabled_makes_every_call(+ self, verifier_no_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that with caching disabled, every call makes a request."""+ # Add multiple responses for the same token+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )++ # First call+ await verifier_no_cache.verify_token("test-token")++ # Second call - should also make a request+ await verifier_no_cache.verify_token("test-token")++ # Two requests were made+ requests = httpx_mock.get_requests()+ assert len(requests) == 2++ async def test_different_tokens_are_cached_separately(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that different tokens have separate cache entries."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-1"},+ )+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-2"},+ )++ # Verify two different tokens+ result1 = await verifier_with_cache.verify_token("token-1")+ result2 = await verifier_with_cache.verify_token("token-2")++ assert result1 is not None+ assert result1.client_id == "user-1"+ assert result2 is not None+ assert result2.client_id == "user-2"++ # Two requests were made+ requests = httpx_mock.get_requests()+ assert len(requests) == 2++ # Verify both again - no new requests+ await verifier_with_cache.verify_token("token-1")+ await verifier_with_cache.verify_token("token-2")++ requests = httpx_mock.get_requests()+ assert len(requests) == 2++ async def test_http_errors_are_not_cached(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that HTTP errors are not cached (transient failures)."""+ # First call - HTTP error+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ status_code=500,+ text="Internal Server Error",+ )+ # Second call - success+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )++ # First verification - fails+ result1 = await verifier_with_cache.verify_token("test-token")+ assert result1 is None++ # Second verification - should retry since error wasn't cached+ result2 = await verifier_with_cache.verify_token("test-token")+ assert result2 is not None+ assert result2.client_id == "user-123"++ # Two requests were made+ requests = httpx_mock.get_requests()+ assert len(requests) == 2++ async def test_timeout_errors_are_not_cached(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that timeout errors are not cached (transient failures)."""+ from httpx import TimeoutException++ # First call - timeout+ httpx_mock.add_exception(+ TimeoutException("Request timed out"),+ url="https://auth.example.com/oauth/introspect",+ )+ # Second call - success+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )++ # First verification - times out+ result1 = await verifier_with_cache.verify_token("test-token")+ assert result1 is None++ # Second verification - should retry since timeout wasn't cached+ result2 = await verifier_with_cache.verify_token("test-token")+ assert result2 is not None++ # Two requests were made+ requests = httpx_mock.get_requests()+ assert len(requests) == 2++ def test_token_hashing(self, verifier_with_cache: IntrospectionTokenVerifier):+ """Test that tokens are hashed consistently."""+ hash1 = verifier_with_cache._hash_token("test-token")+ hash2 = verifier_with_cache._hash_token("test-token")+ hash3 = verifier_with_cache._hash_token("different-token")++ # Same token produces same hash+ assert hash1 == hash2+ # Different tokens produce different hashes+ assert hash1 != hash3+ # Hash is a hex string (SHA-256 = 64 chars)+ assert len(hash1) == 64++ async def test_cache_respects_token_expiration(+ self, verifier_with_cache: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that cache respects token's exp claim for TTL."""+ # Token expiring in 60 seconds (shorter than cache TTL of 300)+ short_exp = int(time.time()) + 60++ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "exp": short_exp,+ },+ )++ await verifier_with_cache.verify_token("test-token")++ # Check that cache entry uses the shorter expiration+ cache_key = verifier_with_cache._hash_token("test-token")+ entry = verifier_with_cache._cache[cache_key]+ # Cache expiration should be at or before token expiration+ assert entry.expires_at <= short_exp++ async def test_expired_cache_entry_triggers_new_introspection(+ self, httpx_mock: HTTPXMock+ ):+ """Test that expired cache entries are evicted and a new call is made."""+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=1, # 1 second TTL+ )++ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )++ # First call β caches the result+ await verifier.verify_token("test-token")+ assert len(httpx_mock.get_requests()) == 1++ # Expire the cache entry manually+ cache_key = verifier._hash_token("test-token")+ verifier._cache[cache_key].expires_at = time.time() - 1++ # Second call β cache miss, new introspection+ await verifier.verify_token("test-token")+ assert len(httpx_mock.get_requests()) == 2++ async def test_cache_eviction_at_max_size(self, httpx_mock: HTTPXMock):+ """Test that cache evicts entries when max size is reached."""+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ cache_ttl_seconds=300,+ max_cache_size=2,+ )++ for i in range(3):+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": f"user-{i}"},+ )++ # Fill cache to capacity+ await verifier.verify_token("token-0")+ await verifier.verify_token("token-1")+ assert len(verifier._cache) == 2++ # Third token should evict the oldest entry+ await verifier.verify_token("token-2")+ assert len(verifier._cache) == 2++ # token-0 should have been evicted (FIFO)+ hash_0 = verifier._hash_token("token-0")+ assert hash_0 not in verifier._cache++class TestIntrospectionTokenVerifierIntegration:"""Integration tests with FastMCP server."""