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(proxy): sort BYOK models by their displayed name in /v2/model/info (#28079)
Shivam Rawatfbe0ee81f1c7
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 268b244c86d..97252b4c977 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -20,6 +20,7 @@ from typing import (TYPE_CHECKING,Any,AsyncGenerator,+ Callable,Dict,List,Literal,@@ -10889,13 +10890,130 @@ def _enrich_model_info_with_litellm_data(return model+async def _get_caller_byok_team_scope(+ user_api_key_dict: Optional[UserAPIKeyAuth],+ prisma_client: Optional[Any],+) -> Optional[Set[str]]:+ """+ Return the team IDs whose BYOK rows the caller is allowed to see via+ `/v2/model/info` search results.++ `None` means "no scoping" — used for admins and for callers/paths that+ have already been scoped upstream (or in tests that supply their own+ pre-filtered input set). A returned set (possibly empty) means BYOK rows+ must have `model_info.team_id` ∈ that set, otherwise they belong to a+ team the caller is not a member of and must be dropped.+ """+ if user_api_key_dict is None or prisma_client is None:+ return None+ if user_api_key_dict.user_role in (+ LitellmUserRoles.PROXY_ADMIN,+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,+ ):+ return None+ user_id = user_api_key_dict.user_id+ if user_id is None:+ return set()+ try:+ user_row = await prisma_client.db.litellm_usertable.find_unique(+ where={"user_id": user_id}+ )+ except Exception:+ verbose_proxy_logger.exception(+ "Failed to look up caller teams while scoping BYOK search; "+ "defaulting to no team access."+ )+ return set()+ if user_row is None:+ return set()+ return set(user_row.teams or [])+++# Hard cap on rows the DB-side BYOK search may pull when results need to be+# sorted across the full match set. Without this, an authenticated caller+# can hit `/v2/model/info?search=<broad>&sortBy=<field>` and force the+# proxy to materialize and decrypt every matching BYOK row on each request.+_SORTED_SEARCH_DB_FETCH_CAP = 500+++async def _fetch_db_models_for_search(+ prisma_client: Any,+ proxy_config: Any,+ search_lower: str,+ db_model_ids_in_router: Set[str],+ router_models_count: int,+ page: int,+ size: int,+ sort_by: Optional[str],+ is_byok_outside_caller_teams: Callable[[Dict[str, Any]], bool],+) -> Tuple[List[Dict[str, Any]], int]:+ """+ Run the bounded DB query that backs `/v2/model/info?search=`. Returns+ `(decrypted_models, total_count)` where `total_count` is the cheap+ `count(...)` of rows matching `search` (not yet team-scoped) so the+ UI's pagination stays accurate without materializing every row.++ Earlier iterations also OR'd a JSON-path match on+ `model_info.team_public_model_name` to surface BYOK rows that live+ only in the DB. That branch fell back to `string_contains: ""`+ because Prisma's JSON `string_contains` is case-sensitive on+ Postgres, which let any authenticated caller force a full BYOK-table+ read via `/v2/model/info?search=x`. We rely on the router-side+ filter for `team_public_model_name` instead and keep the DB cost+ bounded by `search`.+ """+ db_where_condition: Dict[str, Any] = {+ "model_name": {"contains": search_lower, "mode": "insensitive"}+ }+ if db_model_ids_in_router:+ db_where_condition["model_id"] = {"not": {"in": list(db_model_ids_in_router)}}++ # Unsorted searches only need enough DB rows to fill the current+ # page after counting router-side matches. Sorted searches need+ # ordering across the full match set, so fall back to a hard cap.+ if sort_by:+ take_limit = _SORTED_SEARCH_DB_FETCH_CAP+ else:+ take_limit = max(0, page * size - router_models_count)++ db_models_total_count = await prisma_client.db.litellm_proxymodeltable.count(+ where=db_where_condition+ )++ db_models_raw: list = []+ if take_limit > 0:+ db_models_raw = await prisma_client.db.litellm_proxymodeltable.find_many(+ where=db_where_condition,+ take=take_limit,+ )++ # Scope BYOK rows to the caller's allowed teams so non-admin callers+ # can't enumerate other teams' BYOK metadata via `?search=...`.+ matching_db_rows = [+ m+ for m in db_models_raw+ if not is_byok_outside_caller_teams(+ m.model_info if isinstance(m.model_info, dict) else {}+ )+ ]++ decrypted: List[Dict[str, Any]] = []+ for db_model in matching_db_rows:+ decrypted_models = proxy_config.decrypt_model_list_from_db([db_model])+ if decrypted_models:+ decrypted.extend(decrypted_models)++ return decrypted, db_models_total_count++async def _apply_search_filter_to_models(all_models: List[Dict[str, Any]],search: str,- page: int,- size: int,prisma_client: Optional[Any],proxy_config: Any,+ user_api_key_dict: Optional[UserAPIKeyAuth] = None,+ page: int = 1,+ size: int = 50,sort_by: Optional[str] = None,) -> Tuple[List[Dict[str, Any]], Optional[int]]:"""@@ -10904,11 +11022,19 @@ async def _apply_search_filter_to_models(Args:all_models: List of models to filtersearch: Search term (case-insensitive)- page: Current page number- size: Page sizeprisma_client: Prisma client for database queriesproxy_config: Proxy config for decrypting models- sort_by: Optional sort field - if provided, fetch all matching models instead of paginating at DB level+ user_api_key_dict: Caller identity used to scope BYOK matches to+ teams the caller belongs to. When omitted (None), no team+ scoping is applied — pass it from request handlers that expose+ this function to non-admin callers.+ page: Current page number (1-indexed). Used with ``size`` to bound+ the DB ``find_many(take=...)`` so a broad search term can't+ force a full table read + decrypt on every request.+ size: Page size. See ``page``.+ sort_by: Sort field. When set, results must be sorted across the+ full match set, so the DB fetch is capped at+ ``_SORTED_SEARCH_DB_FETCH_CAP`` instead of one page.Returns:Tuple of (filtered_models, total_count). total_count is None if not searching.@@ -10918,9 +11044,43 @@ async def _apply_search_filter_to_models(search_lower = search.lower().strip()- # Filter models in router by search term+ allowed_team_ids = await _get_caller_byok_team_scope(+ user_api_key_dict=user_api_key_dict,+ prisma_client=prisma_client,+ )++ def _is_byok_outside_caller_teams(model_info_dict: Dict[str, Any]) -> bool:+ # `team_id` is only set on team BYOK rows. Non-team rows fall+ # through unaffected — they are gated by other paths (router+ # membership, direct_access, include_team_models).+ if allowed_team_ids is None:+ return False+ team_id = model_info_dict.get("team_id")+ if team_id is None:+ return False+ return team_id not in allowed_team_ids++ def _model_matches_search(m: Dict[str, Any]) -> bool:+ # Team BYOK models persist an internal `model_name`+ # (e.g. `model_name_{team_id}_{uuid}`) and expose the user-facing+ # name via `model_info.team_public_model_name`. Match both so the+ # name shown in the UI is searchable.+ if search_lower in (m.get("model_name") or "").lower():+ return True+ team_public_model_name = (m.get("model_info") or {}).get(+ "team_public_model_name"+ ) or ""+ return search_lower in team_public_model_name.lower()++ # Filter models in router by search term, dropping BYOK rows that+ # belong to teams the caller is not a member of so search can't leak+ # other teams' models when the request omits `include_team_models` /+ # `teamId`.filtered_router_models = [- m for m in all_models if search_lower in m.get("model_name", "").lower()+ m+ for m in all_models+ if _model_matches_search(m)+ and not _is_byok_outside_caller_teams(m.get("model_info") or {})]# Separate filtered models into config vs db models, and track db model IDs@@ -10942,91 +11102,30 @@ async def _apply_search_filter_to_models(router_models_count = config_models_count + db_models_in_router_count# Query database for additional models with search term- db_models = []- db_models_total_count = 0- models_needed_for_page = size * page-- # Only query database if prisma_client is available+ db_models: List[Dict[str, Any]] = []if prisma_client is not None:try:- # Build where condition for database query- db_where_condition: Dict[str, Any] = {- "model_name": {- "contains": search_lower,- "mode": "insensitive",- }- }- # Exclude models already in router if we have any- if db_model_ids_in_router:- db_where_condition["model_id"] = {- "not": {"in": list(db_model_ids_in_router)}- }-- # Get total count of matching database models- db_models_total_count = (- await prisma_client.db.litellm_proxymodeltable.count(- where=db_where_condition- )+ db_models, db_models_total_count = await _fetch_db_models_for_search(+ prisma_client=prisma_client,+ proxy_config=proxy_config,+ search_lower=search_lower,+ db_model_ids_in_router=db_model_ids_in_router,+ router_models_count=router_models_count,+ page=page,+ size=size,+ sort_by=sort_by,+ is_byok_outside_caller_teams=_is_byok_outside_caller_teams,)-- # Calculate total count for search resultssearch_total_count = router_models_count + db_models_total_count-- # If sorting is requested, we need to fetch ALL matching models to sort correctly- # Otherwise, we can optimize by only fetching what's needed for the current page- if sort_by:- # Fetch all matching database models for sorting- if db_models_total_count > 0:- db_models_raw = (- await prisma_client.db.litellm_proxymodeltable.find_many(- where=db_where_condition,- take=db_models_total_count, # Fetch all matching models- )- )-- # Convert database models to router format- for db_model in db_models_raw:- decrypted_models = proxy_config.decrypt_model_list_from_db(- [db_model]- )- if decrypted_models:- db_models.extend(decrypted_models)- else:- # Fetch database models if we need more for the current page- if router_models_count < models_needed_for_page:- models_to_fetch = min(- models_needed_for_page - router_models_count,- db_models_total_count,- )-- if models_to_fetch > 0:- db_models_raw = (- await prisma_client.db.litellm_proxymodeltable.find_many(- where=db_where_condition,- take=models_to_fetch,- )- )-- # Convert database models to router format- for db_model in db_models_raw:- decrypted_models = proxy_config.decrypt_model_list_from_db(- [db_model]- )- if decrypted_models:- db_models.extend(decrypted_models)except Exception as e:verbose_proxy_logger.exception(f"Error querying database models with search: {str(e)}")- # If error, use router models count as fallbacksearch_total_count = router_models_countelse:- # If no prisma_client, only use router modelssearch_total_count = router_models_count- # Combine all models- filtered_models = filtered_router_models + db_models- return filtered_models, search_total_count+ return filtered_router_models + db_models, search_total_countdef _normalize_datetime_for_sorting(dt: Any) -> Optional[datetime]:@@ -11102,6 +11201,15 @@ def _sort_models(model_info = model.get("model_info", {})if sort_by == "model_name":+ # Team BYOK models persist an internal `model_name` (e.g.+ # `model_name_{team_id}_{uuid}`) and expose the user-facing+ # name via `model_info.team_public_model_name` — same as the+ # UI's getDisplayModelName. Sort by the displayed name so+ # BYOK rows interleave alphabetically with non-BYOK rows+ # instead of clumping at the end on their opaque IDs.+ team_public_model_name = model_info.get("team_public_model_name")+ if team_public_model_name:+ return str(team_public_model_name).lower()return model.get("model_name", "").lower()elif sort_by == "created_at":@@ -11286,28 +11394,81 @@ async def _gather_team_accessible_model_ids(return team_accessible_model_ids+async def _authorize_team_id_query(+ team_id: str,+ user_api_key_dict: UserAPIKeyAuth,+ prisma_client: PrismaClient,+) -> None:+ """+ `teamId` arrives untrusted via the /v2/model/info query string and the+ filter below includes BYOK rows solely on `model_info.team_id == team_id`.+ Without this guard, any authenticated user who knows (or guesses) another+ team's id could enumerate that team's BYOK model metadata. Allow only+ proxy admins or members of the requested team.+ """+ if user_api_key_dict.user_role in (+ LitellmUserRoles.PROXY_ADMIN,+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,+ ):+ return++ user_id = user_api_key_dict.user_id+ if user_id is None:+ raise HTTPException(+ status_code=403,+ detail={"error": "Not authorized to view this team's models"},+ )+ try:+ user_row = await prisma_client.db.litellm_usertable.find_unique(+ where={"user_id": user_id}+ )+ except Exception:+ verbose_proxy_logger.exception(+ "Failed to look up caller teams while authorizing teamId filter"+ )+ raise HTTPException(+ status_code=403,+ detail={"error": "Not authorized to view this team's models"},+ )++ if user_row is None or team_id not in (user_row.teams or []):+ raise HTTPException(+ status_code=403,+ detail={"error": "Not authorized to view this team's models"},+ )++async def _filter_models_by_team_id(all_models: List[Dict[str, Any]],team_id: str,prisma_client: PrismaClient,llm_router: Router,+ user_api_key_dict: Optional[UserAPIKeyAuth] = None,) -> List[Dict[str, Any]]:"""Filter models by team ID. Returns models where:- - direct_access is True, OR- - team_id is in access_via_team_ids-- Also searches config and database for models accessible to the team.+ - team_id matches the model's BYOK team_id, OR+ - team_id is in access_via_team_ids, OR+ - model_id is reachable via team.models / access groupsArgs:all_models: List of models to filterteam_id: Team ID to filter byprisma_client: Prisma client for database queriesllm_router: Router instance for config queries+ user_api_key_dict: Caller auth context. When provided, the caller must+ be a proxy admin or a member of `team_id`; otherwise raises 403.Returns:Filtered list of models"""+ if user_api_key_dict is not None:+ await _authorize_team_id_query(+ team_id=team_id,+ user_api_key_dict=user_api_key_dict,+ prisma_client=prisma_client,+ )+team_object = await _load_team_object_for_model_filter(team_id, prisma_client)if team_object is None:return []@@ -11316,26 +11477,30 @@ async def _filter_models_by_team_id(team_object, team_id, prisma_client, llm_router)- # Filter models based on direct_access or access_via_team_ids- # Models are already enriched with these fields before this function is called+ # When filtering by a specific team we want exactly the models that team+ # can use: its BYOK rows and the deployments resolved from team.models /+ # access groups. `direct_access` describes the viewer's own permissions+ # (the admin path sets it on every non-team model) and must NOT widen the+ # team's visible set, otherwise selecting a team in the UI still shows+ # every public model the admin can call.filtered_models = []for _model in all_models:model_info = _model.get("model_info", {})model_id = model_info.get("id", None)- # Include if direct_access is True- if model_info.get("direct_access", False):+ # BYOK rows owned by this team are always accessible to it, even if+ # they haven't been re-added to team.models for some reason.+ if model_info.get("team_id") == team_id:filtered_models.append(_model)continue- # Include if team_id is in access_via_team_idsaccess_via_team_ids = model_info.get("access_via_team_ids", [])if isinstance(access_via_team_ids, list) and team_id in access_via_team_ids:filtered_models.append(_model)continue- # Also include if model_id is in team_accessible_model_ids (from config/db search)- # This catches models that might not have been enriched with access_via_team_ids yet+ # Catches models resolved from team.models / access groups that+ # weren't enriched with access_via_team_ids upstream.if model_id and model_id in team_accessible_model_ids:filtered_models.append(_model)@@ -11477,10 +11642,11 @@ async def model_info_v2(all_models, search_total_count = await _apply_search_filter_to_models(all_models=all_models,search=search or "",- page=page,- size=size,prisma_client=prisma_client,proxy_config=proxy_config,+ user_api_key_dict=user_api_key_dict,+ page=page,+ size=size,sort_by=sortBy,)@@ -11516,6 +11682,7 @@ async def model_info_v2(team_id=teamId.strip(),prisma_client=prisma_client,llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,)# Update search_total_count after teamId filter is appliedsearch_total_count = len(all_models)diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex bedc9c1f6e8..73d53631622 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -1169,6 +1169,434 @@ def test_add_team_models_to_all_models():assert result == {"gpt-4-model-2": {"team1"}}+async def test_apply_search_filter_matches_team_public_model_name():+ """+ Regression test: team BYOK models persist an internal model_name+ (e.g. `model_name_{team_id}_{uuid}`) and surface the user-facing name+ via `model_info.team_public_model_name`. The /v2/model/info search+ filter must match that public name so BYOK rows appear in results.+ """+ from litellm.proxy.proxy_server import _apply_search_filter_to_models++ byok_model = {+ "model_name": "model_name_team-abc-123_4a6b8",+ "litellm_params": {"model": "claude-sonnet-4-5"},+ "model_info": {+ "id": "byok-id-1",+ "team_id": "team-abc-123",+ "team_public_model_name": "team-claude-sonnet",+ "db_model": True,+ },+ }+ unrelated_model = {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4"},+ "model_info": {"id": "normal-id-1", "db_model": False},+ }++ # Search matching only team_public_model_name should still include BYOK+ filtered, _ = await _apply_search_filter_to_models(+ all_models=[byok_model, unrelated_model],+ search="claude",+ prisma_client=None,+ proxy_config=MagicMock(),+ )+ filtered_ids = {m["model_info"]["id"] for m in filtered}+ assert "byok-id-1" in filtered_ids+ assert "normal-id-1" not in filtered_ids++ # Search by internal model_name still matches as before+ filtered, _ = await _apply_search_filter_to_models(+ all_models=[byok_model, unrelated_model],+ search="model_name_team-abc-123",+ prisma_client=None,+ proxy_config=MagicMock(),+ )+ assert [m["model_info"]["id"] for m in filtered] == ["byok-id-1"]++ # Non-matching search returns nothing+ filtered, _ = await _apply_search_filter_to_models(+ all_models=[byok_model, unrelated_model],+ search="gemini",+ prisma_client=None,+ proxy_config=MagicMock(),+ )+ assert filtered == []+++async def test_apply_search_filter_scopes_byok_to_caller_teams():+ """+ Regression test: `/v2/model/info?search=...` must not leak BYOK rows+ from teams the caller is not a member of. Even with a bounded+ `model_name`-contains DB query, a non-admin caller could otherwise+ see other teams' BYOK rows that happen to match by internal name.+ The post-fetch team scope drops those.+ """+ from litellm.proxy.proxy_server import _apply_search_filter_to_models++ # In-router BYOK rows: one in the caller's team, one in someone else's.+ caller_team_byok = {+ "model_name": "model_name_team-mine_internal",+ "litellm_params": {"model": "claude-sonnet"},+ "model_info": {+ "id": "byok-mine",+ "team_id": "team-mine",+ "team_public_model_name": "claude-sonnet-prod",+ "db_model": True,+ },+ }+ other_team_byok = {+ "model_name": "model_name_team-other_internal",+ "litellm_params": {"model": "claude-sonnet"},+ "model_info": {+ "id": "byok-other",+ "team_id": "team-other",+ "team_public_model_name": "claude-sonnet-staging",+ "db_model": True,+ },+ }+ # Non-team row stays in the router-side result regardless of teams.+ public_model = {+ "model_name": "claude-public",+ "litellm_params": {"model": "claude-sonnet"},+ "model_info": {"id": "public-id", "db_model": False},+ }++ # DB-only BYOK rows fetched by the over-broad JSON branch.+ db_caller_row = MagicMock()+ db_caller_row.model_id = "byok-db-mine"+ db_caller_row.model_name = "model_name_team-mine_db"+ db_caller_row.model_info = {+ "id": "byok-db-mine",+ "team_id": "team-mine",+ "team_public_model_name": "Claude DB Mine",+ "db_model": True,+ }+ db_other_row = MagicMock()+ db_other_row.model_id = "byok-db-other"+ db_other_row.model_name = "model_name_team-other_db"+ db_other_row.model_info = {+ "id": "byok-db-other",+ "team_id": "team-other",+ "team_public_model_name": "Claude DB Other",+ "db_model": True,+ }++ prisma_client = MagicMock()+ prisma_client.db.litellm_proxymodeltable.count = AsyncMock(return_value=2)+ prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(+ return_value=[db_caller_row, db_other_row]+ )+ caller_user_row = MagicMock()+ caller_user_row.teams = ["team-mine"]+ prisma_client.db.litellm_usertable.find_unique = AsyncMock(+ return_value=caller_user_row+ )++ proxy_config = MagicMock()+ proxy_config.decrypt_model_list_from_db = lambda rows: [+ {+ "model_name": r.model_name,+ "model_info": r.model_info,+ "litellm_params": {"model": "claude-sonnet"},+ }+ for r in rows+ ]++ non_admin = MagicMock(spec=UserAPIKeyAuth)+ non_admin.user_role = LitellmUserRoles.INTERNAL_USER+ non_admin.user_id = "user-mine"++ filtered, total_count = await _apply_search_filter_to_models(+ all_models=[caller_team_byok, other_team_byok, public_model],+ search="claude",+ prisma_client=prisma_client,+ proxy_config=proxy_config,+ user_api_key_dict=non_admin,+ )++ filtered_ids = {m["model_info"]["id"] for m in filtered}+ assert "byok-mine" in filtered_ids+ assert "byok-db-mine" in filtered_ids+ assert "public-id" in filtered_ids+ assert "byok-other" not in filtered_ids, (+ "router-side BYOK from another team must be dropped from search "+ "when caller doesn't belong to that team"+ )+ assert "byok-db-other" not in filtered_ids, (+ "DB-only BYOK from another team must be dropped from search when "+ "caller doesn't belong to that team"+ )+ # total_count is router_models_count (2: caller_team_byok + public_model,+ # other_team_byok dropped router-side) + DB count (2 from the mocked+ # `count()`). The DB count is the *unscoped* match count; non-admin+ # team scoping applies only to the returned page so the count can be+ # over-reported, but it must never under-report (callers can paginate+ # within the bound).+ assert total_count == 4++ # Admins keep the un-scoped view across teams.+ admin = MagicMock(spec=UserAPIKeyAuth)+ admin.user_role = LitellmUserRoles.PROXY_ADMIN+ admin.user_id = "admin-1"++ filtered_admin, _ = await _apply_search_filter_to_models(+ all_models=[caller_team_byok, other_team_byok, public_model],+ search="claude",+ prisma_client=prisma_client,+ proxy_config=proxy_config,+ user_api_key_dict=admin,+ )+ admin_ids = {m["model_info"]["id"] for m in filtered_admin}+ assert "byok-other" in admin_ids+ assert "byok-db-other" in admin_ids+++async def test_apply_search_filter_bounds_db_fetch_by_page_and_cap():+ """+ Regression test: a broad search term must not force a full BYOK-table+ read + decrypt on each request.++ * Unsorted searches: `find_many(take=N)` where N is just enough to+ fill the current page after counting router-side matches.+ * Sorted searches: `find_many(take=cap)` falls back to+ `_SORTED_SEARCH_DB_FETCH_CAP` so ordering still works across a+ large match set without scanning the whole table.+ """+ from litellm.proxy.proxy_server import (+ _SORTED_SEARCH_DB_FETCH_CAP,+ _apply_search_filter_to_models,+ )++ prisma_client = MagicMock()+ prisma_client.db.litellm_proxymodeltable.count = AsyncMock(return_value=10_000)+ prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])++ proxy_config = MagicMock()+ proxy_config.decrypt_model_list_from_db = lambda rows: []++ # Unsorted: page=1, size=50, no router-side matches -> take must be 50.+ await _apply_search_filter_to_models(+ all_models=[],+ search="model",+ prisma_client=prisma_client,+ proxy_config=proxy_config,+ page=1,+ size=50,+ sort_by=None,+ )+ take = prisma_client.db.litellm_proxymodeltable.find_many.call_args.kwargs["take"]+ assert take == 50, "unsorted search must take just one page's worth of rows"++ # Sorted: still bounded, but by the hard cap rather than the page.+ prisma_client.db.litellm_proxymodeltable.find_many.reset_mock()+ await _apply_search_filter_to_models(+ all_models=[],+ search="model",+ prisma_client=prisma_client,+ proxy_config=proxy_config,+ page=1,+ size=50,+ sort_by="model_name",+ )+ take = prisma_client.db.litellm_proxymodeltable.find_many.call_args.kwargs["take"]+ assert take == _SORTED_SEARCH_DB_FETCH_CAP+ assert take < 10_000, "sorted search must cap below the full match set"+++async def test_filter_models_by_team_id_excludes_viewer_direct_access():+ """+ Regression test: when the UI picks a specific team in the Current Team+ selector, the model list must show only that team's BYOK rows + the+ models assigned to the team. The admin viewer's `direct_access` flag+ (set on every non-team model upstream) must NOT widen the team's+ visible set, or selecting team-111 still shows every public model.+ """+ from litellm.proxy.proxy_server import _filter_models_by_team_id++ public_model = {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4"},+ "model_info": {+ "id": "public-id",+ # admin viewer has direct_access on this public model+ "direct_access": True,+ # team-111 is NOT in access_via_team_ids -> shouldn't show for team-111+ "access_via_team_ids": ["team-222"],+ },+ }+ team111_byok = {+ "model_name": "model_name_team-111_uuid",+ "litellm_params": {"model": "claude-sonnet"},+ "model_info": {+ "id": "byok-team-111",+ "team_id": "team-111",+ "team_public_model_name": "team-claude",+ "access_via_team_ids": ["team-111"],+ },+ }+ team222_byok = {+ "model_name": "model_name_team-222_uuid",+ "litellm_params": {"model": "claude-haiku"},+ "model_info": {+ "id": "byok-team-222",+ "team_id": "team-222",+ "team_public_model_name": "team-haiku",+ "access_via_team_ids": ["team-222"],+ },+ }++ prisma = MagicMock()+ team_db = MagicMock()+ team_db.model_dump.return_value = {+ "team_id": "team-111",+ "team_alias": "Team 111",+ # specific models list that doesn't include the BYOK's internal name+ "models": ["some-other-model"],+ "access_group_ids": None,+ }+ prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=team_db)+ prisma.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])++ router = MagicMock()+ router.get_model_access_groups = MagicMock(return_value={})+ # team-111 only resolves "some-other-model", which has no deployments+ router.get_model_list = MagicMock(return_value=[])++ filtered = await _filter_models_by_team_id(+ all_models=[public_model, team111_byok, team222_byok],+ team_id="team-111",+ prisma_client=prisma,+ llm_router=router,+ )+ visible_ids = sorted(m["model_info"]["id"] for m in filtered)++ assert "byok-team-111" in visible_ids, "team-111's own BYOK must always be visible"+ assert "byok-team-222" not in visible_ids, "must not leak other teams' BYOK"+ assert (+ "public-id" not in visible_ids+ ), "viewer's direct_access must not widen the team's visible set"+++async def test_filter_models_by_team_id_rejects_non_member():+ """+ Regression test: /v2/model/info?teamId=X includes BYOK rows solely on+ `model_info.team_id == X`. Without an auth check, any authenticated user+ could enumerate another team's BYOK metadata by guessing its id. Callers+ that are neither proxy admins nor members of `team_id` must get 403.+ """+ from fastapi import HTTPException++ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy.proxy_server import _filter_models_by_team_id++ byok = {+ "model_name": "model_name_team-111_uuid",+ "litellm_params": {"model": "claude"},+ "model_info": {"id": "byok-team-111", "team_id": "team-111"},+ }++ prisma = MagicMock()+ # Caller is in team-222 only+ user_row = MagicMock()+ user_row.teams = ["team-222"]+ prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=user_row)++ caller = UserAPIKeyAuth(+ user_id="alice",+ user_role=LitellmUserRoles.INTERNAL_USER,+ api_key="sk-test",+ )++ with pytest.raises(HTTPException) as excinfo:+ await _filter_models_by_team_id(+ all_models=[byok],+ team_id="team-111",+ prisma_client=prisma,+ llm_router=MagicMock(),+ user_api_key_dict=caller,+ )+ assert excinfo.value.status_code == 403+++async def test_filter_models_by_team_id_allows_team_member():+ """+ A caller who IS a member of `team_id` must be allowed to filter, and+ should see that team's BYOK rows.+ """+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy.proxy_server import _filter_models_by_team_id++ byok = {+ "model_name": "model_name_team-111_uuid",+ "litellm_params": {"model": "claude"},+ "model_info": {"id": "byok-team-111", "team_id": "team-111"},+ }++ prisma = MagicMock()+ user_row = MagicMock()+ user_row.teams = ["team-111", "team-999"]+ prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=user_row)+ team_db = MagicMock()+ team_db.model_dump.return_value = {+ "team_id": "team-111",+ "team_alias": "Team 111",+ "models": [],+ "access_group_ids": None,+ }+ prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=team_db)+ prisma.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])++ router = MagicMock()+ router.get_model_access_groups = MagicMock(return_value={})+ router.get_model_list = MagicMock(return_value=[byok])++ caller = UserAPIKeyAuth(+ user_id="bob",+ user_role=LitellmUserRoles.INTERNAL_USER,+ api_key="sk-test",+ )++ result = await _filter_models_by_team_id(+ all_models=[byok],+ team_id="team-111",+ prisma_client=prisma,+ llm_router=router,+ user_api_key_dict=caller,+ )+ assert [m["model_info"]["id"] for m in result] == ["byok-team-111"]+++async def test_caller_byok_team_scope_treats_view_only_admin_as_unscoped():+ """+ Regression test: `PROXY_ADMIN_VIEW_ONLY` is an admin role+ ("can login, view all own keys, view all spend"). Search results for+ this role must show BYOK rows across all teams, not be silently scoped+ to the user-id's `teams` field — that path narrows results to whatever+ teams the admin happens to be a member of, regressing pre-PR behavior.+ """+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+ from litellm.proxy.proxy_server import _get_caller_byok_team_scope++ caller = UserAPIKeyAuth(+ user_id="view-admin",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,+ api_key="sk-test",+ )+ scope = await _get_caller_byok_team_scope(+ user_api_key_dict=caller,+ prisma_client=MagicMock(),+ )+ assert scope is None, "PROXY_ADMIN_VIEW_ONLY must be unscoped, like PROXY_ADMIN"++@pytest.mark.asyncioasync def test_add_access_group_models_to_team_models():"""@@ -6922,3 +7350,80 @@ class TestTransformRequestBannedParams:f"Expected 400 for banned param '{banned}', "f"got {response.status_code}: {response.json()}")+++class TestSortModelsByDisplayName:+ """Regression: team BYOK rows persist an internal `model_name` like+ `model_name_{team_id}_{uuid}` and expose the user-facing name via+ `model_info.team_public_model_name`. Sorting must use the displayed+ name so BYOK rows interleave with non-BYOK rows alphabetically —+ otherwise they clump at the end on their opaque IDs even though the+ UI shows them under a normal-looking name.+ """++ def test_byok_models_sort_by_team_public_model_name(self):+ from litellm.proxy.proxy_server import _sort_models++ models = [+ {"model_name": "claude-haiku-4-5", "model_info": {}},+ {+ # Opaque internal name; UI displays team_public_model_name.+ "model_name": "model_name_team-1_abc123",+ "model_info": {"team_public_model_name": "anthropic/claude"},+ },+ {"model_name": "gpt-4o", "model_info": {}},+ ]++ sorted_models = _sort_models(+ all_models=models, sort_by="model_name", sort_order="asc"+ )+ displayed_order = [+ m["model_info"].get("team_public_model_name") or m["model_name"]+ for m in sorted_models+ ]+ assert displayed_order == [+ "anthropic/claude",+ "claude-haiku-4-5",+ "gpt-4o",+ ]++ def test_byok_models_sort_descending_by_display_name(self):+ from litellm.proxy.proxy_server import _sort_models++ models = [+ {"model_name": "claude-haiku-4-5", "model_info": {}},+ {+ "model_name": "model_name_team-1_zzz",+ "model_info": {"team_public_model_name": "zeta/model"},+ },+ {"model_name": "gpt-4o", "model_info": {}},+ ]++ sorted_models = _sort_models(+ all_models=models, sort_by="model_name", sort_order="desc"+ )+ displayed_order = [+ m["model_info"].get("team_public_model_name") or m["model_name"]+ for m in sorted_models+ ]+ assert displayed_order == [+ "zeta/model",+ "gpt-4o",+ "claude-haiku-4-5",+ ]++ def test_empty_team_public_model_name_falls_back_to_model_name(self):+ # Empty string for team_public_model_name (not None) must still+ # fall back to model_name — otherwise BYOK rows with a blank+ # display name would sort to the top.+ from litellm.proxy.proxy_server import _sort_models++ models = [+ {"model_name": "alpha", "model_info": {"team_public_model_name": ""}},+ {"model_name": "beta", "model_info": {}},+ ]++ sorted_models = _sort_models(+ all_models=models, sort_by="model_name", sort_order="asc"+ )+ assert [m["model_name"] for m in sorted_models] == ["alpha", "beta"]