Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ async def _common_key_generation_helper( # noqa: PLR0915
await validate_key_mcp_servers_against_team(
object_permission=data_json.get("object_permission"),
team_obj=team_table,
prisma_client=prisma_client,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Key generation discards normalized object permission return value

Low Severity

In the key generation path, the return value of validate_key_mcp_servers_against_team is discarded (await without assignment), while the key update path explicitly captures and applies it via LiteLLM_ObjectPermissionBase(**normalized_object_permission). The generation path relies silently on in-place dict mutation propagating through data_json, creating an asymmetric and fragile pattern that would silently break if the function ever stops mutating in-place.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e01e698. Configure here.

)
await validate_key_search_tools_against_team(
object_permission=data_json.get("object_permission"),
Expand Down Expand Up @@ -2133,6 +2134,7 @@ async def _validate_mcp_servers_for_key_update(
await validate_key_mcp_servers_against_team(
object_permission=object_permission_dict,
team_obj=effective_team_obj,
prisma_client=prisma_client,
)
await validate_key_search_tools_against_team(
object_permission=object_permission_dict,
Expand Down
48 changes: 47 additions & 1 deletion litellm/proxy/management_helpers/object_permission_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,45 @@ def _extract_requested_mcp_toolsets(
return set()


async def _get_stale_mcp_server_ids(
requested_servers: Set[str],
prisma_client: Optional[PrismaClient],
) -> Set[str]:
"""
Return the subset of *requested_servers* that no longer exist.

Queries the DB when *prisma_client* is available (authoritative); falls back
to the in-memory registry for config-only deployments without a DB.
"""
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)

if prisma_client is not None:
from litellm.proxy._experimental.mcp_server.db import get_mcp_servers

existing_in_db = await get_mcp_servers(prisma_client, list(requested_servers))
existing_ids = {s.server_id for s in existing_in_db}
# Config-file servers live only in the in-memory registry and are never
# written to the DB — include them so they are not misclassified as stale.
existing_ids |= {
sid
for sid in requested_servers
if global_mcp_server_manager.get_mcp_server_by_id(sid) is not None
}
return requested_servers - existing_ids

return {
sid
for sid in requested_servers
if global_mcp_server_manager.get_mcp_server_by_id(sid) is None
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused helper function never called anywhere in codebase

Low Severity

The _get_stale_mcp_server_ids function is defined but never called. Its logic for identifying stale MCP server identifiers was inlined within validate_key_mcp_servers_against_team, leaving this function as dead code.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e01e698. Configure here.



async def validate_key_mcp_servers_against_team(
object_permission: Optional[dict],
team_obj: Optional["LiteLLM_TeamTableCachedObj"],
prisma_client: Optional[PrismaClient] = None,
):
"""
Validate that MCP servers requested on a key are within the allowed scope.
Expand Down Expand Up @@ -332,7 +368,17 @@ async def validate_key_mcp_servers_against_team(

# Validate requested server IDs
if requested_servers:
disallowed_servers = requested_servers - all_allowed_servers
# Strip IDs for deleted servers — carrying a stale ID from a form that
# hasn't refreshed is not an authorization violation.
stale_ids = await _get_stale_mcp_server_ids(requested_servers, prisma_client)
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
if stale_ids:
verbose_proxy_logger.warning(
"validate_key_mcp_servers_against_team: ignoring stale MCP server "
f"IDs (no longer in registry): {sorted(stale_ids)}"
)
active_requested_servers = requested_servers - stale_ids

disallowed_servers = active_requested_servers - all_allowed_servers
if disallowed_servers:
if team_obj is not None:
team_id = team_obj.team_id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,19 @@ def _make_team_obj(
return mock_team


def _make_mock_mcp_manager(*existing_ids: str):
"""
Return a mock global_mcp_server_manager whose get_mcp_server_by_id returns a
non-None value for every ID in *existing_ids and None for everything else.
"""
mock_mgr = MagicMock()
existing = set(existing_ids)
mock_mgr.get_mcp_server_by_id.side_effect = lambda sid: (
MagicMock() if sid in existing else None
)
return mock_mgr


@pytest.mark.asyncio
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
Expand All @@ -171,6 +184,10 @@ async def test_validate_no_object_permission(mock_access_groups, mock_allow_all)


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("server-1", "server-2"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value=set(),
Expand All @@ -192,6 +209,10 @@ async def test_validate_key_servers_within_team_scope(


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("server-1", "server-outside"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value=set(),
Expand All @@ -204,7 +225,7 @@ async def test_validate_key_servers_within_team_scope(
async def test_validate_key_servers_outside_team_scope_raises(
mock_access_groups, mock_allow_all
):
"""Key requests servers NOT in the team's scope — should raise 403."""
"""Key requests a server that exists but is NOT in the team's scope — should raise 403."""
team_obj = _make_team_obj(mcp_servers=["server-1"])
with pytest.raises(HTTPException) as exc_info:
await validate_key_mcp_servers_against_team(
Expand All @@ -216,6 +237,10 @@ async def test_validate_key_servers_outside_team_scope_raises(


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("server-1", "global-server"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value={"global-server"},
Expand All @@ -237,6 +262,10 @@ async def test_validate_allow_all_keys_servers_always_allowed(


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("global-server"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value={"global-server"},
Expand All @@ -248,14 +277,17 @@ async def test_validate_allow_all_keys_servers_always_allowed(
)
async def test_validate_no_team_only_allow_all_keys(mock_access_groups, mock_allow_all):
"""Key without a team can only use allow_all_keys servers."""
# This should pass — requesting a global server without a team
await validate_key_mcp_servers_against_team(
object_permission={"mcp_servers": ["global-server"]},
team_obj=None,
)


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("private-server"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value={"global-server"},
Expand All @@ -268,7 +300,7 @@ async def test_validate_no_team_only_allow_all_keys(mock_access_groups, mock_all
async def test_validate_no_team_non_global_server_raises(
mock_access_groups, mock_allow_all
):
"""Key without a team requesting a non-global server — should raise 403."""
"""Key without a team requesting an existing non-global server — should raise 403."""
with pytest.raises(HTTPException) as exc_info:
await validate_key_mcp_servers_against_team(
object_permission={"mcp_servers": ["private-server"]},
Expand All @@ -279,6 +311,10 @@ async def test_validate_no_team_non_global_server_raises(


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("some-server"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value=set(),
Expand All @@ -302,6 +338,10 @@ async def test_validate_team_no_mcp_config_blocks_all(


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager("server-outside"),
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value=set(),
Expand All @@ -314,7 +354,7 @@ async def test_validate_team_no_mcp_config_blocks_all(
async def test_validate_tool_permissions_validated_against_team(
mock_access_groups, mock_allow_all
):
"""Server IDs in mcp_tool_permissions should also be validated."""
"""Server IDs in mcp_tool_permissions should also be validated when they exist."""
team_obj = _make_team_obj(mcp_servers=["server-1"])
with pytest.raises(HTTPException) as exc_info:
await validate_key_mcp_servers_against_team(
Expand All @@ -325,6 +365,66 @@ async def test_validate_tool_permissions_validated_against_team(
assert "server-outside" in str(exc_info.value.detail)


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager(), # empty registry — all IDs are stale
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value=set(),
)
@patch(
"litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.MCPRequestHandler._get_mcp_servers_from_access_groups",
new_callable=AsyncMock,
return_value=[],
)
async def test_validate_stale_mcp_server_ids_are_silently_dropped(
mock_access_groups, mock_allow_all
):
"""
Stale MCP server IDs (servers deleted and no longer in the registry) must not
block a key save with a 403. They are silently stripped instead.

Scenario: key/team were configured with S1+S2, those servers were deleted and
replaced with S3+S4. The UI form still holds S1+S2 in its local state. Saving
should succeed, not raise a 403.
"""
team_obj = _make_team_obj(mcp_servers=["s3", "s4"])
await validate_key_mcp_servers_against_team(
object_permission={"mcp_servers": ["s1-stale", "s2-stale"]},
team_obj=team_obj,
) # Must not raise


@pytest.mark.asyncio
@patch(
"litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
new=_make_mock_mcp_manager(), # empty registry — all IDs are stale
)
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
return_value=set(),
)
@patch(
"litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.MCPRequestHandler._get_mcp_servers_from_access_groups",
new_callable=AsyncMock,
return_value=[],
)
async def test_validate_stale_ids_in_mcp_tool_permissions_silently_dropped(
mock_access_groups, mock_allow_all
):
"""
Stale server IDs referenced only as keys in mcp_tool_permissions (not in
mcp_servers) must also be silently stripped rather than raising a 403.
"""
team_obj = _make_team_obj(mcp_servers=["s3", "s4"])
await validate_key_mcp_servers_against_team(
object_permission={"mcp_tool_permissions": {"s1-stale": ["tool1"]}},
team_obj=team_obj,
) # Must not raise


@pytest.mark.asyncio
@patch(
"litellm.proxy.management_helpers.object_permission_utils._get_allow_all_keys_server_ids",
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
Expand Down
Loading