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(auth): carry team grants in lite login session tokens (#36826)
Yassin Kortam4bc27f1664d1
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex b1e444e55d6..17ebb4446e2 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -2556,6 +2556,8 @@ class ExperimentalUIJWTToken:user_info: LiteLLM_UserTable,team_id: str | None = None,team_alias: str | None = None,+ team_models: Sequence[str] | None = None,+ team_model_aliases: Mapping[str, str] | None = None,max_budget: float | None = None,) -> str:"""@@ -2568,6 +2570,8 @@ class ExperimentalUIJWTToken:user_info: User information from the databaseteam_id: Team ID for the user (optional, uses user's team if available)team_alias: Team alias for the selected team, if available+ team_models: Model allowlist granted by the selected team+ team_model_aliases: Team model aliases for the selected teamReturns:Encrypted JWT token string@@ -2606,7 +2610,9 @@ class ExperimentalUIJWTToken:user_id=user_info.user_id,team_id=_team_id,team_alias=team_alias,- models=user_info.models,+ team_models=list(team_models) if team_models is not None else [],+ team_model_aliases=dict(team_model_aliases) if team_model_aliases is not None else None,+ models=[] if _team_id is not None else user_info.models,max_parallel_requests=None,user_role=LitellmUserRoles(user_info.user_role),is_session_token=True,diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.pyindex a2c50590dd5..b87ad8597dc 100644--- a/litellm/proxy/management_endpoints/ui_sso.py+++ b/litellm/proxy/management_endpoints/ui_sso.py@@ -21,6 +21,7 @@ from copy import deepcopyfrom html import escapefrom typing import (TYPE_CHECKING,+ Annotated,Any,Final,Literal,@@ -40,6 +41,7 @@ if TYPE_CHECKING:import jwtfrom fastapi import APIRouter, Depends, Header, HTTPException, Request, Response, statusfrom fastapi.responses import RedirectResponse+from pydantic import BaseModel, BeforeValidator, ConfigDict, TypeAdapter, ValidationErrorimport litellmfrom litellm._logging import verbose_proxy_logger@@ -185,6 +187,7 @@ class _PrismaTableActions(Protocol[_DbRecordT]):async def find_many(self,where: Mapping[str, object] | None = None,+ include: Mapping[str, bool] | None = None,) -> Sequence[_DbRecordT]: ...async def update(@@ -241,6 +244,45 @@ def _team_detail_db(repo: "_HasTeamDetailTable") -> "_PrismaTableActions[_TeamDereturn repo.table+_MODEL_ALIASES_ADAPTER: Final = TypeAdapter(dict[str, str])+++def _decode_model_aliases(value: object) -> object:+ """``/team/new`` stores team model aliases as a JSON-encoded string in the Json column."""+ if not isinstance(value, str):+ return value+ try:+ return _MODEL_ALIASES_ADAPTER.validate_json(value)+ except ValidationError:+ return None+++class _TeamModelAliasTable(BaseModel):+ model_config = ConfigDict(protected_namespaces=())++ model_aliases: Annotated[Mapping[str, str] | None, BeforeValidator(_decode_model_aliases)] = None+++class _TeamRowGrants(BaseModel):+ team_id: str+ team_alias: str | None = None+ models: tuple[str, ...] = ()+ litellm_model_table: _TeamModelAliasTable | None = None+++class _CliSsoTeamDetail(BaseModel):+ """The per-team snapshot cached in the CLI SSO flow and echoed to the CLI on poll."""++ team_id: str | None = None+ team_alias: str | None = None+ team_models: tuple[str, ...]+ team_model_aliases: Mapping[str, str] | None = None+++_CLI_SSO_TEAM_DETAILS_ADAPTER: Final = TypeAdapter(tuple[_CliSsoTeamDetail, ...])+_TEAMLESS_CLI_SSO_TEAM_DETAIL: Final = _CliSsoTeamDetail(team_models=())++class _CustomSsoCall(Protocol):async def __call__(self, sso_response: object) -> SSOUserDefinedValues | None: ...@@ -2147,27 +2189,55 @@ async def _build_cli_sso_user_defined_values()+def _cli_sso_team_detail(team_row: Mapping[str, object]) -> _CliSsoTeamDetail:+ team: Final = _TeamRowGrants.model_validate(team_row)+ alias_table: Final = team.litellm_model_table+ return _CliSsoTeamDetail(+ team_id=team.team_id,+ team_alias=team.team_alias,+ team_models=team.models,+ team_model_aliases=alias_table.model_aliases if alias_table is not None else None,+ )++async def _fetch_cli_sso_team_details(prisma_client: PrismaClient,teams: Sequence[str],-) -> list[dict[str, object]]:- team_details: Final[list[dict[str, object]]] = []+) -> tuple[_CliSsoTeamDetail, ...] | None:+ """``None`` means the lookup itself failed, which is not the same as the user having no teams."""+ if not teams:+ return ()try:- if teams:- prisma_teams: Final = await _team_detail_db(TeamRepository(prisma_client)).find_many(- where={"team_id": {"in": teams}}- )- for team_row in prisma_teams:- team_dict = team_row.model_dump()- team_details.append(- {- "team_id": team_dict.get("team_id"),- "team_alias": team_dict.get("team_alias"),- }- )+ prisma_teams: Final = await _team_detail_db(TeamRepository(prisma_client)).find_many(+ where={"team_id": {"in": teams}},+ include={"litellm_model_table": True},+ )except Exception as e:verbose_proxy_logger.error("Error fetching team details for CLI SSO session: %s", e)- return team_details+ return None+ return tuple(_cli_sso_team_detail(team_row.model_dump()) for team_row in prisma_teams)+++def _cli_sso_session_teams(team_details: Sequence[_CliSsoTeamDetail]) -> list[str]:+ """The teams a login may bind to: only those whose row still exists.++ A team deleted out from under a membership, which is what deleting an organization+ leaves behind, can never resolve its grants, so offering it would refuse every+ future login for that user with nothing they could do to recover.+ """+ return [detail.team_id for detail in team_details if detail.team_id is not None]+++def _selected_cli_sso_team_detail(team_details: object, team_id: str | None) -> _CliSsoTeamDetail | None:+ """``None`` means the team's grants are unknown. An empty grant is a real value meaning unrestricted,+ so an unknown one must not be minted as empty."""+ if team_id is None:+ return _TEAMLESS_CLI_SSO_TEAM_DETAIL+ try:+ details: Final = _CLI_SSO_TEAM_DETAILS_ADAPTER.validate_python(team_details)+ except ValidationError:+ return None+ return next((detail for detail in details if detail.team_id == team_id), None)async def _complete_cli_sso_callback_session(@@ -2210,6 +2280,12 @@ async def _complete_cli_sso_callback_session(teams = user_info.teams if isinstance(user_info.teams, list) else []team_details: Final = await _fetch_cli_sso_team_details(prisma_client=prisma_client, teams=teams)+ if team_details is None:+ raise HTTPException(+ status_code=500,+ detail="Could not resolve team model grants for this login. Please try again",+ )+ 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(@@ -2223,8 +2299,8 @@ async def _complete_cli_sso_callback_session("user_role": user_info.user_role,"models": user_info.models if hasattr(user_info, "models") else [],"user_email": user_email,- "teams": teams,- "team_details": team_details,+ "teams": resolved_teams,+ "team_details": [detail.model_dump() for detail in team_details],"attribution_metadata": attribution_metadata,}flow["sso_complete"] = True@@ -2233,7 +2309,10 @@ async def _complete_cli_sso_callback_session(_set_cli_sso_flow(login_id=key, cache=cli_sso_session_cache, flow=flow)verbose_proxy_logger.info(- "Stored CLI SSO session for user: %s, teams: %s, num_teams: %s", user_info.user_id, teams, len(teams)+ "Stored CLI SSO session for user: %s, teams: %s, num_teams: %s",+ user_info.user_id,+ resolved_teams,+ len(resolved_teams),)verify_url: Final = get_custom_url(request_base_url=str(request.base_url),@@ -2401,11 +2480,14 @@ async def cli_poll_key(# If no team_id provided and user has 0 or 1 team, use first team (or None)team_id = user_teams[0] if len(user_teams) > 0 else None- team_alias = None- if team_id and isinstance(user_team_details, list):- team_alias = next(- (team.get("team_alias") for team in user_team_details if team.get("team_id") == team_id),- None,+ selected_team: Final = _selected_cli_sso_team_detail(+ team_details=user_team_details,+ team_id=team_id,+ )+ if selected_team is None:+ raise HTTPException(+ status_code=500,+ detail=f"Could not resolve the model grants for team: {team_id}. Please run `lite login` again",)user_info: Final = LiteLLM_UserTable(@@ -2417,7 +2499,9 @@ async def cli_poll_key(jwt_token: Final = ExperimentalUIJWTToken.get_cli_jwt_auth_token(user_info=user_info,team_id=team_id,- team_alias=team_alias,+ team_alias=selected_team.team_alias,+ team_models=selected_team.team_models,+ team_model_aliases=selected_team.team_model_aliases,max_budget=None,)diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.pyindex 298f8a31b64..28eda6633e8 100644--- a/tests/test_litellm/proxy/auth/test_auth_checks.py+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py@@ -155,6 +155,55 @@ def test_get_cli_jwt_auth_token_includes_team_alias(valid_sso_user_defined_valueassert token_data["team_alias"] == "test-team"+def test_get_cli_jwt_auth_token_carries_team_grants_not_user_allowlist(+ valid_sso_user_defined_values,+):+ """A team-bound `lite login` session token must snapshot the team's grants.++ Without team_models the /v1/models bail-out (`not key_models and not team_models`)+ treats the session as unrestricted and lists the whole proxy; without+ team_model_aliases a team alias never resolves on /chat/completions. The user's+ personal allowlist must stay out of the key `models` slot, since a team-bound+ credential is governed by the team grant, not by a per-user list.+ """+ token = ExperimentalUIJWTToken.get_cli_jwt_auth_token(+ valid_sso_user_defined_values,+ team_id="team-123",+ team_alias="test-team",+ team_models=("claude-sonnet-4-5", "gpt-4.1"),+ team_model_aliases={"team-fast": "gpt-4.1-mini"},+ )++ decrypted_token = decrypt_value_helper(+ token, key="ui_hash_key", exception_type="debug"+ )+ assert decrypted_token is not None+ token_data = json.loads(decrypted_token)++ assert token_data["team_id"] == "team-123"+ assert token_data["team_models"] == ["claude-sonnet-4-5", "gpt-4.1"]+ assert token_data["team_model_aliases"] == {"team-fast": "gpt-4.1-mini"}+ assert valid_sso_user_defined_values.models == ["gpt-3.5-turbo"]+ assert token_data["models"] == []+++def test_get_cli_jwt_auth_token_keeps_user_allowlist_when_no_team(+ valid_sso_user_defined_values,+):+ """A session token with no team bound still carries the user's own allowlist."""+ token = ExperimentalUIJWTToken.get_cli_jwt_auth_token(valid_sso_user_defined_values)++ decrypted_token = decrypt_value_helper(+ token, key="ui_hash_key", exception_type="debug"+ )+ assert decrypted_token is not None+ token_data = json.loads(decrypted_token)++ assert token_data.get("team_id") is None+ assert token_data["models"] == ["gpt-3.5-turbo"]+ assert token_data["team_models"] == []++def test_get_experimental_ui_login_jwt_auth_token_uses_10_min_expiry(valid_sso_user_defined_values,):diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.pyindex 979eb09d7db..da805b864fc 100644--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py@@ -2847,6 +2847,19 @@ class TestCLIKeyRegenerationFlow:"user_code_verified": False,"session_data": None,}+ mock_prisma = MagicMock()+ mock_prisma.db.litellm_teamtable.find_many = AsyncMock(+ return_value=[+ MagicMock(+ model_dump=lambda team_id=team_id: {+ "team_id": team_id,+ "team_alias": team_id,+ "models": [],+ }+ )+ for team_id in ("team1", "team2")+ ]+ )with (patch.dict(os.environ,@@ -2859,7 +2872,7 @@ class TestCLIKeyRegenerationFlow:"litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db",return_value=mock_user_info,),- patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),patch("litellm.proxy.proxy_server.user_api_key_cache", mock_cache),patch("litellm.proxy.proxy_server.cli_sso_session_cache", mock_cache),patch(@@ -3156,9 +3169,9 @@ class TestCLIKeyRegenerationFlow:"user_role": "internal_user","teams": ["team-a", "team-b", "team-c"],"team_details": [- {"team_id": "team-a", "team_alias": "Team A"},- {"team_id": "team-b", "team_alias": "Team B"},- {"team_id": "team-c", "team_alias": "Team C"},+ {"team_id": "team-a", "team_alias": "Team A", "team_models": []},+ {"team_id": "team-b", "team_alias": "Team B", "team_models": []},+ {"team_id": "team-c", "team_alias": "Team C", "team_models": []},],"models": ["gpt-4"],"user_email": "[email protected]",@@ -3225,6 +3238,243 @@ class TestCLIKeyRegenerationFlow:# Verify session was deleted after JWT generationmock_cache.delete_cache.assert_called_once()+ @pytest.mark.asyncio+ async def test_fetch_cli_sso_team_details_projects_team_grants(self):+ """The cached team detail must carry the team's model grants.++ The projection used to drop everything except team_id/team_alias, so the+ minted CLI token had no team_models and no team_model_aliases to snapshot.+ The joined alias table is stored JSON-encoded, so it has to be decoded here+ too, otherwise alias lookup at request time is a substring match on a string.+ """+ from litellm.proxy.management_endpoints.ui_sso import (+ _fetch_cli_sso_team_details,+ )++ team_row = MagicMock()+ team_row.model_dump.return_value = {+ "team_id": "team-a",+ "team_alias": "Team A",+ "models": ["claude-sonnet-4-5", "gpt-4.1"],+ "litellm_model_table": {+ "id": 7,+ "model_aliases": json.dumps({"team-fast": "gpt-4.1-mini"}),+ "created_by": "admin",+ "updated_by": "admin",+ },+ }+ find_many = AsyncMock(return_value=[team_row])+ prisma_client = MagicMock()+ prisma_client.db.litellm_teamtable.find_many = find_many++ details = await _fetch_cli_sso_team_details(+ prisma_client=prisma_client, teams=["team-a"]+ )++ assert find_many.await_args.kwargs["include"] == {"litellm_model_table": True}+ assert [detail.model_dump() for detail in details] == [+ {+ "team_id": "team-a",+ "team_alias": "Team A",+ "team_models": ("claude-sonnet-4-5", "gpt-4.1"),+ "team_model_aliases": {"team-fast": "gpt-4.1-mini"},+ }+ ]++ @pytest.mark.asyncio+ async def test_fetch_cli_sso_team_details_separates_lookup_failure_from_no_teams(self):+ """A failed lookup must not look like a team that resolved to nothing.++ Both used to return [], so a database blip was indistinguishable from a real+ answer. The callback needs them apart: a blip has to fail the login, while a+ real empty answer means the team rows are genuinely gone.+ """+ from litellm.proxy.management_endpoints.ui_sso import (+ _fetch_cli_sso_team_details,+ )++ failing_client = MagicMock()+ failing_client.db.litellm_teamtable.find_many = AsyncMock(+ side_effect=Exception("connection reset")+ )+ assert (+ await _fetch_cli_sso_team_details(+ prisma_client=failing_client, teams=["team-a"]+ )+ is None+ )++ empty_client = MagicMock()+ empty_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[])+ assert (+ await _fetch_cli_sso_team_details(+ prisma_client=empty_client, teams=["team-a"]+ )+ == ()+ )++ @pytest.mark.asyncio+ async def test_cli_poll_key_mints_jwt_with_selected_team_grants(self):+ """The selected team's grants must reach the mint, not just its alias."""+ from litellm.proxy.management_endpoints.ui_sso import (+ _hash_cli_sso_secret,+ cli_poll_key,+ )++ session_data = {+ "user_id": "grants-user",+ "user_role": "internal_user",+ "teams": ["team-a", "team-b"],+ "team_details": [+ {+ "team_id": "team-a",+ "team_alias": "Team A",+ "team_models": ["gpt-4.1"],+ "team_model_aliases": {"a-fast": "gpt-4.1-mini"},+ },+ {+ "team_id": "team-b",+ "team_alias": "Team B",+ "team_models": ["claude-sonnet-4-5"],+ "team_model_aliases": {"b-fast": "claude-haiku-4-5"},+ },+ ],+ "models": ["personal-only"],+ "user_email": "[email protected]",+ }+ mock_cache = MagicMock(redis_cache=None)+ mock_cache.get_cache.return_value = {+ "poll_secret_hash": _hash_cli_sso_secret("poll-secret"),+ "sso_complete": True,+ "user_code_verified": True,+ "session_data": session_data,+ }++ with (+ patch("litellm.proxy.proxy_server.cli_sso_session_cache", mock_cache),+ patch(+ "litellm.proxy.auth.auth_checks.ExperimentalUIJWTToken.get_cli_jwt_auth_token",+ return_value="minted-token",+ ) as mock_get_jwt,+ ):+ result = await cli_poll_key(+ key_id="cli-session-grants",+ team_id="team-b",+ x_litellm_cli_poll_secret="poll-secret",+ )++ assert result["status"] == "ready"+ kwargs = mock_get_jwt.call_args.kwargs+ assert kwargs["team_id"] == "team-b"+ assert kwargs["team_alias"] == "Team B"+ assert kwargs["team_models"] == ("claude-sonnet-4-5",)+ assert kwargs["team_model_aliases"] == {"b-fast": "claude-haiku-4-5"}++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "team_details",+ [+ pytest.param(None, id="detail_fetch_failed"),+ pytest.param(+ [{"team_id": "team-other", "team_models": []}], id="selected_team_absent"+ ),+ pytest.param(+ [{"team_id": "team-a", "team_alias": "Team A"}],+ id="legacy_detail_without_grants",+ ),+ ],+ )+ async def test_cli_poll_key_refuses_to_mint_when_team_grants_are_unknown(+ self, team_details+ ):+ """An unknown team grant must never be minted as an empty one.++ get_complete_model_list falls through to the whole proxy model list when both+ the key allowlist and the team allowlist are empty, and team-bound tokens carry+ an empty key allowlist by design. So minting an unresolved team as empty would+ hand a team-bound CLI session every model on the proxy.+ """+ from litellm.proxy.management_endpoints.ui_sso import (+ _hash_cli_sso_secret,+ cli_poll_key,+ )++ mock_cache = MagicMock(redis_cache=None)+ mock_cache.get_cache.return_value = {+ "poll_secret_hash": _hash_cli_sso_secret("poll-secret"),+ "sso_complete": True,+ "user_code_verified": True,+ "session_data": {+ "user_id": "grants-user",+ "user_role": "internal_user",+ "teams": ["team-a"],+ "team_details": team_details,+ "models": ["personal-only"],+ "user_email": "[email protected]",+ },+ }++ with (+ patch("litellm.proxy.proxy_server.cli_sso_session_cache", mock_cache),+ patch(+ "litellm.proxy.auth.auth_checks.ExperimentalUIJWTToken.get_cli_jwt_auth_token",+ return_value="minted-token",+ ) as mock_get_jwt,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await cli_poll_key(+ key_id="cli-session-grants",+ team_id="team-a",+ x_litellm_cli_poll_secret="poll-secret",+ )++ assert exc_info.value.status_code == 500+ assert "team-a" in str(exc_info.value.detail)+ mock_get_jwt.assert_not_called()+ mock_cache.delete_cache.assert_not_called()++ @pytest.mark.asyncio+ async def test_cli_poll_key_mints_teamless_session_without_team_grants(self):+ """A user with no team still mints, keeping their personal allowlist in the key slot."""+ from litellm.proxy.management_endpoints.ui_sso import (+ _hash_cli_sso_secret,+ cli_poll_key,+ )++ mock_cache = MagicMock(redis_cache=None)+ mock_cache.get_cache.return_value = {+ "poll_secret_hash": _hash_cli_sso_secret("poll-secret"),+ "sso_complete": True,+ "user_code_verified": True,+ "session_data": {+ "user_id": "teamless-user",+ "user_role": "internal_user",+ "teams": [],+ "team_details": [],+ "models": ["personal-only"],+ "user_email": "[email protected]",+ },+ }++ with (+ patch("litellm.proxy.proxy_server.cli_sso_session_cache", mock_cache),+ patch(+ "litellm.proxy.auth.auth_checks.ExperimentalUIJWTToken.get_cli_jwt_auth_token",+ return_value="minted-token",+ ) as mock_get_jwt,+ ):+ result = await cli_poll_key(+ key_id="cli-session-teamless",+ team_id=None,+ x_litellm_cli_poll_secret="poll-secret",+ )++ assert result["status"] == "ready"+ kwargs = mock_get_jwt.call_args.kwargs+ assert kwargs["team_id"] is None+ assert kwargs["team_models"] == ()+ assert kwargs["user_info"].models == ["personal-only"]+@pytest.mark.asyncioasync def test_cli_poll_key_does_not_cap_session_when_user_has_budget(self):"""A user with a configured budget must not get the max_ui_session_budget fallback cap."""@@ -3302,7 +3552,7 @@ class TestCLIKeyRegenerationFlow:"user_id": "unbudgeted-user","user_role": "internal_user","teams": ["team-x"],- "team_details": [{"team_id": "team-x", "team_alias": "Team X"}],+ "team_details": [{"team_id": "team-x", "team_alias": "Team X", "team_models": []}],"models": ["gpt-4"],"user_email": "[email protected]",}@@ -6539,6 +6789,17 @@ class TestCliSsoAttributionMetadata:return_value=MagicMock(metadata={"auth_provider": "generic"}))mock_prisma.db.litellm_usertable.update_many = AsyncMock()+ mock_prisma.db.litellm_teamtable.find_many = AsyncMock(+ return_value=[+ MagicMock(+ model_dump=lambda: {+ "team_id": "team1",+ "team_alias": "team1",+ "models": [],+ }+ )+ ]+ )with (patch.dict(@@ -7879,6 +8140,117 @@ async def test_cli_completion_persists_assertion_under_db_user_id():assert response.status_code == 200+def _cli_callback_kwargs(flow):+ return {+ "request": _cli_callback_request(),+ "key": "cli-login-id",+ "flow": flow,+ "result": {"sub": "raw-idp-subject"},+ "parsed_openid_result": {+ "user_id": "raw-idp-subject",+ "user_email": "[email protected]",+ "user_role": None,+ },+ "user_defined_values": None,+ "prisma_client": MagicMock(),+ "user_api_key_cache": MagicMock(),+ "cli_sso_session_cache": MagicMock(),+ "proxy_logging_obj": MagicMock(),+ }+++def _cli_callback_request():+ mock_request = MagicMock(spec=Request)+ mock_request.base_url = "http://localhost:4000/"+ return mock_request+++def _cli_callback_user_info(teams):+ user_info = MagicMock()+ user_info.user_id = "cli-user-id"+ user_info.user_role = "internal_user"+ user_info.models = ["personal-only"]+ user_info.teams = teams+ return user_info+++async def test_cli_completion_drops_teams_whose_rows_no_longer_exist():+ """A membership pointing at a deleted team must not be offered for selection.++ Deleting an organization removes its team rows but leaves the user's membership+ behind. If that dead team still reached the session, it would be auto-selected+ for a single-team user, its grants could never resolve, and every future login+ would be refused with no way for the user to recover.+ """+ from litellm.proxy.management_endpoints.ui_sso import (+ _CliSsoTeamDetail,+ _complete_cli_sso_callback_session,+ )++ live_detail = _CliSsoTeamDetail(+ team_id="team-live", team_alias="Live", team_models=("gpt-4.1",)+ )+ flow = {}+ with (+ patch(+ "litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db",+ AsyncMock(return_value=_cli_callback_user_info(["team-live", "team-deleted"])),+ ),+ patch(+ "litellm.proxy.management_endpoints.ui_sso._fetch_cli_sso_team_details",+ AsyncMock(return_value=(live_detail,)),+ ),+ 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 = await _complete_cli_sso_callback_session(**_cli_callback_kwargs(flow))++ assert response.status_code == 200+ assert flow["session_data"]["teams"] == ["team-live"]+ assert [d["team_id"] for d in flow["session_data"]["team_details"]] == ["team-live"]+++async def test_cli_completion_fails_the_login_when_team_lookup_fails():+ """A lookup failure must fail the login instead of caching a teamless session.++ Silently dropping every team here would hand a team-bound user a session with+ their personal allowlist, which is the same "unknown grant treated as a real+ grant" bug in a quieter form.+ """+ from litellm.proxy.management_endpoints.ui_sso import (+ _complete_cli_sso_callback_session,+ )++ flow = {}+ with (+ patch(+ "litellm.proxy.management_endpoints.ui_sso.get_user_info_from_db",+ AsyncMock(return_value=_cli_callback_user_info(["team-live"])),+ ),+ patch(+ "litellm.proxy.management_endpoints.ui_sso._fetch_cli_sso_team_details",+ AsyncMock(return_value=None),+ ),+ patch(+ "litellm.proxy.management_endpoints.ui_sso.retain_sso_identity_assertion_for_ema",+ AsyncMock(),+ ),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await _complete_cli_sso_callback_session(**_cli_callback_kwargs(flow))++ assert exc_info.value.status_code == 500+ assert "session_data" not in flow++class TestSameOriginReturnPath:"""The same-origin relative return_to arm added for the MCP gateway DCR authorizeround-trip: only strictly relative paths qualify, so login can never redirect the