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
feat(proxy): let personal keys inherit model access from the owner's current teams (#43692)
devin-ai-integration[bot]aa5292721655
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex d29a0e03d5b..a7ea9ce4583 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -477,6 +477,7 @@ max_end_user_budget_id: Optional[str] = None# pass through unchanged.validate_end_user_id_in_db: bool = Falseblock_requests_for_models_without_pricing: bool = False+personal_key_model_access_from_teams: bool = Falsedisable_end_user_cost_tracking: Optional[bool] = Nonedisable_end_user_cost_tracking_prometheus_only: Optional[bool] = Noneenable_end_user_cost_tracking_prometheus_only: Optional[bool] = Nonediff --git a/litellm/constants.py b/litellm/constants.pyindex d9441f36a1f..04ed307330c 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -1963,6 +1963,7 @@ LITELLM_SETTINGS_SAFE_DB_OVERRIDES: Final = ["openai_system_messages_first","max_ui_session_budget","budget_rollover",+ "personal_key_model_access_from_teams","mcp_tool_search","turn_off_message_logging","datadog_params",diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex 56773789059..9e7fa2c28e8 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -1308,6 +1308,20 @@ async def common_checks(valid_token=valid_token,)+ if _model and valid_token is not None and personal_key_team_model_access_applies(valid_token):+ await can_personal_key_call_model_via_teams(+ model=(+ *((_model,) if isinstance(_model, str) else _model),+ *request_fallback_model_names(_typed_request_body(request_body)),+ ),+ user_object=user_object,+ valid_token=valid_token,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+# 1.1 - 2.2 - 3.0.2 - 3.0.3: Project checks (blocked, model access, budget)with tracer.trace("litellm.proxy.auth.common_checks.run_project_checks"):await _run_project_checks(@@ -5331,6 +5345,31 @@ async def can_key_call_model(raise+async def _personal_key_owner(+ valid_token: UserAPIKeyAuth,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache,+ proxy_logging_obj: ProxyLogging,+) -> LiteLLM_UserTable | None:+ if valid_token.user_id is None:+ return None+ try:+ return await get_user_object(+ user_id=valid_token.user_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ user_id_upsert=False,+ parent_otel_span=valid_token.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )+ except Exception as e: # noqa: BLE001 # fail closed: an owner that cannot be loaded grants nothing+ verbose_proxy_logger.warning(+ "Personal key team model access: owner lookup failed, granting nothing: %s",+ e,+ )+ return None++async def can_key_call_resolved_model(model: str,llm_model_list: Sequence[object] | None,@@ -5410,6 +5449,23 @@ async def can_key_call_resolved_model(key_model_aliases=key_model_aliases_for_auth_check(valid_token),)+ if personal_key_team_model_access_applies(valid_token) and valid_token.user_id is not None:+ owner: Final = await _personal_key_owner(+ valid_token=valid_token,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ await can_personal_key_call_model_via_teams(+ model=model,+ user_object=owner,+ valid_token=valid_token,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+if valid_token.project_id is not None:project_object: Final = await get_project_object(project_id=valid_token.project_id,@@ -5674,6 +5730,241 @@ async def can_user_call_model()+def personal_key_team_model_access_applies(valid_token: UserAPIKeyAuth | None) -> bool:+ return (+ bool(litellm.personal_key_model_access_from_teams)+ and valid_token is not None+ and valid_token.team_id is None+ and valid_token.user_id is not None+ and valid_token.api_key != LITELLM_PROXY_MASTER_KEY_ALIAS+ and valid_token.user_role != LitellmUserRoles.PROXY_ADMIN+ )+++async def _load_personal_key_team(+ team_id: str,+ valid_token: UserAPIKeyAuth,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache,+ proxy_logging_obj: ProxyLogging,+) -> LiteLLM_TeamTableCachedObj | None:+ try:+ team_object: Final = await get_team_object(+ team_id=team_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=valid_token.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )+ except Exception as e: # noqa: BLE001 # fail closed: a team that cannot be loaded grants nothing+ verbose_proxy_logger.warning(+ "Personal key team model access: team=%s lookup failed, granting nothing: %s", team_id, e+ )+ return None+ return None if team_object.blocked is True else team_object+++async def _load_personal_key_teams(+ user_object: LiteLLM_UserTable,+ valid_token: UserAPIKeyAuth,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache,+ proxy_logging_obj: ProxyLogging,+) -> tuple[LiteLLM_TeamTableCachedObj | None, ...]:+ return tuple(+ await asyncio.gather(+ *(+ _load_personal_key_team(+ team_id=team_id,+ valid_token=valid_token,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ for team_id in dict.fromkeys(user_object.teams)+ )+ )+ )+++async def _team_grants_personal_key_model(+ model: str,+ team_object: LiteLLM_TeamTableCachedObj,+ valid_token: UserAPIKeyAuth,+ llm_router: Router | None,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache,+ proxy_logging_obj: ProxyLogging,+) -> bool:+ key_model_aliases: Final = key_model_aliases_for_auth_check(valid_token)+ try:+ await can_team_access_model(+ model=model,+ team_object=team_object,+ llm_router=llm_router,+ key_model_aliases=key_model_aliases,+ prisma_client=prisma_client,+ )+ await _check_team_member_model_access(+ model=model,+ team_object=team_object,+ valid_token=valid_token,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ key_model_aliases=key_model_aliases,+ )+ except ProxyException:+ return False+ except Exception as e: # noqa: BLE001 # fail closed: a team check that errors grants nothing+ verbose_proxy_logger.warning(+ "Personal key team model access: team=%s check failed, granting nothing: %s", team_object.team_id, e+ )+ return False+ return True+++async def _loaded_teams_allow_model(+ model: str,+ teams: tuple[LiteLLM_TeamTableCachedObj | None, ...],+ valid_token: UserAPIKeyAuth,+ llm_router: Router | None,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache,+ proxy_logging_obj: ProxyLogging,+) -> bool:+ loaded: Final = tuple(team for team in teams if team is not None)+ if not loaded:+ return False+ grants: Final = await asyncio.gather(+ *(+ _team_grants_personal_key_model(+ model=model,+ team_object=team,+ valid_token=valid_token,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ for team in loaded+ )+ )+ return any(grants)+++async def _personal_key_listing_teams(+ user_api_key_dict: UserAPIKeyAuth,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache | None,+ proxy_logging_obj: ProxyLogging | None,+) -> tuple[LiteLLM_TeamTableCachedObj | None, ...]:+ if (+ user_api_key_dict.user_id is None+ or prisma_client is None+ or user_api_key_cache is None+ or proxy_logging_obj is None+ ):+ return ()+ owner: Final = await _personal_key_owner(+ valid_token=user_api_key_dict,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ if owner is None:+ return ()+ return await _load_personal_key_teams(+ user_object=owner,+ valid_token=user_api_key_dict,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+++async def personal_key_team_visible_models(+ models: Sequence[str],+ user_api_key_dict: UserAPIKeyAuth,+ llm_router: Router | None,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache | None,+ proxy_logging_obj: ProxyLogging | None,+) -> tuple[str, ...]:+ teams: Final = await _personal_key_listing_teams(+ user_api_key_dict=user_api_key_dict,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ return tuple(+ [+ model+ for model in (models if teams else ())+ if (+ prisma_client is not None+ and user_api_key_cache is not None+ and proxy_logging_obj is not None+ and await _loaded_teams_allow_model(+ model=model,+ teams=teams,+ valid_token=user_api_key_dict,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ )+ ]+ )+++async def can_personal_key_call_model_via_teams(+ model: str | Sequence[str],+ user_object: LiteLLM_UserTable | None,+ valid_token: UserAPIKeyAuth,+ llm_router: Router | None,+ prisma_client: PrismaClient | None,+ user_api_key_cache: UserApiKeyCache,+ proxy_logging_obj: ProxyLogging,+) -> Literal[True]:+ requested_models: Final = (model,) if isinstance(model, str) else tuple(model)+ teams: Final = (+ await _load_personal_key_teams(+ user_object=user_object,+ valid_token=valid_token,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ if user_object is not None+ else ()+ )+ for requested_model in requested_models:+ if user_object is None or not await _loaded_teams_allow_model(+ model=requested_model,+ teams=teams,+ valid_token=valid_token,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ ):+ raise ModelAccessDeniedProxyException(+ message=model_access_denied_client_message(model=requested_model),+ internal_message=(+ f"Personal key model access is derived from the owner's teams. User={valid_token.user_id}, "+ f"teams={user_object.teams if user_object is not None else None}, "+ f"model={requested_model}"+ ),+ type=ProxyErrorTypes.key_model_access_denied,+ param="model",+ code=status.HTTP_403_FORBIDDEN,+ )+ return True++def _search_tool_names_from_object_permission(object_permission: LiteLLM_ObjectPermissionTable | None,) -> list[str]:diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 1c7cf54ab4d..7fe175131d8 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -18845,6 +18845,14 @@ _GENERAL_SETTINGS_UI_LITELLM_FIELDS: Final[dict[str, GeneralSettingsUILiteLLMFie"forgiving it. Applies to key, user, team, team member, org, tag and end-user budgets."),},+ "personal_key_model_access_from_teams": {+ "type": "Boolean",+ "description": (+ "Caps each personal key (a key with no team) to the models its owner's current teams can call, "+ "re-evaluated on every request. A user in no team gets no model access. A user in several teams "+ "can call any model one of those teams can call. Team keys are unaffected."+ ),+ },"max_ui_session_budget": {"type": "Dollar","default": 1.0,diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 5bcba4a5992..5fa78a44d09 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -8972,6 +8972,10 @@ async def get_available_models_for_user(Returns:List of model names available to the user"""+ from litellm.proxy.auth.auth_checks import (+ personal_key_team_model_access_applies,+ personal_key_team_visible_models,+ )from litellm.proxy.auth.model_checks import (get_complete_model_list,get_key_models,@@ -9042,7 +9046,7 @@ async def get_available_models_for_user(granted_team_models: Final = (*team_models, *access_group_models) if team_models else team_models# Get complete model list- all_models: Final = get_complete_model_list(+ complete_models: Final = get_complete_model_list(key_models=granted_key_models,team_models=granted_team_models,proxy_model_list=proxy_model_list,@@ -9055,6 +9059,20 @@ async def get_available_models_for_user(only_model_access_groups=only_model_access_groups,team_id=effective_team_id,)+ all_models: Final = (+ list(+ await personal_key_team_visible_models(+ models=complete_models,+ user_api_key_dict=user_api_key_dict,+ llm_router=llm_router,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ )+ if personal_key_team_model_access_applies(user_api_key_dict)+ else complete_models+ )agent_visible: Final = await _agent_access_group_visible_models(user_api_key_dict=user_api_key_dict,diff --git a/tests/unit/proxy/auth/test_personal_key_team_model_access.py b/tests/unit/proxy/auth/test_personal_key_team_model_access.pynew file mode 100644index 00000000000..38f34adb48e--- /dev/null+++ b/tests/unit/proxy/auth/test_personal_key_team_model_access.py@@ -0,0 +1,377 @@+from collections.abc import Iterator, Mapping+from typing import Final+from unittest.mock import AsyncMock, MagicMock++import pytest+from fastapi import Request++import litellm+from litellm.proxy import proxy_server+from litellm.proxy._types import (+ LiteLLM_TeamTableCachedObj,+ LiteLLM_UserTable,+ LitellmUserRoles,+ ModelAccessDeniedProxyException,+ UserAPIKeyAuth,+)+from litellm.proxy.auth import auth_checks+from litellm.proxy.auth.auth_checks import can_key_call_resolved_model, common_checks+from litellm.proxy.utils import get_available_models_for_user++_TEAMS: Final[Mapping[str, LiteLLM_TeamTableCachedObj]] = {+ "team-a": LiteLLM_TeamTableCachedObj(team_id="team-a", models=["gpt-a", "shared"]),+ "team-b": LiteLLM_TeamTableCachedObj(team_id="team-b", models=["gpt-b", "shared"]),+ "team-open": LiteLLM_TeamTableCachedObj(team_id="team-open", models=[]),+ "team-blocked": LiteLLM_TeamTableCachedObj(team_id="team-blocked", models=["gpt-a"], blocked=True),+}++_ROUTER: Final = litellm.Router(+ model_list=[+ {"model_name": name, "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-fake"}}+ for name in ("gpt-a", "gpt-b", "shared", "gpt-c")+ ]+)+++def teams(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ async def _get_team_object(team_id: str, **_: object) -> LiteLLM_TeamTableCachedObj:+ if team_id not in _TEAMS:+ raise Exception(f"team {team_id} lookup failed")+ return _TEAMS[team_id]++ async def _no_membership(**_: object) -> None:+ return None++ monkeypatch.setattr(auth_checks, "get_team_object", _get_team_object)+ monkeypatch.setattr(auth_checks, "get_team_membership", _no_membership)+ yield+++def _enable(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(litellm, "personal_key_model_access_from_teams", True)+++async def _common_checks(+ model: str | list[str],+ user: LiteLLM_UserTable | None,+ token: UserAPIKeyAuth,+ fallbacks: tuple[str, ...] = (),+) -> bool:+ request_body: Final = {"model": model} | ({"fallbacks": list(fallbacks)} if fallbacks else {})+ return await common_checks(+ request_body=request_body,+ team_object=None,+ user_object=user,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route="/chat/completions",+ llm_router=_ROUTER,+ proxy_logging_obj=MagicMock(),+ valid_token=token,+ request=MagicMock(spec=Request),+ )+++ "model, allowed",+ [+ ("gpt-a", True),+ ("gpt-b", True),+ ("shared", True),+ ("gpt-c", False),+ ],+)+async def test_personal_key_inherits_the_union_of_its_owner_team_models(+ monkeypatch: pytest.MonkeyPatch, teams: None, model: str, allowed: bool+) -> None:+ _enable(monkeypatch)+ user: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")++ if allowed:+ assert await _common_checks(model, user, token) is True+ else:+ with pytest.raises(ModelAccessDeniedProxyException):+ await _common_checks(model, user, token)+++async def test_personal_key_without_teams_gets_no_models(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ with pytest.raises(ModelAccessDeniedProxyException):+ await _common_checks(+ "gpt-a", LiteLLM_UserTable(user_id="u1", teams=[]), UserAPIKeyAuth(token="k1", user_id="u1")+ )+++async def test_personal_key_denied_when_owner_not_loaded(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ with pytest.raises(ModelAccessDeniedProxyException):+ await _common_checks("gpt-a", None, UserAPIKeyAuth(token="k1", user_id="u1"))+++async def test_proxy_admin_personal_key_is_not_capped(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ user: Final = LiteLLM_UserTable(user_id="admin", teams=[], user_role=LitellmUserRoles.PROXY_ADMIN.value)+ token: Final = UserAPIKeyAuth(token="k1", user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN)+ assert await _common_checks("gpt-c", user, token) is True+++async def test_personal_key_unrestricted_when_flag_off(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ monkeypatch.setattr(litellm, "personal_key_model_access_from_teams", False)+ user: Final = LiteLLM_UserTable(user_id="u1", teams=[])+ assert await _common_checks("gpt-c", user, UserAPIKeyAuth(token="k1", user_id="u1")) is True+++async def test_personal_key_fallbacks_are_capped_by_owner_teams(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")++ with pytest.raises(ModelAccessDeniedProxyException) as exc_info:+ await _common_checks("gpt-a", owner, token, fallbacks=("gpt-c",))+ assert str(exc_info.value.code) == "403"+ assert await _common_checks("gpt-a", owner, token, fallbacks=("shared",)) is True+++async def test_personal_key_list_models_can_be_allowed_by_different_teams(+ monkeypatch: pytest.MonkeyPatch, teams: None+) -> None:+ _enable(monkeypatch)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")++ assert await _common_checks(["gpt-a", "gpt-b"], owner, token) is True+++async def test_personal_key_list_models_denies_the_unavailable_model(+ monkeypatch: pytest.MonkeyPatch, teams: None+) -> None:+ _enable(monkeypatch)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")++ with pytest.raises(ModelAccessDeniedProxyException) as exc_info:+ await _common_checks(["gpt-a", "gpt-c"], owner, token)++ assert exc_info.value.code == "403"+ assert "gpt-c" in exc_info.value.message+++async def test_personal_key_fallbacks_are_unchanged_when_flag_off(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ monkeypatch.setattr(litellm, "personal_key_model_access_from_teams", False)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")+ assert await _common_checks("gpt-a", owner, token, fallbacks=("gpt-c",)) is True+++async def test_personal_key_fallbacks_load_each_owner_team_once(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ get_team: Final = AsyncMock(wraps=auth_checks.get_team_object)+ monkeypatch.setattr(auth_checks, "get_team_object", get_team)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")++ assert await _common_checks("gpt-a", owner, token, fallbacks=("shared", "gpt-a")) is True+ assert sorted(call.kwargs["team_id"] for call in get_team.call_args_list) == ["team-a", "team-b"]+++async def test_team_key_is_not_capped_by_owner_teams(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ user: Final = LiteLLM_UserTable(user_id="u1", teams=[])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1", team_id="team-open")+ assert await _common_checks("gpt-c", user, token, fallbacks=("gpt-c",)) is True+++ "teams_of_user, allowed",+ [+ (["team-missing", "team-a"], True),+ (["team-missing"], False),+ (["team-blocked"], False),+ (["team-blocked", "team-a"], True),+ ],+)+async def test_unloadable_or_blocked_team_grants_nothing(+ monkeypatch: pytest.MonkeyPatch, teams: None, teams_of_user: list[str], allowed: bool+) -> None:+ _enable(monkeypatch)+ user: Final = LiteLLM_UserTable(user_id="u1", teams=teams_of_user)+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")+ if allowed:+ assert await _common_checks("gpt-a", user, token) is True+ else:+ with pytest.raises(ModelAccessDeniedProxyException):+ await _common_checks("gpt-a", user, token)+++async def test_membership_change_applies_to_existing_key(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")+ assert await _common_checks("gpt-a", LiteLLM_UserTable(user_id="u1", teams=["team-a"]), token) is True+ with pytest.raises(ModelAccessDeniedProxyException):+ await _common_checks("gpt-a", LiteLLM_UserTable(user_id="u1", teams=["team-b"]), token)+++async def test_resolved_model_check_caps_personal_key(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a"])++ async def _get_user_object(**_: object) -> LiteLLM_UserTable:+ return owner++ monkeypatch.setattr(auth_checks, "get_user_object", _get_user_object)+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")++ await can_key_call_resolved_model(model="gpt-a", llm_model_list=None, valid_token=token, llm_router=_ROUTER)+ with pytest.raises(ModelAccessDeniedProxyException):+ await can_key_call_resolved_model(model="gpt-b", llm_model_list=None, valid_token=token, llm_router=_ROUTER)+++async def test_resolved_model_check_denies_when_personal_key_owner_lookup_fails(+ monkeypatch: pytest.MonkeyPatch, teams: None+) -> None:+ _enable(monkeypatch)+ monkeypatch.setattr(proxy_server, "prisma_client", None)+ token: Final = UserAPIKeyAuth(token="k1", user_id="u-no-db")+ await proxy_server.user_api_key_cache.async_delete_cache("u-no-db")+ assert await proxy_server.user_api_key_cache.async_get_cache(key="u-no-db", model_type=LiteLLM_UserTable) is None++ with pytest.raises(ModelAccessDeniedProxyException) as exc_info:+ await can_key_call_resolved_model(model="gpt-a", llm_model_list=None, valid_token=token, llm_router=_ROUTER)+ assert str(exc_info.value.code) == "403"+++async def _list_models(monkeypatch: pytest.MonkeyPatch, owner: LiteLLM_UserTable, token: UserAPIKeyAuth) -> list[str]:+ async def _get_user_object(**_: object) -> LiteLLM_UserTable:+ return owner++ monkeypatch.setattr(auth_checks, "get_user_object", _get_user_object)+ return await get_available_models_for_user(+ user_api_key_dict=token,+ llm_router=_ROUTER,+ general_settings={},+ user_model=None,+ prisma_client=MagicMock(),+ proxy_logging_obj=MagicMock(),+ user_api_key_cache=MagicMock(),+ )+++ "key_models, expected",+ [+ ([], {"gpt-a", "gpt-b", "shared"}),+ (["gpt-a", "gpt-c"], {"gpt-a"}),+ ],+)+async def test_model_listing_matches_team_derived_access(+ monkeypatch: pytest.MonkeyPatch, teams: None, key_models: list[str], expected: set[str]+) -> None:+ _enable(monkeypatch)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b"])+ listed: Final = await _list_models(monkeypatch, owner, UserAPIKeyAuth(token="k1", user_id="u1", models=key_models))+ assert set(listed) == expected+++async def test_model_listing_empty_without_teams(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=[])+ assert await _list_models(monkeypatch, owner, UserAPIKeyAuth(token="k1", user_id="u1")) == []+++async def test_model_listing_unchanged_when_flag_off(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ monkeypatch.setattr(litellm, "personal_key_model_access_from_teams", False)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=[])+ listed: Final = await _list_models(monkeypatch, owner, UserAPIKeyAuth(token="k1", user_id="u1"))+ assert set(listed) == {"gpt-a", "gpt-b", "shared", "gpt-c"}+++async def test_model_listing_loads_each_team_once(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ get_team: Final = AsyncMock(wraps=auth_checks.get_team_object)+ monkeypatch.setattr(auth_checks, "get_team_object", get_team)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b", "team-a"])+ listed: Final = await _list_models(monkeypatch, owner, UserAPIKeyAuth(token="k1", user_id="u1"))+ assert set(listed) == {"gpt-a", "gpt-b", "shared"}+ assert sorted(call.kwargs["team_id"] for call in get_team.call_args_list) == ["team-a", "team-b"]+++async def test_team_check_error_grants_nothing_for_that_team(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ check_team: Final = auth_checks.can_team_access_model++ async def _failing_for_team_b(model: str, team_object: LiteLLM_TeamTableCachedObj, **_: object) -> bool:+ if team_object.team_id == "team-b":+ raise RuntimeError("access group lookup failed")+ return await check_team(model=model, team_object=team_object, llm_router=_ROUTER)++ monkeypatch.setattr(auth_checks, "can_team_access_model", _failing_for_team_b)+ owner: Final = LiteLLM_UserTable(user_id="u1", teams=["team-a", "team-b"])+ token: Final = UserAPIKeyAuth(token="k1", user_id="u1")+ assert await _common_checks("gpt-a", owner, token) is True+ with pytest.raises(ModelAccessDeniedProxyException):+ await _common_checks("gpt-b", owner, token)+++async def _owner_lookup_fails(**_: object) -> LiteLLM_UserTable:+ raise RuntimeError("database unavailable")+++async def _owner_missing(**_: object) -> None:+ return None++[email protected]("get_owner", [_owner_lookup_fails, _owner_missing])+async def test_model_listing_empty_when_owner_not_loaded(+ monkeypatch: pytest.MonkeyPatch, teams: None, get_owner: object+) -> None:+ _enable(monkeypatch)+ monkeypatch.setattr(auth_checks, "get_user_object", get_owner)+ listed: Final = await get_available_models_for_user(+ user_api_key_dict=UserAPIKeyAuth(token="k1", user_id="u1"),+ llm_router=_ROUTER,+ general_settings={},+ user_model=None,+ prisma_client=MagicMock(),+ proxy_logging_obj=MagicMock(),+ user_api_key_cache=MagicMock(),+ )+ assert listed == []+++async def test_model_listing_empty_without_database(monkeypatch: pytest.MonkeyPatch, teams: None) -> None:+ _enable(monkeypatch)+ listed: Final = await get_available_models_for_user(+ user_api_key_dict=UserAPIKeyAuth(token="k1", user_id="u1"),+ llm_router=_ROUTER,+ general_settings={},+ user_model=None,+ prisma_client=None,+ proxy_logging_obj=MagicMock(),+ user_api_key_cache=MagicMock(),+ )+ assert listed == []