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]

[Feat] SSO - Allow users to run a custom sso login handler (#12465)

Ishaan Jaff17ea770ab532
diff --git a/docs/my-website/docs/proxy/custom_sso.md b/docs/my-website/docs/proxy/custom_sso.md
index a89de0f324f..8e869a11393 100644
--- a/docs/my-website/docs/proxy/custom_sso.md
+++ b/docs/my-website/docs/proxy/custom_sso.md
@@ -1,20 +1,126 @@
-# Event Hook for SSO Login (Custom Handler)
+# ✨ Event Hooks for SSO Login
-Use this if you want to run your own code after a user signs on to the LiteLLM UI using SSO
+:::info
-## How it works
+✨ This is an Enterprise only feature [Get Started with Enterprise here](https://www.litellm.ai/enterprise)
+
+:::
+
+## Overview
+
+LiteLLM provides two different SSO hooks depending on your authentication setup:
+
+| Hook Type | When to Use | What It Does |
+|-----------|-------------|--------------|
+| **Custom UI SSO Sign-in Handler** | You have an OAuth proxy (oauth2-proxy, Gatekeeper, Vouch, etc.) in front of LiteLLM | Parses user info from request headers and signs user into UI |
+| **Custom SSO Handler** | You use direct SSO providers (Google, Microsoft, SAML) and want custom post-auth logic | Runs custom code after standard OAuth flow to set user permissions/teams |
+
+**Quick Decision Guide:**
+- ✅ **Use Custom UI SSO Sign-in Handler** if user authentication happens outside LiteLLM (via headers)
+- ✅ **Use Custom SSO Handler** if you want LiteLLM to handle OAuth flow + run custom logic afterward
+
+---
+
+## Option 1: Custom UI SSO Sign-in Handler
+
+Use this when you have an **OAuth proxy in front of LiteLLM** that has already authenticated the user and passes user information via request headers.
+
+### How it works
+- User lands on Admin UI
+- 👉 **Your custom SSO sign-in handler is called to parse request headers and return user info**
+- LiteLLM has retrieved user information from your custom handler
+- User signed in to UI
+
+### Usage
+
+#### 1. Create a custom UI SSO handler file
+
+This handler parses request headers and returns user information as an OpenID object:
+
+```python
+from fastapi import Request
+from fastapi_sso.sso.base import OpenID
+from litellm.integrations.custom_sso_handler import CustomSSOLoginHandler
+
+
+class MyCustomSSOLoginHandler(CustomSSOLoginHandler):
+ """
+ Custom handler for parsing OAuth proxy headers
+
+ Use this when you have an OAuth proxy (like oauth2-proxy, Vouch, etc.)
+ in front of LiteLLM that adds user info to request headers
+ """
+ async def handle_custom_ui_sso_sign_in(
+ self,
+ request: Request,
+ ) -> OpenID:
+ # Parse headers from your OAuth proxy
+ request_headers = dict(request.headers)
+
+ # Extract user info from headers (adjust header names for your proxy)
+ user_id = request_headers.get("x-forwarded-user") or request_headers.get("x-user")
+ user_email = request_headers.get("x-forwarded-email") or request_headers.get("x-email")
+ user_name = request_headers.get("x-forwarded-preferred-username") or request_headers.get("x-preferred-username")
+
+ # Return OpenID object with user information
+ return OpenID(
+ id=user_id or "unknown",
+ email=user_email or "[email protected]",
+ first_name=user_name or "Unknown",
+ last_name="User",
+ display_name=user_name or "Unknown User",
+ picture=None,
+ provider="oauth-proxy",
+ )
+
+# Create an instance to be used by LiteLLM
+custom_ui_sso_sign_in_handler = MyCustomSSOLoginHandler()
+```
+
+#### 2. Configure in config.yaml
+
+```yaml
+model_list:
+ - model_name: "openai-model"
+ litellm_params:
+ model: "gpt-3.5-turbo"
+
+general_settings:
+ custom_ui_sso_sign_in_handler: custom_sso_handler.custom_ui_sso_sign_in_handler
+
+litellm_settings:
+ drop_params: True
+ set_verbose: True
+```
+
+#### 3. Start the proxy
+```shell
+$ litellm --config /path/to/config.yaml
+```
+
+#### 4. Navigate to the Admin UI
+
+When a user attempts navigating to the LiteLLM Admin UI, the request will be routed to your custom UI SSO sign-in handler.
+
+---
+
+## Option 2: Custom SSO Handler (Post-Authentication)
+
+Use this if you want to run your own code **after** a user signs on to the LiteLLM UI using standard SSO providers (Google, Microsoft, etc.)
+
+### How it works
- User lands on Admin UI
-- LiteLLM redirects user to your SSO provider
-- Your SSO provider redirects user back to LiteLLM
+- LiteLLM redirects user to your SSO provider (Google, Microsoft, etc.)
+- Your SSO provider redirects user back to LiteLLM
- LiteLLM has retrieved user information from your IDP
-- **Your custom SSO handler is called and returns an object of type SSOUserDefinedValues**
+- 👉 **Your custom SSO handler is called and returns an object of type SSOUserDefinedValues**
- User signed in to UI
-## Usage
+### Usage
-#### 1. Create a custom sso handler file.
+#### 1. Create a custom SSO handler file
-Make sure the response type follows the `SSOUserDefinedValues` pydantic object. This is used for logging the user into the Admin UI
+Make sure the response type follows the `SSOUserDefinedValues` pydantic object. This is used for logging the user into the Admin UI:
```python
from fastapi import Request
@@ -40,7 +146,7 @@ async def custom_sso_handler(userIDPInfo: OpenID) -> SSOUserDefinedValues:
#################################################
- # Run you custom code / logic here
+ # Run your custom code / logic here
# check if user exists in litellm proxy DB
_user_info = await user_info(user_id=userIDPInfo.id)
print("_user_info from litellm DB ", _user_info) # noqa
@@ -58,23 +164,24 @@ async def custom_sso_handler(userIDPInfo: OpenID) -> SSOUserDefinedValues:
raise Exception("Failed custom auth")
```
-#### 2. Pass the filepath (relative to the config.yaml)
+#### 2. Configure in config.yaml
-Pass the filepath to the config.yaml
+Pass the filepath to the config.yaml.
e.g. if they're both in the same dir - `./config.yaml` and `./custom_sso.py`, this is what it looks like:
+
```yaml
model_list:
- model_name: "openai-model"
litellm_params:
model: "gpt-3.5-turbo"
+general_settings:
+ custom_sso: custom_sso.custom_sso_handler
+
litellm_settings:
drop_params: True
set_verbose: True
-
-general_settings:
- custom_sso: custom_sso.custom_sso_handler
```
#### 3. Start the proxy
diff --git a/enterprise/litellm_enterprise/proxy/auth/__init__.py b/enterprise/litellm_enterprise/proxy/auth/__init__.py
new file mode 100644
index 00000000000..f67826ca7fa
--- /dev/null
+++ b/enterprise/litellm_enterprise/proxy/auth/__init__.py
@@ -0,0 +1,10 @@
+"""
+Enterprise Authentication Module for LiteLLM Proxy
+
+This module contains enterprise-specific authentication functionality,
+including custom SSO handlers and advanced authentication features.
+"""
+
+from .custom_sso_handler import EnterpriseCustomSSOHandler
+
+__all__ = ["EnterpriseCustomSSOHandler"]
\ No newline at end of file
diff --git a/enterprise/litellm_enterprise/proxy/auth/custom_sso_handler.py b/enterprise/litellm_enterprise/proxy/auth/custom_sso_handler.py
new file mode 100644
index 00000000000..a3682320387
--- /dev/null
+++ b/enterprise/litellm_enterprise/proxy/auth/custom_sso_handler.py
@@ -0,0 +1,86 @@
+"""
+Enterprise Custom SSO Handler for LiteLLM Proxy
+
+This module contains enterprise-specific custom SSO authentication functionality
+that allows users to implement their own SSO handling logic by providing custom
+handlers that process incoming request headers and return OpenID objects.
+
+Use this when you have an OAuth proxy in front of LiteLLM (where the OAuth proxy
+has already authenticated the user) and you need to extract user information from
+custom headers or other request attributes.
+"""
+
+from typing import TYPE_CHECKING, Dict, Optional, Union, cast
+
+from fastapi import Request
+from fastapi.responses import RedirectResponse
+
+if TYPE_CHECKING:
+ from fastapi_sso.sso.base import OpenID
+else:
+ from typing import Any as OpenID
+
+from litellm.proxy.management_endpoints.types import CustomOpenID
+
+
+class EnterpriseCustomSSOHandler:
+ """
+ Enterprise Custom SSO Handler for LiteLLM Proxy
+
+ This class provides methods for handling custom SSO authentication flows
+ where users can implement their own authentication logic by processing
+ request headers and returning user information in OpenID format.
+ """
+
+ @staticmethod
+ async def handle_custom_ui_sso_sign_in(
+ request: Request,
+ ) -> RedirectResponse:
+ """
+ Allow a user to execute their custom code to parse incoming request headers and return a OpenID object
+
+ Use this when you have an OAuth proxy in front of LiteLLM (where the OAuth proxy has already authenticated the user)
+
+ Args:
+ request: The FastAPI request object containing headers and other request data
+
+ Returns:
+ RedirectResponse: Redirect response that sends the user to the LiteLLM UI with authentication token
+
+ Raises:
+ ValueError: If custom_ui_sso_sign_in_handler is not configured
+
+ Example:
+ This method is typically called when a user has already been authenticated by an
+ external OAuth proxy and the proxy has added custom headers containing user information.
+ The custom handler extracts this information and converts it to an OpenID object.
+ """
+ from fastapi_sso.sso.base import OpenID
+
+ from litellm.integrations.custom_sso_handler import CustomSSOLoginHandler
+ from litellm.proxy.proxy_server import (
+ CommonProxyErrors,
+ premium_user,
+ user_custom_ui_sso_sign_in_handler,
+ )
+ if premium_user is not True:
+ raise ValueError(CommonProxyErrors.not_premium_user.value)
+
+ if user_custom_ui_sso_sign_in_handler is None:
+ raise ValueError("custom_ui_sso_sign_in_handler is not configured. Please set it in general_settings.")
+
+ custom_sso_login_handler = cast(CustomSSOLoginHandler, user_custom_ui_sso_sign_in_handler)
+ openid_response: OpenID = await custom_sso_login_handler.handle_custom_ui_sso_sign_in(
+ request=request,
+ )
+
+ # Import here to avoid circular imports
+ from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler
+
+ return await SSOAuthenticationHandler.get_redirect_response_from_openid(
+ result=openid_response,
+ request=request,
+ received_response=None,
+ generic_client_id=None,
+ ui_access_mode=None,
+ )
\ No newline at end of file
diff --git a/litellm/integrations/custom_sso_handler.py b/litellm/integrations/custom_sso_handler.py
new file mode 100644
index 00000000000..bc80966f8ca
--- /dev/null
+++ b/litellm/integrations/custom_sso_handler.py
@@ -0,0 +1,29 @@
+from fastapi import Request
+from fastapi_sso.sso.base import OpenID
+
+from litellm.integrations.custom_logger import CustomLogger
+
+
+class CustomSSOLoginHandler(CustomLogger):
+ """
+ Custom logger for the UI SSO sign in
+
+ Use this to parse the request headers and return a OpenID object
+
+ Useful when you have an OAuth proxy in front of LiteLLM
+ and you want to use the headers from the proxy to sign in the user
+ """
+ async def handle_custom_ui_sso_sign_in(
+ self,
+ request: Request,
+ ) -> OpenID:
+ request_headers_dict = dict(request.headers)
+ return OpenID(
+ id=request_headers_dict.get("x-litellm-user-id"),
+ email=request_headers_dict.get("x-litellm-user-email"),
+ first_name="Test",
+ last_name="Test",
+ display_name="Test",
+ picture="https://test.com/test.png",
+ provider="test",
+ )
\ No newline at end of file
diff --git a/litellm/proxy/custom_hooks/custom_ui_sso_hook.py b/litellm/proxy/custom_hooks/custom_ui_sso_hook.py
new file mode 100644
index 00000000000..cad0e62ff56
--- /dev/null
+++ b/litellm/proxy/custom_hooks/custom_ui_sso_hook.py
@@ -0,0 +1,32 @@
+from fastapi import Request
+from fastapi_sso.sso.base import OpenID
+
+from litellm._logging import verbose_logger
+from litellm.integrations.custom_logger import CustomLogger
+
+
+class CustomSSOLoginHandler(CustomLogger):
+ """
+ Custom logger for the UI SSO sign in
+
+ Use this to parse the request headers and return a OpenID object
+
+ Useful when you have an OAuth proxy in front of LiteLLM
+ and you want to use the headers from the proxy to sign in the user
+ """
+ async def handle_custom_ui_sso_sign_in(
+ self,
+ request: Request,
+ ) -> OpenID:
+ request_headers_dict = dict(request.headers)
+ verbose_logger.debug("inside custom ui sso sign in hook...")
+ return OpenID(
+ id=request_headers_dict.get("x-litellm-user-id") or "123",
+ email=request_headers_dict.get("x-litellm-user-email") or "[email protected]",
+ first_name="Test",
+ last_name="Test",
+ display_name="Test",
+ picture="https://test.com/test.png",
+ provider="test",
+ )
+custom_ui_sso_sign_in_handler = CustomSSOLoginHandler()
\ No newline at end of file
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 383543275a7..e2836ca191f 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -78,7 +78,10 @@ async def google_login(request: Request, source: Optional[str] = None, key: Opti
PROXY_BASE_URL should be the your deployed proxy endpoint, e.g. PROXY_BASE_URL="https://litellm-production-7002.up.railway.app/"
Example:
"""
- from litellm.proxy.proxy_server import premium_user
+ from litellm.proxy.proxy_server import (
+ premium_user,
+ user_custom_ui_sso_sign_in_handler,
+ )
microsoft_client_id = os.getenv("MICROSOFT_CLIENT_ID", None)
google_client_id = os.getenv("GOOGLE_CLIENT_ID", None)
@@ -123,6 +126,18 @@ async def google_login(request: Request, source: Optional[str] = None, key: Opti
key=key,
)
+ # check if user defined a custom auth sso sign in handler, if yes, use it
+ if user_custom_ui_sso_sign_in_handler is not None:
+ try:
+ from litellm_enterprise.proxy.auth.custom_sso_handler import (
+ EnterpriseCustomSSOHandler,
+ )
+ return await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(
+ request=request,
+ )
+ except ImportError:
+ raise ValueError("Enterprise features are not available. Custom UI SSO sign-in requires LiteLLM Enterprise.")
+
# Check if we should use SSO handler
if (
SSOAuthenticationHandler.should_use_sso_handler(
@@ -516,21 +531,13 @@ async def auth_callback(request: Request, state: Optional[str] = None): # noqa:
from litellm.proxy._types import LiteLLM_JWTAuth
from litellm.proxy.auth.handle_jwt import JWTHandler
- from litellm.proxy.management_endpoints.key_management_endpoints import (
- generate_key_helper_fn,
- )
from litellm.proxy.proxy_server import (
general_settings,
jwt_handler,
master_key,
- premium_user,
prisma_client,
- proxy_logging_obj,
user_api_key_cache,
- user_custom_sso,
)
- from litellm.proxy.utils import get_custom_url
- from litellm.types.proxy.ui_sso import ReturnedUITokenObject
if prisma_client is None:
raise HTTPException(
@@ -596,199 +603,17 @@ async def auth_callback(request: Request, state: Optional[str] = None): # noqa:
status_code=401,
detail="Result not returned by SSO provider.",
)
-
- # User is Authe'd in - generate key for the UI to access Proxy
- verbose_proxy_logger.info(f"SSO callback result: {result}")
-
- user_email: Optional[str] = getattr(result, "email", None)
- user_id: Optional[str] = getattr(result, "id", None) if result is not None else None
-
- if user_email is not None and os.getenv("ALLOWED_EMAIL_DOMAINS") is not None:
- email_domain = user_email.split("@")[1]
- allowed_domains = os.getenv("ALLOWED_EMAIL_DOMAINS").split(",") # type: ignore
- if email_domain not in allowed_domains:
- raise HTTPException(
- status_code=401,
- detail={
- "message": "The email domain={}, is not an allowed email domain={}. Contact your admin to change this.".format(
- email_domain, allowed_domains
- )
- },
- )
-
- # generic client id
- if generic_client_id is not None and result is not None:
- generic_user_role_attribute_name = os.getenv(
- "GENERIC_USER_ROLE_ATTRIBUTE", "role"
- )
- user_id = getattr(result, "id", None)
- user_email = getattr(result, "email", None)
- user_role = getattr(result, generic_user_role_attribute_name, None) # type: ignore
-
- if user_id is None and result is not None:
- _first_name = getattr(result, "first_name", "") or ""
- _last_name = 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):
- user_id = user_email
-
- user_info = None
- user_id_models: List = []
- max_internal_user_budget = litellm.max_internal_user_budget
- internal_user_budget_duration = litellm.internal_user_budget_duration
-
- # User might not be already created on first generation of key
- # But if it is, we want their models preferences
- default_ui_key_values: Dict[str, Any] = {
- "duration": "24hr",
- "key_max_budget": litellm.max_ui_session_budget,
- "aliases": {},
- "config": {},
- "spend": 0,
- "team_id": "litellm-dashboard",
- }
- user_defined_values: Optional[SSOUserDefinedValues] = None
-
- if user_custom_sso is not None:
- if asyncio.iscoroutinefunction(user_custom_sso):
- user_defined_values = await user_custom_sso(result) # type: ignore
- else:
- raise ValueError("user_custom_sso must be a coroutine function")
- elif user_id is not None:
- user_defined_values = SSOUserDefinedValues(
- models=user_id_models,
- user_id=user_id,
- user_email=user_email,
- max_budget=max_internal_user_budget,
- user_role=None,
- budget_duration=internal_user_budget_duration,
- )
-
- # (IF SET) Verify user is in restricted SSO group
- SSOAuthenticationHandler.verify_user_in_restricted_sso_group(
- general_settings=general_settings,
+
+ return await SSOAuthenticationHandler.get_redirect_response_from_openid(
result=result,
+ request=request,
received_response=received_response,
+ generic_client_id=generic_client_id,
+ ui_access_mode=ui_access_mode,
)
- user_info = await get_user_info_from_db(
- result=result,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- proxy_logging_obj=proxy_logging_obj,
- user_email=user_email,
- user_defined_values=user_defined_values,
- alternate_user_id=user_id,
- )
-
- user_defined_values = apply_user_info_values_to_sso_user_defined_values(
- user_info=user_info, user_defined_values=user_defined_values
- )
-
- if user_defined_values is None:
- raise Exception(
- "Unable to map user identity to known values. 'user_defined_values' is None. File an issue - https://github.com/BerriAI/litellm/issues"
- )
-
- verbose_proxy_logger.info(
- f"user_defined_values for creating ui key: {user_defined_values}"
- )
-
- default_ui_key_values.update(user_defined_values)
- default_ui_key_values["request_type"] = "key"
- response = await generate_key_helper_fn(
- **default_ui_key_values, # type: ignore
- table_name="key",
- )
-
- key = response["token"] # type: ignore
- user_id = response["user_id"] # type: ignore
-
- litellm_dashboard_ui = get_custom_url(
- request_base_url=str(request.base_url), route="ui/"
- )
- user_role = (
- user_defined_values["user_role"]
- or LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value
- )
- if user_id and isinstance(user_id, str):
- user_role = await check_and_update_if_proxy_admin_id(
- user_role=user_role, user_id=user_id, prisma_client=prisma_client
- )
-
- verbose_proxy_logger.debug(
- f"user_role: {user_role}; ui_access_mode: {ui_access_mode}"
- )
- ## CHECK IF ROLE ALLOWED TO USE PROXY ##
- is_admin_only_access = check_is_admin_only_access(ui_access_mode or {})
- if is_admin_only_access:
- has_access = has_admin_ui_access(user_role)
- if not has_access:
- raise HTTPException(
- status_code=401,
- detail={
- "error": f"User not allowed to access proxy. User role={user_role}, proxy mode={ui_access_mode}"
- },
- )
-
- disabled_non_admin_personal_key_creation = (
- get_disabled_non_admin_personal_key_creation()
- )
-
- import jwt
-
- if get_secret_bool("EXPERIMENTAL_UI_LOGIN"):
- _user_info: Optional[LiteLLM_UserTable] = None
- if (
- user_defined_values is not None
- and user_defined_values["user_id"] is not None
- ):
- _user_info = LiteLLM_UserTable(
- user_id=user_defined_values["user_id"],
- user_role=user_defined_values["user_role"] or user_role,
- models=[],
- max_budget=litellm.max_ui_session_budget,
- )
- if _user_info is None:
- raise HTTPException(
- status_code=401,
- detail={
- "error": "User Information is required for experimental UI login"
- },
- )
-
- key = ExperimentalUIJWTToken.get_experimental_ui_login_jwt_auth_token(
- _user_info
- )
-
- returned_ui_token_object = ReturnedUITokenObject(
- user_id=cast(str, user_id),
- key=key,
- user_email=user_email,
- user_role=user_role,
- login_method="sso",
- premium_user=premium_user,
- auth_header_name=general_settings.get(
- "litellm_key_header_name", "Authorization"
- ),
- disabled_non_admin_personal_key_creation=disabled_non_admin_personal_key_creation,
- server_root_path=get_server_root_path(),
- )
-
- jwt_token = jwt.encode( # type: ignore
- cast(dict, returned_ui_token_object),
- master_key,
- algorithm="HS256",
- )
- verbose_proxy_logger.info(f"user_id: {user_id}; jwt_token: {jwt_token}")
- if user_id is not None and isinstance(user_id, str):
- litellm_dashboard_ui += "?login=success"
- verbose_proxy_logger.info(f"Redirecting to {litellm_dashboard_ui}")
- redirect_response = RedirectResponse(url=litellm_dashboard_ui, status_code=303)
- redirect_response.set_cookie(key="token", value=jwt_token)
- return redirect_response
+
async def cli_sso_callback(request: Request, key: Optional[str] = None):
"""CLI SSO callback - generates the key with pre-specified ID"""
@@ -981,7 +806,6 @@ class SSOAuthenticationHandler:
"""
Handler for SSO Authentication across all SSO providers
"""
-
@staticmethod
async def get_sso_login_redirect(
redirect_url: str,
@@ -1348,8 +1172,224 @@ class SSOAuthenticationHandler:
LITELLM_CLI_SOURCE_IDENTIFIER,
)
return f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:{key}" if source == LITELLM_CLI_SOURCE_IDENTIFIER and key else None
+
+
+
+ @staticmethod
+ async def get_redirect_response_from_openid( # noqa: PLR0915
+ result: Union[OpenID, dict, CustomOpenID],
+ request: Request,
+ received_response: Optional[dict] = None,
+ generic_client_id: Optional[str] = None,
+ ui_access_mode: Optional[Dict] = None,
+ ) -> RedirectResponse:
+ import jwt
+
+ from litellm.proxy.proxy_server import (
+ general_settings,
+ generate_key_helper_fn,
+ master_key,
+ premium_user,
+ proxy_logging_obj,
+ user_api_key_cache,
+ user_custom_sso,
+ )
+ from litellm.proxy.utils import get_custom_url, get_prisma_client_or_throw
+ from litellm.types.proxy.ui_sso import ReturnedUITokenObject
+ prisma_client = get_prisma_client_or_throw("Prisma client is None, connect a database to your proxy")
+
+
+ # User is Authe'd in - generate key for the UI to access Proxy
+ verbose_proxy_logger.info(f"SSO callback result: {result}")
+
+ user_email: Optional[str] = getattr(result, "email", None)
+ user_id: Optional[str] = getattr(result, "id", None) if result is not None else None
+
+ if user_email is not None and os.getenv("ALLOWED_EMAIL_DOMAINS") is not None:
+ email_domain = user_email.split("@")[1]
+ allowed_domains = os.getenv("ALLOWED_EMAIL_DOMAINS").split(",") # type: ignore
+ if email_domain not in allowed_domains:
+ raise HTTPException(
+ status_code=401,
+ detail={
+ "message": "The email domain={}, is not an allowed email domain={}. Contact your admin to change this.".format(
+ email_domain, allowed_domains
+ )
+ },
+ )
+
+ # generic client id
+ if generic_client_id is not None and result is not None:
+ generic_user_role_attribute_name = os.getenv(
+ "GENERIC_USER_ROLE_ATTRIBUTE", "role"
+ )
+ user_id = getattr(result, "id", None)
+ user_email = getattr(result, "email", None)
+ user_role = getattr(result, generic_user_role_attribute_name, None) # type: ignore
+
+ if user_id is None and result is not None:
+ _first_name = getattr(result, "first_name", "") or ""
+ _last_name = 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):
+ user_id = user_email
+
+ user_info = None
+ user_id_models: List = []
+ max_internal_user_budget = litellm.max_internal_user_budget
+ internal_user_budget_duration = litellm.internal_user_budget_duration
+
+ # User might not be already created on first generation of key
+ # But if it is, we want their models preferences
+ default_ui_key_values: Dict[str, Any] = {
+ "duration": "24hr",
+ "key_max_budget": litellm.max_ui_session_budget,
+ "aliases": {},
+ "config": {},
+ "spend": 0,
+ "team_id": "litellm-dashboard",
+ }
+ user_defined_values: Optional[SSOUserDefinedValues] = None
+ if user_custom_sso is not None:
+ if asyncio.iscoroutinefunction(user_custom_sso):
+ user_defined_values = await user_custom_sso(result) # type: ignore
+ else:
+ raise ValueError("user_custom_sso must be a coroutine function")
+ elif user_id is not None:
+ user_defined_values = SSOUserDefinedValues(
+ models=user_id_models,
+ user_id=user_id,
+ user_email=user_email,
+ max_budget=max_internal_user_budget,
+ user_role=None,
+ budget_duration=internal_user_budget_duration,
+ )
+
+ # (IF SET) Verify user is in restricted SSO group
+ SSOAuthenticationHandler.verify_user_in_restricted_sso_group(
+ general_settings=general_settings,
+ result=result,
+ received_response=received_response,
+ )
+
+ user_info = await get_user_info_from_db(
+ result=result,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ user_email=user_email,
+ user_defined_values=user_defined_values,
+ alternate_user_id=user_id,
+ )
+
+ user_defined_values = apply_user_info_values_to_sso_user_defined_values(
+ user_info=user_info, user_defined_values=user_defined_values
+ )
+
+ if user_defined_values is None:
+ raise Exception(
+ "Unable to map user identity to known values. 'user_defined_values' is None. File an issue - https://github.com/BerriAI/litellm/issues"
+ )
+
+ verbose_proxy_logger.info(
+ f"user_defined_values for creating ui key: {user_defined_values}"
+ )
+
+ default_ui_key_values.update(user_defined_values)
+ default_ui_key_values["request_type"] = "key"
+ response = await generate_key_helper_fn(
+ **default_ui_key_values, # type: ignore
+ table_name="key",
+ )
+
+ key = response["token"] # type: ignore
+ user_id = response["user_id"] # type: ignore
+
+ user_role = (
+ user_defined_values["user_role"]
+ or LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value
+ )
+ if user_id and isinstance(user_id, str):
+ user_role = await check_and_update_if_proxy_admin_id(
+ user_role=user_role, user_id=user_id, prisma_client=prisma_client
+ )
+
+ verbose_proxy_logger.debug(
+ f"user_role: {user_role}; ui_access_mode: {ui_access_mode}"
+ )
+ ## CHECK IF ROLE ALLOWED TO USE PROXY ##
+ is_admin_only_access = check_is_admin_only_access(ui_access_mode or {})
+ if is_admin_only_access:
+ has_access = has_admin_ui_access(user_role)
+ if not has_access:
+ raise HTTPException(
+ status_code=401,
+ detail={
+ "error": f"User not allowed to access proxy. User role={user_role}, proxy mode={ui_access_mode}"
+ },
+ )
+
+ disabled_non_admin_personal_key_creation = (
+ get_disabled_non_admin_personal_key_creation()
+ )
+ litellm_dashboard_ui = get_custom_url(
+ request_base_url=str(request.base_url), route="ui/"
+ )
+
+ if get_secret_bool("EXPERIMENTAL_UI_LOGIN"):
+ _user_info: Optional[LiteLLM_UserTable] = None
+ if (
+ user_defined_values is not None
+ and user_defined_values["user_id"] is not None
+ ):
+ _user_info = LiteLLM_UserTable(
+ user_id=user_defined_values["user_id"],
+ user_role=user_defined_values["user_role"] or user_role,
+ models=[],
+ max_budget=litellm.max_ui_session_budget,
+ )
+ if _user_info is None:
+ raise HTTPException(
+ status_code=401,
+ detail={
+ "error": "User Information is required for experimental UI login"
+ },
+ )
+
+ key = ExperimentalUIJWTToken.get_experimental_ui_login_jwt_auth_token(
+ _user_info
+ )
+
+ returned_ui_token_object = ReturnedUITokenObject(
+ user_id=cast(str, user_id),
+ key=key,
+ user_email=user_email,
+ user_role=user_role,
+ login_method="sso",
+ premium_user=premium_user,
+ auth_header_name=general_settings.get(
+ "litellm_key_header_name", "Authorization"
+ ),
+ disabled_non_admin_personal_key_creation=disabled_non_admin_personal_key_creation,
+ server_root_path=get_server_root_path(),
+ )
+
+ jwt_token = jwt.encode(
+ cast(dict, returned_ui_token_object),
+ master_key or "",
+ algorithm="HS256",
+ )
+ verbose_proxy_logger.info(f"user_id: {user_id}; jwt_token: {jwt_token}")
+ if user_id is not None and isinstance(user_id, str):
+ litellm_dashboard_ui += "?login=success"
+ verbose_proxy_logger.info(f"Redirecting to {litellm_dashboard_ui}")
+ redirect_response = RedirectResponse(url=litellm_dashboard_ui, status_code=303)
+ redirect_response.set_cookie(key="token", value=jwt_token)
+ return redirect_response
+
class MicrosoftSSOHandler:
"""
Handles Microsoft SSO callback response and returns a CustomOpenID object
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index 21e25056f2c..23022989fa3 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -6,6 +6,9 @@ model_list:
litellm_params:
model: openai/*
+general_settings:
+ custom_ui_sso_sign_in_handler: "custom_hooks.custom_ui_sso_hook.custom_ui_sso_sign_in_handler"
+
guardrails:
- guardrail_name: "bedrock-pre-guard"
litellm_params:
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 0ec2f5b411c..9c4a2bdee56 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -481,7 +481,7 @@ _description = (
def cleanup_router_config_variables():
- global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_sso, use_background_health_checks, health_check_interval, prisma_client
+ global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_sso, user_custom_ui_sso_sign_in_handler, use_background_health_checks, health_check_interval, prisma_client
# Set all variables to None
master_key = None
@@ -491,6 +491,7 @@ def cleanup_router_config_variables():
user_custom_auth_path = None
user_custom_key_generate = None
user_custom_sso = None
+ user_custom_ui_sso_sign_in_handler = None
use_background_health_checks = None
health_check_interval = None
prisma_client = None
@@ -911,6 +912,7 @@ redis_usage_cache: Optional[RedisCache] = (
user_custom_auth = None
user_custom_key_generate = None
user_custom_sso = None
+user_custom_ui_sso_sign_in_handler = None
use_background_health_checks = None
use_queue = False
health_check_interval = None
@@ -1644,7 +1646,7 @@ class ProxyConfig:
"""
Load config values into proxy global state
"""
- global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_sso, use_background_health_checks, health_check_interval, use_queue, proxy_budget_rescheduler_max_time, proxy_budget_rescheduler_min_time, ui_access_mode, litellm_master_key_hash, proxy_batch_write_at, disable_spend_logs, prompt_injection_detection_obj, redis_usage_cache, store_model_in_db, premium_user, open_telemetry_logger, health_check_details, callback_settings
+ global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_sso, user_custom_ui_sso_sign_in_handler, use_background_health_checks, health_check_interval, use_queue, proxy_budget_rescheduler_max_time, proxy_budget_rescheduler_min_time, ui_access_mode, litellm_master_key_hash, proxy_batch_write_at, disable_spend_logs, prompt_injection_detection_obj, redis_usage_cache, store_model_in_db, premium_user, open_telemetry_logger, health_check_details, callback_settings
config: dict = await self.get_config(config_file_path=config_file_path)
@@ -1947,6 +1949,12 @@ class ProxyConfig:
value=custom_sso, config_file_path=config_file_path
)
+ custom_ui_sso_sign_in_handler = general_settings.get("custom_ui_sso_sign_in_handler", None)
+ if custom_ui_sso_sign_in_handler is not None:
+ user_custom_ui_sso_sign_in_handler = get_instance_fn(
+ value=custom_ui_sso_sign_in_handler, config_file_path=config_file_path
+ )
+
if enterprise_proxy_config is not None:
await enterprise_proxy_config.load_enterprise_config(general_settings)
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index cc26769e206..dfdf6f57e8f 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -3170,3 +3170,14 @@ def get_server_root_path() -> str:
- Otherwise, default to "/".
"""
return os.getenv("SERVER_ROOT_PATH", "/")
+
+
+def get_prisma_client_or_throw(message: str):
+ from litellm.proxy.proxy_server import prisma_client
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail={"error": message},
+ )
+ return prisma_client
\ No newline at end of file
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
index 583e953dca7..73a7339afd0 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -540,7 +540,7 @@ async def test_get_user_info_from_db():
) as mock_get_user_object:
user_info = await get_user_info_from_db(**args)
mock_get_user_object.assert_called_once()
- mock_get_user_object.call_args.kwargs["user_id"] = "krrishd"
+ assert mock_get_user_object.call_args.kwargs["user_id"] == "krrishd"
async def test_get_user_info_from_db_alternate_user_id():
@@ -581,7 +581,7 @@ async def test_get_user_info_from_db_alternate_user_id():
) as mock_get_user_object:
user_info = await get_user_info_from_db(**args)
mock_get_user_object.assert_called_once()
- mock_get_user_object.call_args.kwargs["user_id"] = "krrishd-email1234"
+ assert mock_get_user_object.call_args.kwargs["user_id"] == "krrishd-email1234"
@pytest.mark.asyncio
@@ -1045,3 +1045,203 @@ class TestHTMLIntegration:
assert isinstance(html, str)
assert len(html) > 0
+
+
+class TestCustomUISSO:
+ """Test the custom UI SSO sign-in handler functionality"""
+
+ def test_enterprise_import_error_handling(self):
+ """Test that proper error is raised when enterprise module is not available"""
+ from unittest.mock import MagicMock, patch
+
+ from litellm.proxy.management_endpoints.ui_sso import google_login
+
+ # Mock request
+ mock_request = MagicMock()
+ mock_request.base_url = "https://test.example.com/"
+
+ # Mock user_custom_ui_sso_sign_in_handler to exist but make enterprise import fail
+ with patch("litellm.proxy.proxy_server.premium_user", True):
+ with patch("litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler", MagicMock()):
+ with patch.dict('sys.modules', {'enterprise.litellm_enterprise.proxy.auth.custom_sso_handler': None}):
+ # Temporarily mock the google_login function call to test the import error path
+ async def mock_google_login():
+ # This mimics the relevant part of google_login that would trigger the import error
+ try:
+ from enterprise.litellm_enterprise.proxy.auth.custom_sso_handler import (
+ EnterpriseCustomSSOHandler,
+ )
+ return "success"
+ except ImportError:
+ raise ValueError("Enterprise features are not available. Custom UI SSO sign-in requires LiteLLM Enterprise.")
+
+ # Test that the ValueError is raised with the correct message
+ import pytest
+ with pytest.raises(ValueError, match="Enterprise features are not available"):
+ asyncio.run(mock_google_login())
+
+ @pytest.mark.asyncio
+ async def test_handle_custom_ui_sso_sign_in_success(self):
+ """Test successful custom UI SSO sign-in with valid headers"""
+ from fastapi_sso.sso.base import OpenID
+
+ from enterprise.litellm_enterprise.proxy.auth.custom_sso_handler import (
+ EnterpriseCustomSSOHandler,
+ )
+ from litellm.integrations.custom_sso_handler import CustomSSOLoginHandler
+
+ # Mock request with custom headers
+ mock_request = MagicMock(spec=Request)
+ mock_request.headers = {
+ "x-litellm-user-id": "test_user_123",
+ "x-litellm-user-email": "[email protected]",
+ "x-forwarded-for": "192.168.1.1",
+ }
+ mock_request.base_url = "https://test.litellm.ai/"
+
+ # Mock the custom handler
+ mock_custom_handler = MagicMock(spec=CustomSSOLoginHandler)
+ expected_openid = OpenID(
+ id="test_user_123",
+ first_name="Test",
+ last_name="User",
+ display_name="Test User",
+ picture=None,
+ provider="custom",
+ )
+ mock_custom_handler.handle_custom_ui_sso_sign_in = AsyncMock(
+ return_value=expected_openid
+ )
+
+ # Mock the redirect response method
+ mock_redirect_response = MagicMock()
+ mock_redirect_response.status_code = 303
+
+ with patch("litellm.proxy.proxy_server.premium_user", True):
+ with patch(
+ "litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler",
+ mock_custom_handler,
+ ):
+ with patch.object(
+ SSOAuthenticationHandler,
+ "get_redirect_response_from_openid",
+ return_value=mock_redirect_response,
+ ) as mock_get_redirect:
+ # Act
+ result = await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(
+ request=mock_request
+ )
+
+ # Assert
+ # Verify the custom handler was called with the request
+ mock_custom_handler.handle_custom_ui_sso_sign_in.assert_called_once_with(
+ request=mock_request
+ )
+
+ # Verify the redirect response was generated with correct OpenID
+ mock_get_redirect.assert_called_once_with(
+ result=expected_openid,
+ request=mock_request,
+ received_response=None,
+ generic_client_id=None,
+ ui_access_mode=None,
+ )
+
+ # Verify the result is the redirect response
+ assert result == mock_redirect_response
+ assert result.status_code == 303
+
+ @pytest.mark.asyncio
+ async def test_custom_ui_sso_handler_execution_with_real_class(self):
+ """
+ Test that when a user provides a custom class instance, it gets properly executed
+ and its methods are called with the correct parameters
+ """
+ from fastapi_sso.sso.base import OpenID
+
+ from enterprise.litellm_enterprise.proxy.auth.custom_sso_handler import (
+ EnterpriseCustomSSOHandler,
+ )
+ from litellm.integrations.custom_sso_handler import CustomSSOLoginHandler
+
+ # Create a real custom handler class instance
+ class TestCustomSSOHandler(CustomSSOLoginHandler):
+ def __init__(self):
+ super().__init__()
+ self.method_called = False
+ self.received_request = None
+
+ async def handle_custom_ui_sso_sign_in(self, request: Request) -> OpenID:
+ self.method_called = True
+ self.received_request = request
+
+ # Parse headers like the actual implementation would
+ request_headers_dict = dict(request.headers)
+ return OpenID(
+ id=request_headers_dict.get("x-litellm-user-id", "default_user"),
+ email=request_headers_dict.get("x-litellm-user-email", "[email protected]"),
+ first_name="Custom",
+ last_name="Handler",
+ display_name="Custom Handler Test",
+ picture=None,
+ provider="custom",
+ )
+
+ # Create instance of our test handler
+ test_handler_instance = TestCustomSSOHandler()
+
+ # Mock request with custom headers
+ mock_request = MagicMock(spec=Request)
+ mock_request.headers = {
+ "x-litellm-user-id": "custom_test_user_456",
+ "x-litellm-user-email": "[email protected]",
+ "x-forwarded-for": "10.0.0.1",
+ }
+ mock_request.base_url = "https://custom.litellm.ai/"
+
+ # Mock the redirect response method
+ mock_redirect_response = MagicMock()
+ mock_redirect_response.status_code = 303
+
+ with patch("litellm.proxy.proxy_server.premium_user", True):
+ with patch(
+ "litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler",
+ test_handler_instance,
+ ):
+ with patch.object(
+ SSOAuthenticationHandler,
+ "get_redirect_response_from_openid",
+ return_value=mock_redirect_response,
+ ) as mock_get_redirect:
+ # Act
+ result = await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(
+ request=mock_request
+ )
+
+ # Assert that our custom handler was executed
+ assert test_handler_instance.method_called is True
+ assert test_handler_instance.received_request == mock_request
+
+ # Verify the redirect response was called with the OpenID from our custom handler
+ mock_get_redirect.assert_called_once()
+ call_args = mock_get_redirect.call_args.kwargs
+
+ # Verify the OpenID object has the expected values from our custom handler
+ openid_result = call_args["result"]
+ assert openid_result.id == "custom_test_user_456"
+ assert openid_result.email == "[email protected]"
+ assert openid_result.first_name == "Custom"
+ assert openid_result.last_name == "Handler"
+ assert openid_result.display_name == "Custom Handler Test"
+ assert openid_result.provider == "custom"
+
+ # Verify the request and other parameters were passed correctly
+ assert call_args["request"] == mock_request
+ assert call_args["received_response"] is None
+ assert call_args["generic_client_id"] is None
+ assert call_args["ui_access_mode"] is None
+
+ # Verify the result is the redirect response
+ assert result == mock_redirect_response
+ assert result.status_code == 303
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index d33b637f8e3..8f677f9b6e0 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -661,3 +661,57 @@ async def test_add_proxy_budget_to_db_only_creates_user_no_keys():
assert call_args.kwargs["max_budget"] == 100.0
assert call_args.kwargs["budget_duration"] == "30d"
assert call_args.kwargs["query_type"] == "update_data"
+
+
+async def test_custom_ui_sso_sign_in_handler_config_loading():
+ """
+ Test that custom_ui_sso_sign_in_handler from config gets properly loaded into the global variable
+ """
+ import tempfile
+ from unittest.mock import MagicMock, patch
+
+ import yaml
+
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ # Create a test config with custom_ui_sso_sign_in_handler
+ test_config = {
+ "general_settings": {
+ "custom_ui_sso_sign_in_handler": "custom_hooks.custom_ui_sso_hook.custom_ui_sso_sign_in_handler"
+ },
+ "model_list": [],
+ "router_settings": {},
+ "litellm_settings": {}
+ }
+
+ # Create temporary config file
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
+ yaml.dump(test_config, f)
+ config_file_path = f.name
+
+ # Mock the get_instance_fn to return a mock handler
+ mock_custom_handler = MagicMock()
+
+ try:
+ with patch("litellm.proxy.proxy_server.get_instance_fn", return_value=mock_custom_handler) as mock_get_instance:
+ # Create ProxyConfig instance and load config
+ proxy_config = ProxyConfig()
+ # Create a mock router since load_config requires it
+ mock_router = MagicMock()
+ await proxy_config.load_config(router=mock_router, config_file_path=config_file_path)
+
+ # Verify get_instance_fn was called with correct parameters
+ mock_get_instance.assert_called_with(
+ value="custom_hooks.custom_ui_sso_hook.custom_ui_sso_sign_in_handler",
+ config_file_path=config_file_path
+ )
+
+ # Verify the global variable was set
+ from litellm.proxy.proxy_server import user_custom_ui_sso_sign_in_handler
+ assert user_custom_ui_sso_sign_in_handler == mock_custom_handler
+
+ finally:
+ # Clean up temporary file
+ import os
+ os.unlink(config_file_path)