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(proxy): route SSO token exchange and userinfo calls through litellm's httpx client (#46547)

Yassin Kortam40e27812a788
diff --git a/litellm/proxy/management_endpoints/sso/__init__.py b/litellm/proxy/management_endpoints/sso/__init__.py
index 0f77e84cefe..eaa33bd8dd9 100644
--- a/litellm/proxy/management_endpoints/sso/__init__.py
+++ b/litellm/proxy/management_endpoints/sso/__init__.py
@@ -7,5 +7,10 @@ This package contains custom SSO implementations and utilities.
from litellm.proxy.management_endpoints.sso.custom_microsoft_sso import (
CustomMicrosoftSSO,
)
+from litellm.proxy.management_endpoints.sso.litellm_http_client_sso import (
+ LiteLLMGoogleSSO,
+ LiteLLMHttpClientSSO,
+ create_generic_sso_provider,
+)
-__all__ = ["CustomMicrosoftSSO"]
+__all__ = ["CustomMicrosoftSSO", "LiteLLMGoogleSSO", "LiteLLMHttpClientSSO", "create_generic_sso_provider"]
diff --git a/litellm/proxy/management_endpoints/sso/custom_microsoft_sso.py b/litellm/proxy/management_endpoints/sso/custom_microsoft_sso.py
index 6075a6aa1f6..dd4a3d3df9e 100644
--- a/litellm/proxy/management_endpoints/sso/custom_microsoft_sso.py
+++ b/litellm/proxy/management_endpoints/sso/custom_microsoft_sso.py
@@ -21,9 +21,10 @@ from fastapi_sso.sso.base import DiscoveryDocument
from fastapi_sso.sso.microsoft import MicrosoftSSO
from litellm._logging import verbose_proxy_logger
+from litellm.proxy.management_endpoints.sso.litellm_http_client_sso import LiteLLMHttpClientSSO
-class CustomMicrosoftSSO(MicrosoftSSO):
+class CustomMicrosoftSSO(LiteLLMHttpClientSSO, MicrosoftSSO):
"""
Microsoft SSO subclass that allows overriding default endpoints via environment variables.
diff --git a/litellm/proxy/management_endpoints/sso/litellm_http_client_sso.py b/litellm/proxy/management_endpoints/sso/litellm_http_client_sso.py
new file mode 100644
index 00000000000..90c0f490e61
--- /dev/null
+++ b/litellm/proxy/management_endpoints/sso/litellm_http_client_sso.py
@@ -0,0 +1,217 @@
+# pyright: reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false
+# pyright: reportUnknownParameterType=false, reportUntypedBaseClass=false
+# fastapi_sso (a proxy extra) and oauthlib are not installed in the type-check gate venv, so pyright sees them as Unknown
+"""fastapi_sso providers whose IdP requests go through litellm's configured httpx client.
+
+fastapi_sso opens a bare ``httpx.AsyncClient()`` for the token exchange and the userinfo call, so
+``ssl_verify``, ``SSL_VERIFY`` and ``SSL_CERT_FILE`` were ignored on every non-PKCE SSO login.
+"""
+
+import json
+import warnings
+from collections.abc import Awaitable, Callable, Mapping
+from dataclasses import dataclass
+from typing import Final, Literal, overload
+
+import httpx
+import jwt
+from fastapi import Request, status
+from fastapi_sso.sso.base import DiscoveryDocument, OpenID, ReusedOauthClientWarning, SSOBase, SSOLoginError
+from fastapi_sso.sso.generic import create_provider
+from fastapi_sso.sso.google import GoogleSSO
+from pydantic import TypeAdapter
+
+from litellm._logging import verbose_proxy_logger
+from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+from litellm.proxy._types import ProxyErrorTypes, ProxyException
+from litellm.types.llms.custom_http import httpxSpecialProvider
+
+_IDP_REQUEST_TIMEOUT_SECONDS: Final = 30.0
+_JSON_OBJECT: Final = TypeAdapter(dict[str, object])
+_STRING_HEADERS: Final = TypeAdapter(dict[str, str])
+
+
+@dataclass(frozen=True, slots=True)
+class _DiscoveryEndpoints:
+ authorization_endpoint: str
+ token_endpoint: str
+ userinfo_endpoint: str
+
+
+_DISCOVERY_ENDPOINTS: Final = TypeAdapter(_DiscoveryEndpoints)
+
+
+_TOKEN_REQUEST: Final = TypeAdapter(tuple[str, dict[str, str], str])
+_USERINFO_REQUEST: Final = TypeAdapter(tuple[str, dict[str, str], str | None])
+
+
+def _sso_http_client() -> httpx.AsyncClient:
+ return get_async_httpx_client(llm_provider=httpxSpecialProvider.SSO_HANDLER).client
+
+
+def _optional_str(value: object) -> str | None:
+ return value if isinstance(value, str) else None
+
+
+def _required_endpoint(endpoint: str | None, name: str) -> str:
+ if endpoint is None:
+ raise SSOLoginError(500, f"SSO provider has no {name}")
+ return endpoint
+
+
+async def _send_or_raise(request: Awaitable[httpx.Response], endpoint: str, param: str) -> httpx.Response:
+ try:
+ return await request
+ except httpx.HTTPError as exc:
+ verbose_proxy_logger.error("SSO request to %s failed: %s", endpoint, exc)
+ raise ProxyException(
+ message=f"SSO request to {endpoint} failed: {exc}",
+ type=ProxyErrorTypes.auth_error,
+ param=param,
+ code=status.HTTP_401_UNAUTHORIZED,
+ ) from exc
+
+
+class LiteLLMHttpClientSSO(SSOBase):
+ """Mixin that replays fastapi_sso's login exchange on litellm's shared SSO httpx client."""
+
+ @overload
+ async def process_login(
+ self,
+ code: str,
+ request: Request,
+ *,
+ params: Mapping[str, object] | None = None,
+ additional_headers: Mapping[str, object] | None = None,
+ redirect_uri: str | None = None,
+ pkce_code_verifier: str | None = None,
+ convert_response: Literal[True] = True,
+ ) -> OpenID | None: ...
+
+ @overload
+ async def process_login(
+ self,
+ code: str,
+ request: Request,
+ *,
+ params: Mapping[str, object] | None = None,
+ additional_headers: Mapping[str, object] | None = None,
+ redirect_uri: str | None = None,
+ pkce_code_verifier: str | None = None,
+ convert_response: Literal[False],
+ ) -> dict[str, object] | None: ... # mutable-ok: fastapi_sso returns the raw userinfo dict
+
+ async def process_login(
+ self,
+ code: str,
+ request: Request,
+ *,
+ params: Mapping[str, object] | None = None,
+ additional_headers: Mapping[str, object] | None = None,
+ redirect_uri: str | None = None,
+ pkce_code_verifier: str | None = None,
+ convert_response: bool = True,
+ ) -> OpenID | dict[str, object] | None: # mutable-ok: fastapi_sso returns the raw userinfo dict
+ self._forget_reused_oauth_client()
+ token_params: Final = {
+ **(params or {}),
+ **_JSON_OBJECT.validate_python(self._extra_query_params),
+ **({"code_verifier": pkce_code_verifier} if pkce_code_verifier else {}),
+ }
+ extra_headers: Final = _STRING_HEADERS.validate_python(
+ {**(additional_headers or {}), **(self.additional_headers or {})}
+ )
+ callback_url: Final = str(request.url)
+ authorization_response: Final = (
+ callback_url
+ if self.allow_insecure_http or request.url.scheme == "https"
+ else callback_url.replace("http://", "https://")
+ )
+ callback_path: Final = f"{request.url.scheme}://{request.url.netloc}{request.url.path}"
+ token_url, token_headers, body = _TOKEN_REQUEST.validate_python(
+ self.oauth_client.prepare_token_request(
+ _required_endpoint(await self.token_endpoint, "token_endpoint"),
+ authorization_response=authorization_response,
+ redirect_url=redirect_uri or (str(self.redirect_uri) if self.redirect_uri else callback_path),
+ code=code,
+ **token_params, # pyright: ignore[reportArgumentType] # oauthlib stubs type the kwargs slots as str
+ )
+ )
+ client: Final = _sso_http_client()
+ token_response: Final = await _send_or_raise(
+ client.post(
+ token_url,
+ headers={**token_headers, **extra_headers},
+ content=body,
+ auth=httpx.BasicAuth(self.client_id, self.client_secret),
+ timeout=_IDP_REQUEST_TIMEOUT_SECONDS,
+ ),
+ endpoint=token_url,
+ param="token_exchange",
+ )
+ token_content: Final = _JSON_OBJECT.validate_python(token_response.json())
+ self._refresh_token = _optional_str(token_content.get("refresh_token"))
+ self._id_token = _optional_str(token_content.get("id_token"))
+ self.oauth_client.parse_request_body_response(json.dumps(token_content))
+ userinfo_url, userinfo_headers, _ = _USERINFO_REQUEST.validate_python(
+ self.oauth_client.add_token(_required_endpoint(await self.userinfo_endpoint, "userinfo_endpoint"))
+ )
+ userinfo_response: Final = await _send_or_raise(
+ client.get(
+ userinfo_url, headers={**userinfo_headers, **extra_headers}, timeout=_IDP_REQUEST_TIMEOUT_SECONDS
+ ),
+ endpoint=userinfo_url,
+ param="userinfo",
+ )
+ userinfo: Final = _JSON_OBJECT.validate_python(userinfo_response.json())
+ if not convert_response:
+ return userinfo
+ if not self.use_id_token_for_user_info:
+ return await self.openid_from_response(userinfo, client)
+ if not self._id_token:
+ raise SSOLoginError(401, f"Provider {self.provider!r} did not return id token.")
+ id_token_claims: Final = _JSON_OBJECT.validate_python(
+ jwt.decode(self._id_token, options={"verify_signature": False})
+ )
+ return await self.openid_from_token(id_token_claims, client)
+
+ def _forget_reused_oauth_client(self) -> None:
+ if self._oauth_client is None:
+ return
+ self._oauth_client = None
+ self._refresh_token = None
+ self._id_token = None
+ warnings.warn(
+ "Reusing the SSO object is not safe and caused a security issue in previous versions. "
+ "To make sure you don't see this warning, please use the SSO object as a context manager.",
+ ReusedOauthClientWarning,
+ )
+
+
+class LiteLLMGoogleSSO(LiteLLMHttpClientSSO, GoogleSSO):
+ async def get_discovery_document(self) -> DiscoveryDocument:
+ response: Final = await _send_or_raise(
+ _sso_http_client().get(self.discovery_url, timeout=_IDP_REQUEST_TIMEOUT_SECONDS),
+ endpoint=self.discovery_url,
+ param="discovery_document",
+ )
+ endpoints: Final = _DISCOVERY_ENDPOINTS.validate_python(response.json())
+ return DiscoveryDocument(
+ authorization_endpoint=endpoints.authorization_endpoint,
+ token_endpoint=endpoints.token_endpoint,
+ userinfo_endpoint=endpoints.userinfo_endpoint,
+ )
+
+
+def create_generic_sso_provider(
+ *,
+ name: str,
+ discovery_document: DiscoveryDocument,
+ response_convertor: Callable[[Mapping[str, object], httpx.AsyncClient | None], OpenID],
+) -> type[SSOBase]:
+ provider: Final = create_provider(
+ name=name,
+ discovery_document=discovery_document,
+ response_convertor=response_convertor,
+ )
+ return type(f"LiteLLM{provider.__name__}", (LiteLLMHttpClientSSO, provider), {})
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 16e62513b7f..c5b4940b384 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -112,7 +112,7 @@ from litellm.proxy.common_utils.html_forms.ui_login import build_ui_login_form
from litellm.proxy.common_utils.user_api_key_cache import AUTH_OBJECTS_TARGET, UserApiKeyCache
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.management_endpoints.internal_user_endpoints import new_user
-from litellm.proxy.management_endpoints.sso import CustomMicrosoftSSO
+from litellm.proxy.management_endpoints.sso import CustomMicrosoftSSO, LiteLLMGoogleSSO, create_generic_sso_provider
from litellm.proxy.management_endpoints.sso.id_jag_assertion_capture import (
id_jag_assertion_capture_gap,
)
@@ -1569,7 +1569,6 @@ async def get_generic_sso_response(
]: # (result, received_response, access_token_payload, sso_assertion)
# make generic sso provider
from fastapi_sso.sso.base import DiscoveryDocument
- from fastapi_sso.sso.generic import create_provider
received_response: dict | None = None
sso_assertion: SSOIdentityAssertion | None = None
@@ -1624,7 +1623,7 @@ async def get_generic_sso_response(
team_mappings=team_mappings,
)
- SSOProvider: Final = create_provider(
+ SSOProvider: Final = create_generic_sso_provider(
name="oidc",
discovery_document=discovery,
response_convertor=response_convertor,
@@ -3081,8 +3080,6 @@ class SSOAuthenticationHandler:
"""
# Google SSO Auth
if google_client_id is not None:
- from fastapi_sso.sso.google import GoogleSSO
-
google_client_secret: Final = os.getenv("GOOGLE_CLIENT_SECRET", None)
if google_client_secret is None:
raise ProxyException(
@@ -3091,7 +3088,7 @@ class SSOAuthenticationHandler:
param="GOOGLE_CLIENT_SECRET",
code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
- google_sso: Final = GoogleSSO(
+ google_sso: Final = LiteLLMGoogleSSO(
client_id=google_client_id,
client_secret=google_client_secret,
redirect_uri=redirect_url,
@@ -4803,7 +4800,6 @@ class GoogleSSOHandler:
Args:
return_raw_sso_response: If True, return the raw SSO response
"""
- from fastapi_sso.sso.google import GoogleSSO
google_client_secret: Final = os.getenv("GOOGLE_CLIENT_SECRET", None)
if google_client_secret is None:
@@ -4813,7 +4809,7 @@ class GoogleSSOHandler:
param="GOOGLE_CLIENT_SECRET",
code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
- google_sso: Final = GoogleSSO(
+ google_sso: Final = LiteLLMGoogleSSO(
client_id=google_client_id,
redirect_uri=redirect_url,
client_secret=google_client_secret,
diff --git a/tests/unit/proxy/management_endpoints/sso/test_litellm_http_client_sso.py b/tests/unit/proxy/management_endpoints/sso/test_litellm_http_client_sso.py
new file mode 100644
index 00000000000..54be0693bf5
--- /dev/null
+++ b/tests/unit/proxy/management_endpoints/sso/test_litellm_http_client_sso.py
@@ -0,0 +1,263 @@
+import datetime
+import ipaddress
+import json
+import ssl
+import threading
+from collections.abc import Callable, Iterator, Mapping
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Final
+
+import pytest
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.x509.oid import NameOID
+from fastapi import Request
+from fastapi_sso.sso.base import DiscoveryDocument, OpenID, SSOBase
+
+import litellm
+from litellm.caching.llm_caching_handler import LLMClientCache
+from litellm.llms.custom_httpx.http_handler import (
+ get_async_httpx_client, # pyright: ignore[reportUnknownVariableType] # params is an untyped dict
+)
+from litellm.proxy._types import ProxyException
+from litellm.proxy.management_endpoints.sso import (
+ CustomMicrosoftSSO,
+ LiteLLMGoogleSSO,
+ create_generic_sso_provider,
+)
+from litellm.types.llms.custom_http import httpxSpecialProvider
+
+_ACCESS_TOKEN: Final = "idp-access-token"
+_USERINFO: Final = {
+ "sub": "u-9445",
+ "id": "u-9445",
+ "email": "[email protected]",
+ "email_verified": True,
+ "mail": "[email protected]",
+}
+
+
+@dataclass(slots=True)
+class _SelfSignedIdP:
+ base_url: str
+ requests: list[tuple[str, str, dict[str, str], str]] = field(default_factory=list)
+
+
+def _write_self_signed_cert(directory: Path) -> tuple[Path, Path]:
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")])
+ now = datetime.datetime.now(datetime.UTC)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(name)
+ .issuer_name(name)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(days=1))
+ .not_valid_after(now + datetime.timedelta(days=1))
+ .add_extension(
+ x509.SubjectAlternativeName([x509.IPAddress(ipaddress.IPv4Address("127.0.0.1"))]), critical=False
+ )
+ .sign(key, hashes.SHA256())
+ )
+ cert_path = directory / "cert.pem"
+ key_path = directory / "key.pem"
+ cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
+ key_path.write_bytes(
+ key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ )
+ )
+ return cert_path, key_path
+
+
+def self_signed_idp(tmp_path: Path) -> Iterator[_SelfSignedIdP]:
+ """An HTTPS IdP on 127.0.0.1 whose certificate no trust store knows, like an internal-CA IdP."""
+ cert_path, key_path = _write_self_signed_cert(tmp_path)
+ idp = _SelfSignedIdP(base_url="")
+
+ class Handler(BaseHTTPRequestHandler):
+ def _reply(self, body: Mapping[str, object]) -> None:
+ data = json.dumps(body).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_POST(self) -> None:
+ body = self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode()
+ idp.requests.append(("POST", self.path, {k.lower(): v for k, v in self.headers.items()}, body))
+ self._reply({"access_token": _ACCESS_TOKEN, "token_type": "Bearer", "expires_in": 3600})
+
+ def do_GET(self) -> None:
+ idp.requests.append(("GET", self.path, {k.lower(): v for k, v in self.headers.items()}, ""))
+ if self.path == "/discovery":
+ self._reply(
+ {
+ "authorization_endpoint": f"{idp.base_url}/authorize",
+ "token_endpoint": f"{idp.base_url}/token",
+ "userinfo_endpoint": f"{idp.base_url}/userinfo",
+ }
+ )
+ return
+ self._reply(_USERINFO)
+
+ def log_message(self, format: str, *args: object) -> None: # matches BaseHTTPRequestHandler
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(cert_path, key_path)
+ server.socket = context.wrap_socket(server.socket, server_side=True)
+ idp.base_url = f"https://127.0.0.1:{server.server_address[1]}"
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield idp
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def fresh_sso_http_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ """A new litellm client cache so the SSO client is built from this test's TLS settings."""
+ monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", LLMClientCache())
+ monkeypatch.delenv("SSL_VERIFY", raising=False)
+ monkeypatch.delenv("SSL_CERT_FILE", raising=False)
+ yield
+
+
+def _callback_request(code: str = "abc") -> Request:
+ return Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "scheme": "https",
+ "server": ("proxy.example.com", 443),
+ "path": "/sso/callback",
+ "query_string": f"code={code}".encode(),
+ "headers": [],
+ }
+ )
+
+
+def _generic_provider(idp: _SelfSignedIdP, _monkeypatch: pytest.MonkeyPatch) -> SSOBase:
+ provider = create_generic_sso_provider(
+ name="oidc",
+ discovery_document=DiscoveryDocument(
+ authorization_endpoint=f"{idp.base_url}/authorize",
+ token_endpoint=f"{idp.base_url}/token",
+ userinfo_endpoint=f"{idp.base_url}/userinfo",
+ ),
+ response_convertor=lambda userinfo, _session: OpenID(
+ id=str(userinfo["sub"]), email=str(userinfo["email"]), provider="oidc"
+ ),
+ )
+ return provider(
+ client_id="litellm-ui",
+ client_secret="s3cret",
+ redirect_uri="https://proxy.example.com/sso/callback",
+ allow_insecure_http=True,
+ )
+
+
+def _google_provider(idp: _SelfSignedIdP, _monkeypatch: pytest.MonkeyPatch) -> SSOBase:
+ sso = LiteLLMGoogleSSO(
+ client_id="litellm-ui", client_secret="s3cret", redirect_uri="https://proxy.example.com/sso/callback"
+ )
+ sso.discovery_url = f"{idp.base_url}/discovery"
+ return sso
+
+
+def _microsoft_provider(idp: _SelfSignedIdP, monkeypatch: pytest.MonkeyPatch) -> SSOBase:
+ monkeypatch.setenv("MICROSOFT_AUTHORIZATION_ENDPOINT", f"{idp.base_url}/authorize")
+ monkeypatch.setenv("MICROSOFT_TOKEN_ENDPOINT", f"{idp.base_url}/token")
+ monkeypatch.setenv("MICROSOFT_USERINFO_ENDPOINT", f"{idp.base_url}/userinfo")
+ return CustomMicrosoftSSO(
+ client_id="litellm-ui",
+ client_secret="s3cret",
+ redirect_uri="https://proxy.example.com/sso/callback",
+ tenant="common",
+ )
+
+
+_PROVIDERS: Final = {
+ "generic": _generic_provider,
+ "google": _google_provider,
+ "microsoft": _microsoft_provider,
+}
+
+
[email protected]("build_provider", _PROVIDERS.values(), ids=_PROVIDERS.keys())
+async def test_login_honours_litellm_ssl_verify_against_self_signed_idp(
+ build_provider: Callable[[_SelfSignedIdP, pytest.MonkeyPatch], SSOBase],
+ self_signed_idp: _SelfSignedIdP,
+ fresh_sso_http_client: None,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Regression for LIT-9445: the token exchange and userinfo call went out on a bare httpx client,
+ so an IdP on an internal CA failed with CERTIFICATE_VERIFY_FAILED even with litellm.ssl_verify=False."""
+ monkeypatch.setattr(litellm, "ssl_verify", False)
+ sso = build_provider(self_signed_idp, monkeypatch)
+
+ result = await sso.verify_and_process(_callback_request(code="code-9445"))
+
+ assert result is not None
+ assert result.email == "[email protected]"
+ assert result.id == "u-9445"
+ assert sso.access_token == _ACCESS_TOKEN
+ token_requests = [body for _method, path, _headers, body in self_signed_idp.requests if path == "/token"]
+ assert len(token_requests) == 1
+ assert "code=code-9445" in token_requests[0]
+ assert "grant_type=authorization_code" in token_requests[0]
+ userinfo_headers = [headers for _method, path, headers, _body in self_signed_idp.requests if path == "/userinfo"]
+ assert len(userinfo_headers) == 1
+ assert userinfo_headers[0]["authorization"] == f"Bearer {_ACCESS_TOKEN}"
+ await get_async_httpx_client(llm_provider=httpxSpecialProvider.SSO_HANDLER).client.aclose()
+
+
+async def test_login_does_not_leave_the_bearer_token_on_the_shared_client(
+ self_signed_idp: _SelfSignedIdP,
+ fresh_sso_http_client: None,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The SSO client is shared across logins, so one user's bearer token must not stick to it."""
+ monkeypatch.setattr(litellm, "ssl_verify", False)
+ sso = _generic_provider(self_signed_idp, monkeypatch)
+
+ await sso.verify_and_process(_callback_request())
+
+ client = get_async_httpx_client(llm_provider=httpxSpecialProvider.SSO_HANDLER).client
+ assert "authorization" not in client.headers
+ await client.aclose()
+
+
+async def test_untrusted_idp_certificate_fails_closed_naming_the_token_endpoint(
+ self_signed_idp: _SelfSignedIdP,
+ fresh_sso_http_client: None,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """With verification on, an untrusted IdP certificate is a ProxyException that names the endpoint
+ and the TLS error, not a bare httpx error that the proxy reports as an internal or database error."""
+ monkeypatch.setattr(litellm, "ssl_verify", True)
+ sso = _generic_provider(self_signed_idp, monkeypatch)
+
+ with pytest.raises(ProxyException) as exc_info:
+ await sso.verify_and_process(_callback_request())
+
+ assert str(exc_info.value.code) == "401"
+ assert f"{self_signed_idp.base_url}/token" in exc_info.value.message
+ assert "certificate" in exc_info.value.message.lower()
+ assert self_signed_idp.requests == []
+ await get_async_httpx_client(llm_provider=httpxSpecialProvider.SSO_HANDLER).client.aclose()
diff --git a/tests/unit/proxy/management_endpoints/test_ui_sso.py b/tests/unit/proxy/management_endpoints/test_ui_sso.py
index ddcaad3a570..f69c069cfea 100644
--- a/tests/unit/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/unit/proxy/management_endpoints/test_ui_sso.py
@@ -15,6 +15,7 @@ from fastapi import HTTPException, Request
import litellm
from litellm._uuid import uuid
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.proxy._types import LiteLLM_UserTable, NewUserResponse
from litellm.proxy.auth.handle_jwt import JWTHandler
from litellm.proxy.management_endpoints.sso import CustomMicrosoftSSO
@@ -40,6 +41,16 @@ from litellm.types.proxy.management_endpoints.ui_sso import (
)
from tests._master_key import MASTER_KEY
+
+def _sso_http_handler(route: Callable[[httpx.Request], httpx.Response] | None = None) -> AsyncHTTPHandler:
+ """litellm's SSO httpx client answered in-process, by ``route`` or by the active respx mock."""
+ handler = AsyncHTTPHandler()
+ handler.client = httpx.AsyncClient(transport=httpx.MockTransport(route)) if route else httpx.AsyncClient()
+ return handler
+
+
+_SSO_HTTP_CLIENT_FACTORY = "litellm.proxy.management_endpoints.sso.litellm_http_client_sso.get_async_httpx_client"
+
_SSO_PROVIDER_ENV_VARS = (
"DISABLE_ADMIN_UI",
"MICROSOFT_CLIENT_ID",
@@ -2155,7 +2166,7 @@ async def test_get_generic_sso_response_with_additional_headers():
with patch.dict(os.environ, test_env_vars):
with patch("fastapi_sso.sso.base.DiscoveryDocument"):
with patch(
- "fastapi_sso.sso.generic.create_provider", return_value=mock_sso_class
+ "litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=mock_sso_class
):
# Act
result, received_response, _, _ = await get_generic_sso_response(
@@ -2219,7 +2230,7 @@ async def test_get_generic_sso_response_with_empty_headers():
with patch.dict(os.environ, test_env_vars):
with patch("fastapi_sso.sso.base.DiscoveryDocument"):
with patch(
- "fastapi_sso.sso.generic.create_provider", return_value=mock_sso_class
+ "litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=mock_sso_class
):
# Act
result, received_response, _, _ = await get_generic_sso_response(
@@ -2292,7 +2303,7 @@ async def test_get_generic_sso_response_includes_token_claims_when_enabled(monke
monkeypatch.setenv("GENERIC_ROLE_MAPPINGS_GROUP_CLAIM", "groups")
with patch("fastapi_sso.sso.base.DiscoveryDocument"):
- with patch("fastapi_sso.sso.generic.create_provider", side_effect=fake_create_provider):
+ with patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", side_effect=fake_create_provider):
result, received_response, _, _ = await get_generic_sso_response(
request=mock_request,
jwt_handler=mock_jwt_handler,
@@ -2351,7 +2362,7 @@ async def test_get_generic_sso_response_does_not_include_token_claims_when_disab
monkeypatch.setenv("GENERIC_ROLE_MAPPINGS_GROUP_CLAIM", "groups")
with patch("fastapi_sso.sso.base.DiscoveryDocument"):
- with patch("fastapi_sso.sso.generic.create_provider", side_effect=fake_create_provider):
+ with patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", side_effect=fake_create_provider):
result, received_response, _, _ = await get_generic_sso_response(
request=mock_request,
jwt_handler=mock_jwt_handler,
@@ -2511,7 +2522,7 @@ async def test_get_generic_sso_response_ignores_opaque_and_empty_token_claims(mo
monkeypatch.setenv("GENERIC_INCLUDE_TOKEN_CLAIMS", "true")
with patch("fastapi_sso.sso.base.DiscoveryDocument"):
- with patch("fastapi_sso.sso.generic.create_provider", side_effect=fake_create_provider):
+ with patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", side_effect=fake_create_provider):
result, received_response, _, _ = await get_generic_sso_response(
request=mock_request,
jwt_handler=mock_jwt_handler,
@@ -8518,7 +8529,7 @@ class TestPKCEStateCookieBinding:
),
),
patch("fastapi_sso.sso.base.DiscoveryDocument"),
- patch("fastapi_sso.sso.generic.create_provider", return_value=MagicMock()),
+ patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=MagicMock()),
patch.dict(
os.environ,
{
@@ -8570,7 +8581,7 @@ class TestPKCEStateCookieBinding:
),
),
patch("fastapi_sso.sso.base.DiscoveryDocument"),
- patch("fastapi_sso.sso.generic.create_provider", return_value=MagicMock()),
+ patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=MagicMock()),
patch.dict(
os.environ,
{
@@ -8636,7 +8647,7 @@ class TestPKCEStateCookieBinding:
AsyncMock(),
),
patch("fastapi_sso.sso.base.DiscoveryDocument"),
- patch("fastapi_sso.sso.generic.create_provider", return_value=MagicMock()),
+ patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=MagicMock()),
patch.dict(
os.environ,
{
@@ -9296,7 +9307,7 @@ async def test_pkce_arm_captures_sso_assertion():
),
patch.object(SSOAuthenticationHandler, "delete_pkce_verifier", AsyncMock()),
patch("fastapi_sso.sso.base.DiscoveryDocument"),
- patch("fastapi_sso.sso.generic.create_provider", return_value=MagicMock()),
+ patch("litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=MagicMock()),
patch.dict(
os.environ,
{
@@ -9357,7 +9368,7 @@ async def test_verify_and_process_arm_captures_sso_assertion():
):
with patch("fastapi_sso.sso.base.DiscoveryDocument"):
with patch(
- "fastapi_sso.sso.generic.create_provider", return_value=mock_sso_class
+ "litellm.proxy.management_endpoints.ui_sso.create_generic_sso_provider", return_value=mock_sso_class
):
_, _, _, sso_assertion = await get_generic_sso_response(
request=mock_request,
@@ -9404,6 +9415,46 @@ def _generic_sso_jwt_handler() -> MagicMock:
return jwt_handler
+async def test_non_pkce_generic_login_exchanges_tokens_on_litellm_sso_client():
+ """Regression for LIT-9445: the non-PKCE arm let fastapi_sso open a bare httpx client, so
+ ssl_verify / SSL_VERIFY / SSL_CERT_FILE were ignored. Both IdP calls must go out on litellm's
+ SSO client, and the bearer token must not stick to that shared client."""
+ from litellm.proxy.management_endpoints.ui_sso import get_generic_sso_response
+ from litellm.types.llms.custom_http import httpxSpecialProvider
+
+ seen: list[httpx.Request] = []
+
+ def idp(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ if request.url.path == "/token":
+ return httpx.Response(200, json={"access_token": "at-9445", "token_type": "Bearer"})
+ return httpx.Response(200, json={"sub": "u-9445", "email": "[email protected]", "preferred_username": "u9445"})
+
+ handler = _sso_http_handler(idp)
+ with (
+ patch.dict(os.environ, _GENERIC_SSO_CALLBACK_ENV),
+ patch(_SSO_HTTP_CLIENT_FACTORY, return_value=handler) as sso_client_factory,
+ ):
+ result, _, _, _ = await get_generic_sso_response(
+ request=_generic_sso_callback_request(),
+ jwt_handler=_generic_sso_jwt_handler(),
+ generic_client_id="test_client_id",
+ redirect_url="https://proxy.example.com/sso/callback",
+ sso_jwt_handler=None,
+ )
+
+ assert result is not None
+ assert result.email == "[email protected]"
+ sso_client_factory.assert_called_with(llm_provider=httpxSpecialProvider.SSO_HANDLER)
+ token_request, userinfo_request = seen
+ assert token_request.method == "POST"
+ assert str(token_request.url) == "https://auth.example.com/token"
+ assert "code=abc" in token_request.content.decode()
+ assert userinfo_request.headers["authorization"] == "Bearer at-9445"
+ assert "authorization" not in handler.client.headers
+
+
@pytest.mark.asyncio
async def test_non_json_userinfo_falls_back_to_id_token_claims():
"""A userinfo endpoint answering with a non-JSON body (ADFS 401, Content-Length 0)
@@ -9422,6 +9473,7 @@ async def test_non_json_userinfo_falls_back_to_id_token_claims():
with (
respx.mock,
patch.dict(os.environ, _GENERIC_SSO_CALLBACK_ENV),
+ patch(_SSO_HTTP_CLIENT_FACTORY, return_value=_sso_http_handler()),
):
respx.post("https://auth.example.com/token").mock(
return_value=httpx.Response(200, json={"access_token": "at", "token_type": "Bearer", "id_token": id_token})
@@ -9459,6 +9511,7 @@ async def test_non_json_userinfo_without_id_token_raises_401():
with (
respx.mock,
patch.dict(os.environ, _GENERIC_SSO_CALLBACK_ENV),
+ patch(_SSO_HTTP_CLIENT_FACTORY, return_value=_sso_http_handler()),
):
respx.post("https://auth.example.com/token").mock(
return_value=httpx.Response(200, json={"access_token": "at", "token_type": "Bearer"})
@@ -9491,6 +9544,7 @@ async def test_non_json_token_response_is_not_swallowed_by_userinfo_fallback():
with (
respx.mock,
patch.dict(os.environ, _GENERIC_SSO_CALLBACK_ENV),
+ patch(_SSO_HTTP_CLIENT_FACTORY, return_value=_sso_http_handler()),
):
respx.post("https://auth.example.com/token").mock(
return_value=httpx.Response(200, content=b"", headers={"content-type": "text/html"})
@@ -10467,11 +10521,11 @@ async def _sso_key_generate_on_ui_disabled_node(*, source, key, google_sso_confi
patch("litellm.proxy.proxy_server.cli_sso_session_cache", cli_cache),
patch("litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler", None),
patch("litellm.proxy.management_endpoints.ui_sso.show_missing_vars_in_env", return_value=None),
- respx.mock(assert_all_called=False) as router,
+ patch(
+ _SSO_HTTP_CLIENT_FACTORY,
+ return_value=_sso_http_handler(lambda _request: httpx.Response(200, json=_GOOGLE_DISCOVERY_DOCUMENT)),
+ ),
):
- router.get("https://accounts.google.com/.well-known/openid-configuration").mock(
- return_value=httpx.Response(200, json=_GOOGLE_DISCOVERY_DOCUMENT)
- )
return await google_login(request=mock_request, source=source, key=key)