Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(sso): share SAML sign-in state over Redis without enable_redis_auth_cache (#46807)

yuneng-jiangcf1e6b19ab62
diff --git a/litellm/proxy/management_endpoints/sso/saml_sso.py b/litellm/proxy/management_endpoints/sso/saml_sso.py
index 292ba3c5988..4991436edac 100644
--- a/litellm/proxy/management_endpoints/sso/saml_sso.py
+++ b/litellm/proxy/management_endpoints/sso/saml_sso.py
@@ -60,7 +60,7 @@ _SAML_AUTHN_STATE_COOKIE: Final = "litellm_saml_authn"
_SAML_IDP_SETTINGS_CACHE_PREFIX: Final = "saml_idp_settings"
_SAML_AUTHN_REQUEST_CACHE_PREFIX: Final = "saml_authn_request"
_SAML_CONSUMED_ASSERTION_CACHE_PREFIX: Final = "saml_consumed_assertion"
-_SAML_AUTHN_REQUEST_TTL_SECONDS: Final = 600
+SAML_AUTHN_REQUEST_TTL_SECONDS: Final = 600
_SAML_IDP_METADATA_TTL_SECONDS: Final = 3600
_SAML_METADATA_FETCH_TIMEOUT_SECONDS: Final = 10
_SAML_MAX_POST_BYTES: Final = 5 * 1024 * 1024
@@ -161,7 +161,7 @@ class SAMLAuthHandler:
)
cache_key: Final = f"{_SAML_IDP_SETTINGS_CACHE_PREFIX}:{hashlib.sha256(source.encode()).hexdigest()}"
- cached: Final = cache.get_cache(key=cache_key)
+ cached: Final = await cache.async_get_cache(key=cache_key)
if isinstance(cached, dict):
return cast(dict[str, object], cached) # cast-ok: untyped python3-saml
@@ -181,7 +181,7 @@ class SAMLAuthHandler:
status_code=status.HTTP_502_BAD_GATEWAY,
detail="Could not parse an IdP entityID/SSO URL/certificate from the SAML metadata.",
)
- cache.set_cache(key=cache_key, value=idp_settings, ttl=_SAML_IDP_METADATA_TTL_SECONDS)
+ await cache.async_set_cache(key=cache_key, value=idp_settings, ttl=_SAML_IDP_METADATA_TTL_SECONDS)
return idp_settings
@staticmethod
@@ -253,16 +253,16 @@ class SAMLAuthHandler:
response: Final = RedirectResponse(url=redirect_url, status_code=303)
request_id: Final = cast(str | None, auth.get_last_request_id()) # cast-ok: untyped python3-saml
if request_id is not None:
- cache.set_cache(
+ await cache.async_set_cache(
key=f"{_SAML_AUTHN_REQUEST_CACHE_PREFIX}:{request_id}",
value="1",
- ttl=_SAML_AUTHN_REQUEST_TTL_SECONDS,
+ ttl=SAML_AUTHN_REQUEST_TTL_SECONDS,
)
secure: Final = SAMLAuthHandler._is_https(request)
response.set_cookie(
key=_SAML_AUTHN_STATE_COOKIE,
value=request_id,
- max_age=_SAML_AUTHN_REQUEST_TTL_SECONDS,
+ max_age=SAML_AUTHN_REQUEST_TTL_SECONDS,
httponly=True,
secure=secure,
samesite="none" if secure else "lax",
@@ -372,7 +372,7 @@ class SAMLAuthHandler:
if in_response_to is not None:
authn_key: Final = f"{_SAML_AUTHN_REQUEST_CACHE_PREFIX}:{in_response_to}"
- if cache.get_cache(key=authn_key) is None:
+ if await cache.async_get_cache(key=authn_key) is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="SAML response references an unknown or already-used login request.",
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index c5b4940b384..4629103070f 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -1101,7 +1101,7 @@ async def google_login(
general_settings,
premium_user,
prisma_client,
- user_api_key_cache,
+ saml_sso_cache,
user_custom_ui_sso_sign_in_handler,
)
@@ -1169,7 +1169,7 @@ async def google_login(
verbose_proxy_logger.info("Redirecting to SAML SSO login")
return await SAMLAuthHandler.build_login_redirect(
request=request,
- cache=user_api_key_cache,
+ cache=saml_sso_cache,
relay_state=return_to,
)
@@ -2257,20 +2257,20 @@ async def auth_callback(request: Request, state: str | None = None):
@router.get("/sso/saml/login", tags=["experimental"], include_in_schema=False)
async def saml_login(request: Request, return_to: str | None = None):
"""SP-initiated SAML login. Redirects the user to the configured IdP."""
- from litellm.proxy.proxy_server import user_api_key_cache
+ from litellm.proxy.proxy_server import saml_sso_cache
if is_admin_ui_disabled():
return admin_ui_disabled()
- return await SAMLAuthHandler.build_login_redirect(request=request, cache=user_api_key_cache, relay_state=return_to)
+ return await SAMLAuthHandler.build_login_redirect(request=request, cache=saml_sso_cache, relay_state=return_to)
@router.get("/sso/saml/metadata", tags=["experimental"], include_in_schema=False)
async def saml_metadata(request: Request):
"""Service Provider metadata XML, for registering this proxy at the IdP."""
- from litellm.proxy.proxy_server import user_api_key_cache
+ from litellm.proxy.proxy_server import saml_sso_cache
- metadata: Final = await SAMLAuthHandler.build_sp_metadata(request=request, cache=user_api_key_cache)
+ metadata: Final = await SAMLAuthHandler.build_sp_metadata(request=request, cache=saml_sso_cache)
return Response(content=metadata, media_type="application/xml")
@@ -2283,7 +2283,7 @@ async def saml_callback(request: Request):
master_key,
premium_user,
prisma_client,
- user_api_key_cache,
+ saml_sso_cache,
)
if is_admin_ui_disabled():
@@ -2303,7 +2303,7 @@ async def saml_callback(request: Request):
if "SAMLResponse" not in post_data:
raise HTTPException(status_code=400, detail="Missing SAMLResponse in callback request.")
- result: Final = await SAMLAuthHandler.handle_acs(request=request, cache=user_api_key_cache, post_data=post_data)
+ result: Final = await SAMLAuthHandler.handle_acs(request=request, cache=saml_sso_cache, post_data=post_data)
await _raise_if_sso_exceeds_free_user_limit(premium_user, prisma_client)
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 621dd0d8c04..4b4c6a13b1d 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -714,6 +714,7 @@ from litellm.proxy.management_endpoints.router_settings_endpoints import (
from litellm.proxy.management_endpoints.session_endpoints import (
router as session_management_router,
)
+from litellm.proxy.management_endpoints.sso.saml_sso import SAML_AUTHN_REQUEST_TTL_SECONDS
from litellm.proxy.management_endpoints.tag_management_endpoints import (
router as tag_management_router,
)
@@ -2830,6 +2831,7 @@ user_api_key_cache: UserApiKeyCache = UserApiKeyCache(
)
spend_counter_cache: Final = DualCache(default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value)
cli_sso_session_cache: Final = DualCache(default_in_memory_ttl=CLI_SSO_SESSION_TTL_SECONDS)
+saml_sso_cache: Final = DualCache(default_in_memory_ttl=SAML_AUTHN_REQUEST_TTL_SECONDS)
model_max_budget_limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=spend_counter_cache)
litellm.logging_callback_manager.add_litellm_callback(model_max_budget_limiter)
redis_usage_cache: RedisCache | None = None # redis cache used for tracking spend, tpm/rpm limits
@@ -5191,12 +5193,13 @@ def _attach_redis_usage_cache(redis_cache: RedisCache, enable_redis_auth_cache:
"""
Wires an established coordination Redis into the proxy-level caches that
consume it directly: the spend counter cache, the CLI SSO login-session
- cache, the cluster-wide config cache, and (only when opted in) the
- virtual-key auth cache.
+ cache, the SAML SSO sign-in cache, the cluster-wide config cache, and (only
+ when opted in) the virtual-key auth cache.
- The CLI SSO login-session cache is always backed by Redis when available so
- that the browser SSO flow behind `lite login` survives landing on different
- workers; it must not be gated behind enable_redis_auth_cache.
+ The CLI SSO login-session cache and the SAML SSO sign-in cache are always
+ backed by Redis when available so that the browser SSO flows behind
+ `lite login` and SAML sign-in survive landing on different workers; they
+ must not be gated behind enable_redis_auth_cache.
"""
spend_counter_cache.attach_redis_cache(
redis_cache,
@@ -5206,6 +5209,10 @@ def _attach_redis_usage_cache(redis_cache: RedisCache, enable_redis_auth_cache:
redis_cache,
default_redis_ttl=CLI_SSO_SESSION_TTL_SECONDS,
)
+ saml_sso_cache.attach_redis_cache(
+ redis_cache,
+ default_redis_ttl=SAML_AUTHN_REQUEST_TTL_SECONDS,
+ )
if enable_redis_auth_cache is True:
user_api_key_cache.attach_redis_cache(
redis_cache,
diff --git a/tests/integration/authorization/test_sso_blank_identity.py b/tests/integration/authorization/test_sso_blank_identity.py
index c2f0e29221d..6d9b3b50cc0 100644
--- a/tests/integration/authorization/test_sso_blank_identity.py
+++ b/tests/integration/authorization/test_sso_blank_identity.py
@@ -169,8 +169,9 @@ class SamlIdp:
"</IDPSSODescriptor></EntityDescriptor>"
)
- def response(self, acs: str, request_id: str, name_id: str, email: str | None) -> str:
+ def response(self, acs: str, request_id: str | None, name_id: str, email: str | None) -> str:
now: Final = datetime.now(timezone.utc)
+ in_response_to: Final = "" if request_id is None else f' InResponseTo="{request_id}"'
issued: Final = (now - timedelta(seconds=1)).strftime("%Y-%m-%dT%H:%M:%SZ")
not_before: Final = (now - timedelta(seconds=60)).strftime("%Y-%m-%dT%H:%M:%SZ")
expires: Final = (now + timedelta(seconds=300)).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -186,7 +187,7 @@ class SamlIdp:
'<saml:Subject><saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">'
f"{name_id}</saml:NameID>"
'<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">'
- f'<saml:SubjectConfirmationData InResponseTo="{request_id}" NotOnOrAfter="{expires}" Recipient="{acs}"/>'
+ f'<saml:SubjectConfirmationData{in_response_to} NotOnOrAfter="{expires}" Recipient="{acs}"/>'
"</saml:SubjectConfirmation></saml:Subject>"
f'<saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{expires}">'
f"<saml:AudienceRestriction><saml:Audience>{SAML_SP_ENTITY}</saml:Audience>"
@@ -206,7 +207,7 @@ class SamlIdp:
'<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" '
'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" '
f'ID="_response_{uuid.uuid4().hex}" Version="2.0" IssueInstant="{issued}" '
- f'Destination="{acs}" InResponseTo="{request_id}">'
+ f'Destination="{acs}"{in_response_to}>'
f"<saml:Issuer>{SAML_IDP_ENTITY}</saml:Issuer>"
'<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>'
f"{signed_text}</samlp:Response>"
@@ -258,6 +259,54 @@ def _saml_sign_in(proxy: Gateway, idp: SamlIdp, name_id: str, email: str | None)
return browser.post(acs, data={"SAMLResponse": idp.response(acs, request_id, name_id, email)})
+SAML_PAIR_BASE: Final = "http://saml-pair.integration.invalid"
+SAML_PAIR_ACS: Final = f"{SAML_PAIR_BASE}/sso/saml/callback"
+
+
+@dataclass(frozen=True, slots=True)
+class SamlPair:
+ first: Gateway
+ second: Gateway
+
+
[email protected](scope="module")
+def saml_pair(
+ saml_idp: SamlIdp, gateway_module: Gateway, tmp_path_factory: pytest.TempPathFactory
+) -> Iterator[SamlPair]:
+ environment: Final = {
+ "SAML_IDP_METADATA_XML": saml_idp.metadata(),
+ "SAML_SP_ENTITY_ID": SAML_SP_ENTITY,
+ "SAML_ALLOW_UNSOLICITED": "true",
+ "PROXY_BASE_URL": SAML_PAIR_BASE,
+ }
+ config: Final = Path("tests/integration/coordination_redis_proxy_config.yaml")
+ with (
+ owned_proxy_process(
+ gateway_module, tmp_path_factory.mktemp("saml-pair-first"), environment, config=config
+ ) as first,
+ owned_proxy_process(
+ gateway_module, tmp_path_factory.mktemp("saml-pair-second"), environment, config=config
+ ) as second,
+ ):
+ yield SamlPair(first.gateway, second.gateway)
+
+
+def _saml_login_ticket(proxy: Gateway) -> str:
+ with _browser() as browser:
+ login: Final = browser.get(f"{_proxy_url(proxy)}/sso/key/generate", params={"return_to": "/ui/"})
+ assert login.status_code == 303, f"{login.status_code} {login.text}"
+ return login.cookies[SAML_STATE_COOKIE]
+
+
+def _post_saml_response(proxy: Gateway, saml_response: str, ticket: str | None) -> httpx.Response:
+ with _browser() as browser:
+ return browser.post(
+ f"{_proxy_url(proxy)}/sso/saml/callback",
+ data={"SAMLResponse": saml_response},
+ headers={} if ticket is None else {"cookie": f"{SAML_STATE_COOKIE}={ticket}"},
+ )
+
+
@pytest.fixture(scope="module")
def graph() -> Iterator[Graph]:
profiles: Final[dict[str, Reply]] = {}
@@ -811,3 +860,44 @@ def test_saml_sign_in_with_an_email_signs_in_as_a_real_account(
assert callback.status_code == 303 and session is not None, f"{callback.status_code} {callback.text}"
assert session["user_id"] == expected, f"session issued for user_id={session['user_id']!r}"
assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_saml_sign_in_started_on_one_proxy_completes_on_another(
+ saml_pair: SamlPair, saml_idp: SamlIdp, gateway_module: Gateway
+) -> None:
+ email: Final = f"saml-pair-{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ ticket: Final = _saml_login_ticket(saml_pair.first)
+ callback: Final = _post_saml_response(
+ saml_pair.second, saml_idp.response(SAML_PAIR_ACS, ticket, email, email), ticket
+ )
+ assert callback.status_code == 303 and _session(callback) is not None, f"{callback.status_code} {callback.text}"
+ assert callback.headers["location"].startswith(f"{SAML_PAIR_BASE}/ui/"), callback.headers["location"]
+
+
+def test_saml_response_replayed_on_another_proxy_is_refused(
+ saml_pair: SamlPair, saml_idp: SamlIdp, gateway_module: Gateway
+) -> None:
+ email: Final = f"saml-pair-{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ ticket: Final = _saml_login_ticket(saml_pair.first)
+ saml_response: Final = saml_idp.response(SAML_PAIR_ACS, ticket, email, email)
+ accepted: Final = _post_saml_response(saml_pair.second, saml_response, ticket)
+ assert accepted.status_code == 303, f"{accepted.status_code} {accepted.text}"
+ replayed: Final = _post_saml_response(saml_pair.first, saml_response, ticket)
+ assert replayed.status_code == 401 and _session(replayed) is None, f"{replayed.status_code} {replayed.text}"
+ assert "already been used" in string_value(JSON_OBJECT.validate_json(replayed.content)["detail"]), replayed.text
+
+
+def test_idp_initiated_saml_sign_in_completes_on_any_proxy(
+ saml_pair: SamlPair, saml_idp: SamlIdp, gateway_module: Gateway
+) -> None:
+ email: Final = f"saml-pair-{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ callback: Final = _post_saml_response(
+ saml_pair.second, saml_idp.response(SAML_PAIR_ACS, None, email, email), None
+ )
+ assert callback.status_code == 303 and _session(callback) is not None, f"{callback.status_code} {callback.text}"
diff --git a/tests/unit/proxy/management_endpoints/test_saml_sso.py b/tests/unit/proxy/management_endpoints/test_saml_sso.py
index 635e6332958..01f8fc929a3 100644
--- a/tests/unit/proxy/management_endpoints/test_saml_sso.py
+++ b/tests/unit/proxy/management_endpoints/test_saml_sso.py
@@ -10,6 +10,7 @@ makes a test fail.
import base64
import datetime
import time
+from http.cookies import SimpleCookie
import pytest
from fastapi import HTTPException, Request
@@ -637,6 +638,35 @@ async def test_idp_initiated_replay_rejected_across_workers(saml_env_idp_initiat
assert exc.value.status_code == 401
+async def test_sp_initiated_login_endpoint_ticket_is_accepted_by_another_worker(saml_env, monkeypatch):
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy.management_endpoints.ui_sso import saml_login
+
+ key_pem, cert_pem = saml_env
+ shared_store = InMemoryCache()
+ monkeypatch.setattr(proxy_server, "saml_sso_cache", _shared_cache(shared_store))
+
+ redirect = await saml_login(_fake_request())
+ assert redirect.headers["location"].startswith(SSO_URL)
+ ticket = SimpleCookie(redirect.headers["set-cookie"])[_SAML_AUTHN_STATE_COOKIE].value
+
+ resp = _build_signed_response(key_pem, cert_pem, in_response_to=ticket, email="[email protected]")
+ result = await _acs(_b64(resp), _shared_cache(shared_store), cookies={_SAML_AUTHN_STATE_COOKIE: ticket})
+ assert result.email == "[email protected]"
+
+
+async def test_sp_metadata_endpoint_serves_acs_and_entity_id(saml_env):
+ from litellm.proxy.management_endpoints.ui_sso import saml_metadata
+
+ response = await saml_metadata(_fake_request())
+ body = bytes(response.body).decode()
+ assert response.media_type == "application/xml"
+ assert ACS in body
+ assert SP_ENTITY in body
+
+
class _FakeChunkedRequest:
def __init__(self, chunks, content_length=None):
self._chunks = chunks
diff --git a/tests/unit/proxy/test_redis_auth_cache_flag.py b/tests/unit/proxy/test_redis_auth_cache_flag.py
index cb600bbb5fd..d414e17b078 100644
--- a/tests/unit/proxy/test_redis_auth_cache_flag.py
+++ b/tests/unit/proxy/test_redis_auth_cache_flag.py
@@ -73,6 +73,7 @@ def _patched_init_cache(litellm_settings: dict, cache_params: dict):
patch.object(ps, "user_api_key_cache", fresh_user_cache),
patch.object(ps, "spend_counter_cache", fresh_spend_cache),
patch.object(ps, "cli_sso_session_cache", fresh_cli_sso_cache),
+ patch.object(ps, "saml_sso_cache", DualCache()),
patch.object(ps, "litellm_config_cache", fresh_config_cache),
patch.object(ps, "llm_router", None),
# Cache is locally imported inside _init_cache: patch it at source.
@@ -182,6 +183,7 @@ class TestRedisAuthCacheFlag:
limiter_cache,
ps.spend_counter_cache,
ps.cli_sso_session_cache,
+ ps.saml_sso_cache,
ps.user_api_key_cache,
ps.litellm_config_cache,
)
@@ -191,3 +193,16 @@ class TestRedisAuthCacheFlag:
ps._attach_redis_usage_cache(fake_redis, enable_redis_auth_cache=False)
assert limiter_cache.redis_cache is fake_redis
assert ps.user_api_key_cache.redis_cache is None
+
+
+ "litellm_settings",
+ [{"enable_redis_auth_cache": True}, {"enable_redis_auth_cache": False}, {}],
+ ids=["flag-true", "flag-false", "flag-absent"],
+)
+def test_saml_sso_cache_always_gets_redis_regardless_of_flag(litellm_settings: dict[str, bool]) -> None:
+ with _patched_init_cache(
+ litellm_settings=litellm_settings,
+ cache_params={"type": "redis", "host": "localhost", "port": 6379},
+ ):
+ assert ps.saml_sso_cache.redis_cache is not None