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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(sso): capture the IdP id_token on Microsoft and Google logins for oauth2_id_jag (#46747)
Yassin Kortam3501e36fa95d
diff --git a/litellm/proxy/_experimental/mcp_server/oauth_utils.py b/litellm/proxy/_experimental/mcp_server/oauth_utils.pyindex 69732186d75..133bad780bf 100644--- a/litellm/proxy/_experimental/mcp_server/oauth_utils.py+++ b/litellm/proxy/_experimental/mcp_server/oauth_utils.py@@ -19,6 +19,9 @@ from litellm.proxy._experimental.mcp_server.auth.token_endpoint_auth import (build_token_endpoint_client_auth,normalize_token_endpoint_auth_method,)+from litellm.proxy._experimental.mcp_server.outbound_credentials.sso_assertion_store import (+ GOOGLE_REFRESH_TOKEN_PARAMS,+)from litellm.proxy.auth.ip_address_utils import IPAddressUtilsfrom litellm.proxy.middleware.per_request_root_path_middleware import get_request_root_path@@ -59,7 +62,7 @@ _DEFAULT_NATIVE_REDIRECT_URIS: Final[list[str]] = []_GOOGLE_AUTHORIZATION_HOSTS: Final = frozenset({"accounts.google.com"})-_GOOGLE_OFFLINE_ACCESS_PARAMS: Final = MappingProxyType({"access_type": "offline", "prompt": "consent"})+_GOOGLE_OFFLINE_ACCESS_PARAMS: Final = GOOGLE_REFRESH_TOKEN_PARAMS_warned_invalid_proxy_base_url: str | None = Nonediff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_refresher.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_refresher.pyindex bca5848febe..c41730ce9ec 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_refresher.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_refresher.py@@ -12,15 +12,18 @@ not the size of the user table) and single-flighted per user through the same ``the ``authorization_code`` arm uses, because an IdP that rotates refresh tokens treats two concurrentredemptions of one token as replay and can revoke the whole grant chain.-The refresh is redeemed against the generic-OIDC client the login itself used-(``GENERIC_TOKEN_ENDPOINT`` / ``GENERIC_CLIENT_ID`` / ``GENERIC_CLIENT_SECRET``, which the proxy-reconciles from the stored SSO row into the process environment at startup), authenticated the way-that login authenticated: the non-PKCE path always sends HTTP Basic, while the PKCE path sends the-credentials in the body when ``GENERIC_INCLUDE_CLIENT_ID`` is set, and an IdP application may accept-only one of the two. An assertion can only exist if that client minted it, so no other client could-redeem its refresh token, and no other method is known to be accepted. A deployment whose-``GENERIC_SCOPE`` omits ``offline_access`` captures no refresh token at all, which is why that miss-logs the scope by name rather than failing silently.+The refresh is redeemed against the SSO client the login itself used, resolved in the same order+the login callback dispatches (Google, then Microsoft, then generic OIDC, from the client ids the+proxy reconciles from the stored SSO row into the process environment at startup), authenticated the+way that login authenticated: the Google and Microsoft logins and the non-PKCE generic path send+HTTP Basic, while the PKCE generic path sends the credentials in the body when+``GENERIC_INCLUDE_CLIENT_ID`` is set, and an IdP application may accept only one of the two. An+assertion can only exist if that client minted it, so no other client could redeem its refresh+token, and no other method is known to be accepted. A login whose authorization request never asked+for a refresh token captures none at all: the Google and Microsoft logins ask (``access_type=offline``,+``offline_access``) only while an ``oauth2_id_jag`` server exists, and generic OIDC asks only when+``GENERIC_SCOPE`` carries ``offline_access``, which is why that miss names the cause rather than+failing silently.Failures are values internally (``Result[_, RefreshFailure]``). At the store boundary they collapseonto the protocol's existing two-outcome contract: a refusal returns the expired assertion unchanged@@ -92,6 +95,10 @@ _SINGLE_FLIGHT_KEY: Final = "sso_identity_assertion"# Renew this far ahead of ``exp`` so a token that would die between resolution and the second leg of# the exchange is replaced first. Matches the sibling per-user token store's skew._DEFAULT_EXPIRY_SKEW_SECONDS: Final = 60.0+# Where fastapi-sso's Google login redeemed the authorization code, read from Google's discovery+# document; Microsoft's mirrors ``CustomMicrosoftSSO``, override first, tenant template second.+_GOOGLE_TOKEN_ENDPOINT: Final = "https://oauth2.googleapis.com/token"+_MICROSOFT_TOKEN_ENDPOINT_TEMPLATE: Final = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"class AssertionRead(Protocol):@@ -122,7 +129,7 @@ class FormPost(Protocol):@dataclass(frozen=True, slots=True)class SSOClientConfig:- """The generic-OIDC client credentials a refresh_token grant has to authenticate as, and how."""+ """The SSO client credentials a refresh_token grant has to authenticate as, and how."""token_endpoint: strclient_id: str@@ -131,32 +138,58 @@ class SSOClientConfig:def sso_client_config(env: Mapping[str, str]) -> SSOClientConfig | None:- """The configured generic-OIDC client, or ``None`` when the deployment has none.-- Read from the process environment because that is where the login path reads it- (``_setup_generic_sso_env_vars``) and where the proxy materializes the stored ``sso_config`` row- at startup, so this resolves to the same client that minted the assertion. ``None`` is an- ordinary state, not an error: a deployment signing in through a provider that captures no+ """The configured SSO client the login used, or ``None`` when the deployment has none.++ Read from the process environment because that is where the login callback reads it and where+ the proxy materializes the stored ``sso_config`` row at startup, and resolved in the callback's+ own order (``GOOGLE_CLIENT_ID``, then ``MICROSOFT_CLIENT_ID``, then ``GENERIC_CLIENT_ID``, each+ selecting its branch when set at all), so this is the same client that minted the assertion: a+ deployment carrying both a Google and a generic client signed the user in through Google. ``None``+ is an ordinary state, not an error: a deployment signing in through a provider that captures noassertion has nothing here to renew, and a client with no secret is not a confidential clientthat could redeem one.- ``auth_method`` is derived from the same ``GENERIC_INCLUDE_CLIENT_ID`` the login reads, because- the two login paths do not agree: the non-PKCE path always authenticates with HTTP Basic, while- the PKCE path puts the credentials in the body when that flag is set. Both capture assertions, so- a constant here would authenticate the renewal differently from the sign-in that produced the+ ``auth_method`` follows how each login authenticated at the token endpoint. The Google and+ Microsoft logins (fastapi-sso) and the non-PKCE generic path send HTTP Basic, while the PKCE+ generic path puts the credentials in the body when ``GENERIC_INCLUDE_CLIENT_ID`` is set. A+ constant here would authenticate the renewal differently from the sign-in that produced therefresh token and 401 against an IdP application registered for only one of the two."""- token_endpoint: Final = env.get("GENERIC_TOKEN_ENDPOINT")- client_id: Final = env.get("GENERIC_CLIENT_ID")- client_secret: Final = env.get("GENERIC_CLIENT_SECRET")+ if env.get("GOOGLE_CLIENT_ID") is not None:+ return _confidential_client(+ _GOOGLE_TOKEN_ENDPOINT, env.get("GOOGLE_CLIENT_ID"), env.get("GOOGLE_CLIENT_SECRET"), "client_secret_basic"+ )+ if env.get("MICROSOFT_CLIENT_ID") is not None:+ tenant: Final = env.get("MICROSOFT_TENANT")+ return _confidential_client(+ env.get("MICROSOFT_TOKEN_ENDPOINT")+ or (_MICROSOFT_TOKEN_ENDPOINT_TEMPLATE.format(tenant=tenant) if tenant else None),+ env.get("MICROSOFT_CLIENT_ID"),+ env.get("MICROSOFT_CLIENT_SECRET"),+ "client_secret_basic",+ )+ includes_client_id: Final = env.get("GENERIC_INCLUDE_CLIENT_ID", "false").lower() == "true"+ return _confidential_client(+ env.get("GENERIC_TOKEN_ENDPOINT"),+ env.get("GENERIC_CLIENT_ID"),+ env.get("GENERIC_CLIENT_SECRET"),+ "client_secret_post" if includes_client_id else "client_secret_basic",+ )+++def _confidential_client(+ token_endpoint: str | None,+ client_id: str | None,+ client_secret: str | None,+ auth_method: MCPTokenEndpointAuthMethod,+) -> SSOClientConfig | None:if not token_endpoint or not client_id or not client_secret:return None- includes_client_id: Final = env.get("GENERIC_INCLUDE_CLIENT_ID", "false").lower() == "true"return SSOClientConfig(token_endpoint=token_endpoint,client_id=client_id,client_secret=SecretStr(client_secret),- auth_method="client_secret_post" if includes_client_id else "client_secret_basic",+ auth_method=auth_method,)@@ -263,8 +296,9 @@ class SSOAssertionRefresher:if assertion.refresh_token is None:verbose_proxy_logger.warning("ID-JAG: the stored IdP identity assertion for user_id=%s has expired and no refresh token was "- "captured with it, so it cannot be renewed without another interactive sign-in. Add "- "'offline_access' to GENERIC_SCOPE so the SSO login captures one.",+ "captured with it, so it cannot be renewed without another interactive sign-in. Google and Microsoft "+ "logins ask for one once an oauth2_id_jag MCP server is registered, so a user who signed in before "+ "that has to sign in again. Generic OIDC asks only with 'offline_access' in GENERIC_SCOPE.",user_id,)return Error(RefreshFailure.of_rejected("no refresh token was captured at sign-in"))@@ -272,11 +306,12 @@ class SSOAssertionRefresher:if config is None:verbose_proxy_logger.warning("ID-JAG: the stored IdP identity assertion for user_id=%s has expired and cannot be renewed "- "because the generic SSO client is not configured (GENERIC_TOKEN_ENDPOINT, GENERIC_CLIENT_ID, "- "GENERIC_CLIENT_SECRET).",+ "because the active SSO provider has no confidential client configured (GOOGLE_CLIENT_ID and "+ "GOOGLE_CLIENT_SECRET, MICROSOFT_CLIENT_ID with MICROSOFT_CLIENT_SECRET and MICROSOFT_TENANT, or "+ "GENERIC_TOKEN_ENDPOINT with GENERIC_CLIENT_ID and GENERIC_CLIENT_SECRET).",user_id,)- return Error(RefreshFailure.of_rejected("the generic SSO client is not configured"))+ return Error(RefreshFailure.of_rejected("the SSO client is not configured"))carried_refresh_token: Final = assertion.refresh_token.get_secret_value()# Whichever method the SSO login used for this client, since that is the one the IdPdiff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_store.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_store.pyindex 0bc17d94165..ef30b3d75b6 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_store.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/sso_assertion_store.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport jsonfrom collections.abc import Mapping, Sequencefrom datetime import datetime, timezone+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Final, Protocolimport jwt@@ -35,6 +36,13 @@ if TYPE_CHECKING:from litellm.proxy.utils import PrismaClient+"""What a Google or Microsoft authorization request has to carry for the IdP to issue a refresh token+beside the id_token. Asked for only while an ``oauth2_id_jag`` server exists to renew an assertion for, so+a deployment without one sees no extra consent."""+MICROSOFT_REFRESH_TOKEN_SCOPE: Final = "offline_access"+GOOGLE_REFRESH_TOKEN_PARAMS: Final = MappingProxyType({"access_type": "offline", "prompt": "consent"})++_ASSERTION_DECRYPT_LOG_KEY: Final = "sso_identity_assertion"_STR_ADAPTER: Final[TypeAdapter[str]] = TypeAdapter(str)_MAYBE_STR_ADAPTER: Final[TypeAdapter[str | None]] = TypeAdapter(str | None)diff --git a/litellm/proxy/management_endpoints/sso/id_jag_assertion_capture.py b/litellm/proxy/management_endpoints/sso/id_jag_assertion_capture.pyindex 404fdfc83a9..deb9d2975de 100644--- a/litellm/proxy/management_endpoints/sso/id_jag_assertion_capture.py+++ b/litellm/proxy/management_endpoints/sso/id_jag_assertion_capture.py@@ -1,25 +1,26 @@"""Whether the SSO provider the login callback dispatches to can capture an IdP identity assertion.An ``oauth2_id_jag`` MCP server spends the ``id_token`` captured at SSO login as its RFC 8693-subject token. Only the generic OIDC login path reaches a token response the gateway retains one-from, so a deployment whose SSO runs through Google, Microsoft or SAML never stores an assertion-and every store-sourced ID-JAG exchange fails for every user, however many times they sign in.-Neither side can see that alone: the MCP registration knows nothing about SSO and the login knows-nothing about MCP. This module is the one shared answer both warn from.+subject token. The Google, Microsoft and generic OIDC login paths all reach a token response the+gateway retains one from; SAML has no id_token to capture, and a deployment with no SSO never signs+anyone in, so under either every store-sourced ID-JAG exchange fails for every user, however many+times they sign in. Neither side can see that alone: the MCP registration knows nothing about SSO+and the login knows nothing about MCP. This module is the one shared answer both warn from."""from __future__ import annotationsimport osfrom enum import Enum+from typing import Finalfrom typing_extensions import assert_neverfrom litellm.proxy.management_endpoints.sso.saml_sso import SAMLAuthHandler-_GENERIC_OIDC_REMEDY = (- "Point SSO at the generic OIDC provider (GENERIC_CLIENT_ID), the one login path whose token "- "response the gateway retains an id_token from"+_OIDC_REMEDY: Final = (+ "Point SSO at an OIDC provider (GOOGLE_CLIENT_ID, MICROSOFT_CLIENT_ID or GENERIC_CLIENT_ID), the login "+ "paths whose token response the gateway retains an id_token from")@@ -55,18 +56,18 @@ def id_jag_assertion_capture_gap() -> str | None:or ``None`` when that provider does capture an assertion."""provider = active_sso_provider()match provider:- case ActiveSSOProvider.generic:+ case ActiveSSOProvider.google | ActiveSSOProvider.microsoft | ActiveSSOProvider.generic:return Nonecase ActiveSSOProvider.none:return ("no SSO provider is configured, so no IdP identity assertion is ever captured and "- f"ID-JAG credential resolution fails for every user. {_GENERIC_OIDC_REMEDY}"+ f"ID-JAG credential resolution fails for every user. {_OIDC_REMEDY}")- case ActiveSSOProvider.google | ActiveSSOProvider.microsoft | ActiveSSOProvider.saml:+ case ActiveSSOProvider.saml:return (f"the active SSO provider ({provider.value}) has no identity-assertion capture path, so no ""IdP id_token is ever stored and ID-JAG credential resolution fails for every user no matter "- f"how often they sign in. {_GENERIC_OIDC_REMEDY}"+ f"how often they sign in. {_OIDC_REMEDY}")case _:assert_never(provider)diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.pyindex 4629103070f..c3c5d7401c5 100644--- a/litellm/proxy/management_endpoints/ui_sso.py+++ b/litellm/proxy/management_endpoints/ui_sso.py@@ -37,10 +37,12 @@ from urllib.parse import parse_qs, urlencode, urlparseif TYPE_CHECKING:import httpx+ from litellm.caching.redis_cache import RedisCache+import jwtfrom fastapi import APIRouter, Depends, Header, HTTPException, Request, Response, statusfrom fastapi.responses import RedirectResponse-from pydantic import ConfigDict, TypeAdapter, ValidationError+from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, field_validatorimport litellmfrom litellm._internal_context import with_service_target@@ -70,6 +72,8 @@ from litellm.llms.custom_httpx.http_handler import (httpxSpecialProvider,)from litellm.proxy._experimental.mcp_server.outbound_credentials.sso_assertion_store import (+ GOOGLE_REFRESH_TOKEN_PARAMS,+ MICROSOFT_REFRESH_TOKEN_SCOPE,SSOIdentityAssertion,assertion_from_sso_login,ema_assertion_retention_enabled,@@ -1786,6 +1790,19 @@ async def warn_if_id_jag_assertion_uncaptured()+async def login_asks_for_refresh_token(retention_enabled: RetentionCheck | None = None) -> bool:+ """A refresh token is only issued when the authorization request asks for one, and asking costs the+ user an offline-access consent, so the Google and Microsoft logins ask only while an ``oauth2_id_jag``+ server exists whose assertion the refresher would renew. A store outage answers no: a login must not+ fail over a renewal that is only an optimisation on top of signing in again."""+ try:+ check: Final = retention_enabled if retention_enabled is not None else ema_assertion_retention_enabled+ return await check()+ except Exception as exc: # noqa: BLE001 # the login must not fail over the renewal gate+ verbose_proxy_logger.debug("Could not check for oauth2_id_jag MCP servers before SSO login: %s", exc)+ return False++async def warn_if_id_jag_capture_gap(*, retention_enabled: RetentionCheck | None = None) -> None:gap: Final = id_jag_assertion_capture_gap()if gap is None:@@ -2125,6 +2142,50 @@ async def check_and_update_if_proxy_admin_id(user_role: str, user_id: str, prismreturn user_role+async def _sso_provider_callback(+ request: Request,+ redirect_url: str,+ *,+ google_client_id: str | None,+ microsoft_client_id: str | None,+ generic_client_id: str | None,+ jwt_handler: JWTHandler,+ sso_jwt_handler: JWTHandler | None,+ return_raw_sso_response: bool = False,+) -> tuple[+ OpenID | dict[str, object] | None, dict[str, object] | None, dict[str, object] | None, SSOIdentityAssertion | None+]:+ """Dispatch the callback to the configured provider in the order the login redirect used (Google,+ Microsoft, generic) and hand back what every branch has to agree on: the parsed identity, the raw+ userinfo and access-token claims only the generic branch exposes, and the IdP identity assertion+ an ``oauth2_id_jag`` MCP server spends. ``None`` identity means no provider is configured."""+ if google_client_id is not None:+ google_result, google_assertion = await GoogleSSOHandler.get_google_callback_response(+ request=request,+ google_client_id=google_client_id,+ redirect_url=redirect_url,+ return_raw_sso_response=return_raw_sso_response,+ )+ return google_result, None, None, google_assertion+ if microsoft_client_id is not None:+ microsoft_result, microsoft_assertion = await MicrosoftSSOHandler.get_microsoft_callback_response(+ request=request,+ microsoft_client_id=microsoft_client_id,+ redirect_url=redirect_url,+ return_raw_sso_response=return_raw_sso_response,+ )+ return microsoft_result, None, None, microsoft_assertion+ if generic_client_id is not None:+ return await get_generic_sso_response(+ request=request,+ jwt_handler=jwt_handler,+ generic_client_id=generic_client_id,+ redirect_url=redirect_url,+ sso_jwt_handler=sso_jwt_handler,+ )+ return None, None, None, None++@router.get("/sso/callback", tags=["experimental"], include_in_schema=False)async def auth_callback(request: Request, state: str | None = None):"""Verify login"""@@ -2173,9 +2234,6 @@ async def auth_callback(request: Request, state: str | None = None):microsoft_client_id: Final = os.getenv("MICROSOFT_CLIENT_ID", None)google_client_id: Final = os.getenv("GOOGLE_CLIENT_ID", None)generic_client_id: Final = os.getenv("GENERIC_CLIENT_ID", None)- received_response: dict | None = None- access_token_payload: dict | None = None- sso_assertion: SSOIdentityAssertion | None = None# get url from requestif master_key is None:raise ProxyException(@@ -2187,33 +2245,15 @@ async def auth_callback(request: Request, state: str | None = None):redirect_url = SSOAuthenticationHandler.get_redirect_url_for_sso(request=request, sso_callback_route="sso/callback")verbose_proxy_logger.info("Redirecting to %s", redirect_url)- result = None- if google_client_id is not None:- result = await GoogleSSOHandler.get_google_callback_response(- request=request,- google_client_id=google_client_id,- redirect_url=redirect_url,- )- elif microsoft_client_id is not None:- result = await MicrosoftSSOHandler.get_microsoft_callback_response(- request=request,- microsoft_client_id=microsoft_client_id,- redirect_url=redirect_url,- )-- elif generic_client_id is not None:- (- result,- received_response,- access_token_payload,- sso_assertion,- ) = await get_generic_sso_response(- request=request,- jwt_handler=jwt_handler,- generic_client_id=generic_client_id,- redirect_url=redirect_url,- sso_jwt_handler=sso_jwt_handler,- )+ result, received_response, access_token_payload, sso_assertion = await _sso_provider_callback(+ request,+ redirect_url,+ google_client_id=google_client_id,+ microsoft_client_id=microsoft_client_id,+ generic_client_id=generic_client_id,+ jwt_handler=jwt_handler,+ sso_jwt_handler=sso_jwt_handler,+ )if result is None:raise HTTPException(@@ -2915,8 +2955,8 @@ def _is_same_origin_return_path(return_to: str) -> bool:async def sso_return_to_redirect(return_to: str | None,jwt_token: str,- redis_usage_cache,- user_api_key_cache,+ redis_usage_cache: "RedisCache | None",+ user_api_key_cache: UserApiKeyCache,request: Request,) -> RedirectResponse | None:"""Resolve the post-SSO redirect for a ``return_to``, or None to fall through to the dashboard.@@ -3063,6 +3103,7 @@ class SSOAuthenticationHandler:generic_client_id: str | None = None,state: str | None = None,request: Request | None = None,+ retention_enabled: RetentionCheck | None = None,) -> RedirectResponse | None:"""Step 1. Call Get Login Redirect for the SSO provider. Send the redirect response to `redirect_url`@@ -3074,10 +3115,13 @@ class SSOAuthenticationHandler:generic_client_id (Optional[str], optional): The Generic Client ID. Defaults to None.request: Optional FastAPI request, used to drive the ``Secure``attribute on the ``litellm_oauth_state`` CSRF cookie.+ retention_enabled: Whether an ``oauth2_id_jag`` server exists, deciding if the Google and+ Microsoft logins ask the IdP for a refresh token. Defaults to the store's own check.Returns:RedirectResponse: The redirect response from the SSO provider."""+ asks_for_refresh_token: Final = await login_asks_for_refresh_token(retention_enabled)# Google SSO Authif google_client_id is not None:google_client_secret: Final = os.getenv("GOOGLE_CLIENT_SECRET", None)@@ -3099,7 +3143,10 @@ class SSOAuthenticationHandler:google_client_id,)with google_sso:- return await google_sso.get_login_redirect(state=state)+ return await google_sso.get_login_redirect(+ state=state,+ params=dict(GOOGLE_REFRESH_TOKEN_PARAMS) if asks_for_refresh_token else None,+ )# Microsoft SSO Authelif microsoft_client_id is not None:microsoft_client_secret: Final = os.getenv("MICROSOFT_CLIENT_SECRET", None)@@ -3117,6 +3164,7 @@ class SSOAuthenticationHandler:tenant=microsoft_tenant,redirect_uri=redirect_url,allow_insecure_http=True,+ scope=[*CustomMicrosoftSSO.scope, MICROSOFT_REFRESH_TOKEN_SCOPE] if asks_for_refresh_token else None,)with microsoft_sso:return await microsoft_sso.get_login_redirect(state=state)@@ -4399,6 +4447,21 @@ class SSOAuthenticationHandler:return userinfo+class _SSOTokenResponse(BaseModel):+ """The id_token and refresh token fastapi-sso keeps on the SSO instance after the code exchange,+ read through a validated view because the package ships no type information."""++ model_config = ConfigDict(frozen=True, from_attributes=True)++ id_token: str | None = None+ refresh_token: str | None = None++ @field_validator("id_token", "refresh_token", mode="before")+ @classmethod+ def _strings_only(cls, value: object) -> str | None:+ return value if isinstance(value, str) else None++class MicrosoftSSOHandler:"""Handles Microsoft SSO callback response and returns a CustomOpenID object@@ -4433,9 +4496,10 @@ class MicrosoftSSOHandler:microsoft_client_id: str,redirect_url: str,return_raw_sso_response: bool = False,- ) -> CustomOpenID | OpenID | dict:+ ) -> tuple[CustomOpenID | OpenID | dict[str, object], SSOIdentityAssertion | None]:"""- Get the Microsoft SSO callback response+ Get the Microsoft SSO callback response, with the IdP identity assertion the token+ response carried (the id_token and refresh token an ``oauth2_id_jag`` server spends)Args:return_raw_sso_response: If True, return the raw SSO response@@ -4470,6 +4534,8 @@ class MicrosoftSSOHandler:)or {})+ microsoft_tokens: Final = _SSOTokenResponse.model_validate(microsoft_sso)+ sso_assertion: Final = assertion_from_sso_login(microsoft_tokens.id_token, microsoft_tokens.refresh_token)if not return_raw_sso_response and "error" in original_msft_result and original_msft_result["error"]:verbose_proxy_logger.warning("Microsoft SSO login failed: Graph /me returned an error instead of a profile")raise HTTPException(@@ -4494,7 +4560,7 @@ class MicrosoftSSOHandler:if return_raw_sso_response:original_msft_result[MicrosoftSSOHandler.GRAPH_API_RESPONSE_KEY] = user_team_idsoriginal_msft_result["app_roles"] = app_roles- return original_msft_result or {}+ return original_msft_result or {}, sso_assertionfrom litellm.proxy.management_endpoints.sso.agent_subject_enrollment import microsoft_interactive_subject@@ -4517,7 +4583,7 @@ class MicrosoftSSOHandler:team_ids=user_team_ids,user_role=user_role,)- return result+ return result, sso_assertion@staticmethoddef openid_from_response(@@ -4793,9 +4859,10 @@ class GoogleSSOHandler:google_client_id: str,redirect_url: str,return_raw_sso_response: bool = False,- ) -> OpenID | dict:+ ) -> tuple[OpenID | dict[str, object], SSOIdentityAssertion | None]:"""- Get the Google SSO callback response+ Get the Google SSO callback response, with the IdP identity assertion the token+ response carried (the id_token and refresh token an ``oauth2_id_jag`` server spends)Args:return_raw_sso_response: If True, return the raw SSO response@@ -4816,17 +4883,13 @@ class GoogleSSOHandler:)# if user is trying to get the raw sso response for debugging, return the raw sso response- if return_raw_sso_response:- return (- await google_sso.verify_and_process(- request=request,- convert_response=False,- )- or {}- )-- result: Final = await google_sso.verify_and_process(request)- return result or {}+ result: Final = (+ await google_sso.verify_and_process(request=request, convert_response=False)+ if return_raw_sso_response+ else await google_sso.verify_and_process(request)+ )+ google_tokens: Final = _SSOTokenResponse.model_validate(google_sso)+ return result or {}, assertion_from_sso_login(google_tokens.id_token, google_tokens.refresh_token)def _raise_if_sso_debug_disabled() -> None:@@ -4928,37 +4991,16 @@ async def debug_sso_callback(request: Request):else:redirect_url += "/sso/debug/callback"- result = None- received_response: dict | None = None- access_token_payload: dict | None = None- if google_client_id is not None:- result = await GoogleSSOHandler.get_google_callback_response(- request=request,- google_client_id=google_client_id,- redirect_url=redirect_url,- return_raw_sso_response=True,- )- elif microsoft_client_id is not None:- result = await MicrosoftSSOHandler.get_microsoft_callback_response(- request=request,- microsoft_client_id=microsoft_client_id,- redirect_url=redirect_url,- return_raw_sso_response=True,- )-- elif generic_client_id is not None:- (- result,- received_response,- access_token_payload,- _sso_assertion,- ) = await get_generic_sso_response(- request=request,- jwt_handler=jwt_handler,- generic_client_id=generic_client_id,- redirect_url=redirect_url,- sso_jwt_handler=sso_jwt_handler,- )+ result, received_response, access_token_payload, _sso_assertion = await _sso_provider_callback(+ request,+ redirect_url,+ google_client_id=google_client_id,+ microsoft_client_id=microsoft_client_id,+ generic_client_id=generic_client_id,+ jwt_handler=jwt_handler,+ sso_jwt_handler=sso_jwt_handler,+ return_raw_sso_response=True,+ )# If result is None, return a basic error messageif result is None:diff --git a/tests/unit/proxy/_experimental/mcp_server/outbound_credentials/test_sso_assertion_refresher.py b/tests/unit/proxy/_experimental/mcp_server/outbound_credentials/test_sso_assertion_refresher.pyindex d80913f8d33..4197303fdd0 100644--- a/tests/unit/proxy/_experimental/mcp_server/outbound_credentials/test_sso_assertion_refresher.py+++ b/tests/unit/proxy/_experimental/mcp_server/outbound_credentials/test_sso_assertion_refresher.py@@ -694,6 +694,9 @@ async def test_the_in_process_coordinator_is_retried_until_redis_appears():{"GENERIC_TOKEN_ENDPOINT": TOKEN_ENDPOINT, "GENERIC_CLIENT_SECRET": "s"},{"GENERIC_TOKEN_ENDPOINT": TOKEN_ENDPOINT, "GENERIC_CLIENT_ID": "litellm"},{"GENERIC_TOKEN_ENDPOINT": "", "GENERIC_CLIENT_ID": "litellm", "GENERIC_CLIENT_SECRET": "s"},+ {"GOOGLE_CLIENT_ID": "google-cid"},+ {"MICROSOFT_CLIENT_ID": "ms-cid", "MICROSOFT_CLIENT_SECRET": "s"},+ {"MICROSOFT_CLIENT_ID": "ms-cid", "MICROSOFT_TENANT": "tenant"},],)def test_a_partial_sso_client_is_no_client(env):@@ -717,6 +720,64 @@ def test_the_configured_sso_client_is_the_one_the_login_used():assert config.client_secret.get_secret_value() == "s3cret"+def test_a_google_login_is_renewed_at_googles_token_endpoint_as_the_google_client():+ """fastapi-sso's Google login redeems the code at Google's token endpoint with HTTP Basic, so+ that is where and how the refresh token it handed back is redeemed."""+ config = sso_client_config({"GOOGLE_CLIENT_ID": "google-cid", "GOOGLE_CLIENT_SECRET": "google-secret"})++ assert config is not None+ assert config.token_endpoint == "https://oauth2.googleapis.com/token"+ assert config.client_id == "google-cid"+ assert config.client_secret.get_secret_value() == "google-secret"+ assert config.auth_method == "client_secret_basic"+++def test_a_microsoft_login_is_renewed_at_the_tenant_token_endpoint_as_the_microsoft_client():+ config = sso_client_config(+ {"MICROSOFT_CLIENT_ID": "ms-cid", "MICROSOFT_CLIENT_SECRET": "ms-secret", "MICROSOFT_TENANT": "tenant-123"}+ )++ assert config is not None+ assert config.token_endpoint == "https://login.microsoftonline.com/tenant-123/oauth2/v2.0/token"+ assert config.client_id == "ms-cid"+ assert config.client_secret.get_secret_value() == "ms-secret"+ assert config.auth_method == "client_secret_basic"+++def test_a_custom_microsoft_token_endpoint_wins_over_the_tenant_template():+ """``MICROSOFT_TOKEN_ENDPOINT`` is what the Microsoft login itself honours for sovereign+ clouds, so the renewal has to go to the same place."""+ config = sso_client_config(+ {+ "MICROSOFT_CLIENT_ID": "ms-cid",+ "MICROSOFT_CLIENT_SECRET": "ms-secret",+ "MICROSOFT_TENANT": "tenant-123",+ "MICROSOFT_TOKEN_ENDPOINT": "https://login.microsoftonline.us/tenant-123/oauth2/v2.0/token",+ }+ )++ assert config is not None+ assert config.token_endpoint == "https://login.microsoftonline.us/tenant-123/oauth2/v2.0/token"+++def test_the_client_follows_the_login_callbacks_provider_order():+ """A deployment carrying a Google and a generic client signs users in through Google, so the+ stored refresh token belongs to the Google client and only that client can redeem it."""+ config = sso_client_config(+ {+ "GOOGLE_CLIENT_ID": "google-cid",+ "GOOGLE_CLIENT_SECRET": "google-secret",+ "GENERIC_TOKEN_ENDPOINT": TOKEN_ENDPOINT,+ "GENERIC_CLIENT_ID": "litellm",+ "GENERIC_CLIENT_SECRET": "s3cret",+ }+ )++ assert config is not None+ assert config.client_id == "google-cid"+ assert config.token_endpoint == "https://oauth2.googleapis.com/token"++def test_the_live_store_renews_over_the_database_reader():"""The composition root has to produce a renewing store, or none of this runs in production."""assert isinstance(default_sso_assertion_store(), RefreshingSSOAssertionStore)diff --git a/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_manager.pyindex 536c1eb0b44..4961ca0cf42 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_manager.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_manager.py@@ -1641,9 +1641,9 @@ class TestMCPServerManager:assert server.oauth2_flow is None@pytest.mark.asyncio- async def test_load_servers_from_config_warns_for_id_jag_with_google_sso(self, monkeypatch, caplog):+ async def test_load_servers_from_config_warns_for_id_jag_with_saml_sso(self, monkeypatch, caplog):self._clear_sso_env(monkeypatch)- monkeypatch.setenv("GOOGLE_CLIENT_ID", "google-cid")+ monkeypatch.setenv("SAML_IDP_METADATA_URL", "https://idp.example.com/metadata")manager = MCPServerManager()with (patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=None)),@@ -1655,7 +1655,26 @@ class TestMCPServerManager:warnings = [message for message in caplog.messages if "oauth2_id_jag" in message]assert len(warnings) == 1assert "idjag_server" in warnings[0]- assert "GENERIC_CLIENT_ID" in warnings[0]+ assert "saml" in warnings[0]+ assert "MICROSOFT_CLIENT_ID" in warnings[0]++ @pytest.mark.asyncio+ @pytest.mark.parametrize("client_id_env", ["GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "GENERIC_CLIENT_ID"])+ async def test_load_servers_from_config_is_silent_for_id_jag_under_oidc_logins(+ self, monkeypatch, caplog, client_id_env+ ):+ """Every OIDC login captures the IdP id_token an id_jag server spends, so none of them is a gap."""+ self._clear_sso_env(monkeypatch)+ monkeypatch.setenv(client_id_env, "cid")+ manager = MCPServerManager()+ with (+ patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=None)),+ patch.object(manager, "hydrate_config_servers_dcr_clients", new=AsyncMock()),+ caplog.at_level(logging.WARNING, logger="LiteLLM"),+ ):+ await manager.load_servers_from_config(self._id_jag_config())++ assert not any("oauth2_id_jag" in message for message in caplog.messages)@pytest.mark.asyncioasync def test_load_servers_from_config_does_not_warn_for_id_jag_without_sso(self, monkeypatch, caplog):diff --git a/tests/unit/proxy/management_endpoints/test_id_jag_assertion_capture.py b/tests/unit/proxy/management_endpoints/test_id_jag_assertion_capture.pyindex ff4fbbfb695..2218473de6b 100644--- a/tests/unit/proxy/management_endpoints/test_id_jag_assertion_capture.py+++ b/tests/unit/proxy/management_endpoints/test_id_jag_assertion_capture.py@@ -49,8 +49,8 @@ class TestActiveSSOProviderMirrorsTheCallback:assert active_sso_provider() is ActiveSSOProvider.nonedef test_google_outranks_a_co_configured_generic_client(self, monkeypatch):- """The callback tests GOOGLE_CLIENT_ID first, so the generic arm never runs here and- no assertion is captured; reporting generic would clear a gap that is still open."""+ """The callback tests GOOGLE_CLIENT_ID first, so the generic arm never runs here and the+ assertion the refresher later renews was minted by the Google client, not the generic one."""monkeypatch.setenv("GOOGLE_CLIENT_ID", "google-cid")monkeypatch.setenv("GENERIC_CLIENT_ID", "generic-cid")assert active_sso_provider() is ActiveSSOProvider.google@@ -67,23 +67,20 @@ class TestActiveSSOProviderMirrorsTheCallback:class TestIdJagAssertionCaptureGap:- def test_generic_oidc_has_no_gap(self, monkeypatch):- monkeypatch.setenv("GENERIC_CLIENT_ID", "generic-cid")+ @pytest.mark.parametrize("env_var", ["GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "GENERIC_CLIENT_ID"])+ def test_every_oidc_login_captures_so_has_no_gap(self, monkeypatch, env_var):+ """Google, Microsoft and generic OIDC all read the id_token off the token response, so a+ deployment on any of them must not be told to switch providers."""+ monkeypatch.setenv(env_var, "configured")assert id_jag_assertion_capture_gap() is None- @pytest.mark.parametrize(- "env_var, provider_label",- [- ("GOOGLE_CLIENT_ID", "google"),- ("MICROSOFT_CLIENT_ID", "microsoft"),- ("SAML_IDP_METADATA_URL", "saml"),- ],- )- def test_non_capturing_provider_is_named_with_the_remedy(self, monkeypatch, env_var, provider_label):- monkeypatch.setenv(env_var, "configured")+ def test_saml_is_named_with_the_oidc_remedy(self, monkeypatch):+ monkeypatch.setenv("SAML_IDP_METADATA_URL", "https://idp.example.com/metadata")gap = id_jag_assertion_capture_gap()assert gap is not None- assert provider_label in gap+ assert "saml" in gap+ assert "GOOGLE_CLIENT_ID" in gap+ assert "MICROSOFT_CLIENT_ID" in gapassert "GENERIC_CLIENT_ID" in gapdef test_no_sso_configured_reports_a_gap(self):@@ -91,27 +88,26 @@ class TestIdJagAssertionCaptureGap:assert gap is not Noneassert "no SSO provider is configured" in gap- def test_google_beside_generic_still_reports_a_gap(self, monkeypatch):- """The precedence trap in operator terms: adding a generic client id without removing- GOOGLE_CLIENT_ID does not fix the deployment, so the gap must not clear."""- monkeypatch.setenv("GOOGLE_CLIENT_ID", "google-cid")- monkeypatch.setenv("GENERIC_CLIENT_ID", "generic-cid")- gap = id_jag_assertion_capture_gap()- assert gap is not None- assert "google" in gap+ def test_saml_beside_an_oidc_client_has_no_gap(self, monkeypatch):+ """The callback dispatches to the OIDC client before SAML, so that is the login that runs+ and it captures; reporting SAML's gap would tell the operator to fix a path nobody takes."""+ monkeypatch.setenv("MICROSOFT_CLIENT_ID", "ms-cid")+ monkeypatch.setenv("SAML_IDP_METADATA_URL", "https://idp.example.com/metadata")+ assert id_jag_assertion_capture_gap() is Noneclass TestIdJagAssertionCaptureGapAtStartup:def test_no_provider_at_startup_is_not_yet_a_gap(self):assert id_jag_assertion_capture_gap_at_startup() is None- def test_google_provider_at_startup_reports_the_capture_gap(self, monkeypatch):- monkeypatch.setenv("GOOGLE_CLIENT_ID", "google-cid")+ def test_saml_at_startup_reports_the_capture_gap(self, monkeypatch):+ monkeypatch.setenv("SAML_IDP_METADATA_URL", "https://idp.example.com/metadata")startup_gap = id_jag_assertion_capture_gap_at_startup()callback_gap = id_jag_assertion_capture_gap()assert startup_gap is not Noneassert startup_gap == callback_gap- def test_generic_provider_at_startup_has_no_gap(self, monkeypatch):- monkeypatch.setenv("GENERIC_CLIENT_ID", "generic-cid")+ @pytest.mark.parametrize("env_var", ["GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "GENERIC_CLIENT_ID"])+ def test_an_oidc_provider_at_startup_has_no_gap(self, monkeypatch, env_var):+ monkeypatch.setenv(env_var, "configured")assert id_jag_assertion_capture_gap_at_startup() is Nonediff --git a/tests/unit/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/unit/proxy/management_endpoints/test_mcp_management_endpoints.pyindex 47aea89843f..cd5d5e475dd 100644--- a/tests/unit/proxy/management_endpoints/test_mcp_management_endpoints.py+++ b/tests/unit/proxy/management_endpoints/test_mcp_management_endpoints.py@@ -4458,9 +4458,9 @@ class TestAddMCPServerAtomicity:class TestIdJagRegistrationWarnsAboutTheSSOGap:"""An `oauth2_id_jag` server only ever works when the login path captures an IdP identity- assertion, and only the generic OIDC arm does. Registering one under Google or Microsoft- succeeds and then fails for every user on every call, so the mismatch has to be said at- registration time, while the admin is still looking at the configuration."""+ assertion, and only the OIDC logins (Google, Microsoft, generic) do. Registering one under SAML+ or with no SSO succeeds and then fails for every user on every call, so the mismatch has to be+ said at registration time, while the admin is still looking at the configuration."""@staticmethoddef _clear_sso_env(monkeypatch):@@ -4530,8 +4530,6 @@ class TestIdJagRegistrationWarnsAboutTheSSOGap:@pytest.mark.parametrize("provider_env, expected_fragment",[- ({"GOOGLE_CLIENT_ID": "cid"}, "google"),- ({"MICROSOFT_CLIENT_ID": "cid"}, "microsoft"),({"SAML_IDP_METADATA_URL": "https://idp.example.com/metadata"}, "saml"),({}, "no SSO provider is configured"),],@@ -4546,8 +4544,9 @@ class TestIdJagRegistrationWarnsAboutTheSSOGap:assert "ema-1" in str(warnings[0])@pytest.mark.asyncio- async def test_create_is_silent_under_generic_oidc(self, monkeypatch, caplog):- await self._run_create(monkeypatch, {"GENERIC_CLIENT_ID": "cid"}, MCPAuth.oauth2_id_jag, caplog)+ @pytest.mark.parametrize("client_id_env", ["GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "GENERIC_CLIENT_ID"])+ async def test_create_is_silent_under_oidc_logins(self, monkeypatch, caplog, client_id_env):+ await self._run_create(monkeypatch, {client_id_env: "cid"}, MCPAuth.oauth2_id_jag, caplog)assert self._id_jag_warnings(caplog) == []@pytest.mark.asyncio@@ -4565,7 +4564,7 @@ class TestIdJagRegistrationWarnsAboutTheSSOGap:)self._clear_sso_env(monkeypatch)- monkeypatch.setenv("GOOGLE_CLIENT_ID", "cid")+ monkeypatch.setenv("SAML_IDP_METADATA_URL", "https://idp.example.com/metadata")mock_manager = MagicMock()mock_manager.update_server = AsyncMock()@@ -4602,7 +4601,7 @@ class TestIdJagRegistrationWarnsAboutTheSSOGap:warnings = self._id_jag_warnings(caplog)assert len(warnings) == 1- assert "google" in str(warnings[0])+ assert "saml" in str(warnings[0])class TestHealthCheckServers:diff --git a/tests/unit/proxy/management_endpoints/test_ui_sso.py b/tests/unit/proxy/management_endpoints/test_ui_sso.pyindex f69c069cfea..91a8d4f7101 100644--- a/tests/unit/proxy/management_endpoints/test_ui_sso.py+++ b/tests/unit/proxy/management_endpoints/test_ui_sso.py@@ -243,17 +243,24 @@ def test_get_microsoft_callback_response(stubbed_graph_api):"surname": "User",}+ id_token = _ema_id_token(sub="msft123")++ async def fake_verify(self, *args, **kwargs):+ self._id_token = id_token+ self._refresh_token = "msft-refresh-token"+ return mock_response+with patch.dict(os.environ,{"MICROSOFT_CLIENT_SECRET": "mock_secret", "MICROSOFT_TENANT": "mock_tenant"},):- mock_verify = AsyncMock(return_value=mock_response)- with patch(+ with patch( # test-quality-ok: stubs the upstream Microsoft IdP boundary, where the token response is read"fastapi_sso.sso.microsoft.MicrosoftSSO.verify_and_process",- new=mock_verify,+ autospec=True,+ side_effect=fake_verify,):# Act- result = asyncio.run(+ result, sso_assertion = asyncio.run(MicrosoftSSOHandler.get_microsoft_callback_response(request=mock_request,microsoft_client_id="mock_client_id",@@ -269,6 +276,11 @@ def test_get_microsoft_callback_response(stubbed_graph_api):assert result.id == "msft123"assert result.first_name == "Microsoft"assert result.last_name == "User"+ assert sso_assertion is not None+ assert sso_assertion.id_token.get_secret_value() == id_token+ assert sso_assertion.refresh_token is not None+ assert sso_assertion.refresh_token.get_secret_value() == "msft-refresh-token"+ assert sso_assertion.issuer == "https://idp.example.com"GRAPH_ERROR_BODIES: Final = (@@ -317,7 +329,7 @@ def test_get_microsoft_callback_response_signs_in_a_profile_with_an_empty_error_"fastapi_sso.sso.microsoft.MicrosoftSSO.verify_and_process",new=AsyncMock(return_value={**profile, "error": empty_error}),):- result = asyncio.run(+ result, _ = asyncio.run(MicrosoftSSOHandler.get_microsoft_callback_response(request=mock_request,microsoft_client_id="mock_client_id",@@ -342,7 +354,7 @@ def test_get_microsoft_callback_response_raw_sso_response_keeps_the_graph_error("fastapi_sso.sso.microsoft.MicrosoftSSO.verify_and_process",new=AsyncMock(return_value=dict(graph_error)),):- result = asyncio.run(+ result, _ = asyncio.run(MicrosoftSSOHandler.get_microsoft_callback_response(request=mock_request,microsoft_client_id="mock_client_id",@@ -376,7 +388,7 @@ def test_get_microsoft_callback_response_raw_sso_response(stubbed_graph_api):new=mock_verify,):# Act- result = asyncio.run(+ result, _ = asyncio.run(MicrosoftSSOHandler.get_microsoft_callback_response(request=mock_request,microsoft_client_id="mock_client_id",@@ -405,13 +417,19 @@ def test_get_google_callback_response():"family_name": "User",}+ id_token = _ema_id_token(sub="google123")++ async def fake_verify(self, *args, **kwargs):+ self._id_token = id_token+ self._refresh_token = None+ return mock_response+with patch.dict(os.environ, {"GOOGLE_CLIENT_SECRET": "mock_secret"}):- mock_verify = AsyncMock(return_value=mock_response)- with patch(- "fastapi_sso.sso.google.GoogleSSO.verify_and_process", new=mock_verify+ with patch( # test-quality-ok: stubs the upstream Google IdP boundary, where the token response is read+ "fastapi_sso.sso.google.GoogleSSO.verify_and_process", autospec=True, side_effect=fake_verify):# Act- result = asyncio.run(+ result, sso_assertion = asyncio.run(GoogleSSOHandler.get_google_callback_response(request=mock_request,google_client_id="mock_client_id",@@ -426,6 +444,9 @@ def test_get_google_callback_response():assert result.get("sub") == "google123"assert result.get("given_name") == "Google"assert result.get("family_name") == "User"+ assert sso_assertion is not None+ assert sso_assertion.id_token.get_secret_value() == id_token+ assert sso_assertion.refresh_token is None@pytest.mark.asyncio@@ -4018,7 +4039,13 @@ class TestCLIKeyRegenerationFlow:cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:cli-new-session-key-456"# Mock the CLI callback and required proxy server components+ from litellm.proxy._experimental.mcp_server.outbound_credentials.sso_assertion_store import (+ assertion_from_sso_login,+ )+mock_result = {"user_id": "test-user", "email": "[email protected]"}+ google_assertion = assertion_from_sso_login(_ema_id_token(sub="test-user"), None)+ assert google_assertion is not Nonewith (patch(@@ -4032,7 +4059,7 @@ class TestCLIKeyRegenerationFlow:patch.dict(os.environ, {"GOOGLE_CLIENT_ID": "test-google-id"}, clear=True),patch("litellm.proxy.management_endpoints.ui_sso.GoogleSSOHandler.get_google_callback_response",- return_value=mock_result,+ return_value=(mock_result, google_assertion),),):mock_cli_callback.return_value = MagicMock()@@ -4046,7 +4073,7 @@ class TestCLIKeyRegenerationFlow:prefill_user_code=None,result=mock_result,received_response=None,- sso_assertion=None,+ sso_assertion=google_assertion,)@pytest.mark.asyncio@@ -4074,7 +4101,7 @@ class TestCLIKeyRegenerationFlow:patch.dict(os.environ, {"GOOGLE_CLIENT_ID": "test-google-id"}, clear=True),patch("litellm.proxy.management_endpoints.ui_sso.GoogleSSOHandler.get_google_callback_response",- return_value=mock_result,+ return_value=(mock_result, None),),):mock_cli_callback.return_value = MagicMock()@@ -8836,7 +8863,7 @@ async def test_debug_sso_callback_handles_missing_raw_response():)async def fake_microsoft_callback(**kwargs):- return parsed_openid+ return parsed_openid, Nonewith (patch.dict(@@ -8886,7 +8913,7 @@ async def _render_debug_page(provider_env, id_jag_registered, force_inert=False)return parsed, {"sub": "user_123"}, {"scope": "openid"}, Noneasync def fake_google(**kwargs):- return parsed+ return parsed, Nonestack = [patch.dict(os.environ, {**provider_env, "ENABLE_SSO_DEBUG": "true"}, clear=False),@@ -8925,14 +8952,14 @@ async def _render_debug_page(provider_env, id_jag_registered, force_inert=False)@pytest.mark.asyncio-async def test_debug_page_logs_the_capture_gap_but_never_renders_it(caplog):+async def test_debug_page_logs_no_capture_gap_for_a_google_login(caplog):+ """Google reads the id_token off its token response like generic OIDC does, so the debug page+ under GOOGLE_CLIENT_ID with an oauth2_id_jag server registered has no gap to log and nothing+ to render about it."""with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):body = await _render_debug_page({"GOOGLE_CLIENT_ID": _GOOGLE_DEBUG_CLIENT_ID}, id_jag_registered=True)- warnings = _id_jag_gap_warnings(caplog)- assert len(warnings) == 1- assert "google" in warnings[0]- assert "GENERIC_CLIENT_ID" in warnings[0]+ assert _id_jag_gap_warnings(caplog) == []assert "id_jag" not in bodyassert "GENERIC_CLIENT_ID" not in body@@ -8977,7 +9004,7 @@ async def test_debug_page_survives_a_store_outage(monkeypatch, caplog):not the page."""from litellm.proxy.management_endpoints.ui_sso import warn_if_id_jag_capture_gap- monkeypatch.setenv("GOOGLE_CLIENT_ID", _GOOGLE_DEBUG_CLIENT_ID)+ monkeypatch.setenv("SAML_IDP_METADATA_URL", "https://idp.example.com/metadata")retention_check = AsyncMock(side_effect=Exception("db down"))with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):assert await warn_if_id_jag_capture_gap(retention_enabled=retention_check) is None@@ -9635,6 +9662,158 @@ async def test_redirect_from_openid_persists_assertion_under_canonical_user_id()assert response is not None+ "provider_env, sso_class, payload, needs_graph",+ [+ (+ {"MICROSOFT_CLIENT_ID": "ms-cid", "MICROSOFT_CLIENT_SECRET": "ms-secret", "MICROSOFT_TENANT": "tenant"},+ "fastapi_sso.sso.microsoft.MicrosoftSSO",+ {"mail": "[email protected]", "displayName": "U Ser", "id": "idp-subject"},+ True,+ ),+ (+ {"GOOGLE_CLIENT_ID": "google-cid", "GOOGLE_CLIENT_SECRET": "google-secret"},+ "fastapi_sso.sso.google.GoogleSSO",+ {"email": "[email protected]", "name": "U Ser", "sub": "idp-subject"},+ False,+ ),+ ],+)+async def test_ui_login_through_microsoft_or_google_hands_its_assertion_to_the_redirect(+ request, provider_env, sso_class, payload, needs_graph+):+ """The UI funnel used to capture an assertion only on the generic branch, so an ``oauth2_id_jag``+ server had nothing to spend for a deployment signing in through Entra or Google. The real+ Microsoft and Google handlers run here, only the IdP token exchange is stubbed, so the id_token+ and refresh token the IdP returned must reach the redirect that persists them."""+ from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler, auth_callback++ if needs_graph:+ request.getfixturevalue("stubbed_graph_api")+ id_token = _ema_id_token(sub="idp-subject")++ async def fake_verify(self, *args, **kwargs):+ self._id_token = id_token+ self._refresh_token = "idp-refresh"+ return payload++ mock_request = MagicMock(spec=Request)+ mock_request.query_params = {"code": "auth-code"}+ mock_request.cookies = {}+ mock_request.scope = {}+ mock_request.base_url = "http://localhost:4000/"+ redirect_mock = AsyncMock(return_value=MagicMock())++ with (+ patch.dict(os.environ, provider_env, clear=True),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.master_key", "sk-master"),+ patch("litellm.proxy.proxy_server.general_settings", {}),+ patch("litellm.proxy.proxy_server.jwt_handler", MagicMock()),+ patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),+ patch( # test-quality-ok: stubs the upstream IdP token exchange, where the token response is read+ f"{sso_class}.verify_and_process", autospec=True, side_effect=fake_verify+ ),+ patch.object( # test-quality-ok: the DB and key-mint boundary after the login, asserted on its inputs+ SSOAuthenticationHandler, "get_redirect_response_from_openid", redirect_mock+ ),+ ):+ await auth_callback(request=mock_request, state=None)++ redirect_mock.assert_awaited_once()+ assert redirect_mock.await_args.kwargs["result"] is not None+ sso_assertion = redirect_mock.await_args.kwargs["sso_assertion"]+ assert sso_assertion is not None+ assert sso_assertion.id_token.get_secret_value() == id_token+ assert sso_assertion.refresh_token is not None+ assert sso_assertion.refresh_token.get_secret_value() == "idp-refresh"+++ "retention_enabled, expected_params",+ [+ (AsyncMock(return_value=True), {"access_type": "offline", "prompt": "consent"}),+ (AsyncMock(return_value=False), None),+ (AsyncMock(side_effect=RuntimeError("store down")), None),+ ],+)+async def test_google_login_asks_for_a_refresh_token_only_while_an_id_jag_server_exists(+ retention_enabled, expected_params+):+ """Google issues a refresh token only when the authorization request carries ``access_type=offline``,+ and the refresher cannot renew a Google assertion without one. The login asks only while an+ ``oauth2_id_jag`` server exists, and a store outage must not fail the login or add the consent."""+ from fastapi.responses import RedirectResponse++ from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler++ seen: dict[str, object] = {}++ async def fake_redirect(self, *, redirect_uri=None, params=None, state=None):+ seen["params"] = params+ return RedirectResponse(url="https://accounts.google.com/o/oauth2/v2/auth")++ with (+ patch.dict(os.environ, {"GOOGLE_CLIENT_SECRET": "google-secret"}),+ patch( # test-quality-ok: stubs the upstream Google authorization boundary, where the request leaves+ "fastapi_sso.sso.google.GoogleSSO.get_login_redirect", autospec=True, side_effect=fake_redirect+ ),+ ):+ response = await SSOAuthenticationHandler.get_sso_login_redirect(+ redirect_url="http://localhost:4000/sso/callback",+ google_client_id="google-cid",+ retention_enabled=retention_enabled,+ )++ assert response is not None+ assert seen["params"] == expected_params+++ "retention_enabled, asks_offline_access",+ [+ (AsyncMock(return_value=True), True),+ (AsyncMock(return_value=False), False),+ (AsyncMock(side_effect=RuntimeError("store down")), False),+ ],+)+async def test_microsoft_login_asks_for_offline_access_only_while_an_id_jag_server_exists(+ retention_enabled, asks_offline_access+):+ """Entra issues a refresh token only when ``offline_access`` is in the requested scope, and the+ refresher cannot renew an Entra assertion without one. The default sign-in scopes stay in place so+ the login keeps resolving the same profile."""+ from fastapi.responses import RedirectResponse+ from fastapi_sso.sso.microsoft import MicrosoftSSO++ from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler++ seen: dict[str, object] = {}++ async def fake_redirect(self, *, redirect_uri=None, params=None, state=None):+ seen["scope"] = list(self._scope)+ return RedirectResponse(url="https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize")++ with (+ patch.dict(os.environ, {"MICROSOFT_CLIENT_SECRET": "ms-secret", "MICROSOFT_TENANT": "tenant"}),+ patch( # test-quality-ok: stubs the upstream Entra authorization boundary, where the request leaves+ "fastapi_sso.sso.microsoft.MicrosoftSSO.get_login_redirect", autospec=True, side_effect=fake_redirect+ ),+ ):+ response = await SSOAuthenticationHandler.get_sso_login_redirect(+ redirect_url="http://localhost:4000/sso/callback",+ microsoft_client_id="ms-cid",+ retention_enabled=retention_enabled,+ )++ assert response is not None+ assert all(default in seen["scope"] for default in MicrosoftSSO.scope), seen["scope"]+ assert ("offline_access" in seen["scope"]) is asks_offline_access, seen["scope"]++@pytest.mark.asyncioasync def test_cli_completion_persists_assertion_under_db_user_id():"""The CLI funnel persists the captured assertion under the DB-resolved user_id."""@@ -9710,8 +9889,7 @@ def _id_jag_gap_warnings(caplog) -> list[str]:@pytest.mark.parametrize("provider_env, expected_fragment",[- ({"GOOGLE_CLIENT_ID": "cid"}, "google"),- ({"MICROSOFT_CLIENT_ID": "cid", "MICROSOFT_TENANT": "t"}, "microsoft"),+ ({"SAML_IDP_METADATA_URL": "https://idp.example.com/metadata"}, "saml"),({}, "no SSO provider is configured"),],)@@ -9738,16 +9916,17 @@ async def test_uncaptured_assertion_warns_when_an_id_jag_server_is_registered(@pytest.mark.asyncio-async def test_generic_provider_that_returned_no_id_token_still_warns(monkeypatch, caplog):- """Generic OIDC has a capture path, so there is no configuration gap to report; the login- still handed the id_jag arm nothing, and that must not pass silently."""[email protected]("provider_env_var", ["GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "GENERIC_CLIENT_ID"])+async def test_a_capturing_provider_that_returned_no_id_token_still_warns(monkeypatch, caplog, provider_env_var):+ """Google, Microsoft and generic OIDC all have a capture path, so there is no configuration gap+ to report; the login still handed the id_jag arm nothing, and that must not pass silently."""from litellm.proxy.management_endpoints.ui_sso import (warn_if_id_jag_assertion_uncaptured,)- for name in ("GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "SAML_IDP_METADATA_URL"):+ for name in ("GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "GENERIC_CLIENT_ID", "SAML_IDP_METADATA_URL"):monkeypatch.delenv(name, raising=False)- monkeypatch.setenv("GENERIC_CLIENT_ID", "cid")+ monkeypatch.setenv(provider_env_var, "cid")with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):await warn_if_id_jag_assertion_uncaptured(None, retention_enabled=AsyncMock(return_value=True))@@ -9875,7 +10054,7 @@ async def test_browser_funnel_reports_an_uncaptured_assertion(monkeypatch, caplowarnings = _id_jag_gap_warnings(caplog)assert len(warnings) == 1- assert "google" in str(warnings[0])+ assert "no usable id_token" in str(warnings[0])@pytest.mark.asyncio@@ -9939,7 +10118,7 @@ async def test_cli_funnel_reports_an_uncaptured_assertion(monkeypatch, caplog):warnings = _id_jag_gap_warnings(caplog)assert len(warnings) == 1- assert "microsoft" in str(warnings[0])+ assert "no usable id_token" in str(warnings[0])def _cli_callback_kwargs(flow):