Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix: resolve ruff PLR0915 and F401 lint errors

yuneng-jiangf77b5a24c3b5
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py
index 5621017b0cd..06338a33e4b 100644
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@ -1469,6 +1469,72 @@ def _validate_sort_params(
return order_by
+async def _authorize_user_list_request(
+ user_api_key_dict: UserAPIKeyAuth,
+ organization_ids: Optional[str],
+ prisma_client: Any,
+ user_api_key_cache: Any,
+ proxy_logging_obj: Any,
+) -> Optional[str]:
+ """
+ Authorize the /user/list request and return the (possibly scoped) organization_ids string.
+
+ - Proxy admins: returns organization_ids unchanged (may be None).
+ - Org admins: returns comma-separated org IDs scoped to their allowed orgs.
+ - Others: raises 403.
+ """
+ if _user_has_admin_view(user_api_key_dict):
+ return organization_ids
+
+ if user_api_key_dict.user_id is None:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": "Only proxy admins and organization admins can list users."},
+ )
+ try:
+ caller_user = await get_user_object(
+ user_id=user_api_key_dict.user_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ user_id_upsert=False,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ except ValueError:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": "Only proxy admins and organization admins can list users."},
+ )
+ if caller_user is None:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": "Only proxy admins and organization admins can list users."},
+ )
+
+ allowed_org_ids = [
+ m.organization_id
+ for m in (caller_user.organization_memberships or [])
+ if m.user_role == LitellmUserRoles.ORG_ADMIN.value
+ ]
+ if not allowed_org_ids:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": "Only proxy admins and organization admins can list users."},
+ )
+
+ # If client also sent organization_ids, intersect with allowed orgs
+ if organization_ids:
+ requested = set(oid.strip() for oid in organization_ids.split(",") if oid.strip())
+ intersection = list(requested & set(allowed_org_ids))
+ if not intersection:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": "You do not have org_admin access to the requested organization(s)."},
+ )
+ allowed_org_ids = intersection
+
+ return ",".join(allowed_org_ids)
+
+
@router.get(
"/user/list",
tags=["Internal User management"],
@@ -1548,65 +1614,13 @@ async def get_users(
)
# Server-side authorization: proxy admins see all, org admins see only their org(s)
- is_proxy_admin = _user_has_admin_view(user_api_key_dict)
- allowed_org_ids: Optional[List[str]] = None
- if not is_proxy_admin:
- if user_api_key_dict.user_id is None:
- raise HTTPException(
- status_code=403,
- detail={
- "error": "Only proxy admins and organization admins can list users."
- },
- )
- try:
- caller_user = await get_user_object(
- user_id=user_api_key_dict.user_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- user_id_upsert=False,
- proxy_logging_obj=proxy_logging_obj,
- )
- except ValueError:
- raise HTTPException(
- status_code=403,
- detail={
- "error": "Only proxy admins and organization admins can list users."
- },
- )
- if caller_user is None:
- raise HTTPException(
- status_code=403,
- detail={
- "error": "Only proxy admins and organization admins can list users."
- },
- )
- allowed_org_ids = [
- m.organization_id
- for m in (caller_user.organization_memberships or [])
- if m.user_role == LitellmUserRoles.ORG_ADMIN.value
- ]
- if not allowed_org_ids:
- raise HTTPException(
- status_code=403,
- detail={
- "error": "Only proxy admins and organization admins can list users."
- },
- )
- # If client also sent organization_ids, intersect with allowed orgs
- if organization_ids:
- requested = set(oid.strip() for oid in organization_ids.split(",") if oid.strip())
- allowed = set(allowed_org_ids)
- intersection = list(requested & allowed)
- if not intersection:
- raise HTTPException(
- status_code=403,
- detail={
- "error": "You do not have org_admin access to the requested organization(s)."
- },
- )
- allowed_org_ids = intersection
- # For org admins, always enforce org scoping via comma-separated string
- organization_ids = ",".join(allowed_org_ids)
+ organization_ids = await _authorize_user_list_request(
+ user_api_key_dict=user_api_key_dict,
+ organization_ids=organization_ids,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
# Calculate skip and take for pagination
skip = (page - 1) * page_size
@@ -1910,9 +1924,6 @@ async def _resolve_org_filter_for_user_search(
Reads the ``scope_user_search_to_org`` UI-setting flag and applies
role-based access rules when the flag is ON.
"""
- from litellm.proxy.management_endpoints.common_utils import (
- _is_user_team_admin,
- )
from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (
get_ui_settings_cached,
)
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index a79bbc1cf07..86b988f581d 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -3381,41 +3381,21 @@ async def list_team_v2(
}
- "/team/list", tags=["team management"], dependencies=[Depends(user_api_key_auth)]
-)
-@management_endpoint_wrapper
-async def list_team(
- http_request: Request,
- user_id: Optional[str] = fastapi.Query(
- default=None, description="Only return teams which this 'user_id' belongs to"
- ),
- organization_id: Optional[str] = None,
- user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
-):
+async def _authorize_and_filter_teams(
+ user_api_key_dict: UserAPIKeyAuth,
+ user_id: Optional[str],
+ prisma_client: Any,
+ user_api_key_cache: Any,
+ proxy_logging_obj: Any,
+) -> list:
"""
- ```
- curl --location --request GET 'http://0.0.0.0:4000/team/list' \
- --header 'Authorization: Bearer sk-1234'
- ```
+ Authorize the /team/list request and return filtered teams.
- Parameters:
- - user_id: str - Optional. If passed will only return teams that the user_id is a member of.
- - organization_id: str - Optional. If passed will only return teams that belong to the organization_id. Pass 'default_organization' to get all teams without organization_id.
+ - Proxy admins: all teams (or filtered by user_id if provided).
+ - Org admins: teams from their orgs + teams they are direct members of.
+ - Own query (user_id matches caller): teams the user is a member of.
+ - Others: 401.
"""
- from litellm.proxy.proxy_server import (
- prisma_client,
- proxy_logging_obj,
- user_api_key_cache,
- )
-
- if prisma_client is None:
- raise HTTPException(
- status_code=400,
- detail={"error": CommonProxyErrors.db_not_connected_error.value},
- )
-
- # Determine access level and org-admin scoping
is_proxy_admin = _user_has_admin_view(user_api_key_dict)
allowed_org_ids: Optional[List[str]] = None
@@ -3444,7 +3424,6 @@ async def list_team(
if not allowed_org_ids:
allowed_org_ids = None
- # If not an org admin and not querying own teams, reject
if allowed_org_ids is None and not is_own_query:
raise HTTPException(
status_code=401,
@@ -3456,45 +3435,78 @@ async def list_team(
)
response = await prisma_client.db.litellm_teamtable.find_many(
- include={
- "litellm_model_table": True,
- }
+ include={"litellm_model_table": True}
)
- filtered_response = []
if allowed_org_ids is not None:
- # Org admin: return teams from their organizations
allowed_org_set = set(allowed_org_ids)
- seen_team_ids = set()
+ seen_team_ids: set = set()
+ filtered: list = []
for team in response:
if team.organization_id in allowed_org_set:
- filtered_response.append(team)
+ filtered.append(team)
seen_team_ids.add(team.team_id)
- # Also include teams the user is a direct member of (outside their orgs)
+ # Also include teams the user is a direct member of
if user_id:
for team in response:
if team.team_id not in seen_team_ids and team.members_with_roles:
for member in team.members_with_roles:
- if (
- "user_id" in member
- and member["user_id"] is not None
- and member["user_id"] == user_id
- ):
- filtered_response.append(team)
+ if member.get("user_id") == user_id:
+ filtered.append(team)
seen_team_ids.add(team.team_id)
+ return filtered
elif user_id:
- # Regular user querying their own teams
- for team in response:
- if team.members_with_roles:
- for member in team.members_with_roles:
- if (
- "user_id" in member
- and member["user_id"] is not None
- and member["user_id"] == user_id
- ):
- filtered_response.append(team)
+ return [
+ team
+ for team in response
+ if team.members_with_roles
+ and any(m.get("user_id") == user_id for m in team.members_with_roles)
+ ]
else:
- filtered_response = response
+ return list(response)
+
+
+ "/team/list", tags=["team management"], dependencies=[Depends(user_api_key_auth)]
+)
+@management_endpoint_wrapper
+async def list_team(
+ http_request: Request,
+ user_id: Optional[str] = fastapi.Query(
+ default=None, description="Only return teams which this 'user_id' belongs to"
+ ),
+ organization_id: Optional[str] = None,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ ```
+ curl --location --request GET 'http://0.0.0.0:4000/team/list' \
+ --header 'Authorization: Bearer sk-1234'
+ ```
+
+ Parameters:
+ - user_id: str - Optional. If passed will only return teams that the user_id is a member of.
+ - organization_id: str - Optional. If passed will only return teams that belong to the organization_id. Pass 'default_organization' to get all teams without organization_id.
+ """
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ filtered_response = await _authorize_and_filter_teams(
+ user_api_key_dict=user_api_key_dict,
+ user_id=user_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
_team_ids = [team.team_id for team in filtered_response]
returned_tm = await get_all_team_memberships(