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]

tests

yuneng-jiang5a78486a153e
diff --git a/tests/proxy_unit_tests/test_auth_checks.py b/tests/proxy_unit_tests/test_auth_checks.py
index 7adf3251f59..5d63742c106 100644
--- a/tests/proxy_unit_tests/test_auth_checks.py
+++ b/tests/proxy_unit_tests/test_auth_checks.py
@@ -754,3 +754,225 @@ async def test_can_key_call_model_with_aliases(model, alias_map, expect_to_work)
valid_token=user_api_key_object,
llm_router=router,
)
+
+
+# ---------------------------------------------------------------------------
+# Access group cache helpers (_cache_access_object, _delete_cache_access_object)
+# ---------------------------------------------------------------------------
+
+
+async def test_cache_access_object():
+ """Test _cache_access_object stores access group in cache with correct key."""
+ from litellm.proxy.auth.auth_checks import _cache_access_object
+ from litellm.proxy._types import LiteLLM_AccessGroupTable
+
+ cache = DualCache()
+ ag_id = "ag-test-123"
+ ag_table = LiteLLM_AccessGroupTable(
+ access_group_id=ag_id,
+ access_group_name="test-group",
+ access_model_names=["gpt-4"],
+ )
+ await _cache_access_object(
+ access_group_id=ag_id,
+ access_group_table=ag_table,
+ user_api_key_cache=cache,
+ )
+ cached = await cache.async_get_cache(key=f"access_group_id:{ag_id}")
+ assert cached is not None
+ if isinstance(cached, dict):
+ assert cached.get("access_group_id") == ag_id
+ assert cached.get("access_group_name") == "test-group"
+ else:
+ assert cached.access_group_id == ag_id
+ assert cached.access_group_name == "test-group"
+
+
+async def test_delete_cache_access_object():
+ """Test _delete_cache_access_object removes access group from in-memory cache."""
+ from litellm.proxy.auth.auth_checks import _delete_cache_access_object
+ from litellm.proxy._types import LiteLLM_AccessGroupTable
+
+ cache = DualCache()
+ ag_id = "ag-delete-test"
+ ag_table = LiteLLM_AccessGroupTable(
+ access_group_id=ag_id,
+ access_group_name="to-delete",
+ )
+ await cache.async_set_cache(key=f"access_group_id:{ag_id}", value=ag_table, ttl=60)
+ await _delete_cache_access_object(access_group_id=ag_id, user_api_key_cache=cache)
+ cached = await cache.async_get_cache(key=f"access_group_id:{ag_id}")
+ assert cached is None
+
+
+# ---------------------------------------------------------------------------
+# Access group resource fetchers (_get_models_from_access_groups, _get_agent_ids_from_access_groups)
+# ---------------------------------------------------------------------------
+
+
+ "resource_field, access_group_data, expected",
+ [
+ (
+ "access_model_names",
+ {"access_group_id": "ag-1", "access_model_names": ["gpt-4", "claude-3"]},
+ ["gpt-4", "claude-3"],
+ ),
+ (
+ "access_agent_ids",
+ {"access_group_id": "ag-2", "access_agent_ids": ["agent-a", "agent-b"]},
+ ["agent-a", "agent-b"],
+ ),
+ (
+ "access_model_names",
+ {"access_group_id": "ag-3", "access_model_names": []},
+ [],
+ ),
+ ],
+)
+async def test_get_resources_from_access_groups(resource_field, access_group_data, expected):
+ """Test _get_resources_from_access_groups returns correct resource list from access groups."""
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ from litellm.proxy._types import LiteLLM_AccessGroupTable
+ from litellm.proxy.auth.auth_checks import (
+ _get_agent_ids_from_access_groups,
+ _get_models_from_access_groups,
+ )
+
+ ag_table = LiteLLM_AccessGroupTable(
+ access_group_id=access_group_data["access_group_id"],
+ access_group_name="test",
+ access_model_names=access_group_data.get("access_model_names", []),
+ access_agent_ids=access_group_data.get("access_agent_ids", []),
+ )
+
+ with patch(
+ "litellm.proxy.auth.auth_checks.get_access_object",
+ new_callable=AsyncMock,
+ return_value=ag_table,
+ ):
+ if resource_field == "access_model_names":
+ result = await _get_models_from_access_groups(
+ access_group_ids=[access_group_data["access_group_id"]],
+ prisma_client=MagicMock(),
+ user_api_key_cache=DualCache(),
+ )
+ else:
+ result = await _get_agent_ids_from_access_groups(
+ access_group_ids=[access_group_data["access_group_id"]],
+ prisma_client=MagicMock(),
+ user_api_key_cache=DualCache(),
+ )
+ assert sorted(result) == sorted(expected)
+
+
+async def test_get_models_from_access_groups_empty_ids():
+ """Test _get_models_from_access_groups returns empty list when access_group_ids is empty."""
+ from litellm.proxy.auth.auth_checks import _get_models_from_access_groups
+
+ result = await _get_models_from_access_groups(access_group_ids=[])
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# can_team_access_model with access_group_ids fallback
+# ---------------------------------------------------------------------------
+
+
+async def test_can_team_access_model_via_access_group_ids():
+ """Test can_team_access_model allows access when team has access_group_ids granting model access."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.proxy.auth.auth_checks import can_team_access_model
+
+ team_object = LiteLLM_TeamTable(
+ team_id="test-team",
+ models=[],
+ access_group_ids=["ag-with-gpt4"],
+ )
+
+ with patch(
+ "litellm.proxy.auth.auth_checks._get_models_from_access_groups",
+ new_callable=AsyncMock,
+ return_value=["gpt-4"],
+ ):
+ result = await can_team_access_model(
+ model="gpt-4",
+ team_object=team_object,
+ llm_router=None,
+ team_model_aliases=None,
+ )
+ assert result is True
+
+
+async def test_can_team_access_model_access_group_ids_denied():
+ """Test can_team_access_model denies when neither team models nor access_group_ids grant access."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.proxy.auth.auth_checks import can_team_access_model
+ from litellm.proxy._types import ProxyException
+
+ team_object = LiteLLM_TeamTable(
+ team_id="test-team",
+ models=["gpt-3.5-turbo"],
+ access_group_ids=["ag-other"],
+ )
+
+ with patch(
+ "litellm.proxy.auth.auth_checks._get_models_from_access_groups",
+ new_callable=AsyncMock,
+ return_value=["claude-3"],
+ ):
+ with pytest.raises(ProxyException):
+ await can_team_access_model(
+ model="gpt-4",
+ team_object=team_object,
+ llm_router=None,
+ team_model_aliases=None,
+ )
+
+
+# ---------------------------------------------------------------------------
+# can_key_call_model with access_group_ids fallback
+# ---------------------------------------------------------------------------
+
+
+async def test_can_key_call_model_via_access_group_ids():
+ """Test can_key_call_model allows access when key has access_group_ids granting model access."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.proxy.auth.auth_checks import can_key_call_model
+
+ user_api_key_object = UserAPIKeyAuth(
+ token="test-token",
+ models=[],
+ access_group_ids=["ag-with-gpt4"],
+ )
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "openai/gpt-4", "api_key": "test"},
+ }
+ ]
+ )
+
+ with patch(
+ "litellm.proxy.auth.auth_checks._get_models_from_access_groups",
+ new_callable=AsyncMock,
+ return_value=["gpt-4"],
+ ):
+ await can_key_call_model(
+ model="gpt-4",
+ llm_model_list=[],
+ valid_token=user_api_key_object,
+ llm_router=router,
+ )
diff --git a/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.py b/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.py
index 111dd7c0764..533dc0557b5 100644
--- a/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.py
+++ b/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.py
@@ -4,7 +4,7 @@ Unit tests for AgentRequestHandler - Agent permission management for keys and te
import os
import sys
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
import pytest
@@ -111,3 +111,57 @@ class TestAgentRequestHandler:
result = await AgentRequestHandler.get_allowed_agents(user_api_key_auth=mock_user_auth)
assert result == []
+
+ async def test_get_allowed_agents_for_key_via_access_group_ids(self):
+ """
+ Test that _get_allowed_agents_for_key includes agents from key's access_group_ids
+ (unified access groups) when key has no native object_permission.
+ """
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="test-key",
+ user_id="test-user",
+ access_group_ids=["ag-with-agents"],
+ )
+
+ with patch.object(
+ AgentRequestHandler, "_get_key_object_permission", return_value=None
+ ):
+ with patch(
+ "litellm.proxy.auth.auth_checks._get_agent_ids_from_access_groups",
+ new_callable=AsyncMock,
+ return_value=["agent-from-ag-1", "agent-from-ag-2"],
+ ):
+ result = await AgentRequestHandler._get_allowed_agents_for_key(
+ user_api_key_auth=mock_user_auth
+ )
+ assert sorted(result) == ["agent-from-ag-1", "agent-from-ag-2"]
+
+ async def test_get_allowed_agents_for_key_combines_native_and_access_groups(self):
+ """
+ Test that _get_allowed_agents_for_key combines agents from native object_permission
+ and key's access_group_ids (unified access groups).
+ """
+ from litellm.proxy._types import LiteLLM_ObjectPermissionTable
+
+ mock_permission = LiteLLM_ObjectPermissionTable(
+ object_permission_id="obj-1",
+ agents=["native-agent-1"],
+ agent_access_groups=[],
+ )
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="test-key",
+ user_id="test-user",
+ access_group_ids=["ag-1"],
+ )
+ # Attach object_permission so _get_key_object_permission returns it
+ mock_user_auth.object_permission = mock_permission
+
+ with patch(
+ "litellm.proxy.auth.auth_checks._get_agent_ids_from_access_groups",
+ new_callable=AsyncMock,
+ return_value=["agent-from-ag"],
+ ):
+ result = await AgentRequestHandler._get_allowed_agents_for_key(
+ user_api_key_auth=mock_user_auth
+ )
+ assert sorted(result) == ["agent-from-ag", "native-agent-1"]
diff --git a/tests/test_litellm/proxy/management_endpoints/test_access_group_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_access_group_endpoints.py
index 54df8941fa5..181ec8464ff 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_access_group_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_access_group_endpoints.py
@@ -37,19 +37,27 @@ def _make_access_group_record(
updated_by: str | None = "admin-user",
created_at: datetime | None = None,
):
+ created_at_val = created_at or datetime.now()
+ updated_at_val = datetime.now()
+ data = {
+ "access_group_id": access_group_id,
+ "access_group_name": access_group_name,
+ "description": description,
+ "access_model_names": access_model_names or [],
+ "access_mcp_server_ids": access_mcp_server_ids or [],
+ "access_agent_ids": access_agent_ids or [],
+ "assigned_team_ids": assigned_team_ids or [],
+ "assigned_key_ids": assigned_key_ids or [],
+ "created_at": created_at_val,
+ "created_by": created_by,
+ "updated_at": updated_at_val,
+ "updated_by": updated_by,
+ }
record = MagicMock()
- record.access_group_id = access_group_id
- record.access_group_name = access_group_name
- record.description = description
- record.access_model_names = access_model_names or []
- record.access_mcp_server_ids = access_mcp_server_ids or []
- record.access_agent_ids = access_agent_ids or []
- record.assigned_team_ids = assigned_team_ids or []
- record.assigned_key_ids = assigned_key_ids or []
- record.created_at = created_at or datetime.now()
- record.created_by = created_by
- record.updated_at = datetime.now()
- record.updated_by = updated_by
+ for k, v in data.items():
+ setattr(record, k, v)
+ record.dict = lambda: data
+ record.model_dump = lambda: data
return record
@@ -116,6 +124,20 @@ def client_and_mocks(monkeypatch):
monkeypatch.setattr(ps, "prisma_client", mock_prisma)
+ # Mock user_api_key_cache and proxy_logging_obj for cache operations (create/update/delete)
+ mock_cache = MagicMock()
+ mock_cache.async_set_cache = AsyncMock(return_value=None)
+ mock_cache.delete_cache = MagicMock(return_value=None)
+ monkeypatch.setattr(ps, "user_api_key_cache", mock_cache)
+
+ mock_proxy_logging = MagicMock()
+ mock_proxy_logging.internal_usage_cache = MagicMock()
+ mock_proxy_logging.internal_usage_cache.dual_cache = MagicMock()
+ mock_proxy_logging.internal_usage_cache.dual_cache.async_delete_cache = AsyncMock(
+ return_value=None
+ )
+ monkeypatch.setattr(ps, "proxy_logging_obj", mock_proxy_logging)
+
admin_user = UserAPIKeyAuth(
user_id="admin_user",
user_role=LitellmUserRoles.PROXY_ADMIN,
@@ -632,3 +654,25 @@ def test_access_group_endpoints_db_not_connected(client_and_mocks, monkeypatch,
resp = getattr(client, method)(url, **factory())
assert resp.status_code == 500
assert resp.json()["detail"]["error"] == CommonProxyErrors.db_not_connected_error.value
+
+
+# ---------------------------------------------------------------------------
+# Unit tests for cache helpers (_record_to_access_group_table)
+# ---------------------------------------------------------------------------
+
+
+def test_record_to_access_group_table():
+ """Test _record_to_access_group_table converts Prisma-like record to LiteLLM_AccessGroupTable."""
+ from litellm.proxy.management_endpoints.access_group_endpoints import _record_to_access_group_table
+
+ record = _make_access_group_record(
+ access_group_id="ag-unit-test",
+ access_group_name="unit-test-group",
+ access_model_names=["gpt-4", "claude-3"],
+ access_agent_ids=["agent-1"],
+ )
+ result = _record_to_access_group_table(record)
+ assert result.access_group_id == "ag-unit-test"
+ assert result.access_group_name == "unit-test-group"
+ assert result.access_model_names == ["gpt-4", "claude-3"]
+ assert result.access_agent_ids == ["agent-1"]
diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
index ad5819df1c7..de2c940943b 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
@@ -520,6 +520,51 @@ async def test_key_generation_with_object_permission(monkeypatch):
assert key_insert_calls[0]["data"].get("object_permission_id") == "objperm123"
+async def test_generate_key_helper_fn_with_access_group_ids(monkeypatch):
+ """Ensure generate_key_helper_fn passes access_group_ids into the key insert payload."""
+ mock_prisma_client = AsyncMock()
+ mock_prisma_client.jsonify_object = lambda data: data # type: ignore
+ mock_prisma_client.db = MagicMock()
+ mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
+ mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
+ return_value=MagicMock(object_permission_id=None)
+ )
+
+ captured_key_data = {}
+
+ async def _insert_data_side_effect(*args, **kwargs):
+ table_name = kwargs.get("table_name")
+ if table_name == "user":
+ return MagicMock(models=[], spend=0)
+ elif table_name == "key":
+ captured_key_data.update(kwargs.get("data", {}))
+ return MagicMock(
+ token="hashed_token_789",
+ litellm_budget_table=None,
+ object_permission=None,
+ created_at=None,
+ updated_at=None,
+ )
+ return MagicMock()
+
+ mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ generate_key_helper_fn,
+ )
+
+ await generate_key_helper_fn(
+ request_type="key",
+ table_name="key",
+ user_id="test-user",
+ access_group_ids=["ag-1", "ag-2"],
+ )
+
+ assert captured_key_data.get("access_group_ids") == ["ag-1", "ag-2"]
+
+
@pytest.mark.asyncio
async def test_key_generation_with_mcp_tool_permissions(monkeypatch):
"""