π The fast, Pythonic way to build MCP servers and clients.
fix(auth): cache OIDC discovery configuration (#4861)
sui-ni23820f87b1478
diff --git a/fastmcp_slim/fastmcp/server/auth/oidc_proxy.py b/fastmcp_slim/fastmcp/server/auth/oidc_proxy.pyindex 5e4086c7a..1075ac77c 100644--- a/fastmcp_slim/fastmcp/server/auth/oidc_proxy.py+++ b/fastmcp_slim/fastmcp/server/auth/oidc_proxy.py@@ -9,7 +9,11 @@ This implementation is based on:OAuth 2.0 Authorization Server Metadata - https://datatracker.ietf.org/doc/html/rfc8414"""+from collections import OrderedDictfrom collections.abc import Sequence+from copy import deepcopy+from threading import Lock+from time import monotonicfrom typing import Any, Literalimport httpx2@@ -32,6 +36,24 @@ logger = get_logger(__name__)#: back to the HTTP client's own default timeout instead.DEFAULT_OIDC_DISCOVERY_TIMEOUT_SECONDS = 10+#: Maximum age, in seconds, of a successfully validated OIDC discovery document.+_OIDC_DISCOVERY_CACHE_TTL_SECONDS = 300++#: Maximum number of distinct discovery configurations cached per process.+_OIDC_DISCOVERY_CACHE_MAX_SIZE = 128++_OIDCDiscoveryCacheKey = tuple[type[BaseModel], str, bool | None, int | None]+_OIDCDiscoveryCacheValue = tuple[float, dict[str, Any]]+_oidc_configuration_cache: OrderedDict[+ _OIDCDiscoveryCacheKey, _OIDCDiscoveryCacheValue+] = OrderedDict()+_oidc_configuration_cache_lock = Lock()+++def _clear_oidc_configuration_cache() -> None:+ with _oidc_configuration_cache_lock:+ _oidc_configuration_cache.clear()+class OIDCConfiguration(BaseModel):"""OIDC Configuration.@@ -153,11 +175,37 @@ class OIDCConfiguration(BaseModel):) -> Self:"""Get the OIDC configuration for the specified config URL.+ Successful discovery responses are cached briefly to avoid repeatedly hitting+ the issuer for identical provider construction. Cached data is copied and+ revalidated for every caller so mutable model instances are never shared.+Args:config_url: The OIDC config URLstrict: The strict flag for the configurationtimeout_seconds: HTTP request timeout in seconds"""+ cache_key: _OIDCDiscoveryCacheKey = (+ cls,+ str(config_url),+ strict,+ timeout_seconds,+ )+ now = monotonic()+ cached_data: dict[str, Any] | None = None++ with _oidc_configuration_cache_lock:+ cached = _oidc_configuration_cache.get(cache_key)+ if cached is not None:+ expires_at, cached_snapshot = cached+ if expires_at > now:+ _oidc_configuration_cache.move_to_end(cache_key)+ cached_data = deepcopy(cached_snapshot)+ else:+ del _oidc_configuration_cache[cache_key]++ if cached_data is not None:+ return cls.model_validate(cached_data)+get_kwargs: dict[str, Any] = {}if timeout_seconds is not None:get_kwargs["timeout"] = timeout_seconds@@ -170,13 +218,23 @@ class OIDCConfiguration(BaseModel):if strict is not None:config_data["strict"] = strict- return cls.model_validate(config_data)+ config = cls.model_validate(config_data)except Exception:logger.exception(f"Unable to get OIDC configuration for config url: {config_url}")raise+ cached_snapshot = config.model_dump(mode="json")+ expires_at = monotonic() + _OIDC_DISCOVERY_CACHE_TTL_SECONDS+ with _oidc_configuration_cache_lock:+ _oidc_configuration_cache[cache_key] = (expires_at, cached_snapshot)+ _oidc_configuration_cache.move_to_end(cache_key)+ while len(_oidc_configuration_cache) > _OIDC_DISCOVERY_CACHE_MAX_SIZE:+ _oidc_configuration_cache.popitem(last=False)++ return config+class OIDCProxy(OAuthProxy):"""OAuth provider that wraps OAuthProxy to provide configuration via an OIDC configuration URL.diff --git a/tests/server/auth/conftest.py b/tests/server/auth/conftest.pynew file mode 100644index 000000000..42c40d46e--- /dev/null+++ b/tests/server/auth/conftest.py@@ -0,0 +1,13 @@+"""Shared fixtures for authentication tests."""++import pytest++from fastmcp.server.auth.oidc_proxy import _clear_oidc_configuration_cache++[email protected](autouse=True)+def clear_oidc_discovery_cache():+ """Prevent process-local discovery cache state from leaking between tests."""+ _clear_oidc_configuration_cache()+ yield+ _clear_oidc_configuration_cache()diff --git a/tests/server/auth/test_oidc_discovery_cache.py b/tests/server/auth/test_oidc_discovery_cache.pynew file mode 100644index 000000000..eb04e6740--- /dev/null+++ b/tests/server/auth/test_oidc_discovery_cache.py@@ -0,0 +1,162 @@+"""Regression tests for OIDC discovery caching."""++from unittest.mock import MagicMock, patch++import pytest+from httpx2 import Response+from pydantic import AnyHttpUrl++from fastmcp.server.auth.oidc_proxy import (+ _OIDC_DISCOVERY_CACHE_TTL_SECONDS,+ OIDCConfiguration,+)++CONFIG_URL = AnyHttpUrl("https://cache.example.com/.well-known/openid-configuration")+++def discovery_document() -> dict[str, object]:+ return {+ "issuer": "https://cache.example.com",+ "authorization_endpoint": "https://cache.example.com/authorize",+ "token_endpoint": "https://cache.example.com/token",+ "jwks_uri": "https://cache.example.com/jwks",+ "response_types_supported": ["code"],+ "subject_types_supported": ["public"],+ "id_token_signing_alg_values_supported": ["RS256"],+ }+++def _response(document: dict[str, object]) -> MagicMock:+ response = MagicMock(spec=Response)+ response.json.return_value = document+ return response+++def test_identical_discovery_configuration_is_cached(discovery_document):+ response = _response(discovery_document)++ with patch("httpx2.get", return_value=response) as mock_get:+ first = OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )+ second = OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ assert first == second+ mock_get.assert_called_once()+++def test_cached_configuration_expires_and_refetches(discovery_document):+ response = _response(discovery_document)++ with (+ patch("httpx2.get", return_value=response) as mock_get,+ patch(+ "fastmcp.server.auth.oidc_proxy.monotonic",+ side_effect=[+ 0.0,+ 0.0,+ _OIDC_DISCOVERY_CACHE_TTL_SECONDS + 1,+ _OIDC_DISCOVERY_CACHE_TTL_SECONDS + 1,+ ],+ ),+ ):+ OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )+ OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ assert mock_get.call_count == 2+++def test_cached_configuration_is_isolated_between_callers(discovery_document):+ response = _response(discovery_document)++ with patch("httpx2.get", return_value=response) as mock_get:+ first = OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )+ second = OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ assert first is not second+ assert isinstance(first.response_types_supported, list)+ first.response_types_supported.append("token")+ first.authorization_endpoint = "https://mutated.example.com/authorize"++ third = OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ assert list(second.response_types_supported or []) == ["code"]+ assert list(third.response_types_supported or []) == ["code"]+ assert str(third.authorization_endpoint) == "https://cache.example.com/authorize"+ mock_get.assert_called_once()+++def test_cache_isolated_by_configuration_class(discovery_document):+ class ProviderOIDCConfiguration(OIDCConfiguration):+ provider_specific: str++ provider_document = {+ **discovery_document,+ "provider_specific": "provider-value",+ }+ response = _response(provider_document)++ with patch("httpx2.get", return_value=response) as mock_get:+ OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )+ provider = ProviderOIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ assert provider.provider_specific == "provider-value"+ assert mock_get.call_count == 2+++def test_failed_discovery_is_not_cached(discovery_document):+ invalid_document = {"issuer": "https://cache.example.com"}+ response = MagicMock(spec=Response)+ response.json.side_effect = [invalid_document, discovery_document]++ with patch("httpx2.get", return_value=response) as mock_get:+ with pytest.raises(ValueError, match="Missing required configuration metadata"):+ OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ config = OIDCConfiguration.get_oidc_configuration(+ config_url=CONFIG_URL,+ strict=True,+ timeout_seconds=10,+ )++ assert str(config.issuer) == "https://cache.example.com"+ assert mock_get.call_count == 2