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)!: reject empty identities before session creation (#44098)

yucheng-berrid17cd947b984
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 1d0583d7ebb..ba85ea590b5 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -110,6 +110,7 @@ from litellm.proxy.common_utils.html_forms.jwt_display_template import (
)
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.id_jag_assertion_capture import (
@@ -1839,6 +1840,7 @@ async def get_existing_user_info_from_db(
prisma_client: PrismaClient,
user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
+ raise_database_outage: bool = False,
) -> LiteLLM_UserTable | None:
try:
user_info = await get_user_object(
@@ -1852,12 +1854,23 @@ async def get_existing_user_info_from_db(
sso_user_id=user_id,
)
except Exception as e:
+ if raise_database_outage and PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(e):
+ raise
verbose_proxy_logger.debug("Error getting user object: %s", e)
user_info = None
return user_info
+def sso_lookup_user_ids(alternate_user_id: str | None, provider_id: str | None) -> tuple[str, ...]:
+ """The nonblank ids an SSO sign-in can match an existing account by, the alternate id first"""
+ return tuple(
+ user_id
+ for user_id in (alternate_user_id, provider_id)
+ if user_id is not None and not _is_blank_sso_user_id(user_id)
+ )
+
+
async def get_user_info_from_db(
result: CustomOpenID | OpenID | dict,
prisma_client: PrismaClient,
@@ -1867,18 +1880,15 @@ async def get_user_info_from_db(
user_defined_values: SSOUserDefinedValues | None,
alternate_user_id: str | None = None,
) -> LiteLLM_UserTable | NewUserResponse | None:
+ mapped_user_id: Final = None if user_defined_values is None else user_defined_values.get("user_id")
+ resolved_by_database_only: Final = user_defined_values is not None and (
+ not isinstance(mapped_user_id, str) or _is_blank_sso_user_id(mapped_user_id)
+ )
try:
- potential_user_ids: Final = []
- if alternate_user_id is not None:
- potential_user_ids.append(alternate_user_id)
- if not isinstance(result, dict):
- _id = getattr(result, "id", None)
- if _id is not None and isinstance(_id, str):
- potential_user_ids.append(_id)
- else:
- _id = result.get("id", None)
- if _id is not None and isinstance(_id, str):
- potential_user_ids.append(_id)
+ provider_id: Final = result.get("id", None) if isinstance(result, dict) else getattr(result, "id", None)
+ potential_user_ids: Final = sso_lookup_user_ids(
+ alternate_user_id, provider_id if isinstance(provider_id, str) else None
+ )
user_email = normalize_email(
getattr(result, "email", None) if not isinstance(result, dict) else result.get("email", None)
@@ -1893,6 +1903,7 @@ async def get_user_info_from_db(
prisma_client=prisma_client,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
+ raise_database_outage=resolved_by_database_only,
)
if user_info is not None:
break
@@ -1908,6 +1919,7 @@ async def get_user_info_from_db(
user_email=user_email,
user_defined_values=user_defined_values,
prisma_client=prisma_client,
+ raise_database_outage=resolved_by_database_only,
)
await SSOAuthenticationHandler.add_user_to_teams_from_sso_response(
@@ -1917,6 +1929,9 @@ async def get_user_info_from_db(
return user_info
except Exception as e:
+ if resolved_by_database_only and PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(e):
+ verbose_proxy_logger.exception("SSO login failed: the database could not resolve the account: %s", e)
+ raise HTTPException(status_code=500, detail="Failed to retrieve user information from SSO") from e
verbose_proxy_logger.exception("[Non-Blocking] Error trying to add sso user to db: %s", e)
return None
@@ -2395,7 +2410,11 @@ async def _complete_cli_sso_callback_session(
):
from fastapi.responses import HTMLResponse
+ from litellm.proxy.proxy_server import user_custom_sso
+
user_id: Final = parsed_openid_result.get("user_id")
+ if user_custom_sso is None:
+ _require_sso_user_id(user_id)
user_email: Final = parsed_openid_result.get("user_email")
user_info: Final = await get_user_info_from_db(
result=result,
@@ -2407,11 +2426,12 @@ async def _complete_cli_sso_callback_session(
alternate_user_id=user_id,
)
if user_info is None:
+ if user_defined_values is not None:
+ _require_sso_user_id(user_defined_values["user_id"])
raise HTTPException(status_code=500, detail="Failed to retrieve user information from SSO")
- if not user_info.user_id:
- raise HTTPException(status_code=500, detail="Failed to retrieve user information from SSO")
+ resolved_user_id: Final = _require_sso_user_id(user_info.user_id)
- await retain_sso_identity_assertion_for_ema(user_id=user_info.user_id, assertion=sso_assertion)
+ await retain_sso_identity_assertion_for_ema(user_id=resolved_user_id, assertion=sso_assertion)
await warn_if_id_jag_assertion_uncaptured(sso_assertion)
teams: list[str] = []
@@ -2427,19 +2447,19 @@ async def _complete_cli_sso_callback_session(
from litellm.proxy.management_endpoints.sso.agent_subject_enrollment import enroll_microsoft_subject
await enroll_microsoft_subject(
- request.scope.get("litellm_microsoft_interactive_subject"), user_info.user_id, prisma_client
+ request.scope.get("litellm_microsoft_interactive_subject"), resolved_user_id, prisma_client
)
resolved_teams: Final = _cli_sso_session_teams(team_details)
attribution_metadata: Final = build_cli_sso_attribution_metadata(result=result)
if attribution_metadata:
await _persist_cli_sso_user_metadata(
prisma_client=prisma_client,
- user_id=cast(str, user_info.user_id),
+ user_id=resolved_user_id,
attribution_metadata=attribution_metadata,
)
flow["session_data"] = {
- "user_id": cast(str, user_info.user_id),
+ "user_id": resolved_user_id,
"user_role": user_info.user_role,
"models": user_info.models if hasattr(user_info, "models") else [],
"user_email": user_email,
@@ -2454,7 +2474,7 @@ async def _complete_cli_sso_callback_session(
verbose_proxy_logger.info(
"Stored CLI SSO session for user: %s, teams: %s, num_teams: %s",
- user_info.user_id,
+ resolved_user_id,
resolved_teams,
len(resolved_teams),
)
@@ -2700,6 +2720,8 @@ async def insert_sso_user(
if user_defined_values is None:
raise ValueError("user_defined_values is None")
+ if _is_blank_sso_user_id(user_defined_values.get("user_id")):
+ raise ValueError("SSO user id is blank")
# Apply default_internal_user_params
if litellm.default_internal_user_params:
@@ -2974,6 +2996,18 @@ def _persist_return_to_cookie(response: Response, return_to: str | None, request
)
+def _is_blank_sso_user_id(user_id: object) -> bool:
+ return isinstance(user_id, str) and not user_id.strip()
+
+
+def _require_sso_user_id(user_id: object) -> str:
+ """Return a nonblank SSO user id or reject the login with a 401"""
+ if not isinstance(user_id, str) or _is_blank_sso_user_id(user_id):
+ verbose_proxy_logger.warning("SSO login rejected: the sign-in did not resolve to a user id")
+ raise HTTPException(status_code=401, detail="SSO login failed: this sign-in did not resolve to a user id")
+ return user_id
+
+
class SSOAuthenticationHandler:
"""
Handler for SSO Authentication across all SSO providers
@@ -3357,6 +3391,7 @@ class SSOAuthenticationHandler:
user_email: str | None,
user_defined_values: SSOUserDefinedValues | None,
prisma_client: PrismaClient,
+ raise_database_outage: bool = False,
):
"""
Connects the SSO Users to the User Table in LiteLLM DB
@@ -3386,6 +3421,12 @@ class SSOAuthenticationHandler:
)
return user_info
except Exception as e:
+ if (
+ user_info is None
+ and raise_database_outage
+ and PrismaDBExceptionHandler.is_database_service_unavailable_error_in_chain(e)
+ ):
+ raise
verbose_proxy_logger.exception("Error upserting SSO user into LiteLLM DB: %s", e)
return user_info
@@ -3606,7 +3647,7 @@ class SSOAuthenticationHandler:
_last_name: Final = getattr(result, "last_name", "") or ""
user_id = _first_name + _last_name
- if user_email is not None and (user_id is None or len(user_id) == 0):
+ if user_email is not None and (user_id is None or not user_id.strip()):
user_id = user_email
return ParsedOpenIDResult(
@@ -3686,6 +3727,9 @@ class SSOAuthenticationHandler:
received_response=received_response,
)
+ if custom_sso_handler is None:
+ _require_sso_user_id(user_id)
+
user_info = await get_user_info_from_db(
result=result,
prisma_client=prisma_client,
@@ -3731,7 +3775,7 @@ class SSOAuthenticationHandler:
spend=0,
team_id="litellm-dashboard",
models=user_defined_values["models"],
- user_id=user_defined_values["user_id"],
+ user_id=_require_sso_user_id(user_defined_values["user_id"]),
user_email=user_defined_values["user_email"],
user_role=user_defined_values["user_role"],
max_budget=user_defined_values["max_budget"],
@@ -4422,6 +4466,12 @@ class MicrosoftSSOHandler:
)
or {}
)
+ 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(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="SSO login failed: Microsoft Graph returned an error instead of the user profile",
+ )
user_team_ids: Final = await MicrosoftSSOHandler.get_user_groups_from_graph_api(
access_token=microsoft_sso.access_token
diff --git a/tests/integration/authorization/test_sso_blank_identity.py b/tests/integration/authorization/test_sso_blank_identity.py
new file mode 100644
index 00000000000..c2f0e29221d
--- /dev/null
+++ b/tests/integration/authorization/test_sso_blank_identity.py
@@ -0,0 +1,813 @@
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import uuid
+from collections.abc import Iterator, Mapping
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from hashlib import sha256
+from pathlib import Path
+from typing import Final
+from urllib.parse import parse_qs, urlencode, urlparse
+
+import httpx
+import jwt
+import pytest
+import yaml
+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 onelogin.saml2.utils import OneLogin_Saml2_Utils
+
+from tests.integration._support.client import JSON_OBJECT, Gateway, Scenario, gateway_from_environment, string_value
+from tests.integration._support.database import read_rows, write_rows
+from tests.integration._support.database_relay import dropped_connection_relay
+from tests.integration._support.process import OwnedProxy, owned_proxy_process
+from tests.integration._support.wire import Reply, Request, Wire, wire_server
+
+pytestmark: Final = pytest.mark.timeout(300)
+
+CLIENT_ID: Final = "integration-entra-client"
+CLIENT_SECRET: Final = "integration-entra-secret"
+TENANT: Final = "integration-entra-tenant"
+CLI_SOURCE: Final = "litellm-cli"
+POLL_SECRET_HEADER: Final = "x-litellm-cli-poll-secret"
+CLI_LOGIN_PAGE_TITLE: Final = "<title>LiteLLM CLI Login</title>"
+CLI_SUCCESS_PAGE_TITLE: Final = "<title>CLI Authentication Successful - LiteLLM</title>"
+REFUSED: Final = "SSO login failed: this sign-in did not resolve to a user id"
+GRAPH_REFUSED: Final = "SSO login failed: Microsoft Graph returned an error instead of the user profile"
+LOOKUP_FAILED: Final = "Failed to retrieve user information from SSO"
+BLANK: Final = r"^\s*$"
+COMPLETE_TOKEN_FIELD: Final = re.compile(r'name="browser_complete_token" value="([^"]+)"')
+COMPLETE_FORM_ACTION: Final = re.compile(r'action="([^"]+/sso/cli/complete/[^"]+)"')
+GRAPH_ERROR: Final = json.dumps(
+ {"error": {"code": "Authentication_MissingOrMalformed", "message": "Access Token missing or malformed."}}
+).encode()
+CUSTOM_SSO_MODULE: Final = """
+async def custom_sso(result: object) -> dict[str, object] | None:
+ email: str = getattr(result, "email", None) or ""
+ for prefix, user_id in (("mapped-blank-", " "), ("mapped-none-", None)):
+ if email.startswith(prefix):
+ return {
+ "models": [],
+ "user_id": user_id,
+ "user_email": email,
+ "max_budget": None,
+ "user_role": None,
+ "budget_duration": None,
+ }
+ return None
+"""
+
+
+@dataclass(frozen=True, slots=True)
+class Graph:
+ """Entra sign-in plus the Graph `/me` lookup, one scripted reply per login hint."""
+
+ wire: Wire
+ profiles: dict[str, Reply]
+
+ def profile(self, reply: Reply) -> str:
+ hint: Final = f"hint-{uuid.uuid4().hex}"
+ self.profiles[hint] = reply
+ return hint
+
+
+@dataclass(frozen=True, slots=True)
+class CliSession:
+ login_id: str
+ poll_secret: str
+ user_code: str
+
+
+def _between(value: str, prefix: str) -> str:
+ return value.removeprefix(prefix).rsplit("-", 1)[0]
+
+
+def _graph_reply(profiles: Mapping[str, Reply], request: Request) -> Reply:
+ target: Final = urlparse(request.target)
+ if target.path == "/authorize":
+ query: Final = parse_qs(target.query)
+ code: Final = f"code-{query['login_hint'][0]}-{uuid.uuid4().hex}"
+ state: Final = {"state": query["state"][0]} if "state" in query else {}
+ location: Final = f"{query['redirect_uri'][0]}?{urlencode({'code': code, **state})}"
+ return Reply(status=302, body=b"", headers={"location": location})
+ if target.path == "/token":
+ form: Final = parse_qs(request.body.decode())
+ code_value: Final = form.get("code", [""])[0]
+ if form.get("grant_type") != ["authorization_code"] or not code_value.startswith("code-"):
+ return Reply(status=400, body=b'{"error": "invalid_grant"}')
+ token: Final = f"graph-{_between(code_value, 'code-')}-{uuid.uuid4().hex}"
+ return Reply(body=json.dumps({"access_token": token, "token_type": "Bearer", "expires_in": 3600}).encode())
+ bearer: Final = request.headers.get("authorization", "")
+ if not bearer.startswith("Bearer graph-"):
+ return Reply(status=401, body=GRAPH_ERROR)
+ hint: Final = _between(bearer, "Bearer graph-")
+ if target.path == "/v1.0/me":
+ return profiles[hint]
+ if target.path.startswith("/v1.0/me/memberOf"):
+ failed: Final = profiles[hint].status != 200
+ return Reply(status=401, body=GRAPH_ERROR) if failed else Reply(body=b'{"value": []}')
+ return Reply(status=404, body=b'{"error": {"code": "Request_ResourceNotFound"}}')
+
+
+def _profile(user_id: str, email: str) -> Reply:
+ return Reply(
+ body=json.dumps(
+ {
+ "id": user_id,
+ "userPrincipalName": email,
+ "mail": email,
+ "displayName": "Synthetic Person",
+ "givenName": "Synthetic",
+ "surname": "Person",
+ }
+ ).encode()
+ )
+
+
+def _entra_environment(graph_url: str) -> Mapping[str, str]:
+ return {
+ "MICROSOFT_CLIENT_ID": CLIENT_ID,
+ "MICROSOFT_CLIENT_SECRET": CLIENT_SECRET,
+ "MICROSOFT_TENANT": TENANT,
+ "MICROSOFT_AUTHORIZATION_ENDPOINT": f"{graph_url}/authorize",
+ "MICROSOFT_TOKEN_ENDPOINT": f"{graph_url}/token",
+ "MICROSOFT_USERINFO_ENDPOINT": f"{graph_url}/v1.0/me",
+ "MICROSOFT_GRAPH_ENDPOINT": f"{graph_url}/v1.0",
+ "OAUTHLIB_INSECURE_TRANSPORT": "1",
+ "ENABLE_SSO_DEBUG": "true",
+ }
+
+
+SAML_SP_ENTITY: Final = "litellm-integration-sp"
+SAML_IDP_ENTITY: Final = "https://idp.integration.invalid/metadata"
+SAML_STATE_COOKIE: Final = "litellm_saml_authn"
+
+
+@dataclass(frozen=True, slots=True)
+class SamlIdp:
+ """A signing SAML IdP the test speaks for: its metadata and signed answers to a proxy login request"""
+
+ key_pem: str
+ cert_pem: str
+
+ def metadata(self) -> str:
+ body: Final = "".join(line for line in self.cert_pem.splitlines() if "CERTIFICATE" not in line)
+ return (
+ f'<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="{SAML_IDP_ENTITY}">'
+ '<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">'
+ '<KeyDescriptor use="signing"><KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">'
+ f"<X509Data><X509Certificate>{body}</X509Certificate></X509Data></KeyInfo></KeyDescriptor>"
+ '<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" '
+ 'Location="https://idp.integration.invalid/sso"/>'
+ "</IDPSSODescriptor></EntityDescriptor>"
+ )
+
+ def response(self, acs: str, request_id: str, name_id: str, email: str | None) -> str:
+ now: Final = datetime.now(timezone.utc)
+ 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")
+ attributes: Final = (
+ '<saml:Attribute Name="givenName"><saml:AttributeValue>Saml</saml:AttributeValue></saml:Attribute>'
+ if email is None
+ else f'<saml:Attribute Name="email"><saml:AttributeValue>{email}</saml:AttributeValue></saml:Attribute>'
+ )
+ assertion: Final = (
+ '<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" '
+ f'ID="_assertion_{uuid.uuid4().hex}" Version="2.0" IssueInstant="{issued}">'
+ f"<saml:Issuer>{SAML_IDP_ENTITY}</saml:Issuer>"
+ '<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}"/>'
+ "</saml:SubjectConfirmation></saml:Subject>"
+ f'<saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{expires}">'
+ f"<saml:AudienceRestriction><saml:Audience>{SAML_SP_ENTITY}</saml:Audience>"
+ "</saml:AudienceRestriction></saml:Conditions>"
+ f'<saml:AuthnStatement AuthnInstant="{issued}" SessionIndex="_session">'
+ "<saml:AuthnContext><saml:AuthnContextClassRef>"
+ "urn:oasis:names:tc:SAML:2.0:ac:classes:Password"
+ "</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement>"
+ f"<saml:AttributeStatement>{attributes}</saml:AttributeStatement>"
+ "</saml:Assertion>"
+ )
+ signed: Final = OneLogin_Saml2_Utils.add_sign(assertion, self.key_pem, self.cert_pem)
+ signed_text: Final = (signed.decode() if isinstance(signed, bytes) else signed).replace(
+ '<?xml version="1.0"?>', ""
+ )
+ document: Final = (
+ '<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"<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>"
+ )
+ return base64.b64encode(document.encode()).decode()
+
+
[email protected](scope="module")
+def saml_idp() -> SamlIdp:
+ key: Final = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ name: Final = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "idp.integration.invalid")])
+ now: Final = datetime.now(timezone.utc)
+ cert: Final = (
+ x509.CertificateBuilder()
+ .subject_name(name)
+ .issuer_name(name)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - timedelta(days=1))
+ .not_valid_after(now + timedelta(days=1))
+ .sign(key, hashes.SHA256())
+ )
+ return SamlIdp(
+ key_pem=key.private_bytes(
+ serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()
+ ).decode(),
+ cert_pem=cert.public_bytes(serialization.Encoding.PEM).decode(),
+ )
+
+
[email protected](scope="module")
+def saml(saml_idp: SamlIdp, gateway_module: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[OwnedProxy]:
+ with owned_proxy_process(
+ gateway_module,
+ tmp_path_factory.mktemp("sso-blank-identity-saml"),
+ {"SAML_IDP_METADATA_XML": saml_idp.metadata(), "SAML_SP_ENTITY_ID": SAML_SP_ENTITY},
+ remove_environment=("PROXY_BASE_URL",),
+ workers=2,
+ ) as owned:
+ yield owned
+
+
+def _saml_sign_in(proxy: Gateway, idp: SamlIdp, name_id: str, email: str | None) -> httpx.Response:
+ acs: Final = f"{_proxy_url(proxy)}/sso/saml/callback"
+ with _browser() as browser:
+ login: Final = browser.get(f"{_proxy_url(proxy)}/sso/saml/login")
+ assert login.is_redirect, f"{login.status_code} {login.text}"
+ request_id: Final = login.cookies[SAML_STATE_COOKIE]
+ return browser.post(acs, data={"SAMLResponse": idp.response(acs, request_id, name_id, email)})
+
+
[email protected](scope="module")
+def graph() -> Iterator[Graph]:
+ profiles: Final[dict[str, Reply]] = {}
+ with wire_server(lambda request: _graph_reply(profiles, request)) as wire:
+ yield Graph(wire, profiles)
+
+
[email protected](scope="module")
+def entra(graph: Graph, gateway_module: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[OwnedProxy]:
+ directory: Final = tmp_path_factory.mktemp("sso-blank-identity")
+ with owned_proxy_process(
+ gateway_module,
+ directory,
+ _entra_environment(graph.wire.url),
+ remove_environment=("PROXY_BASE_URL",),
+ workers=2,
+ ) as owned:
+ yield owned
+
+
+def _custom_mapping_config(directory: Path) -> Path:
+ stock: Final = yaml.safe_load((Path(__file__).resolve().parents[1] / "proxy_config.yaml").read_text())
+ (directory / "blank_identity_custom_sso.py").write_text(CUSTOM_SSO_MODULE)
+ config: Final = directory / "custom_sso_config.yaml"
+ config.write_text(
+ json.dumps(
+ {
+ **stock,
+ "general_settings": {
+ **stock["general_settings"],
+ "custom_sso": "blank_identity_custom_sso.custom_sso",
+ },
+ }
+ )
+ )
+ return config
+
+
[email protected](scope="module")
+def entra_custom_mapping(
+ graph: Graph, gateway_module: Gateway, tmp_path_factory: pytest.TempPathFactory
+) -> Iterator[OwnedProxy]:
+ directory: Final = tmp_path_factory.mktemp("sso-blank-identity-custom")
+ with owned_proxy_process(
+ gateway_module,
+ directory,
+ _entra_environment(graph.wire.url),
+ config=_custom_mapping_config(directory),
+ remove_environment=("PROXY_BASE_URL",),
+ workers=2,
+ ) as owned:
+ yield owned
+
+
[email protected](scope="module")
+def gateway_module() -> Iterator[Gateway]:
+ with gateway_from_environment() as value:
+ yield value
+
+
+def _blank_accounts() -> tuple[str, ...]:
+ rows: Final = read_rows('SELECT user_id FROM "LiteLLM_UserTable" WHERE user_id ~ %s', (BLANK,))
+ return tuple(repr(row["user_id"]) for row in rows)
+
+
+def _drop_blank_accounts() -> None:
+ write_rows('DELETE FROM "LiteLLM_VerificationToken" WHERE user_id ~ %s', (BLANK,))
+ write_rows('DELETE FROM "LiteLLM_UserTable" WHERE user_id ~ %s', (BLANK,))
+
+
+def _forget_sign_in(scenario: Scenario, email: str) -> None:
+ """Delete the account a sign-in creates for ``email``, and its session keys, whether or not the test passes."""
+ scenario.cleanups.callback(write_rows, 'DELETE FROM "LiteLLM_UserTable" WHERE user_email = %s', (email,))
+ scenario.cleanups.callback(
+ write_rows,
+ 'DELETE FROM "LiteLLM_VerificationToken" WHERE user_id IN '
+ '(SELECT user_id FROM "LiteLLM_UserTable" WHERE user_email = %s)',
+ (email,),
+ )
+
+
+def _seed_account(user_id: str, email: str) -> None:
+ write_rows(
+ 'INSERT INTO "LiteLLM_UserTable" (user_id, user_email, user_role, spend, models) '
+ "VALUES (%s, %s, 'internal_user', 0, '{}')",
+ (user_id, email),
+ )
+
+
+def clean_slate() -> Iterator[None]:
+ """Blank-identity accounts never belong in the database; a refused sign-in must not leave one behind."""
+ _drop_blank_accounts()
+ yield
+ _drop_blank_accounts()
+
+
+def _proxy_url(proxy: Gateway) -> str:
+ return str(proxy.client.base_url).rstrip("/")
+
+
+def _browser() -> httpx.Client:
+ return httpx.Client(follow_redirects=False, trust_env=False, timeout=30)
+
+
+def _through_graph(
+ proxy: Gateway, graph: Graph, browser: httpx.Client, entry: str, hint: str, callback: str = "/sso/callback"
+) -> httpx.Response:
+ link: Final = browser.get(entry)
+ assert link.is_redirect, f"{link.status_code} {link.text}"
+ authorize: Final = link.headers["location"]
+ assert authorize.startswith(f"{graph.wire.url}/authorize?"), authorize
+ assert parse_qs(urlparse(authorize).query)["redirect_uri"] == [f"{_proxy_url(proxy)}{callback}"], authorize
+ at_graph: Final = browser.get(f"{authorize}&{urlencode({'login_hint': hint})}")
+ assert at_graph.status_code == 302, f"{at_graph.status_code} {at_graph.text}"
+ return browser.get(at_graph.headers["location"])
+
+
+def _dashboard_sign_in(proxy: Gateway, graph: Graph, hint: str) -> httpx.Response:
+ with _browser() as browser:
+ return _through_graph(proxy, graph, browser, f"{_proxy_url(proxy)}/sso/key/generate", hint)
+
+
+def _session(callback: httpx.Response) -> Mapping[str, object] | None:
+ cookie: Final = callback.cookies.get("token")
+ return None if cookie is None else jwt.decode(cookie, options={"verify_signature": False})
+
+
+def _list_keys(proxy: Gateway, session_key: str) -> httpx.Response:
+ return proxy.request("GET", "/key/list", key=session_key, params={"return_full_object": "true"})
+
+
+def _listed_tokens(listed: httpx.Response) -> frozenset[str]:
+ keys: Final = JSON_OBJECT.validate_json(listed.content)["keys"]
+ assert isinstance(keys, list), listed.text
+ return frozenset(string_value(JSON_OBJECT.validate_python(item)["token"]) for item in keys)
+
+
+def _visible_tokens(proxy: Gateway, session_key: str) -> frozenset[str]:
+ listed: Final = _list_keys(proxy, session_key)
+ assert listed.status_code == 200, f"{listed.status_code} {listed.text}"
+ return _listed_tokens(listed)
+
+
+def _refusal_report(proxy: Gateway, callback: httpx.Response, victim_token: str) -> str:
+ session: Final = _session(callback)
+ if session is None:
+ return f"{callback.status_code} {callback.text}"
+ issued: Final = (
+ f"{callback.status_code}: a dashboard session was issued for user_id={session['user_id']!r} "
+ f"with role {session.get('user_role')!r}"
+ )
+ listed: Final = _list_keys(proxy, str(session["key"]))
+ if listed.status_code != 200:
+ return f"{issued}; its /key/list answered {listed.status_code}"
+ visible: Final = _listed_tokens(listed)
+ return f"{issued}; it lists {len(visible)} keys and the other account's key is visible={victim_token in visible}"
+
+
+def _victim(scenario: Scenario) -> str:
+ owner: Final = scenario.user(user_role="internal_user")
+ return sha256(scenario.key(user_id=owner, key_alias=f"victim-{uuid.uuid4().hex}").encode()).hexdigest()
+
+
+def _start_cli_login(proxy: Gateway) -> CliSession:
+ response: Final = proxy.client.post("/sso/cli/start")
+ assert response.status_code == 200, response.text
+ body: Final = JSON_OBJECT.validate_json(response.content)
+ return CliSession(
+ string_value(body["login_id"]), string_value(body["poll_secret"]), string_value(body["user_code"])
+ )
+
+
+def _cli_callback(
+ proxy: Gateway, graph: Graph, browser: httpx.Client, session: CliSession, hint: str
+) -> httpx.Response:
+ entry: Final = f"{_proxy_url(proxy)}/sso/key/generate?{urlencode({'source': CLI_SOURCE, 'key': session.login_id})}"
+ return _through_graph(proxy, graph, browser, entry, hint)
+
+
+def _complete_cli(browser: httpx.Client, callback: httpx.Response, session: CliSession) -> httpx.Response:
+ assert callback.status_code == 200 and CLI_LOGIN_PAGE_TITLE in callback.text, (
+ f"{callback.status_code} {callback.text}"
+ )
+ token: Final = COMPLETE_TOKEN_FIELD.search(callback.text)
+ action: Final = COMPLETE_FORM_ACTION.search(callback.text)
+ assert token is not None and action is not None, callback.text
+ return browser.post(
+ action.group(1), data={"user_code": session.user_code, "browser_complete_token": token.group(1)}
+ )
+
+
+def _poll(proxy: Gateway, session: CliSession) -> Mapping[str, object]:
+ response: Final = proxy.client.get(
+ f"/sso/cli/poll/{session.login_id}", headers={POLL_SECRET_HEADER: session.poll_secret}
+ )
+ assert response.status_code == 200, f"{response.status_code} {response.text}"
+ return JSON_OBJECT.validate_json(response.content)
+
+
+def _cli_report(proxy: Gateway, browser: httpx.Client, callback: httpx.Response, session: CliSession) -> str:
+ if callback.status_code != 200:
+ return f"{callback.status_code} {callback.text}"
+ done: Final = _complete_cli(browser, callback, session)
+ polled: Final = _poll(proxy, session)
+ return (
+ f"CLI login completed ({done.status_code}) and poll returned {polled.get('status')!r} "
+ f"for user_id={polled.get('user_id')!r}"
+ )
+
+
+def test_dashboard_sign_in_is_refused_when_the_graph_profile_lookup_fails(
+ entra: OwnedProxy, graph: Graph, gateway_module: Gateway, clean_slate: None
+) -> None:
+ proxy: Final = entra.gateway
+ with gateway_module.scenario() as scenario:
+ victim_token: Final = _victim(scenario)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(Reply(status=401, body=GRAPH_ERROR)))
+ assert callback.status_code == 401 and _session(callback) is None, _refusal_report(
+ proxy, callback, victim_token
+ )
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == GRAPH_REFUSED, callback.text
+ assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_cli_sign_in_is_refused_when_the_graph_profile_lookup_fails(
+ entra: OwnedProxy, graph: Graph, clean_slate: None
+) -> None:
+ proxy: Final = entra.gateway
+ session: Final = _start_cli_login(proxy)
+ with _browser() as browser:
+ callback: Final = _cli_callback(
+ proxy, graph, browser, session, graph.profile(Reply(status=401, body=GRAPH_ERROR))
+ )
+ assert callback.status_code == 401, _cli_report(proxy, browser, callback, session)
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == GRAPH_REFUSED, callback.text
+ assert _poll(proxy, session) == {"status": "pending"}
+ assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_dashboard_sign_in_with_a_valid_profile_sees_only_its_own_keys(
+ entra: OwnedProxy, graph: Graph, gateway_module: Gateway
+) -> None:
+ proxy: Final = entra.gateway
+ subject: Final = str(uuid.uuid4())
+ email: Final = f"valid-{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario:
+ victim_token: Final = _victim(scenario)
+ _forget_sign_in(scenario, email)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(_profile(subject, email)))
+ assert callback.status_code == 303, f"{callback.status_code} {callback.text}"
+ session: Final = _session(callback)
+ assert session is not None and session["user_id"] == subject, session
+ visible: Final = _visible_tokens(proxy, str(session["key"]))
+ assert victim_token not in visible, visible
+ rows: Final = read_rows('SELECT user_email FROM "LiteLLM_UserTable" WHERE user_id = %s', (subject,))
+ assert [row["user_email"] for row in rows] == [email], rows
+
+
+def test_cli_sign_in_with_a_valid_profile_completes(entra: OwnedProxy, graph: Graph, gateway_module: Gateway) -> None:
+ proxy: Final = entra.gateway
+ subject: Final = str(uuid.uuid4())
+ email: Final = f"valid-cli-{uuid.uuid4().hex[:12]}@example.com"
+ session: Final = _start_cli_login(proxy)
+ with gateway_module.scenario() as scenario, _browser() as browser:
+ _forget_sign_in(scenario, email)
+ callback: Final = _cli_callback(proxy, graph, browser, session, graph.profile(_profile(subject, email)))
+ done: Final = _complete_cli(browser, callback, session)
+ assert done.status_code == 200 and CLI_SUCCESS_PAGE_TITLE in done.text, f"{done.status_code} {done.text}"
+ ready: Final = _poll(proxy, session)
+ assert ready["status"] == "ready" and ready["user_id"] == subject, ready
+
+
[email protected]("blank_row", [False, True], ids=["no-blank-row", "blank-row-exists"])
+def test_blank_provider_id_signs_in_as_the_mail_address(
+ entra: OwnedProxy, graph: Graph, gateway_module: Gateway, clean_slate: None, blank_row: bool
+) -> None:
+ proxy: Final = entra.gateway
+ email: Final = f"blank-id-{uuid.uuid4().hex[:12]}@example.com"
+ if blank_row:
+ _seed_account(" ", f"someone-else-{uuid.uuid4().hex[:12]}@example.com")
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(_profile(" ", email)))
+ session: Final = _session(callback)
+ assert callback.status_code == 303 and session is not None, f"{callback.status_code} {callback.text}"
+ assert session["user_id"] == email, f"session issued for user_id={session['user_id']!r}"
+ assert _blank_accounts() == (("' '",) if blank_row else ()), _blank_accounts()
+
+
+def test_dashboard_sign_in_that_resolves_to_a_blank_account_row_is_refused(
+ entra: OwnedProxy, graph: Graph, gateway_module: Gateway, clean_slate: None
+) -> None:
+ proxy: Final = entra.gateway
+ email: Final = f"shared-row-{uuid.uuid4().hex[:12]}@example.com"
+ _seed_account("", email)
+ with gateway_module.scenario() as scenario:
+ victim_token: Final = _victim(scenario)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(_profile(str(uuid.uuid4()), email)))
+ assert callback.status_code == 401 and _session(callback) is None, _refusal_report(
+ proxy, callback, victim_token
+ )
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == REFUSED, callback.text
+ tokens: Final = read_rows('SELECT token FROM "LiteLLM_VerificationToken" WHERE user_id ~ %s', (BLANK,))
+ assert tokens == [], tokens
+
+
[email protected]("blank_id", ["", " "], ids=["empty", "whitespace"])
+def test_cli_sign_in_that_resolves_to_a_blank_account_row_is_refused(
+ entra: OwnedProxy, graph: Graph, clean_slate: None, blank_id: str
+) -> None:
+ proxy: Final = entra.gateway
+ email: Final = f"blank-row-{uuid.uuid4().hex[:12]}@example.com"
+ _seed_account(blank_id, email)
+ session: Final = _start_cli_login(proxy)
+ with _browser() as browser:
+ callback: Final = _cli_callback(
+ proxy, graph, browser, session, graph.profile(_profile(str(uuid.uuid4()), email))
+ )
+ assert callback.status_code == 401, _cli_report(proxy, browser, callback, session)
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == REFUSED, callback.text
+ assert _poll(proxy, session) == {"status": "pending"}
+
+
+def test_cli_sign_in_completes_for_an_existing_account_when_the_custom_mapping_returns_none(
+ entra_custom_mapping: OwnedProxy, graph: Graph, gateway_module: Gateway
+) -> None:
+ proxy: Final = entra_custom_mapping.gateway
+ email: Final = f"unmapped-{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario, _browser() as browser:
+ subject: Final = scenario.user(user_email=email, user_role="internal_user")
+ session: Final = _start_cli_login(proxy)
+ callback: Final = _cli_callback(proxy, graph, browser, session, graph.profile(_profile(subject, email)))
+ done: Final = _complete_cli(browser, callback, session)
+ assert done.status_code == 200 and CLI_SUCCESS_PAGE_TITLE in done.text, f"{done.status_code} {done.text}"
+ ready: Final = _poll(proxy, session)
+ assert ready["status"] == "ready" and ready["user_id"] == subject, ready
+
+
+def test_sign_in_is_refused_when_the_custom_mapping_returns_a_blank_user_id(
+ entra_custom_mapping: OwnedProxy, graph: Graph, gateway_module: Gateway, clean_slate: None
+) -> None:
+ proxy: Final = entra_custom_mapping.gateway
+ with gateway_module.scenario() as scenario:
+ victim_token: Final = _victim(scenario)
+ hint: Final = graph.profile(_profile(str(uuid.uuid4()), f"mapped-blank-{uuid.uuid4().hex[:12]}@example.com"))
+ callback: Final = _dashboard_sign_in(proxy, graph, hint)
+ assert callback.status_code == 401 and _session(callback) is None, _refusal_report(
+ proxy, callback, victim_token
+ )
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == REFUSED, callback.text
+ session: Final = _start_cli_login(proxy)
+ with _browser() as browser:
+ cli_hint: Final = graph.profile(
+ _profile(str(uuid.uuid4()), f"mapped-blank-{uuid.uuid4().hex[:12]}@example.com")
+ )
+ cli_callback: Final = _cli_callback(proxy, graph, browser, session, cli_hint)
+ assert cli_callback.status_code == 401, _cli_report(proxy, browser, cli_callback, session)
+ assert JSON_OBJECT.validate_json(cli_callback.content)["detail"] == REFUSED, cli_callback.text
+ assert _poll(proxy, session) == {"status": "pending"}
+ assert _blank_accounts() == (), _blank_accounts()
+
+
[email protected]("prefix", ["mapped-none-", "mapped-blank-"])
+def test_sign_in_uses_the_matching_account_when_the_custom_mapping_leaves_the_user_id_blank(
+ entra_custom_mapping: OwnedProxy, graph: Graph, gateway_module: Gateway, prefix: str
+) -> None:
+ proxy: Final = entra_custom_mapping.gateway
+ email: Final = f"{prefix}{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario, _browser() as browser:
+ account: Final = scenario.user(user_email=email, user_role="internal_user")
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(_profile(str(uuid.uuid4()), email)))
+ session: Final = _session(callback)
+ assert callback.status_code == 303 and session is not None, f"{callback.status_code} {callback.text}"
+ assert session["user_id"] == account, session
+ login: Final = _start_cli_login(proxy)
+ cli_hint: Final = graph.profile(_profile(str(uuid.uuid4()), email))
+ cli_callback: Final = _cli_callback(proxy, graph, browser, login, cli_hint)
+ done: Final = _complete_cli(browser, cli_callback, login)
+ assert done.status_code == 200 and CLI_SUCCESS_PAGE_TITLE in done.text, f"{done.status_code} {done.text}"
+ ready: Final = _poll(proxy, login)
+ assert ready["status"] == "ready" and ready["user_id"] == account, ready
+
+
+def test_sign_in_creates_an_account_when_the_custom_mapping_leaves_the_user_id_unset(
+ entra_custom_mapping: OwnedProxy, graph: Graph, gateway_module: Gateway
+) -> None:
+ proxy: Final = entra_custom_mapping.gateway
+ email: Final = f"mapped-none-{uuid.uuid4().hex[:12]}@example.com"
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(_profile(str(uuid.uuid4()), email)))
+ session: Final = _session(callback)
+ assert callback.status_code == 303 and session is not None, f"{callback.status_code} {callback.text}"
+ created: Final = read_rows('SELECT user_id FROM "LiteLLM_UserTable" WHERE user_email = %s', (email,))
+ assert [row["user_id"] for row in created] == [session["user_id"]], created
+ assert str(session["user_id"]).strip(), session
+
+
+def test_sign_in_is_refused_while_the_graph_profile_service_is_down(
+ entra: OwnedProxy, graph: Graph, clean_slate: None
+) -> None:
+ proxy: Final = entra.gateway
+ outage: Final = Reply(
+ status=503, body=b'{"error": {"code": "serviceNotAvailable", "message": "Service unavailable"}}'
+ )
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(outage))
+ assert callback.status_code == 401 and _session(callback) is None, f"{callback.status_code} {callback.text}"
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == GRAPH_REFUSED, callback.text
+ session: Final = _start_cli_login(proxy)
+ with _browser() as browser:
+ cli_callback: Final = _cli_callback(proxy, graph, browser, session, graph.profile(outage))
+ assert cli_callback.status_code == 401, _cli_report(proxy, browser, cli_callback, session)
+ assert JSON_OBJECT.validate_json(cli_callback.content)["detail"] == GRAPH_REFUSED, cli_callback.text
+ assert _poll(proxy, session) == {"status": "pending"}
+ assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_a_graph_reply_without_a_profile_falls_back_to_the_blank_id_refusal(
+ entra: OwnedProxy, graph: Graph, gateway_module: Gateway, clean_slate: None
+) -> None:
+ proxy: Final = entra.gateway
+ with gateway_module.scenario() as scenario:
+ victim_token: Final = _victim(scenario)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(Reply(body=b"{}")))
+ assert callback.status_code == 401 and _session(callback) is None, _refusal_report(
+ proxy, callback, victim_token
+ )
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == REFUSED, callback.text
+ assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_a_profile_with_an_empty_error_field_still_signs_in(
+ entra: OwnedProxy, graph: Graph, gateway_module: Gateway
+) -> None:
+ proxy: Final = entra.gateway
+ subject: Final = str(uuid.uuid4())
+ email: Final = f"empty-error-{uuid.uuid4().hex[:12]}@example.com"
+ profile: Final = {**JSON_OBJECT.validate_json(_profile(subject, email).body), "error": None}
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ callback: Final = _dashboard_sign_in(proxy, graph, graph.profile(Reply(body=json.dumps(profile).encode())))
+ assert callback.status_code == 303, f"{callback.status_code} {callback.text}"
+ session: Final = _session(callback)
+ assert session is not None and session["user_id"] == subject, session
+
+
+def test_sso_debug_callback_still_shows_the_graph_error(entra: OwnedProxy, graph: Graph, clean_slate: None) -> None:
+ proxy: Final = entra.gateway
+ with _browser() as browser:
+ callback: Final = _through_graph(
+ proxy,
+ graph,
+ browser,
+ f"{_proxy_url(proxy)}/sso/debug/login",
+ graph.profile(Reply(status=401, body=GRAPH_ERROR)),
+ callback="/sso/debug/callback",
+ )
+ assert callback.status_code == 200, f"{callback.status_code} {callback.text}"
+ assert "Authentication_MissingOrMalformed" in callback.text, callback.text
+ assert _session(callback) is None
+ assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_concurrent_failed_profile_lookups_mint_no_session(entra: OwnedProxy, graph: Graph, clean_slate: None) -> None:
+ proxy: Final = entra.gateway
+ hints: Final = [graph.profile(Reply(status=401, body=GRAPH_ERROR)) for _ in range(8)]
+ with ThreadPoolExecutor(max_workers=len(hints)) as pool:
+ callbacks: Final = list(pool.map(lambda hint: _dashboard_sign_in(proxy, graph, hint), hints))
+ assert [(callback.status_code, _session(callback)) for callback in callbacks] == [(401, None)] * len(hints), [
+ f"{callback.status_code} {callback.text[:120]}" for callback in callbacks
+ ]
+ tokens: Final = read_rows('SELECT token FROM "LiteLLM_VerificationToken" WHERE user_id ~ %s', (BLANK,))
+ assert tokens == [], f"{len(tokens)} blank-identity session keys were minted"
+ assert _blank_accounts() == (), _blank_accounts()
+
+
+def test_custom_mapped_sign_in_fails_with_500_when_the_account_lookup_loses_the_database(
+ graph: Graph, gateway_module: Gateway, tmp_path: Path
+) -> None:
+ outage_marker: Final = uuid.uuid4().hex[:12]
+ dashboard_email: Final = f"mapped-none-{outage_marker}[email protected]"
+ cli_email: Final = f"mapped-none-{outage_marker}[email protected]"
+ with (
+ dropped_connection_relay(os.environ["DATABASE_URL"], outage_marker.encode()) as (relay, relayed_url),
+ owned_proxy_process(
+ gateway_module,
+ tmp_path,
+ {
+ **_entra_environment(graph.wire.url),
+ "DATABASE_URL": relayed_url,
+ "PRISMA_HEALTH_WATCHDOG_ENABLED": "false",
+ },
+ config=_custom_mapping_config(tmp_path),
+ remove_environment=("PROXY_BASE_URL", "DATABASE_URL_READ_REPLICA"),
+ workers=2,
+ ) as owned,
+ gateway_module.scenario() as scenario,
+ ):
+ scenario.user(user_email=dashboard_email, user_role="internal_user")
+ scenario.user(user_email=cli_email, user_role="internal_user")
+ cli_login: Final = _start_cli_login(owned.gateway)
+ relay.arm()
+ callback: Final = _dashboard_sign_in(
+ owned.gateway, graph, graph.profile(_profile(str(uuid.uuid4()), dashboard_email))
+ )
+ dashboard_lookup_dropped: Final = relay.dropped.is_set()
+ relay.dropped.clear()
+ with _browser() as browser:
+ cli_callback: Final = _cli_callback(
+ owned.gateway, graph, browser, cli_login, graph.profile(_profile(str(uuid.uuid4()), cli_email))
+ )
+ relay.disarm()
+ assert dashboard_lookup_dropped and relay.dropped.is_set(), "an account lookup never reached the database"
+ session: Final = _session(callback)
+ assert callback.status_code == 500 and session is None, (
+ f"{callback.status_code}: session for user_id={None if session is None else session['user_id']!r}"
+ )
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == LOOKUP_FAILED, callback.text
+ assert cli_callback.status_code == 500, f"{cli_callback.status_code} {cli_callback.text}"
+ assert JSON_OBJECT.validate_json(cli_callback.content)["detail"] == LOOKUP_FAILED, cli_callback.text
+ assert _poll(owned.gateway, cli_login) == {"status": "pending"}
+
+
+def test_saml_sign_in_with_a_whitespace_name_id_and_no_email_is_refused(
+ saml: OwnedProxy, saml_idp: SamlIdp, gateway_module: Gateway, clean_slate: None
+) -> None:
+ proxy: Final = saml.gateway
+ with gateway_module.scenario() as scenario:
+ victim_token: Final = _victim(scenario)
+ callback: Final = _saml_sign_in(proxy, saml_idp, " ", None)
+ assert callback.status_code == 401 and _session(callback) is None, _refusal_report(
+ proxy, callback, victim_token
+ )
+ assert JSON_OBJECT.validate_json(callback.content)["detail"] == REFUSED, callback.text
+ assert _blank_accounts() == (), _blank_accounts()
+
+
[email protected]("blank_name_id", [True, False], ids=["whitespace-name-id", "name-id"])
+def test_saml_sign_in_with_an_email_signs_in_as_a_real_account(
+ saml: OwnedProxy, saml_idp: SamlIdp, gateway_module: Gateway, clean_slate: None, blank_name_id: bool
+) -> None:
+ proxy: Final = saml.gateway
+ email: Final = f"saml-{uuid.uuid4().hex[:12]}@example.com"
+ name_id: Final = " " if blank_name_id else f"saml-subject-{uuid.uuid4().hex[:12]}"
+ expected: Final = email if blank_name_id else name_id
+ with gateway_module.scenario() as scenario:
+ _forget_sign_in(scenario, email)
+ callback: Final = _saml_sign_in(proxy, saml_idp, name_id, email)
+ session: Final = _session(callback)
+ 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()
diff --git a/tests/unit/proxy/management_endpoints/test_ui_sso.py b/tests/unit/proxy/management_endpoints/test_ui_sso.py
index db5ec90335a..ddcaad3a570 100644
--- a/tests/unit/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/unit/proxy/management_endpoints/test_ui_sso.py
@@ -2,8 +2,10 @@ import asyncio
import json
import logging
import os
+from collections.abc import Awaitable, Callable, Mapping
from contextlib import ExitStack, asynccontextmanager
from types import SimpleNamespace
+from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
@@ -21,10 +23,13 @@ from litellm.proxy.management_endpoints.ui_sso import (
GoogleSSOHandler,
MicrosoftSSOHandler,
SSOAuthenticationHandler,
+ _complete_cli_sso_callback_session,
_setup_team_mappings,
_sync_user_role_from_jwt_role_map,
+ cli_sso_callback,
normalize_email,
process_sso_jwt_access_token,
+ sso_lookup_user_ids,
)
from litellm.types.proxy.management_endpoints.ui_sso import (
DefaultTeamSSOParams,
@@ -255,6 +260,90 @@ def test_get_microsoft_callback_response(stubbed_graph_api):
assert result.last_name == "User"
+GRAPH_ERROR_BODIES: Final = (
+ {"error": {"code": "Authentication_MissingOrMalformed", "message": "Access Token missing or malformed."}},
+ {"error": {"code": "InvalidAuthenticationToken", "message": "IDX14100: JWT is not well formed."}},
+)
+
+
[email protected]("graph_error", GRAPH_ERROR_BODIES)
+def test_get_microsoft_callback_response_fails_the_login_when_graph_returns_an_error(stubbed_graph_api, graph_error):
+ mock_request = MagicMock(spec=Request)
+ mock_request.scope = {}
+
+ with patch.dict(
+ os.environ,
+ {"MICROSOFT_CLIENT_SECRET": "mock_secret", "MICROSOFT_TENANT": "mock_tenant"},
+ ):
+ with patch(
+ "fastapi_sso.sso.microsoft.MicrosoftSSO.verify_and_process",
+ new=AsyncMock(return_value=graph_error),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ asyncio.run(
+ MicrosoftSSOHandler.get_microsoft_callback_response(
+ request=mock_request,
+ microsoft_client_id="mock_client_id",
+ redirect_url="http://mock_redirect_url",
+ )
+ )
+
+ assert exc_info.value.status_code == 401
+ assert exc_info.value.detail == "SSO login failed: Microsoft Graph returned an error instead of the user profile"
+
+
[email protected]("empty_error", [None, ""])
+def test_get_microsoft_callback_response_signs_in_a_profile_with_an_empty_error_field(stubbed_graph_api, empty_error):
+ mock_request = MagicMock(spec=Request)
+ mock_request.scope = {}
+ profile = {"id": "msft123", "mail": "[email protected]", "displayName": "Microsoft User"}
+
+ with patch.dict(
+ os.environ,
+ {"MICROSOFT_CLIENT_SECRET": "mock_secret", "MICROSOFT_TENANT": "mock_tenant"},
+ ):
+ with patch(
+ "fastapi_sso.sso.microsoft.MicrosoftSSO.verify_and_process",
+ new=AsyncMock(return_value={**profile, "error": empty_error}),
+ ):
+ result = asyncio.run(
+ MicrosoftSSOHandler.get_microsoft_callback_response(
+ request=mock_request,
+ microsoft_client_id="mock_client_id",
+ redirect_url="http://mock_redirect_url",
+ )
+ )
+
+ assert isinstance(result, CustomOpenID)
+ assert result.id == "msft123"
+ assert result.email == "[email protected]"
+
+
+def test_get_microsoft_callback_response_raw_sso_response_keeps_the_graph_error(stubbed_graph_api):
+ mock_request = MagicMock(spec=Request)
+ graph_error = GRAPH_ERROR_BODIES[0]
+
+ with patch.dict(
+ os.environ,
+ {"MICROSOFT_CLIENT_SECRET": "mock_secret", "MICROSOFT_TENANT": "mock_tenant"},
+ ):
+ with patch(
+ "fastapi_sso.sso.microsoft.MicrosoftSSO.verify_and_process",
+ new=AsyncMock(return_value=dict(graph_error)),
+ ):
+ result = asyncio.run(
+ MicrosoftSSOHandler.get_microsoft_callback_response(
+ request=mock_request,
+ microsoft_client_id="mock_client_id",
+ redirect_url="http://mock_redirect_url",
+ return_raw_sso_response=True,
+ )
+ )
+
+ assert isinstance(result, dict)
+ assert result["error"] == graph_error["error"]
+
+
def test_get_microsoft_callback_response_raw_sso_response(stubbed_graph_api):
# Arrange
mock_request = MagicMock(spec=Request)
@@ -1181,6 +1270,33 @@ async def test_insert_sso_user_sets_user_alias_from_display_name():
assert new_user_request.user_alias == "Doe, Jane"
[email protected]("user_id", ["", " "])
+async def test_insert_sso_user_refuses_a_blank_user_id(user_id: str) -> None:
+ from litellm.proxy._types import SSOUserDefinedValues
+ from litellm.proxy.management_endpoints.ui_sso import insert_sso_user
+
+ user_defined_values: Final[SSOUserDefinedValues] = {
+ "models": [],
+ "user_id": user_id,
+ "user_email": "[email protected]",
+ "max_budget": None,
+ "user_role": "internal_user",
+ "budget_duration": None,
+ }
+
+ with (
+ patch("litellm.proxy.management_endpoints.ui_sso.new_user") as mock_new_user,
+ pytest.raises(ValueError, match="SSO user id is blank"),
+ ):
+ await insert_sso_user(
+ result_openid=CustomOpenID(email="[email protected]", provider="generic", team_ids=[]),
+ user_defined_values=user_defined_values,
+ )
+
+ mock_new_user.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_upsert_sso_user_does_not_update_invalid_role():
"""
@@ -1306,6 +1422,237 @@ def test_get_user_email_and_id_extracts_microsoft_role():
assert parsed.get("user_role") == "proxy_admin_viewer"
+ ("result", "expected_user_id"),
+ [
+ pytest.param(
+ CustomOpenID(id="entra-object-id", email="[email protected]", provider="microsoft", team_ids=[]),
+ "entra-object-id",
+ id="id",
+ ),
+ pytest.param(CustomOpenID(email="[email protected]", provider="generic", team_ids=[]), "[email protected]", id="email"),
+ pytest.param(
+ CustomOpenID(id=" ", email="[email protected]", provider="generic", team_ids=[]),
+ id="whitespace-id-email-fallback",
+ ),
+ pytest.param(
+ CustomOpenID(first_name=" ", email="[email protected]", provider="generic", team_ids=[]),
+ id="whitespace-name-email-fallback",
+ ),
+ pytest.param(
+ CustomOpenID(first_name="Ada", last_name="Lovelace", provider="generic", team_ids=[]),
+ "AdaLovelace",
+ id="names",
+ ),
+ ],
+)
+def test_get_user_email_and_id_resolves_identity(result: CustomOpenID, expected_user_id: str) -> None:
+ parsed: Final = SSOAuthenticationHandler._get_user_email_and_id_from_result(result=result, generic_client_id=None)
+
+ assert parsed.get("user_id") == expected_user_id
+
+
+def _empty_identity_redirect_patches(
+ custom_sso: Callable[[CustomOpenID], Awaitable[Mapping[str, object] | None]] | None,
+ user_info_from_db: AsyncMock,
+ generate_key: AsyncMock,
+) -> tuple[MagicMock, ExitStack]:
+ mock_request: Final = MagicMock(spec=Request)
+ mock_request.scope = {}
+ mock_request.base_url = "http://localhost:4000/"
+ mock_request.cookies = {}
+ stack: Final = ExitStack()
+ for target, value in (
+ ("litellm.proxy.utils.get_prisma_client_or_throw", MagicMock(return_value=MagicMock())),
+ ("litellm.proxy.proxy_server.master_key", "sk-master"),
+ ("litellm.proxy.proxy_server.general_settings", {}),
+ ("litellm.proxy.proxy_server.premium_user", False),
+ ("litellm.proxy.proxy_server.user_custom_sso", custom_sso),
+ ("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
+ ("litellm.proxy.proxy_server.redis_usage_cache", None),
+ ("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
+ ("litellm.proxy.proxy_server.generate_key_helper_fn", generate_key),
+ ("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", user_info_from_db),
+ ):
+ stack.enter_context(patch(target, value)) # test-quality-ok: endpoint reads proxy globals and DB helpers
+ return mock_request, stack
+
+
+async def test_redirect_from_openid_allows_custom_sso_to_resolve_missing_provider_identity() -> None:
+ async def custom_sso(result: CustomOpenID) -> Mapping[str, object]:
+ return {
+ "models": [],
+ "user_id": (result.extra_fields or {})["employee_id"],
+ "user_email": None,
+ "user_role": None,
+ "max_budget": None,
+ "budget_duration": None,
+ }
+
+ user_info_from_db: Final = AsyncMock(side_effect=RuntimeError("stop after identity resolution"))
+ generate_key: Final = AsyncMock()
+ mock_request, stack = _empty_identity_redirect_patches(custom_sso, user_info_from_db, generate_key)
+ result: Final = CustomOpenID(provider="generic", team_ids=[], extra_fields={"employee_id": "mapped-user"})
+
+ with stack, pytest.raises(RuntimeError, match="stop after identity resolution"):
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=result,
+ request=mock_request,
+ received_response=None,
+ generic_client_id=None,
+ ui_access_mode=None,
+ )
+
+ assert user_info_from_db.await_args.kwargs["user_defined_values"]["user_id"] == "mapped-user"
+ generate_key.assert_not_awaited()
+
+
+_GRAPH_ME_ERROR_PAYLOAD: Final = {
+ "error": {
+ "code": "Authentication_MissingOrMalformed",
+ "message": "Access Token missing or malformed.",
+ }
+}
+
+
+async def test_redirect_from_openid_rejects_graph_error_payload_before_db_and_key_mint() -> None:
+ user_info_from_db: Final = AsyncMock(return_value=None)
+ generate_key: Final = AsyncMock(return_value={"token": "sk-ui-key", "user_id": ""})
+ mock_request, stack = _empty_identity_redirect_patches(None, user_info_from_db, generate_key)
+ graph_error: Final = MicrosoftSSOHandler.openid_from_response(
+ response=_GRAPH_ME_ERROR_PAYLOAD, team_ids=[], user_role=None
+ )
+
+ with stack, pytest.raises(HTTPException) as exc_info:
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=graph_error,
+ request=mock_request,
+ received_response=None,
+ generic_client_id=None,
+ ui_access_mode=None,
+ )
+
+ assert exc_info.value.status_code == 401
+ user_info_from_db.assert_not_awaited()
+ generate_key.assert_not_awaited()
+
+
+async def test_redirect_from_openid_rejects_the_empty_provider_result_before_db_and_key_mint() -> None:
+ user_info_from_db: Final = AsyncMock(return_value=None)
+ generate_key: Final = AsyncMock(return_value={"token": "sk-ui-key", "user_id": ""})
+ mock_request, stack = _empty_identity_redirect_patches(None, user_info_from_db, generate_key)
+
+ with stack, pytest.raises(HTTPException) as exc_info:
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result={},
+ request=mock_request,
+ received_response=None,
+ generic_client_id=None,
+ ui_access_mode=None,
+ )
+
+ assert exc_info.value.status_code == 401
+ user_info_from_db.assert_not_awaited()
+ generate_key.assert_not_awaited()
+
+
+def _custom_sso_returning_user_id(custom_user_id: object) -> Callable[[CustomOpenID], Awaitable[Mapping[str, object]]]:
+ async def custom_sso(result: CustomOpenID) -> Mapping[str, object]:
+ return {
+ "models": [],
+ "user_id": custom_user_id,
+ "user_email": None,
+ "user_role": None,
+ "max_budget": None,
+ "budget_duration": None,
+ }
+
+ return custom_sso
+
+
[email protected]("custom_user_id", [None, "", " ", 424242])
+async def test_redirect_from_openid_signs_a_custom_sso_user_in_as_the_matched_account(custom_user_id: object) -> None:
+ user_info_from_db: Final = AsyncMock(return_value=LiteLLM_UserTable(user_id="existing-user"))
+ generate_key: Final = AsyncMock(side_effect=RuntimeError("stop at key mint"))
+ mock_request, stack = _empty_identity_redirect_patches(
+ _custom_sso_returning_user_id(custom_user_id), user_info_from_db, generate_key
+ )
+
+ with stack, pytest.raises(RuntimeError, match="stop at key mint"):
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=CustomOpenID(id="idp-subject", email="[email protected]", provider="generic", team_ids=[]),
+ request=mock_request,
+ )
+
+ user_info_from_db.assert_awaited_once()
+ assert generate_key.await_args.kwargs["user_id"] == "existing-user"
+
+
[email protected]("custom_user_id", [None, "", " ", 424242])
+async def test_redirect_from_openid_rejects_a_custom_sso_user_id_that_resolves_no_account(
+ custom_user_id: object,
+) -> None:
+ user_info_from_db: Final = AsyncMock(return_value=None)
+ generate_key: Final = AsyncMock(side_effect=AssertionError("A blank identity must not reach key generation"))
+ mock_request, stack = _empty_identity_redirect_patches(
+ _custom_sso_returning_user_id(custom_user_id), user_info_from_db, generate_key
+ )
+
+ with stack, pytest.raises(HTTPException) as exc_info:
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=CustomOpenID(id="idp-subject", provider="generic", team_ids=[]),
+ request=mock_request,
+ )
+
+ assert exc_info.value.status_code == 401
+ user_info_from_db.assert_awaited_once()
+ generate_key.assert_not_awaited()
+
+
[email protected]("user_id", ["", " "])
+async def test_redirect_from_openid_rejects_blank_database_identity_before_key_mint(user_id: str) -> None:
+ user_info_from_db: Final = AsyncMock(return_value=LiteLLM_UserTable(user_id=user_id))
+ generate_key: Final = AsyncMock(side_effect=AssertionError("A blank identity must not reach key generation"))
+ mock_request, stack = _empty_identity_redirect_patches(None, user_info_from_db, generate_key)
+
+ with stack, pytest.raises(HTTPException) as exc_info:
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=CustomOpenID(id="idp-subject", team_ids=[]),
+ request=mock_request,
+ )
+
+ assert exc_info.value.status_code == 401
+ user_info_from_db.assert_awaited_once()
+ generate_key.assert_not_awaited()
+
+
+async def test_redirect_from_openid_keeps_the_unmapped_custom_sso_failure() -> None:
+ async def custom_sso(result: CustomOpenID) -> None:
+ return None
+
+ user_info_from_db: Final = AsyncMock(return_value=LiteLLM_UserTable(user_id="idp-subject"))
+ generate_key: Final = AsyncMock()
+ mock_request, stack = _empty_identity_redirect_patches(custom_sso, user_info_from_db, generate_key)
+
+ with stack, pytest.raises(Exception, match="Unable to map user identity to known values"):
+ await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=CustomOpenID(id="idp-subject", provider="generic", team_ids=[]),
+ request=mock_request,
+ )
+
+ user_info_from_db.assert_awaited_once()
+ generate_key.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_get_user_info_from_db_user_exists():
"""
@@ -1392,6 +1739,21 @@ async def test_get_user_info_from_db_user_exists_alternate_user_id():
assert mock_get_user_object.call_args.kwargs["user_id"] == "krrishd-email1234"
+ ("alternate_user_id", "provider_id", "expected"),
+ [
+ pytest.param("[email protected]", " ", ("[email protected]",), id="blank-provider-id"),
+ pytest.param("", "provider-id", ("provider-id",), id="blank-alternate-id"),
+ pytest.param(None, " ", (), id="nothing-usable"),
+ pytest.param("alt", "provider-id", ("alt", "provider-id"), id="both"),
+ ],
+)
+def test_sso_lookup_user_ids_never_offers_a_blank_id(
+ alternate_user_id: str | None, provider_id: str | None, expected: tuple[str, ...]
+) -> None:
+ assert sso_lookup_user_ids(alternate_user_id, provider_id) == expected
+
+
@pytest.mark.asyncio
async def test_get_user_info_from_db_user_not_exists_creates_user():
"""
@@ -1585,6 +1947,102 @@ async def test_get_user_info_from_db_user_exists_updates_user():
assert user_info == updated_user
+def _database_outage() -> httpx.ConnectError:
+ return httpx.ConnectError("All connection attempts failed")
+
+
+async def _new_user_during_database_outage(**_: object) -> NewUserResponse:
+ raise HTTPException(status_code=500, detail="user insert failed") from _database_outage()
+
+
+async def _sso_user_info_from_db(
+ custom_user_id: object,
+ prisma_client: MagicMock,
+ cached_user: LiteLLM_UserTable | None = None,
+) -> LiteLLM_UserTable | NewUserResponse | None:
+ from litellm.proxy.management_endpoints.ui_sso import get_user_info_from_db
+
+ subject: Final = f"idp-subject-{uuid.uuid4().hex}"
+ email: Final = f"{subject}@example.com"
+ with patch("litellm.proxy.management_endpoints.ui_sso.new_user", _new_user_during_database_outage):
+ return await get_user_info_from_db(
+ result=CustomOpenID(id=subject, email=email, provider="generic", team_ids=[]),
+ prisma_client=prisma_client,
+ user_api_key_cache=MagicMock(
+ async_get_cache=AsyncMock(return_value=cached_user), async_set_cache=AsyncMock()
+ ),
+ proxy_logging_obj=MagicMock(),
+ user_email=email,
+ user_defined_values={
+ "models": [],
+ "user_id": custom_user_id,
+ "user_email": email,
+ "max_budget": None,
+ "user_role": None,
+ "budget_duration": None,
+ },
+ alternate_user_id=subject,
+ )
+
+
[email protected]("custom_user_id", [None, "", " ", 424242])
+async def test_get_user_info_from_db_fails_with_500_when_the_database_is_down_for_a_sign_in_with_no_user_id(
+ custom_user_id: object,
+) -> None:
+ prisma_client: Final = MagicMock(**{"db.litellm_usertable.find_unique": AsyncMock(side_effect=_database_outage())})
+
+ with pytest.raises(HTTPException) as exc_info:
+ await _sso_user_info_from_db(custom_user_id, prisma_client)
+
+ assert (exc_info.value.status_code, exc_info.value.detail) == (500, "Failed to retrieve user information from SSO")
+
+
+async def test_get_user_info_from_db_fails_with_500_when_the_database_drops_while_creating_the_account() -> None:
+ prisma_client: Final = MagicMock(
+ **{
+ "db.litellm_usertable.find_unique": AsyncMock(return_value=None),
+ "db.litellm_usertable.find_first": AsyncMock(return_value=None),
+ }
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await _sso_user_info_from_db(None, prisma_client)
+
+ assert (exc_info.value.status_code, exc_info.value.detail) == (500, "Failed to retrieve user information from SSO")
+
+
[email protected]("custom_user_id", ["", " "])
+async def test_get_user_info_from_db_resolves_no_account_when_the_database_finds_none_for_a_blank_user_id(
+ custom_user_id: str,
+) -> None:
+ prisma_client: Final = MagicMock(
+ **{
+ "db.litellm_usertable.find_unique": AsyncMock(return_value=None),
+ "db.litellm_usertable.find_first": AsyncMock(return_value=None),
+ }
+ )
+
+ assert await _sso_user_info_from_db(custom_user_id, prisma_client) is None
+
+
+async def test_get_user_info_from_db_keeps_reading_a_database_outage_as_no_account_for_a_mapped_user_id() -> None:
+ prisma_client: Final = MagicMock(**{"db.litellm_usertable.find_unique": AsyncMock(side_effect=_database_outage())})
+
+ assert await _sso_user_info_from_db("mapped-user-id", prisma_client) is None
+
+
+async def test_get_user_info_from_db_keeps_the_matched_account_when_its_update_hits_a_database_outage() -> None:
+ matched: Final = LiteLLM_UserTable(user_id="existing-user", user_email="[email protected]")
+ prisma_client: Final = MagicMock(**{"db.litellm_usertable.update_many": AsyncMock(side_effect=_database_outage())})
+
+ assert await _sso_user_info_from_db(None, prisma_client, cached_user=matched) is matched
+
+
@pytest.mark.asyncio
async def test_check_and_update_if_proxy_admin_id():
"""
@@ -3175,7 +3633,7 @@ class TestCLIKeyRegenerationFlow:
teams=[],
models=[],
)
- mock_sso_result = {"user_email": "[email protected]", "user_id": "test-user-123"}
+ mock_sso_result: Final = CustomOpenID(id="test-user-123", email="[email protected]", team_ids=[])
mock_cache = MagicMock(redis_cache=None)
mock_cache.get_cache.return_value = {
@@ -3345,7 +3803,7 @@ class TestCLIKeyRegenerationFlow:
)
# Mock SSO result
- mock_sso_result = {"user_email": "[email protected]", "user_id": "test-user-123"}
+ mock_sso_result: Final = CustomOpenID(id="test-user-123", email="[email protected]", team_ids=[])
# Mock cache
mock_cache = MagicMock(redis_cache=None)
@@ -7288,7 +7746,7 @@ class TestCliSsoAttributionMetadata:
teams=[],
models=[],
)
- mock_sso_result = CustomOpenID(
+ mock_sso_result: Final = CustomOpenID(
id="cli-test-user",
display_name="cli-test-user",
@@ -7345,7 +7803,7 @@ class TestCliSsoAttributionMetadata:
"user_code_verified": False,
"session_data": None,
}
- mock_sso_result = CustomOpenID(
+ mock_sso_result: Final = CustomOpenID(
id="cli-test-user",
display_name="cli-test-user",
@@ -7403,11 +7861,12 @@ class TestCliSsoAttributionMetadata:
teams=["team1"],
models=["gpt-4"],
)
- mock_sso_result = {
- "user_email": "[email protected]",
- "user_id": "test-user-123",
- "employment_type": "contractor",
- }
+ mock_sso_result: Final = CustomOpenID(
+ id="test-user-123",
+ team_ids=[],
+ extra_fields={"employment_type": "contractor"},
+ )
mock_cache = MagicMock(redis_cache=None)
mock_cache.get_cache.return_value = {
"poll_secret_hash": "poll-secret-hash",
@@ -9541,6 +10000,173 @@ async def test_cli_completion_fails_the_login_when_team_lookup_fails():
assert "session_data" not in flow
[email protected]("parsed_user_id", ["", " "])
+async def test_cli_completion_rejects_a_blank_provider_identity_before_db(parsed_user_id: str) -> None:
+ flow: Final = {}
+ defaults: Final = _cli_callback_kwargs(flow)
+ kwargs: Final = {
+ **defaults,
+ "parsed_openid_result": {**defaults["parsed_openid_result"], "user_id": parsed_user_id},
+ }
+ get_user_info_mock: Final = AsyncMock(return_value=_cli_callback_user_info([]))
+
+ with (
+ patch("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", get_user_info_mock),
+ pytest.raises(HTTPException) as exc_info,
+ ):
+ await _complete_cli_sso_callback_session(**kwargs)
+
+ assert exc_info.value.status_code == 401
+ get_user_info_mock.assert_not_awaited()
+ assert "session_data" not in flow
+
+
[email protected]("custom_user_id", [None, "", " ", 424242])
+async def test_cli_completion_signs_a_custom_sso_user_in_as_the_matched_account(custom_user_id: object) -> None:
+ flow: Final = {}
+ defaults: Final = _cli_callback_kwargs(flow)
+ kwargs: Final = {
+ **defaults,
+ "parsed_openid_result": {**defaults["parsed_openid_result"], "user_id": ""},
+ "user_defined_values": {
+ "models": [],
+ "user_id": custom_user_id,
+ "user_email": "[email protected]",
+ "max_budget": None,
+ "user_role": None,
+ "budget_duration": None,
+ },
+ }
+ get_user_info_mock: Final = AsyncMock(return_value=_cli_callback_user_info([]))
+
+ with (
+ patch("litellm.proxy.proxy_server.user_custom_sso", _custom_sso_returning_user_id(custom_user_id)),
+ patch("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", get_user_info_mock),
+ patch("litellm.proxy.management_endpoints.ui_sso.fetch_cli_sso_team_details", AsyncMock(return_value=())),
+ patch("litellm.proxy.management_endpoints.ui_sso.build_cli_sso_attribution_metadata", return_value={}),
+ patch("litellm.proxy.management_endpoints.ui_sso.retain_sso_identity_assertion_for_ema", AsyncMock()),
+ ):
+ response: Final = await _complete_cli_sso_callback_session(**kwargs)
+
+ assert response.status_code == 200
+ get_user_info_mock.assert_awaited_once()
+ assert flow["session_data"]["user_id"] == "cli-user-id"
+
+
+def _cli_custom_sso_kwargs(flow: dict, custom_user_id: object) -> dict:
+ defaults: Final = _cli_callback_kwargs(flow)
+ return {
+ **defaults,
+ "parsed_openid_result": {**defaults["parsed_openid_result"], "user_id": ""},
+ "user_defined_values": {
+ "models": [],
+ "user_id": custom_user_id,
+ "user_email": "[email protected]",
+ "max_budget": None,
+ "user_role": None,
+ "budget_duration": None,
+ },
+ }
+
+
[email protected]("custom_user_id", [None, "", " ", "\t", 424242])
+async def test_cli_completion_rejects_a_custom_sso_user_id_that_resolves_no_account(custom_user_id: object) -> None:
+ flow: Final = {}
+ kwargs: Final = _cli_custom_sso_kwargs(flow, custom_user_id)
+ get_user_info_mock: Final = AsyncMock(return_value=None)
+
+ with (
+ patch("litellm.proxy.proxy_server.user_custom_sso", _custom_sso_returning_user_id(custom_user_id)),
+ patch("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", get_user_info_mock),
+ pytest.raises(HTTPException) as exc_info,
+ ):
+ await _complete_cli_sso_callback_session(**kwargs)
+
+ assert exc_info.value.status_code == 401
+ assert exc_info.value.detail == "SSO login failed: this sign-in did not resolve to a user id"
+ get_user_info_mock.assert_awaited_once()
+ assert "session_data" not in flow
+ kwargs["cli_sso_session_cache"].set_cache.assert_not_called()
+
+
+async def test_cli_completion_keeps_the_lookup_failure_for_a_custom_sso_user_id() -> None:
+ flow: Final = {}
+ kwargs: Final = _cli_custom_sso_kwargs(flow, "mapped-user-id")
+
+ with (
+ patch("litellm.proxy.proxy_server.user_custom_sso", _custom_sso_returning_user_id("mapped-user-id")),
+ patch("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", AsyncMock(return_value=None)),
+ pytest.raises(HTTPException) as exc_info,
+ ):
+ await _complete_cli_sso_callback_session(**kwargs)
+
+ assert exc_info.value.status_code == 500
+ assert exc_info.value.detail == "Failed to retrieve user information from SSO"
+ assert "session_data" not in flow
+
+
[email protected]("user_id", ["", " "])
+async def test_cli_completion_rejects_blank_database_identity_before_session(user_id: str) -> None:
+ flow: Final = {}
+ kwargs: Final = _cli_callback_kwargs(flow)
+ get_user_info_mock: Final = AsyncMock(return_value=LiteLLM_UserTable(user_id=user_id))
+
+ with (
+ patch("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", get_user_info_mock),
+ pytest.raises(HTTPException) as exc_info,
+ ):
+ await _complete_cli_sso_callback_session(**kwargs)
+
+ assert exc_info.value.status_code == 401
+ assert "session_data" not in flow
+ kwargs["cli_sso_session_cache"].set_cache.assert_not_called()
+
+
+async def test_cli_sso_callback_completes_for_an_existing_user_when_custom_sso_returns_none() -> None:
+ async def custom_sso(_result: CustomOpenID) -> None:
+ return None
+
+ mock_request: Final = MagicMock(spec=Request)
+ mock_request.scope = {}
+ mock_request.base_url = "http://internal-proxy.local/"
+ mock_cache: Final = MagicMock(redis_cache=None)
+ mock_cache.get_cache.return_value = {
+ "poll_secret_hash": "poll-secret-hash",
+ "user_code_hash": "user-code-hash",
+ "sso_complete": False,
+ "user_code_verified": False,
+ "session_data": None,
+ }
+ get_user_info_mock: Final = AsyncMock(
+ return_value=LiteLLM_UserTable(user_id="provider-id", user_role="internal_user")
+ )
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", mock_cache),
+ patch("litellm.proxy.proxy_server.cli_sso_session_cache", mock_cache),
+ patch("litellm.proxy.proxy_server.user_custom_sso", custom_sso),
+ patch("litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db", get_user_info_mock),
+ ):
+ response: Final = await cli_sso_callback(
+ request=mock_request,
+ key="cli-session-4567890",
+ result=CustomOpenID(id="provider-id", email="[email protected]", team_ids=[]),
+ )
+
+ assert response.status_code == 200
+ assert get_user_info_mock.await_args.kwargs["alternate_user_id"] == "provider-id"
+ assert get_user_info_mock.await_args.kwargs["user_defined_values"] is None
+ stored_flow: Final = mock_cache.set_cache.call_args.kwargs["value"]
+ assert stored_flow["session_data"]["user_id"] == "provider-id"
+
+
class TestSameOriginReturnPath:
"""The same-origin relative return_to arm added for the MCP gateway DCR authorize
round-trip: only strictly relative paths qualify, so login can never redirect the