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
Merge remote-tracking branch 'origin' into litellm_deleted_keys_team
yuneng-jiang5ff768e5e0bc
diff --cc litellm/proxy/_types.pyindex 3172f866177,3c6e2105261..0f2cd4b3a79--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@@ -2087,23 -2112,9 +2127,24 @@@ class LiteLLM_VerificationToken(LiteLLMrotation_interval: Optional[str] = None # How often to rotate (e.g., "30d", "90d")last_rotation_at: Optional[datetime] = None # When this key was last rotatedkey_rotation_at: Optional[datetime] = None # When this key should next be rotated+ router_settings: Optional[Dict] = None # Router settings for this key (Key > Team > Global precedence)model_config = ConfigDict(protected_namespaces=())+++class LiteLLM_DeletedVerificationToken(LiteLLM_VerificationToken):+ """+ Recording of deleted keys for audit purposes. Mirrors LiteLLM_VerificationToken+ plus metadata captured at deletion time.+ """++ id: Optional[str] = None+ deleted_at: Optional[datetime] = None+ deleted_by: Optional[str] = None+ deleted_by_api_key: Optional[str] = None+ litellm_changed_by: Optional[str] = None++ model_config = ConfigDict(protected_namespaces=())class LiteLLM_VerificationTokenView(LiteLLM_VerificationToken):diff --cc litellm/proxy/management_endpoints/key_management_endpoints.pyindex 50c0a86793c,39b6774a61c..9b9dcb1706b--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@@ -14,9 -14,10 +14,10 @@@ import copimport jsonimport secretsimport traceback+ import yamlfrom datetime import datetime, timedelta, timezone-from typing import List, Literal, Optional, Tuple, cast+from typing import Any, Dict, List, Literal, Optional, Tuple, cast-+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumpsimport fastapifrom fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, statusdiff --cc pyproject.tomlindex 0bb06462314,aa8e6fd97be..f4fd1d9b102--- a/pyproject.toml+++ b/pyproject.toml@@@ -59,7 -59,7 +59,11 @@@ websockets = {version = "^15.0.1", optiboto3 = {version = "1.36.0", optional = true}redisvl = {version = "^0.4.1", optional = true, markers = "python_version >= '3.9' and python_version < '3.14'"}mcp = {version = "^1.21.2", optional = true, python = ">=3.10"}++<<<<<<< HEAD+litellm-proxy-extras = {version = "0.4.15", optional = true}++=======+ litellm-proxy-extras = {version = "0.4.21", optional = true}++>>>>>>> originrich = {version = "13.7.1", optional = true}litellm-enterprise = {version = "0.1.27", optional = true}diskcache = {version = "^5.6.1", optional = true}diff --cc requirements.txtindex d08351c602d,7ec71fb7dc9..73c2742fc43--- a/requirements.txt+++ b/requirements.txt@@@ -47,7 -47,7 +47,11 @@@ sentry_sdk==2.21.0 # for sentry error hdetect-secrets==1.5.0 # Enterprise - secret detection / masking in LLM requestscryptography==44.0.1tzdata==2025.1 # IANA time zone database++<<<<<<< HEAD+litellm-proxy-extras==0.4.15 # for proxy extras - e.g. prisma migrations++=======+ litellm-proxy-extras==0.4.21 # for proxy extras - e.g. prisma migrations++>>>>>>> originllm-sandbox==0.3.31 # for skill execution in sandbox### LITELLM PACKAGE DEPENDENCIESpython-dotenv==1.0.1 # for envdiff --cc tests/test_litellm/proxy/management_endpoints/test_team_endpoints.pyindex 926ecf7ad46,bbff7448e13..a1e8efdbb48--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py@@@ -3967,345 -4325,593 +4332,935 @@@ async def test_update_team_guardrails_wassert first_call_kwargs["include"]["teams"] is True+def test_transform_teams_to_deleted_records():+ from datetime import datetime, timezone++ user_api_key_dict = UserAPIKeyAuth(+ user_id="user-123",+ api_key="sk-test",+ user_role=LitellmUserRoles.PROXY_ADMIN.value,+ )++ team1 = LiteLLM_TeamTable(+ team_id="team-1",+ team_alias="test-team-1",+ members_with_roles=[+ Member(user_id="user-1", role="admin"),+ Member(user_id="user-2", role="user"),+ ],+ metadata={"test": "value"},+ model_max_budget={},+ model_spend={},+ )++ team2 = LiteLLM_TeamTable(+ team_id="team-2",+ team_alias="test-team-2",+ members_with_roles=[],+ metadata=None,+ model_max_budget={"gpt-4": {"budget_limit": 100.0}},+ model_spend={},+ )++ records = _transform_teams_to_deleted_records(+ teams=[team1, team2],+ user_api_key_dict=user_api_key_dict,+ litellm_changed_by="admin-user",+ )++ assert len(records) == 2+ assert all("deleted_at" in record for record in records)+ assert all("deleted_by" in record for record in records)+ assert all("deleted_by_api_key" in record for record in records)+ assert all("litellm_changed_by" in record for record in records)+ assert all(record["deleted_by"] == "user-123" for record in records)+ # UserAPIKeyAuth hashes the api_key, so we check against the hashed value+ assert all(record["deleted_by_api_key"] == user_api_key_dict.api_key for record in records)+ assert all(record["litellm_changed_by"] == "admin-user" for record in records)++ record1 = records[0]+ assert record1["team_id"] == "team-1"+ assert isinstance(record1["members_with_roles"], str)+ assert isinstance(record1["metadata"], str)+ assert "litellm_model_table" not in record1+ assert "object_permission" not in record1+ assert "id" not in record1++ record2 = records[1]+ assert record2["team_id"] == "team-2"+ # model_max_budget should be converted to JSON string if it exists+ if "model_max_budget" in record2:+ assert isinstance(record2["model_max_budget"], str)+++def test_transform_teams_to_deleted_records_empty_list():+ user_api_key_dict = UserAPIKeyAuth(+ user_id="user-123",+ api_key="sk-test",+ user_role=LitellmUserRoles.PROXY_ADMIN.value,+ )++ records = _transform_teams_to_deleted_records(+ teams=[],+ user_api_key_dict=user_api_key_dict,+ )++ assert records == []+++async def test_save_deleted_team_records():+ mock_prisma_client = AsyncMock()+ mock_create_many = AsyncMock()+ mock_prisma_client.db.litellm_deletedteamtable.create_many = mock_create_many++ records = [+ {+ "team_id": "team-1",+ "team_alias": "test-team-1",+ "deleted_at": "2024-01-01T00:00:00Z",+ "deleted_by": "admin",+ },+ {+ "team_id": "team-2",+ "team_alias": "test-team-2",+ "deleted_at": "2024-01-01T00:00:00Z",+ "deleted_by": "admin",+ },+ ]++ await _save_deleted_team_records(records=records, prisma_client=mock_prisma_client)++ mock_create_many.assert_called_once_with(data=records)+++async def test_save_deleted_team_records_empty_list():+ mock_prisma_client = AsyncMock()+ mock_create_many = AsyncMock()+ mock_prisma_client.db.litellm_deletedteamtable.create_many = mock_create_many++ await _save_deleted_team_records(records=[], prisma_client=mock_prisma_client)++ mock_create_many.assert_not_called()+++async def test_persist_deleted_team_records():+ mock_prisma_client = AsyncMock()+ mock_create_many = AsyncMock()+ mock_prisma_client.db.litellm_deletedteamtable.create_many = mock_create_many++ user_api_key_dict = UserAPIKeyAuth(+ user_id="user-123",+ api_key="sk-test",+ user_role=LitellmUserRoles.PROXY_ADMIN.value,+ )++ team = LiteLLM_TeamTable(+ team_id="team-1",+ team_alias="test-team",+ members_with_roles=[+ Member(user_id="user-1", role="admin"),+ ],+ metadata={},+ model_max_budget={},+ model_spend={},+ )++ await _persist_deleted_team_records(+ teams=[team],+ prisma_client=mock_prisma_client,+ user_api_key_dict=user_api_key_dict,+ litellm_changed_by="admin-user",+ )++ mock_create_many.assert_called_once()+ call_args = mock_create_many.call_args+ assert "data" in call_args.kwargs+ records = call_args.kwargs["data"]+ assert len(records) == 1+ assert records[0]["team_id"] == "team-1"+ assert records[0]["deleted_by"] == "user-123"+ assert records[0]["litellm_changed_by"] == "admin-user"+++async def test_delete_team_persists_deleted_teams(monkeypatch):+ from litellm.proxy._types import DeleteTeamRequest++ mock_prisma_client = AsyncMock()+ mock_user_api_key_dict = UserAPIKeyAuth(+ user_id="admin-user",+ api_key="sk-admin",+ user_role=LitellmUserRoles.PROXY_ADMIN.value,+ )++ team1 = LiteLLM_TeamTable(+ team_id="team-1",+ team_alias="test-team-1",+ members_with_roles=[+ Member(user_id="user-1", role="admin"),+ ],+ metadata={},+ model_max_budget={},+ model_spend={},+ )++ mock_find_unique = AsyncMock(return_value=team1)+ mock_prisma_client.db.litellm_teamtable.find_unique = mock_find_unique++ mock_delete_data = AsyncMock(return_value={"deleted_teams": ["team-1"]})+ mock_prisma_client.delete_data = mock_delete_data++ mock_create_many_teams = AsyncMock()+ mock_prisma_client.db.litellm_deletedteamtable.create_many = mock_create_many_teams++ mock_create_many_keys = AsyncMock()+ mock_prisma_client.db.litellm_deletedverificationtoken.create_many = (+ mock_create_many_keys+ )++ mock_find_many_keys = AsyncMock(return_value=[])+ mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many_keys++ monkeypatch.setattr(+ "litellm.proxy.proxy_server.prisma_client",+ mock_prisma_client,+ )+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.create_audit_log_for_update",+ AsyncMock(),+ )+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.litellm_proxy_admin_name",+ "admin",+ )+ monkeypatch.setattr(+ "litellm.proxy.management_endpoints.team_endpoints.team_member_delete",+ AsyncMock(return_value=team1),+ )++ data = DeleteTeamRequest(team_ids=["team-1"])++ result = await delete_team(+ data=data,+ http_request=MagicMock(),+ user_api_key_dict=mock_user_api_key_dict,+ litellm_changed_by="admin-user",+ )++ mock_create_many_teams.assert_called_once()+ call_args = mock_create_many_teams.call_args+ assert "data" in call_args.kwargs+ records = call_args.kwargs["data"]+ assert len(records) == 1+ assert records[0]["team_id"] == "team-1"+ assert records[0]["deleted_by"] == "admin-user"+ assert records[0]["litellm_changed_by"] == "admin-user"+++async def test_team_member_delete_persists_deleted_keys(monkeypatch):+ from litellm.proxy._types import TeamMemberDeleteRequest+ from litellm.proxy.management_endpoints.key_management_endpoints import (+ LiteLLM_VerificationToken,+ )++ mock_prisma_client = AsyncMock()+ mock_user_api_key_dict = UserAPIKeyAuth(+ user_id="admin-user",+ api_key="sk-admin",+ user_role=LitellmUserRoles.PROXY_ADMIN.value,+ )++ team = LiteLLM_TeamTable(+ team_id="team-1",+ team_alias="test-team",+ members_with_roles=[+ Member(user_id="user-123", role="admin"),+ ],+ metadata={},+ model_max_budget={},+ model_spend={},+ )++ key1 = LiteLLM_VerificationToken(+ token="hashed-token-1",+ user_id="user-123",+ team_id="team-1",+ key_alias="test-key-1",+ spend=100.0,+ max_budget=1000.0,+ models=["gpt-4"],+ aliases={},+ config={},+ permissions={},+ metadata={},+ model_max_budget={},+ )++ key2 = LiteLLM_VerificationToken(+ token="hashed-token-2",+ user_id="user-123",+ team_id="team-1",+ key_alias="test-key-2",+ spend=50.0,+ max_budget=500.0,+ models=["gpt-3.5-turbo"],+ aliases={},+ config={},+ permissions={},+ metadata={},+ model_max_budget={},+ )++ mock_find_unique_team = AsyncMock(return_value=team)+ mock_prisma_client.db.litellm_teamtable.find_unique = mock_find_unique_team++ mock_find_many_user = AsyncMock(+ return_value=[+ MagicMock(+ user_id="user-123",+ teams=["team-1"],+ model_dump=lambda: {"user_id": "user-123", "teams": ["team-1"]},+ )+ ]+ )+ mock_prisma_client.db.litellm_usertable.find_many = mock_find_many_user++ mock_update_team = AsyncMock()+ mock_prisma_client.db.litellm_teamtable.update = mock_update_team++ mock_update_user = AsyncMock()+ mock_prisma_client.db.litellm_usertable.update = mock_update_user++ mock_delete_membership = AsyncMock()+ mock_prisma_client.db.litellm_teammembership.delete_many = mock_delete_membership++ mock_find_many_keys = AsyncMock(return_value=[key1, key2])+ mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many_keys++ mock_delete_keys = AsyncMock()+ mock_prisma_client.db.litellm_verificationtoken.delete_many = mock_delete_keys++ mock_create_many_keys = AsyncMock()+ mock_prisma_client.db.litellm_deletedverificationtoken.create_many = (+ mock_create_many_keys+ )++ monkeypatch.setattr(+ "litellm.proxy.proxy_server.prisma_client",+ mock_prisma_client,+ )+ monkeypatch.setattr(+ "litellm.proxy.management_endpoints.team_endpoints._is_user_team_admin",+ lambda **kwargs: True,+ )++ data = TeamMemberDeleteRequest(team_id="team-1", user_id="user-123")++ result = await team_member_delete(+ data=data,+ user_api_key_dict=mock_user_api_key_dict,+ )++ mock_create_many_keys.assert_called_once()+ call_args = mock_create_many_keys.call_args+ assert "data" in call_args.kwargs+ records = call_args.kwargs["data"]+ assert len(records) == 2+ assert all(record["deleted_by"] == "admin-user" for record in records)+ assert all(record["team_id"] == "team-1" for record in records)+ assert all(record["user_id"] == "user-123" for record in records)+ mock_delete_keys.assert_called_once()+ @pytest.mark.asyncio+ async def test_new_team_negative_max_budget():+ """+ Test that NewTeamRequest model allows negative max_budget values.+ Validation is done at API level, not model level.++ This prevents GET requests from breaking when they receive data with negative budgets.+ """+ from litellm.proxy._types import NewTeamRequest++ # Should not raise any errors at model level+ request = NewTeamRequest(team_alias="test-team", max_budget=-7.0)+ assert request.max_budget == -7.0+++ @pytest.mark.asyncio+ async def test_new_team_negative_team_member_budget():+ """+ Test that NewTeamRequest model allows negative team_member_budget values.+ Validation is done at API level, not model level.+ """+ from litellm.proxy._types import NewTeamRequest++ # Should not raise any errors at model level+ request = NewTeamRequest(team_alias="test-team", team_member_budget=-10.0)+ assert request.team_member_budget == -10.0+++ @pytest.mark.asyncio+ async def test_update_team_negative_max_budget():+ """+ Test that UpdateTeamRequest model allows negative max_budget values.+ Validation is done at API level, not model level.+ """+ from litellm.proxy._types import UpdateTeamRequest++ # Should not raise any errors at model level+ request = UpdateTeamRequest(team_id="test-team-id", max_budget=-5.0)+ assert request.max_budget == -5.0+++ @pytest.mark.asyncio+ async def test_update_team_negative_team_member_budget():+ """+ Test that UpdateTeamRequest model allows negative team_member_budget values.+ Validation is done at API level, not model level.+ """+ from litellm.proxy._types import UpdateTeamRequest++ # Should not raise any errors at model level+ request = UpdateTeamRequest(team_id="test-team-id", team_member_budget=-15.0)+ assert request.team_member_budget == -15.0+++ @pytest.mark.asyncio+ async def test_new_team_positive_budgets_accepted():+ """+ Test that NewTeamRequest accepts positive budget values.+ """+ from litellm.proxy._types import NewTeamRequest++ # Should not raise any errors+ request = NewTeamRequest(+ team_alias="test-team",+ max_budget=100.0,+ team_member_budget=50.0+ )+ assert request.max_budget == 100.0+ assert request.team_member_budget == 50.0+++ @pytest.mark.asyncio+ async def test_new_team_with_router_settings(mock_db_client, mock_admin_auth):+ """+ Test that /team/new correctly handles router_settings by:+ 1. Accepting router_settings as a dict parameter+ 2. Serializing router_settings to JSON when saving to database+ 3. Storing router_settings in the team record+ """+ # Configure mocked prisma client+ mock_db_client.jsonify_team_object = lambda db_data: db_data+ mock_db_client.get_data = AsyncMock(return_value=None)+ mock_db_client.update_data = AsyncMock(return_value=MagicMock())+ mock_db_client.db = MagicMock()++ # Mock model table creation+ mock_db_client.db.litellm_modeltable = MagicMock()+ mock_db_client.db.litellm_modeltable.create = AsyncMock(+ return_value=MagicMock(id="model123")+ )++ # Capture team table creation+ team_create_result = MagicMock(+ team_id="team-router-456",+ )+ team_create_result.model_dump.return_value = {+ "team_id": "team-router-456",+ }+ mock_team_create = AsyncMock(return_value=team_create_result)+ mock_team_count = AsyncMock(return_value=0)+ mock_db_client.db.litellm_teamtable = MagicMock()+ mock_db_client.db.litellm_teamtable.create = mock_team_create+ mock_db_client.db.litellm_teamtable.count = mock_team_count+ mock_db_client.db.litellm_teamtable.update = AsyncMock(+ return_value=team_create_result+ )++ # Mock user table+ mock_db_client.db.litellm_usertable = MagicMock()+ mock_db_client.db.litellm_usertable.update = AsyncMock(return_value=MagicMock())++ from fastapi import Request++ from litellm.proxy._types import NewTeamRequest+ from litellm.proxy.management_endpoints.team_endpoints import new_team++ # Test router_settings with sample data+ router_settings_data = {+ "routing_strategy": "usage-based",+ "num_retries": 3,+ "retry_policy": {"max_retries": 5},+ }++ # Build request with router_settings+ team_request = NewTeamRequest(+ team_alias="my-team-router",+ router_settings=router_settings_data,+ )++ dummy_request = MagicMock(spec=Request)++ # Execute the endpoint function+ await new_team(+ data=team_request,+ http_request=dummy_request,+ user_api_key_dict=mock_admin_auth,+ )++ # Verify team creation was called+ assert mock_team_create.call_count == 1+ created_team_kwargs = mock_team_create.call_args.kwargs+ team_data = created_team_kwargs["data"]++ # Verify router_settings is serialized to JSON string+ assert "router_settings" in team_data+ assert isinstance(team_data["router_settings"], str)++ # Verify router_settings can be deserialized and matches input+ deserialized_settings = json.loads(team_data["router_settings"])+ assert deserialized_settings == router_settings_data+++ @pytest.mark.asyncio+ async def test_get_team_daily_activity_non_admin_filters_by_user_api_keys(+ mock_db_client,+ ):+ """+ Test that non-team-admin users only see their own spend (filtered by their API keys)+ when calling /team/daily/activity endpoint.+ """+ from litellm.proxy.management_endpoints.team_endpoints import (+ get_team_daily_activity,+ )++ # Create a non-admin user+ user_id = "test_user_123"+ team_id = "test_team_456"+ user_api_key_dict = UserAPIKeyAuth(+ user_id=user_id, user_role=LitellmUserRoles.INTERNAL_USER+ )++ # Mock user info+ mock_user_info = LiteLLM_UserTable(+ user_id=user_id,+ teams=[team_id],+ max_budget=1000.0,+ spend=0.0,+ user_email="[email protected]",+ user_role="internal_user",+ )++ # Mock team with user as non-admin member+ mock_team_member = Member(user_id=user_id, role="user")+ mock_team = MagicMock(spec=LiteLLM_TeamTable)+ mock_team.team_id = team_id+ mock_team.team_alias = "Test Team"+ mock_team.members_with_roles = [mock_team_member]+ mock_team.model_dump.return_value = {+ "team_id": team_id,+ "team_alias": "Test Team",+ "members_with_roles": [{"user_id": user_id, "role": "user"}],+ }++ # Mock user's API keys+ user_api_key_1 = MagicMock()+ user_api_key_1.token = "user_key_1"+ user_api_key_2 = MagicMock()+ user_api_key_2.token = "user_key_2"++ # Setup mocks+ mock_db_client.db.litellm_teamtable.find_many = AsyncMock(+ return_value=[mock_team]+ )+ mock_db_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[user_api_key_1, user_api_key_2]+ )++ # Mock get_user_object+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_user_object",+ new_callable=AsyncMock,+ ) as mock_get_user_object:+ mock_get_user_object.return_value = mock_user_info++ # Mock get_daily_activity to capture the api_key parameter+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_daily_activity",+ new_callable=AsyncMock,+ ) as mock_get_daily_activity:+ mock_get_daily_activity.return_value = MagicMock()++ # Call the endpoint+ await get_team_daily_activity(+ team_ids=team_id,+ start_date="2024-01-01",+ end_date="2024-01-02",+ model=None,+ api_key=None,+ page=1,+ page_size=10,+ exclude_team_ids=None,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify get_daily_activity was called with user's API keys as filter+ mock_get_daily_activity.assert_called_once()+ call_kwargs = mock_get_daily_activity.call_args[1]+ assert call_kwargs["api_key"] == ["user_key_1", "user_key_2"]+ assert call_kwargs["entity_id"] == [team_id]++ # Verify user's API keys were fetched+ mock_db_client.db.litellm_verificationtoken.find_many.assert_called_once()+ api_key_call_kwargs = (+ mock_db_client.db.litellm_verificationtoken.find_many.call_args[1]+ )+ assert api_key_call_kwargs["where"] == {"user_id": user_id}+++ @pytest.mark.asyncio+ async def test_get_team_daily_activity_team_admin_sees_all_spend(mock_db_client):+ """+ Test that team admin users see all team spend (no API key filtering)+ when calling /team/daily/activity endpoint.+ """+ from litellm.proxy.management_endpoints.team_endpoints import (+ get_team_daily_activity,+ )++ # Create a team admin user+ user_id = "test_admin_123"+ team_id = "test_team_456"+ user_api_key_dict = UserAPIKeyAuth(+ user_id=user_id, user_role=LitellmUserRoles.INTERNAL_USER+ )++ # Mock user info+ mock_user_info = LiteLLM_UserTable(+ user_id=user_id,+ teams=[team_id],+ max_budget=1000.0,+ spend=0.0,+ user_email="[email protected]",+ user_role="internal_user",+ )++ # Mock team with user as admin member+ mock_team_member = Member(user_id=user_id, role="admin")+ mock_team = MagicMock(spec=LiteLLM_TeamTable)+ mock_team.team_id = team_id+ mock_team.team_alias = "Test Team"+ mock_team.members_with_roles = [mock_team_member]+ mock_team.model_dump.return_value = {+ "team_id": team_id,+ "team_alias": "Test Team",+ "members_with_roles": [{"user_id": user_id, "role": "admin"}],+ }++ # Setup mocks+ mock_db_client.db.litellm_teamtable.find_many = AsyncMock(+ return_value=[mock_team]+ )++ # Mock get_user_object+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_user_object",+ new_callable=AsyncMock,+ ) as mock_get_user_object:+ mock_get_user_object.return_value = mock_user_info++ # Mock get_daily_activity to capture the api_key parameter+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_daily_activity",+ new_callable=AsyncMock,+ ) as mock_get_daily_activity:+ mock_get_daily_activity.return_value = MagicMock()++ # Call the endpoint+ await get_team_daily_activity(+ team_ids=team_id,+ start_date="2024-01-01",+ end_date="2024-01-02",+ model=None,+ api_key=None,+ page=1,+ page_size=10,+ exclude_team_ids=None,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify get_daily_activity was called WITHOUT API key filtering+ mock_get_daily_activity.assert_called_once()+ call_kwargs = mock_get_daily_activity.call_args[1]+ assert call_kwargs["api_key"] is None+ assert call_kwargs["entity_id"] == [team_id]++ # Verify user's API keys were NOT fetched (since they're admin)+ if hasattr(+ mock_db_client.db.litellm_verificationtoken, "find_many"+ ) and mock_db_client.db.litellm_verificationtoken.find_many.called:+ # If it was called, that's unexpected for admin users+ assert False, "API keys should not be fetched for team admin users"+++ @pytest.mark.asyncio+ async def test_update_team_with_router_settings(mock_db_client, mock_admin_auth):+ """+ Test that /team/update correctly handles router_settings by:+ 1. Accepting router_settings as a dict parameter+ 2. Serializing router_settings to JSON when updating database+ 3. Updating router_settings in the team record+ """+ # Configure mocked prisma client+ mock_db_client.jsonify_team_object = lambda db_data: db_data+ mock_db_client.db = MagicMock()++ # Mock existing team row+ existing_team_mock = MagicMock()+ existing_team_mock.team_id = "team-router-update-789"+ existing_team_mock.organization_id = None+ existing_team_mock.models = []+ existing_team_mock.members_with_roles = []+ existing_team_mock.model_dump.return_value = {+ "team_id": "team-router-update-789",+ "organization_id": None,+ "models": [],+ "members_with_roles": [],+ }++ # Mock team table find_unique and update+ updated_team_result = MagicMock(+ team_id="team-router-update-789",+ )+ updated_team_result.model_dump.return_value = {+ "team_id": "team-router-update-789",+ }+ mock_team_find_unique = AsyncMock(return_value=existing_team_mock)+ mock_team_update = AsyncMock(return_value=updated_team_result)+ mock_db_client.db.litellm_teamtable = MagicMock()+ mock_db_client.db.litellm_teamtable.find_unique = mock_team_find_unique+ mock_db_client.db.litellm_teamtable.update = mock_team_update++ from fastapi import Request++ from litellm.proxy._types import UpdateTeamRequest+ from litellm.proxy.management_endpoints.team_endpoints import update_team++ # Test router_settings with updated data+ router_settings_data = {+ "routing_strategy": "latency-based",+ "num_retries": 2,+ }++ # Build update request with router_settings+ team_update_request = UpdateTeamRequest(+ team_id="team-router-update-789",+ router_settings=router_settings_data,+ )++ dummy_request = MagicMock(spec=Request)++ # Execute the endpoint function+ await update_team(+ data=team_update_request,+ http_request=dummy_request,+ user_api_key_dict=mock_admin_auth,+ )++ # Verify team update was called+ assert mock_team_update.call_count == 1+ updated_team_kwargs = mock_team_update.call_args.kwargs+ team_data = updated_team_kwargs["data"]++ # Verify router_settings is serialized to JSON string+ assert "router_settings" in team_data+ assert isinstance(team_data["router_settings"], str)++ # Verify router_settings can be deserialized and matches input+ deserialized_settings = json.loads(team_data["router_settings"])+ assert deserialized_settings == router_settings_data+++ @pytest.mark.asyncio+ async def test_get_team_daily_activity_non_admin_filters_by_user_api_keys(+ mock_db_client,+ ):+ """+ Test that non-team-admin users only see their own spend (filtered by their API keys)+ when calling /team/daily/activity endpoint.+ """+ from litellm.proxy.management_endpoints.team_endpoints import (+ get_team_daily_activity,+ )++ # Create a non-admin user+ user_id = "test_user_123"+ team_id = "test_team_456"+ user_api_key_dict = UserAPIKeyAuth(+ user_id=user_id, user_role=LitellmUserRoles.INTERNAL_USER+ )++ # Mock user info+ mock_user_info = LiteLLM_UserTable(+ user_id=user_id,+ teams=[team_id],+ max_budget=1000.0,+ spend=0.0,+ user_email="[email protected]",+ user_role="internal_user",+ )++ # Mock team with user as non-admin member+ mock_team_member = Member(user_id=user_id, role="user")+ mock_team = MagicMock(spec=LiteLLM_TeamTable)+ mock_team.team_id = team_id+ mock_team.team_alias = "Test Team"+ mock_team.members_with_roles = [mock_team_member]+ mock_team.model_dump.return_value = {+ "team_id": team_id,+ "team_alias": "Test Team",+ "members_with_roles": [{"user_id": user_id, "role": "user"}],+ }++ # Mock user's API keys+ user_api_key_1 = MagicMock()+ user_api_key_1.token = "user_key_1"+ user_api_key_2 = MagicMock()+ user_api_key_2.token = "user_key_2"++ # Setup mocks+ mock_db_client.db.litellm_teamtable.find_many = AsyncMock(+ return_value=[mock_team]+ )+ mock_db_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[user_api_key_1, user_api_key_2]+ )++ # Mock get_user_object+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_user_object",+ new_callable=AsyncMock,+ ) as mock_get_user_object:+ mock_get_user_object.return_value = mock_user_info++ # Mock get_daily_activity to capture the api_key parameter+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_daily_activity",+ new_callable=AsyncMock,+ ) as mock_get_daily_activity:+ mock_get_daily_activity.return_value = MagicMock()++ # Call the endpoint+ await get_team_daily_activity(+ team_ids=team_id,+ start_date="2024-01-01",+ end_date="2024-01-02",+ model=None,+ api_key=None,+ page=1,+ page_size=10,+ exclude_team_ids=None,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify get_daily_activity was called with user's API keys as filter+ mock_get_daily_activity.assert_called_once()+ call_kwargs = mock_get_daily_activity.call_args[1]+ assert call_kwargs["api_key"] == ["user_key_1", "user_key_2"]+ assert call_kwargs["entity_id"] == [team_id]++ # Verify user's API keys were fetched+ mock_db_client.db.litellm_verificationtoken.find_many.assert_called_once()+ api_key_call_kwargs = (+ mock_db_client.db.litellm_verificationtoken.find_many.call_args[1]+ )+ assert api_key_call_kwargs["where"] == {"user_id": user_id}+++ @pytest.mark.asyncio+ async def test_get_team_daily_activity_team_admin_sees_all_spend(mock_db_client):+ """+ Test that team admin users see all team spend (no API key filtering)+ when calling /team/daily/activity endpoint.+ """+ from litellm.proxy.management_endpoints.team_endpoints import (+ get_team_daily_activity,+ )++ # Create a team admin user+ user_id = "test_admin_123"+ team_id = "test_team_456"+ user_api_key_dict = UserAPIKeyAuth(+ user_id=user_id, user_role=LitellmUserRoles.INTERNAL_USER+ )++ # Mock user info+ mock_user_info = LiteLLM_UserTable(+ user_id=user_id,+ teams=[team_id],+ max_budget=1000.0,+ spend=0.0,+ user_email="[email protected]",+ user_role="internal_user",+ )++ # Mock team with user as admin member+ mock_team_member = Member(user_id=user_id, role="admin")+ mock_team = MagicMock(spec=LiteLLM_TeamTable)+ mock_team.team_id = team_id+ mock_team.team_alias = "Test Team"+ mock_team.members_with_roles = [mock_team_member]+ mock_team.model_dump.return_value = {+ "team_id": team_id,+ "team_alias": "Test Team",+ "members_with_roles": [{"user_id": user_id, "role": "admin"}],+ }++ # Setup mocks+ mock_db_client.db.litellm_teamtable.find_many = AsyncMock(+ return_value=[mock_team]+ )++ # Mock get_user_object+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_user_object",+ new_callable=AsyncMock,+ ) as mock_get_user_object:+ mock_get_user_object.return_value = mock_user_info++ # Mock get_daily_activity to capture the api_key parameter+ with patch(+ "litellm.proxy.management_endpoints.team_endpoints.get_daily_activity",+ new_callable=AsyncMock,+ ) as mock_get_daily_activity:+ mock_get_daily_activity.return_value = MagicMock()++ # Call the endpoint+ await get_team_daily_activity(+ team_ids=team_id,+ start_date="2024-01-01",+ end_date="2024-01-02",+ model=None,+ api_key=None,+ page=1,+ page_size=10,+ exclude_team_ids=None,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify get_daily_activity was called WITHOUT API key filtering+ mock_get_daily_activity.assert_called_once()+ call_kwargs = mock_get_daily_activity.call_args[1]+ assert call_kwargs["api_key"] is None+ assert call_kwargs["entity_id"] == [team_id]++ # Verify user's API keys were NOT fetched (since they're admin)+ if hasattr(+ mock_db_client.db.litellm_verificationtoken, "find_many"+ ) and mock_db_client.db.litellm_verificationtoken.find_many.called:+ # If it was called, that's unexpected for admin users+ assert False, "API keys should not be fetched for team admin users"