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
[Feature] Allow team members to view entire team usage
yuneng-jiang528b21ad1da5
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 09b4952cd84..9efdace4655 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -237,6 +237,9 @@ class KeyManagementRoutes(str, enum.Enum):# list routesKEY_LIST = "/key/list"+ # team usage routes+ TEAM_DAILY_ACTIVITY = "/team/daily/activity"+class LiteLLMRoutes(enum.Enum):openai_route_names = [@@ -505,6 +508,7 @@ class LiteLLMRoutes(enum.Enum):KeyManagementRoutes.KEY_BLOCK.value,KeyManagementRoutes.KEY_UNBLOCK.value,KeyManagementRoutes.KEY_BULK_UPDATE.value,+ KeyManagementRoutes.TEAM_DAILY_ACTIVITY.value,]management_routes = [diff --git a/litellm/proxy/management_endpoints/common_utils.py b/litellm/proxy/management_endpoints/common_utils.pyindex 34a17f6c274..5030f8c258c 100644--- a/litellm/proxy/management_endpoints/common_utils.py+++ b/litellm/proxy/management_endpoints/common_utils.py@@ -37,6 +37,25 @@ def _is_user_team_admin(return False+def _team_member_has_permission(+ user_api_key_dict: UserAPIKeyAuth,+ team_obj: LiteLLM_TeamTable,+ permission: str,+) -> bool:+ """Check if a non-admin team member has a specific permission on a team."""+ if not team_obj.team_member_permissions:+ return False+ if permission not in team_obj.team_member_permissions:+ return False+ for member in team_obj.members_with_roles:+ if (+ member.user_id is not None+ and member.user_id == user_api_key_dict.user_id+ ):+ return True+ return False++async def _user_has_admin_privileges(user_api_key_dict: UserAPIKeyAuth,prisma_client: Optional["PrismaClient"] = None,diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex f5aabdfcedb..80d50f31a17 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -72,6 +72,7 @@ from litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.management_endpoints.common_utils import (_is_user_team_admin,_set_object_metadata_field,+ _team_member_has_permission,_update_metadata_fields,_upsert_budget_and_membership,_user_has_admin_view,@@ -3971,22 +3972,29 @@ async def get_team_daily_activity(t.team_id: {"team_alias": t.team_alias} for t in team_aliases}- # Check if user is team admin for any requested teams+ # Check if user is team admin or has /team/daily/activity permission# If not, filter by user's API keysuser_api_keys: Optional[List[str]] = Noneif not _user_has_admin_view(user_api_key_dict) and team_ids_list and team_aliases:- # Check if user is team admin for any of the teams- is_team_admin_for_any = False+ # Check if user is team admin or has usage view permission for any team+ has_full_team_view = Falsefor team_alias in team_aliases:team_obj = LiteLLM_TeamTable(**team_alias.model_dump())if _is_user_team_admin(user_api_key_dict=user_api_key_dict, team_obj=team_obj):- is_team_admin_for_any = True+ has_full_team_view = True+ break+ if _team_member_has_permission(+ user_api_key_dict=user_api_key_dict,+ team_obj=team_obj,+ permission="/team/daily/activity",+ ):+ has_full_team_view = Truebreak- # If user is not a team admin for any team, filter by their API keys- if not is_team_admin_for_any:+ # If user does not have full team view, filter by their API keys+ if not has_full_team_view:# Get all API keys for this useruser_keys = await prisma_client.db.litellm_verificationtoken.find_many(where={"user_id": user_api_key_dict.user_id}diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.pyindex c4c953b75fb..b6ac974e2cf 100644--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py@@ -5496,6 +5496,190 @@ async def test_get_team_daily_activity_team_admin_sees_all_spend(mock_db_client)assert False, "API keys should not be fetched for team admin users"+async def test_get_team_daily_activity_member_with_permission_sees_all_spend(+ mock_db_client,+):+ """+ Test that non-admin team members with /team/daily/activity permission+ can see all team spend (no API key filtering), same as team admins.+ """+ from litellm.proxy.management_endpoints.team_endpoints import (+ get_team_daily_activity,+ )++ # Create a non-admin user+ user_id = "test_user_with_perm_123"+ team_id = "test_team_789"+ 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 AND /team/daily/activity permission+ 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.team_member_permissions = ["/team/daily/activity"]+ mock_team.model_dump.return_value = {+ "team_id": team_id,+ "team_alias": "Test Team",+ "members_with_roles": [{"user_id": user_id, "role": "user"}],+ "team_member_permissions": ["/team/daily/activity"],+ }++ # 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+ if hasattr(+ mock_db_client.db.litellm_verificationtoken, "find_many"+ ) and mock_db_client.db.litellm_verificationtoken.find_many.called:+ assert (+ False+ ), "API keys should not be fetched for members with /team/daily/activity permission"+++async def test_get_team_daily_activity_member_without_permission_filters_by_keys(+ mock_db_client,+):+ """+ Test that non-admin team members WITHOUT /team/daily/activity permission+ still have their results filtered by their own API keys.+ """+ from litellm.proxy.management_endpoints.team_endpoints import (+ get_team_daily_activity,+ )++ # Create a non-admin user+ user_id = "test_user_no_perm_123"+ team_id = "test_team_789"+ 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 and NO usage permission+ 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.team_member_permissions = ["/key/info"]+ mock_team.model_dump.return_value = {+ "team_id": team_id,+ "team_alias": "Test Team",+ "members_with_roles": [{"user_id": user_id, "role": "user"}],+ "team_member_permissions": ["/key/info"],+ }++ # Mock user's API keys+ user_api_key_1 = MagicMock()+ user_api_key_1.token = "user_key_abc"+ user_api_key_2 = MagicMock()+ user_api_key_2.token = "user_key_def"++ # 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 API key filtering+ mock_get_daily_activity.assert_called_once()+ call_kwargs = mock_get_daily_activity.call_args[1]+ assert call_kwargs["api_key"] == ["user_key_abc", "user_key_def"]+ 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()++@pytest.mark.asyncioasync def test_update_team_with_router_settings(mock_db_client, mock_admin_auth):"""diff --git a/ui/litellm-dashboard/src/components/team/member_permissions.test.tsx b/ui/litellm-dashboard/src/components/team/member_permissions.test.tsxindex cee2b8d587a..10c78331c68 100644--- a/ui/litellm-dashboard/src/components/team/member_permissions.test.tsx+++ b/ui/litellm-dashboard/src/components/team/member_permissions.test.tsx@@ -97,6 +97,20 @@ describe("MemberPermissions", () => {}});+ it("should render team daily activity permission with correct method and description", async () => {+ vi.mocked(networking.getTeamPermissionsCall).mockResolvedValue({+ all_available_permissions: ["/key/generate", "/team/daily/activity"],+ team_member_permissions: [],+ });++ renderWithProviders(<MemberPermissions teamId="team-123" accessToken="token-123" canEditTeam={true} />);++ await waitFor(() => {+ expect(screen.getByText("/team/daily/activity")).toBeInTheDocument();+ expect(screen.getByText("Member can view all team usage data (not just their own)")).toBeInTheDocument();+ });+ });+it("should not show save button when canEditTeam is false", async () => {vi.mocked(networking.getTeamPermissionsCall).mockResolvedValue({all_available_permissions: ["/key/generate", "/key/list"],diff --git a/ui/litellm-dashboard/src/components/team/permission_definitions.test.tsx b/ui/litellm-dashboard/src/components/team/permission_definitions.test.tsxindex 2d8aeabf383..a85ed8353d2 100644--- a/ui/litellm-dashboard/src/components/team/permission_definitions.test.tsx+++ b/ui/litellm-dashboard/src/components/team/permission_definitions.test.tsx@@ -11,6 +11,10 @@ describe("permission_definitions", () => {expect(getMethodForEndpoint("/key/list")).toBe("GET");});+ it("should return GET for activity endpoints", () => {+ expect(getMethodForEndpoint("/team/daily/activity")).toBe("GET");+ });+it("should return POST for other endpoints", () => {expect(getMethodForEndpoint("/key/generate")).toBe("POST");expect(getMethodForEndpoint("/key/update")).toBe("POST");@@ -48,6 +52,14 @@ describe("permission_definitions", () => {expect(result.description).toBe(PERMISSION_DESCRIPTIONS["/key/service-account/generate"]);});+ it("should return correct info for team daily activity permission", () => {+ const result = getPermissionInfo("/team/daily/activity");+ expect(result.method).toBe("GET");+ expect(result.endpoint).toBe("/team/daily/activity");+ expect(result.description).toBe(PERMISSION_DESCRIPTIONS["/team/daily/activity"]);+ expect(result.route).toBe("/team/daily/activity");+ });+it("should return fallback description for unknown permission", () => {const result = getPermissionInfo("/unknown/endpoint");expect(result.method).toBe("POST");@@ -56,4 +68,11 @@ describe("permission_definitions", () => {expect(result.route).toBe("/unknown/endpoint");});});++ describe("PERMISSION_DESCRIPTIONS", () => {+ it("should include team daily activity permission", () => {+ expect(PERMISSION_DESCRIPTIONS["/team/daily/activity"]).toBeDefined();+ expect(PERMISSION_DESCRIPTIONS["/team/daily/activity"]).toContain("team usage");+ });+ });});diff --git a/ui/litellm-dashboard/src/components/team/permission_definitions.tsx b/ui/litellm-dashboard/src/components/team/permission_definitions.tsxindex 6e7bdaa739c..1c1e795d219 100644--- a/ui/litellm-dashboard/src/components/team/permission_definitions.tsx+++ b/ui/litellm-dashboard/src/components/team/permission_definitions.tsx@@ -20,13 +20,15 @@ export const PERMISSION_DESCRIPTIONS: Record<string, string> = {"/key/list": "Member can list virtual keys belonging to this team","/key/block": "Member can block a virtual key belonging to this team","/key/unblock": "Member can unblock a virtual key belonging to this team",+ "/team/daily/activity":+ "Member can view all team usage data (not just their own)",};/*** Determines the HTTP method for a given permission endpoint*/export const getMethodForEndpoint = (endpoint: string): string => {- if (endpoint.includes("/info") || endpoint.includes("/list")) {+ if (endpoint.includes("/info") || endpoint.includes("/list") || endpoint.includes("/activity")) {return "GET";}return "POST";