The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Fix SSO user login - invalid token error (#10298)
Krish Dholakia0f9ebc23a5c1
diff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.htmldeleted file mode 100644index 048ef581b29..00000000000--- a/litellm/proxy/_experimental/out/onboarding.html+++ /dev/null@@ -1 +0,0 @@-<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/ui/_next/static/chunks/webpack-75a5453f51d60261.js"/><script src="/ui/_next/static/chunks/fd9d1056-205af899b895cbac.js" async=""></script><script src="/ui/_next/static/chunks/117-1c5bfc45bfc4237d.js" async=""></script><script src="/ui/_next/static/chunks/main-app-4f7318ae681a6d94.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/ui/favicon.ico" type="image/x-icon" sizes="16x16"/><meta name="next-size-adjust"/><script src="/ui/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/ui/_next/static/chunks/webpack-75a5453f51d60261.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/ui/_next/static/media/a34f9d1faa5f3315-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/ui/_next/static/css/86f6cc749f6b8493.css\",\"style\"]\n3:HL[\"/ui/_next/static/css/005c96178151b9fd.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[12011,[\"665\",\"static/chunks/3014691f-b7b79b78e27792f3.js\",\"42\",\"static/chunks/42-014374badc35fe9b.js\",\"899\",\"static/chunks/899-54ea329f41297bf0.js\",\"250\",\"static/chunks/250-e4cc2ceb9ff1c37a.js\",\"461\",\"static/chunks/app/onboarding/page-4809c2f644098f19.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\nb:I[61060,[],\"\"]\nc:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"sh3mKTgIKifNl8lsgZ675\",\"assetPrefix\":\"/ui\",\"urlParts\":[\"\",\"onboarding\"],\"initialTree\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"onboarding\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/ui/_next/static/css/86f6cc749f6b8493.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/ui/_next/static/css/005c96178151b9fd.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_cf7686\",\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$La\"],\"globalErrorComponent\":\"$b\",\"missingSlots\":\"$Wc\"}]\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/ui/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"meta\",\"5\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>\ No newline at end of filediff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 354f6bb54cb..a81f4f6c2ab 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -805,6 +805,7 @@ class NewUserRequest(GenerateRequestBase):True # flag used for returning a key as part of the /user/new response)send_invite_email: Optional[bool] = None+ sso_user_id: Optional[str] = Noneclass NewUserResponse(GenerateKeyResponse):diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex ede3624da61..e46cc858acd 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -610,6 +610,7 @@ async def _get_fuzzy_user_object(- Check if user_email is user_email in db- If not, create new user with user_email and sso_user_id and user_id = sso_user_id"""+response = Noneif sso_user_id is not None:response = await prisma_client.db.litellm_usertable.find_unique(diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex 589b30d5246..18012e9612b 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -202,6 +202,7 @@ async def new_user(- team_id: Optional[str] - [DEPRECATED PARAM] The team id of the user. Default is None.- duration: Optional[str] - Duration for the key auto-created on `/user/new`. Default is None.- key_alias: Optional[str] - Alias for the key auto-created on `/user/new`. Default is None.+ - sso_user_id: Optional[str] - The id of the user in the SSO provider.Returns:- key: (str) The generated api key for the userdiff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex 15edab8909e..3fef6a08629 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -1173,6 +1173,7 @@ async def generate_key_helper_fn( # noqa: PLR0915created_by: Optional[str] = None,updated_by: Optional[str] = None,allowed_routes: Optional[list] = None,+ sso_user_id: Optional[str] = None,):from litellm.proxy.proxy_server import (litellm_proxy_budget_name,@@ -1251,6 +1252,7 @@ async def generate_key_helper_fn( # noqa: PLR0915"budget_duration": budget_duration,"budget_reset_at": reset_at,"allowed_cache_controls": allowed_cache_controls,+ "sso_user_id": sso_user_id,}if teams is not None:user_data["teams"] = teamsdiff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.pyindex 23054fc45be..cd91bda264b 100644--- a/litellm/proxy/management_endpoints/ui_sso.py+++ b/litellm/proxy/management_endpoints/ui_sso.py@@ -19,6 +19,7 @@ from fastapi.responses import RedirectResponseimport litellmfrom litellm._logging import verbose_proxy_logger+from litellm.caching import DualCachefrom litellm.constants import MAX_SPENDLOG_ROWS_TO_QUERYfrom litellm.llms.custom_httpx.http_handler import (AsyncHTTPHandler,@@ -26,6 +27,7 @@ from litellm.llms.custom_httpx.http_handler import (httpxSpecialProvider,)from litellm.proxy._types import (+ CommonProxyErrors,LiteLLM_UserTable,LitellmUserRoles,Member,@@ -57,7 +59,7 @@ from litellm.proxy.management_endpoints.sso_helper_utils import ()from litellm.proxy.management_endpoints.team_endpoints import new_team, team_member_addfrom litellm.proxy.management_endpoints.types import CustomOpenID-from litellm.proxy.utils import PrismaClient+from litellm.proxy.utils import PrismaClient, ProxyLoggingfrom litellm.secret_managers.main import str_to_boolfrom litellm.types.proxy.management_endpoints.ui_sso import *@@ -124,6 +126,7 @@ async def google_login(request: Request): # noqa: PLR0915)is True):+ verbose_proxy_logger.info(f"Redirecting to SSO login for {redirect_url}")return await SSOAuthenticationHandler.get_sso_login_redirect(redirect_url=redirect_url,microsoft_client_id=microsoft_client_id,@@ -319,9 +322,109 @@ def get_disabled_non_admin_personal_key_creation():return bool("proxy_admin" in allowed_user_roles)+async def get_existing_user_info_from_db(+ user_id: Optional[str],+ user_email: Optional[str],+ prisma_client: PrismaClient,+ user_api_key_cache: DualCache,+ proxy_logging_obj: ProxyLogging,+) -> Optional[LiteLLM_UserTable]:+ try:+ user_info = await get_user_object(+ user_id=user_id,+ user_email=user_email,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ user_id_upsert=False,+ parent_otel_span=None,+ proxy_logging_obj=proxy_logging_obj,+ sso_user_id=user_id,+ )+ except Exception as e:+ verbose_proxy_logger.debug(f"Error getting user object: {e}")+ user_info = None++ return user_info+++async def get_user_info_from_db(+ result: Union[CustomOpenID, OpenID, dict],+ prisma_client: PrismaClient,+ user_api_key_cache: DualCache,+ proxy_logging_obj: ProxyLogging,+ user_email: Optional[str],+ user_defined_values: Optional[SSOUserDefinedValues],+) -> Optional[Union[LiteLLM_UserTable, NewUserResponse]]:+ try:+ user_info: Optional[+ Union[LiteLLM_UserTable, NewUserResponse]+ ] = await get_existing_user_info_from_db(+ user_id=cast(+ Optional[str],+ getattr(result, "id", None)+ if not isinstance(result, dict)+ else result.get("id", None),+ ),+ user_email=cast(+ Optional[str],+ getattr(result, "email", None)+ if not isinstance(result, dict)+ else result.get("email", None),+ ),+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ verbose_proxy_logger.debug(+ f"user_info: {user_info}; litellm.default_internal_user_params: {litellm.default_internal_user_params}"+ )++ # Upsert SSO User to LiteLLM DB++ if user_info is None:+ user_info = await SSOAuthenticationHandler.upsert_sso_user(+ result=result,+ user_info=user_info,+ user_email=user_email,+ user_defined_values=user_defined_values,+ prisma_client=prisma_client,+ )++ await SSOAuthenticationHandler.add_user_to_teams_from_sso_response(+ result=result,+ user_info=user_info,+ )++ return user_info+ except Exception as e:+ verbose_proxy_logger.exception(+ f"[Non-Blocking] Error trying to add sso user to db: {e}"+ )++ return None+++def apply_user_info_values_to_sso_user_defined_values(+ user_info: Optional[Union[LiteLLM_UserTable, NewUserResponse]],+ user_defined_values: Optional[SSOUserDefinedValues],+) -> Optional[SSOUserDefinedValues]:+ if user_defined_values is None:+ return None+ if user_info is not None and user_info.user_id is not None:+ user_defined_values["user_id"] = user_info.user_id++ if user_info is None or user_info.user_role is None:+ user_defined_values["user_role"] = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY+ else:+ user_defined_values["user_role"] = user_info.user_role++ return user_defined_values++@router.get("/sso/callback", tags=["experimental"], include_in_schema=False)async def auth_callback(request: Request): # noqa: PLR0915"""Verify login"""+ verbose_proxy_logger.info("Starting SSO callback")from litellm.proxy.management_endpoints.key_management_endpoints import (generate_key_helper_fn,)@@ -337,6 +440,11 @@ async def auth_callback(request: Request): # noqa: PLR0915user_custom_sso,)+ if prisma_client is None:+ raise HTTPException(+ status_code=500, detail=CommonProxyErrors.db_not_connected_error.value+ )+microsoft_client_id = os.getenv("MICROSOFT_CLIENT_ID", None)google_client_id = os.getenv("GOOGLE_CLIENT_ID", None)generic_client_id = os.getenv("GENERIC_CLIENT_ID", None)@@ -374,8 +482,15 @@ async def auth_callback(request: Request): # noqa: PLR0915generic_client_id=generic_client_id,redirect_url=redirect_url,)++ if result is None:+ raise HTTPException(+ 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.debug(f"SSO callback result: {result}")+ 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@@ -441,51 +556,18 @@ async def auth_callback(request: Request): # noqa: PLR0915budget_duration=internal_user_budget_duration,)- _user_id_from_sso = user_id- user_role = None- try:- if prisma_client is not None:- try:- user_info = await get_user_object(- user_id=user_id,- user_email=user_email,- prisma_client=prisma_client,- user_api_key_cache=user_api_key_cache,- user_id_upsert=False,- parent_otel_span=None,- proxy_logging_obj=proxy_logging_obj,- sso_user_id=user_id,- )- except Exception as e:- verbose_proxy_logger.debug(f"Error getting user object: {e}")- user_info = None-- verbose_proxy_logger.debug(- f"user_info: {user_info}; litellm.default_internal_user_params: {litellm.default_internal_user_params}"- )-- # Upsert SSO User to LiteLLM DB- user_info = await SSOAuthenticationHandler.upsert_sso_user(- result=result,- user_info=user_info,- user_email=user_email,- user_defined_values=user_defined_values,- prisma_client=prisma_client,- )- if user_info and user_info.user_role is not None:- user_role = user_info.user_role- else:- user_role = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY-- await SSOAuthenticationHandler.add_user_to_teams_from_sso_response(- result=result,- user_info=user_info,- )+ 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,+ )- except Exception as e:- verbose_proxy_logger.debug(- f"[Non-Blocking] Error trying to add sso user to db: {e}"- )+ 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(@@ -507,7 +589,10 @@ async def auth_callback(request: Request): # noqa: PLR0915user_id = response["user_id"] # type: ignorelitellm_dashboard_ui = "/ui/"- user_role = user_role or LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value+ user_role = (+ user_defined_values["user_role"]+ or LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value+ )if (os.getenv("PROXY_ADMIN_ID", None) is not Noneand os.environ["PROXY_ADMIN_ID"] == user_id@@ -552,8 +637,10 @@ async def auth_callback(request: Request): # noqa: PLR0915master_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, secure=True)return redirect_response@@ -605,6 +692,8 @@ async def insert_sso_user(user_role=user_defined_values["user_role"], # type: ignoremax_budget=user_defined_values["max_budget"],budget_duration=user_defined_values["budget_duration"],+ sso_user_id=user_defined_values["user_id"],+ auto_create_key=False,)if result_openid:diff --git a/tests/litellm/proxy/management_endpoints/test_ui_sso.py b/tests/litellm/proxy/management_endpoints/test_ui_sso.pyindex d266cd0f613..1877f8dfc99 100644--- a/tests/litellm/proxy/management_endpoints/test_ui_sso.py+++ b/tests/litellm/proxy/management_endpoints/test_ui_sso.py@@ -19,12 +19,12 @@ from litellm.proxy._types import NewTeamRequestfrom litellm.proxy.auth.handle_jwt import JWTHandlerfrom litellm.proxy.management_endpoints.types import CustomOpenIDfrom litellm.proxy.management_endpoints.ui_sso import (- DefaultTeamSSOParams,GoogleSSOHandler,MicrosoftSSOHandler,SSOAuthenticationHandler,)from litellm.types.proxy.management_endpoints.ui_sso import (+ DefaultTeamSSOParams,MicrosoftGraphAPIUserGroupDirectoryObject,MicrosoftGraphAPIUserGroupResponse,MicrosoftServicePrincipalTeam,@@ -518,3 +518,73 @@ async def test_create_team_without_default_params():assert "max_budget" not in create_call_argsassert "budget_duration" not in create_call_argsassert create_call_args["models"] == []+++def test_apply_user_info_values_to_sso_user_defined_values():+ from litellm.proxy._types import LiteLLM_UserTable+ from litellm.proxy.management_endpoints.ui_sso import (+ apply_user_info_values_to_sso_user_defined_values,+ )++ user_info = LiteLLM_UserTable(+ user_id="123",+ user_email="[email protected]",+ user_role="admin",+ )++ user_defined_values = {+ "user_id": "456",+ "user_email": "[email protected]",+ "user_role": "admin",+ }++ sso_user_defined_values = apply_user_info_values_to_sso_user_defined_values(+ user_info=user_info,+ user_defined_values=user_defined_values,+ )++ assert sso_user_defined_values["user_id"] == "123"+++async def test_get_user_info_from_db():+ """+ received args in get_user_info_from_db: {'result': CustomOpenID(id='krrishd', email='[email protected]', first_name=None, last_name=None, display_name='a3f1c107-04dc-4c93-ae60-7f32eb4b05ce', picture=None, provider=None, team_ids=[]), 'prisma_client': <litellm.proxy.utils.PrismaClient object at 0x14a74e3c0>, 'user_api_key_cache': <litellm.caching.dual_cache.DualCache object at 0x148d37110>, 'proxy_logging_obj': <litellm.proxy.utils.ProxyLogging object at 0x148dd9090>, 'user_email': '[email protected]', 'user_defined_values': {'models': [], 'user_id': 'krrishd', 'user_email': '[email protected]', 'max_budget': None, 'user_role': None, 'budget_duration': None}}+ """+ from litellm.proxy.management_endpoints.ui_sso import get_user_info_from_db++ prisma_client = MagicMock()+ user_api_key_cache = MagicMock()+ proxy_logging_obj = MagicMock()+ user_email = "[email protected]"+ user_defined_values = {+ "models": [],+ "user_id": "krrishd",+ "user_email": "[email protected]",+ "max_budget": None,+ "user_role": None,+ "budget_duration": None,+ }+ args = {+ "result": CustomOpenID(+ id="krrishd",+ email="[email protected]",+ first_name=None,+ last_name=None,+ display_name="a3f1c107-04dc-4c93-ae60-7f32eb4b05ce",+ picture=None,+ provider=None,+ team_ids=[],+ ),+ "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,+ }+ with patch.object(+ litellm.proxy.management_endpoints.ui_sso, "get_user_object"+ ) 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"