From 70889f7ceae2ef70e93950625a820d9c3d2ffdbd Mon Sep 17 00:00:00 2001 From: Kuldeep Joshi Date: Mon, 14 Sep 2026 13:49:34 +0530 Subject: [PATCH] fix: review changes fixed --- .../management_endpoints/project_endpoints.py | 34 ++++-- .../test_project_endpoints_prisma.py | 87 +++++++++++++- .../hooks/projects/useProjects.test.ts | 20 ++++ .../(dashboard)/hooks/projects/useProjects.ts | 4 +- .../components/UsagePageView.test.tsx | 112 +++++++++++++++++- .../_components/components/UsagePageView.tsx | 8 +- .../UsageViewSelect/UsageViewSelect.test.tsx | 34 ++++++ .../UsageViewSelect/UsageViewSelect.tsx | 4 +- .../components/view_logs/log_filter_logic.tsx | 5 - .../src/utils/capabilities.test.ts | 24 ++++ .../src/utils/capabilities.ts | 12 +- 11 files changed, 317 insertions(+), 27 deletions(-) diff --git a/enterprise/litellm_enterprise/proxy/management_endpoints/project_endpoints.py b/enterprise/litellm_enterprise/proxy/management_endpoints/project_endpoints.py index 97ab91a46ac..2c4f0db6e39 100644 --- a/enterprise/litellm_enterprise/proxy/management_endpoints/project_endpoints.py +++ b/enterprise/litellm_enterprise/proxy/management_endpoints/project_endpoints.py @@ -1097,6 +1097,7 @@ def _project_daily_activity_error(*, status_code: int, message: str) -> HTTPExce _MAX_PROJECT_DAILY_ACTIVITY_RANGE_DAYS: Final = 400 +_MAX_PROJECT_DAILY_ACTIVITY_PROJECT_COUNT: Final = 50 def _project_daily_activity_date_range_error(start_date: str | None, end_date: str | None) -> str | None: @@ -1120,11 +1121,16 @@ def _project_daily_activity_date_range_error(start_date: str | None, end_date: s def _project_daily_spend_sql(*, project_count: int) -> str: - project_placeholders: Final = ", ".join(f"${i}" for i in range(3, 3 + project_count)) + """ + Joins each requested project_id against the team_id it currently belongs to, so a + project_id reused by a different team after the original project was deleted cannot + pull that team's historical spend into the new project's report. + """ + pairs: Final = ", ".join(f"(${3 + 2 * i}::text, ${4 + 2 * i}::text)" for i in range(project_count)) return f""" SELECT (DATE_TRUNC('day', sl."startTime" AT TIME ZONE 'UTC'))::date::text AS spend_date, - sl.metadata->>'user_api_key_project_id' AS project_id, + scoped.project_id AS project_id, SUM(sl.spend)::float AS spend, SUM(sl.prompt_tokens)::bigint AS prompt_tokens, SUM(sl.completion_tokens)::bigint AS completion_tokens, @@ -1133,11 +1139,13 @@ def _project_daily_spend_sql(*, project_count: int) -> str: COUNT(*) FILTER (WHERE sl.status IS DISTINCT FROM 'failure')::bigint AS successful_requests, COUNT(*) FILTER (WHERE sl.status = 'failure')::bigint AS failed_requests FROM "LiteLLM_SpendLogs" sl + JOIN (VALUES {pairs}) AS scoped(project_id, team_id) + ON sl.metadata->>'user_api_key_project_id' = scoped.project_id + AND sl.team_id IS NOT DISTINCT FROM scoped.team_id WHERE sl."startTime" >= $1::timestamp AND sl."startTime" < $2::timestamp + INTERVAL '1 day' - AND sl.metadata->>'user_api_key_project_id' IN ({project_placeholders}) - GROUP BY spend_date, project_id - ORDER BY spend_date, project_id + GROUP BY spend_date, scoped.project_id + ORDER BY spend_date, scoped.project_id """ @@ -1155,6 +1163,7 @@ class _ProjectDailySpendDbRow(TypedDict): class _ProjectDailyActivityScope(NamedTuple): project_ids: tuple[str, ...] + project_team_ids: tuple[str | None, ...] project_alias_by_id: Mapping[str, str | None] @@ -1170,9 +1179,14 @@ async def _resolve_project_daily_activity_scope( Proxy admins may query any project. Everyone else must be an admin of the project's team, the same permission /project/update enforces. """ - requested: Final = tuple(pid.strip() for pid in project_ids.split(",") if pid.strip()) + requested: Final = tuple(dict.fromkeys(pid.strip() for pid in project_ids.split(",") if pid.strip())) if not requested: - return _ProjectDailyActivityScope(project_ids=(), project_alias_by_id={}) + return _ProjectDailyActivityScope(project_ids=(), project_team_ids=(), project_alias_by_id={}) + if len(requested) > _MAX_PROJECT_DAILY_ACTIVITY_PROJECT_COUNT: + raise _project_daily_activity_error( + status_code=400, + message=f"At most {_MAX_PROJECT_DAILY_ACTIVITY_PROJECT_COUNT} project_ids may be requested at once", + ) projects: Final = await _project_table(prisma_client).find_many(where={"project_id": {"in": list(requested)}}) found_by_id: Final = {p.project_id: p for p in projects} @@ -1197,6 +1211,7 @@ async def _resolve_project_daily_activity_scope( return _ProjectDailyActivityScope( project_ids=requested, + project_team_ids=tuple(found_by_id[pid].team_id for pid in requested), project_alias_by_id={pid: found_by_id[pid].project_alias for pid in requested}, ) @@ -1262,11 +1277,14 @@ async def get_project_daily_activity( if not scope.project_ids: return ProjectDailySpendResponse(start_date=start_date, end_date=end_date, results=()) + project_team_params: Final = tuple( + value for pair in zip(scope.project_ids, scope.project_team_ids) for value in pair + ) rows: Final[Sequence[_ProjectDailySpendDbRow]] = await prisma_client.db.query_raw( _project_daily_spend_sql(project_count=len(scope.project_ids)), start_date, end_date, - *scope.project_ids, + *project_team_params, ) results: Final = tuple( ProjectDailySpendRow( diff --git a/tests/enterprise/litellm_enterprise/proxy/management_endpoints/test_project_endpoints_prisma.py b/tests/enterprise/litellm_enterprise/proxy/management_endpoints/test_project_endpoints_prisma.py index 1f7221fd2dd..8ef0c04fa0f 100644 --- a/tests/enterprise/litellm_enterprise/proxy/management_endpoints/test_project_endpoints_prisma.py +++ b/tests/enterprise/litellm_enterprise/proxy/management_endpoints/test_project_endpoints_prisma.py @@ -1438,10 +1438,11 @@ async def test_get_project_daily_activity_admin_groups_by_day_and_project(monkey ) sql, *params = mock_prisma.db.query_raw.call_args.args - assert params == ["2026-09-01", "2026-09-02", "project-alpha", "project-beta"] + assert params == ["2026-09-01", "2026-09-02", "project-alpha", "team-1", "project-beta", "team-1"] assert 'FROM "LiteLLM_SpendLogs" sl' in sql - assert "sl.metadata->>'user_api_key_project_id' IN ($3, $4)" in sql - assert "GROUP BY spend_date, project_id" in sql + assert "JOIN (VALUES ($3::text, $4::text), ($5::text, $6::text)) AS scoped(project_id, team_id)" in sql + assert "sl.team_id IS NOT DISTINCT FROM scoped.team_id" in sql + assert "GROUP BY spend_date, scoped.project_id" in sql assert response.start_date == "2026-09-01" assert response.end_date == "2026-09-02" @@ -1452,6 +1453,86 @@ async def test_get_project_daily_activity_admin_groups_by_day_and_project(monkey assert (response.results[0].successful_requests, response.results[0].failed_requests) == (2, 1) +@pytest.mark.asyncio +async def test_get_project_daily_activity_dedupes_repeated_project_ids(monkeypatch): + from unittest.mock import AsyncMock, MagicMock + + project = MagicMock(project_id="project-alpha", project_alias="Alpha", team_id="team-1") + + mock_prisma = MagicMock() + mock_prisma.db.litellm_projecttable.find_many = AsyncMock(return_value=[project]) + mock_prisma.db.query_raw = AsyncMock(return_value=[]) + monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True) + monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma) + + admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin") + await get_project_daily_activity( + user_api_key_dict=admin, + project_ids=",".join(["project-alpha"] * 5000), + start_date="2026-09-01", + end_date="2026-09-02", + ) + + mock_prisma.db.litellm_projecttable.find_many.assert_awaited_once_with(where={"project_id": {"in": ["project-alpha"]}}) + sql, *params = mock_prisma.db.query_raw.call_args.args + assert params == ["2026-09-01", "2026-09-02", "project-alpha", "team-1"] + assert "(VALUES ($3::text, $4::text))" in sql + + +@pytest.mark.asyncio +async def test_get_project_daily_activity_rejects_too_many_project_ids(monkeypatch): + from unittest.mock import AsyncMock, MagicMock + + mock_prisma = MagicMock() + mock_prisma.db.litellm_projecttable.find_many = AsyncMock(return_value=[]) + mock_prisma.db.query_raw = AsyncMock(return_value=[]) + monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True) + monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma) + + too_many_ids = ",".join(f"project-{i}" for i in range(51)) + admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin") + with pytest.raises(HTTPException) as exc_info: + await get_project_daily_activity( + user_api_key_dict=admin, + project_ids=too_many_ids, + start_date="2026-09-01", + end_date="2026-09-02", + ) + assert exc_info.value.status_code == 400 + assert "At most 50 project_ids" in str(exc_info.value.detail) + mock_prisma.db.litellm_projecttable.find_many.assert_not_awaited() + mock_prisma.db.query_raw.assert_not_called() + + +@pytest.mark.asyncio +async def test_get_project_daily_activity_scopes_spend_by_team_to_prevent_reused_id_leak(monkeypatch): + """A project_id can be reused by a different team after the original project is deleted. + The query must join on (project_id, team_id) together so a reused id cannot pull in the + prior team's historical spend.""" + from unittest.mock import AsyncMock, MagicMock + + project_alpha = MagicMock(project_id="project-alpha", project_alias="Alpha", team_id="team-1") + project_beta = MagicMock(project_id="project-beta", project_alias="Beta", team_id="team-2") + + mock_prisma = MagicMock() + mock_prisma.db.litellm_projecttable.find_many = AsyncMock(return_value=[project_alpha, project_beta]) + mock_prisma.db.query_raw = AsyncMock(return_value=[]) + monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True) + monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma) + + admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin") + await get_project_daily_activity( + user_api_key_dict=admin, + project_ids="project-alpha,project-beta", + start_date="2026-09-01", + end_date="2026-09-02", + ) + + sql, *params = mock_prisma.db.query_raw.call_args.args + assert params == ["2026-09-01", "2026-09-02", "project-alpha", "team-1", "project-beta", "team-2"] + assert "sl.team_id IS NOT DISTINCT FROM scoped.team_id" in sql + + @pytest.mark.asyncio async def test_get_project_daily_activity_team_admin_can_view_own_project(monkeypatch): from unittest.mock import AsyncMock, MagicMock diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.test.ts index 39d1b28303d..580828f4411 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.test.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.test.ts @@ -129,4 +129,24 @@ describe("useProjects", () => { expect(result.current.isFetched).toBe(false); expect(global.fetch).not.toHaveBeenCalled(); }); + + it("should not fetch when the caller passes enabled=false, even for an eligible role", () => { + (global.fetch as any).mockResolvedValue({ ok: true, json: async () => mockProjects }); + const { result } = renderHook(() => useProjects(false), { wrapper: makeWrapper(queryClient) }); + expect(result.current.isFetched).toBe(false); + expect(global.fetch).not.toHaveBeenCalled(); + }); + + it("should fetch once the caller flips enabled back to true", async () => { + (global.fetch as any).mockResolvedValue({ ok: true, json: async () => mockProjects }); + const { result, rerender } = renderHook(({ enabled }: { enabled: boolean }) => useProjects(enabled), { + wrapper: makeWrapper(queryClient), + initialProps: { enabled: false }, + }); + expect(global.fetch).not.toHaveBeenCalled(); + + rerender({ enabled: true }); + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(global.fetch).toHaveBeenCalled(); + }); }); diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.ts index c240dbb0170..eabc1a70b58 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/projects/useProjects.ts @@ -70,12 +70,12 @@ const fetchProjects = async (accessToken: string): Promise => // ── Hook ───────────────────────────────────────────────────────────────────── -export const useProjects = () => { +export const useProjects = (enabled: boolean = true) => { const { accessToken, userRole } = useAuthorized(); return useQuery({ queryKey: projectKeys.list({}), queryFn: async () => fetchProjects(accessToken!), - enabled: Boolean(accessToken) && projectReaderRoles.includes(userRole!), + enabled: enabled && Boolean(accessToken) && projectReaderRoles.includes(userRole!), }); }; diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx index 7702488f5bf..e026d8feedb 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.test.tsx @@ -1,5 +1,6 @@ import { useAgents } from "@/app/(dashboard)/hooks/agents/useAgents"; import { useCustomers } from "@/app/(dashboard)/hooks/customers/useCustomers"; +import { useProjects } from "@/app/(dashboard)/hooks/projects/useProjects"; import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; import useIsOrgAdmin from "@/app/(dashboard)/hooks/useIsOrgAdmin"; import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser"; @@ -7,7 +8,7 @@ import { useInfiniteUsers } from "@/app/(dashboard)/hooks/users/useUsers"; import { act, fireEvent, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; -import { renderWithProviders } from "@/../tests/test-utils"; +import { renderWithProviders, testQueryClient } from "@/../tests/test-utils"; import type { Organization } from "@/components/networking"; import * as networking from "@/components/networking"; import UsagePage from "./UsagePageView"; @@ -28,6 +29,7 @@ vi.mock("@/components/networking", () => ({ userDailyActivityCall: vi.fn(), userDailyActivityAggregatedCall: vi.fn(), gatewayDailyActivityCall: vi.fn(), + getUiSettings: vi.fn(), tagListCall: vi.fn(), })); @@ -60,14 +62,25 @@ vi.mock("./EntityUsage/SpendByProvider", () => ({ default: () =>
Spend By Provider
, })); +vi.mock("./ProjectUsage/ProjectUsage", () => ({ + default: ({ projectList }: { projectList: unknown }) => ( +
+ Project Usage Panel +
+ ), +})); + vi.mock("./EndpointUsage/EndpointUsage", () => ({ default: () =>
Endpoint Usage
, })); vi.mock("./UsageViewSelect/UsageViewSelect", async () => { const React = await import("react"); - const UsageViewSelect = ({ value, onChange, canViewTagUsage = false }: any) => { + const UsageViewSelect = ({ value, onChange, canViewTagUsage = false, enableProjectsUI = false }: any) => { const tagOption = canViewTagUsage ? React.createElement("option", { value: "tag" }, "Tag Usage") : null; + const projectOption = enableProjectsUI + ? React.createElement("option", { value: "project" }, "Project Usage") + : null; return React.createElement( "select", { @@ -79,6 +92,7 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => { React.createElement("option", { value: "global" }, "Global Usage"), React.createElement("option", { value: "team" }, "Team Usage"), React.createElement("option", { value: "organization" }, "Organization Usage"), + projectOption, React.createElement("option", { value: "customer" }, "Customer Usage"), tagOption, React.createElement("option", { value: "agent" }, "Agent Usage"), @@ -137,6 +151,10 @@ vi.mock("@/app/(dashboard)/hooks/agents/useAgents", () => ({ useAgents: vi.fn(), })); +vi.mock("@/app/(dashboard)/hooks/projects/useProjects", () => ({ + useProjects: vi.fn(), +})); + vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ __esModule: true, default: vi.fn(), @@ -163,6 +181,8 @@ describe("UsagePage", () => { const mockGatewayDailyActivityCall = vi.mocked(networking.gatewayDailyActivityCall); const mockUseCustomers = vi.mocked(useCustomers); const mockUseAgents = vi.mocked(useAgents); + const mockUseProjects = vi.mocked(useProjects); + const mockGetUiSettings = vi.mocked(networking.getUiSettings); const mockUseAuthorized = vi.mocked(useAuthorized); const mockUseCurrentUser = vi.mocked(useCurrentUser); const mockUseInfiniteUsers = vi.mocked(useInfiniteUsers); @@ -353,6 +373,11 @@ describe("UsagePage", () => { }; beforeEach(() => { + // useUISettings is a real react-query hook (not mocked below), and the shared + // testQueryClient never expires a cached query on its own (staleTime/gcTime: + // Infinity, refetchOnMount: false). Without clearing it, one test's + // getUiSettings mock leaks into the next test's render of the same query key. + testQueryClient.clear(); mockUseAuthorized.mockReturnValue({ isLoading: false, isAuthorized: true, @@ -411,6 +436,15 @@ describe("UsagePage", () => { isLoading: false, error: null, } as any); + mockUseProjects.mockReturnValue({ + data: [], + isLoading: false, + error: null, + } as any); + // Left unset (rather than resolved) by default: enable_projects_ui reads + // as off until a test explicitly turns it on, matching a proxy that has + // not enabled the flag. + mockGetUiSettings.mockReturnValue(new Promise(() => {})); }); it("should render and fetch usage data on mount", async () => { @@ -812,6 +846,80 @@ describe("UsagePage", () => { expect(screen.queryByText("Entity Usage")).not.toBeInTheDocument(); }); + describe("project usage", () => { + // A team admin's session role is "Internal User" — the same role a plain + // member carries — so team-admin-ness only shows up in the team's own + // members_with_roles. + const teamAdminProps = { + ...defaultProps, + teams: [ + { + ...defaultProps.teams[0], + members_with_roles: [{ role: "admin", user_id: "user-123" }], + }, + ], + }; + + it("should not fetch the project list while Project Usage UI is disabled", async () => { + renderWithProviders(); + + await waitFor(() => { + expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled(); + }); + + expect(mockUseProjects).toHaveBeenLastCalledWith(false); + }); + + it("should fetch the project list once Project Usage UI is turned on", async () => { + mockGetUiSettings.mockResolvedValue({ field_schema: {}, values: { enable_projects_ui: true } }); + + renderWithProviders(); + + await waitFor(() => { + expect(mockUseProjects).toHaveBeenLastCalledWith(true); + }); + }); + + it("should let a team admin open Project Usage once it is enabled", async () => { + mockGetUiSettings.mockResolvedValue({ field_schema: {}, values: { enable_projects_ui: true } }); + mockUseAuthorized.mockReturnValue(nonAdminSession); + mockUseProjects.mockReturnValue({ + data: [{ project_id: "project-1", project_alias: "Project One" }], + isLoading: false, + error: null, + } as any); + + renderWithProviders(); + + await screen.findByRole("option", { name: "Project Usage" }); + act(() => { + fireEvent.change(screen.getByTestId("usage-view-select"), { target: { value: "project" } }); + }); + + const projectUsage = await screen.findByTestId("project-usage"); + expect(projectUsage).toHaveAttribute( + "data-project-list", + JSON.stringify([{ label: "Project One", value: "project-1" }]), + ); + }); + + // The dropdown's own capability gating (which roles see the Project Usage option + // at all, including a team admin) is covered by UsageViewSelect.test.tsx; this + // checks the composition point specific to this component: nothing should fetch + // the project list for a session that Project Usage was never going to grant. + it("should not fetch the project list for a plain internal user who administers no team", async () => { + mockGetUiSettings.mockResolvedValue({ field_schema: {}, values: { enable_projects_ui: true } }); + mockUseAuthorized.mockReturnValue(nonAdminSession); + + renderWithProviders(); + + await waitFor(() => { + expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled(); + }); + expect(mockUseProjects).toHaveBeenLastCalledWith(false); + }); + }); + describe("admin user selector", () => { // Anchored on the field's own label, so it does not depend on which library draws the control. const userSelectCombobox = (): HTMLElement => { diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx index 85c5f4faf92..ad87b44b4a0 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsagePageView.tsx @@ -27,7 +27,7 @@ import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser"; import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings"; import { hasCapability } from "@/utils/capabilities"; import { formatNumberWithCommas } from "@/utils/dataUtils"; -import { all_admin_roles, internalUserRoles } from "@/utils/roles"; +import { all_admin_roles, internalUserRoles, isUserTeamAdminForAnyTeam } from "@/utils/roles"; import { ActivityMetrics, processActivityData } from "@/components/activity_metrics"; import CloudZeroExportModal from "@/components/cloudzero_export_modal"; import UserDropdown from "@/components/common_components/UserDropdown"; @@ -105,16 +105,17 @@ const UsagePage: React.FC = ({ teams, organizations }) => { // filter reads as loading rather than as a range with no customers. const { data: customers } = useCustomers(); const { data: agentsResponse } = useAgents(); - const { data: projectsResponse } = useProjects(); const { data: currentUser } = useCurrentUser(); const isAdmin = all_admin_roles.includes(userRole || ""); const canViewTagUsage = isAdmin || internalUserRoles.includes(userRole || ""); const isOrgAdmin = useIsOrgAdmin(); + const isTeamAdmin = isUserTeamAdminForAnyTeam(teams, userID || ""); const canViewOrganizationUsage = hasCapability(userRole, "viewOrganizationUsage", isOrgAdmin); const canViewAgentUsage = hasCapability(userRole, "viewAgentUsage"); const { data: uiSettingsData } = useUISettings(); const enableProjectsUI = Boolean(uiSettingsData?.values?.enable_projects_ui); - const canViewProjectUsage = hasCapability(userRole, "viewProjectUsage") && enableProjectsUI; + const canViewProjectUsage = hasCapability(userRole, "viewProjectUsage", isOrgAdmin, isTeamAdmin) && enableProjectsUI; + const { data: projectsResponse } = useProjects(canViewProjectUsage); // For admins: null means global view (all users), a string means filter by that user // For non-admins: always set to their own user ID @@ -489,6 +490,7 @@ const UsagePage: React.FC = ({ teams, organizations }) => { userRole={userRole} canViewTagUsage={canViewTagUsage} isOrgAdmin={isOrgAdmin} + isTeamAdmin={isTeamAdmin} enableProjectsUI={enableProjectsUI} /> diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.test.tsx index be1951abe4f..ce8544ab06d 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.test.tsx @@ -103,6 +103,40 @@ describe("UsageViewSelect", () => { expect(offers(container, optionName)).toBe(expected); }); + // A team admin's session role is also "Internal User" — team-admin-ness lives in the + // team's members_with_roles — so this cannot be told apart from a plain internal user + // by role alone either. Project Usage must open for them without unlocking the other + // admin-only options the org-admin case above already guards. + it.each([ + ["Project Usage", true], + ["Organization Usage", false], + ["Agent Usage (A2A)", false], + ] as const)("should offer %s to a team admin: %s", async (optionName, expected) => { + const user = userEvent.setup(); + const { container } = render( + , + ); + + await openMenu(user); + expect(offers(container, optionName)).toBe(expected); + }); + + it("should hide Project Usage from a team admin when enableProjectsUI is false", async () => { + const user = userEvent.setup(); + const { container } = render( + , + ); + + await openMenu(user); + expect(offers(container, "Project Usage")).toBe(false); + }); + it("should hide Project Usage from an admin when enableProjectsUI is false", async () => { const user = userEvent.setup(); const { container } = render( diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.tsx index 6cf7cfb1140..be06217a4d0 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/UsageViewSelect/UsageViewSelect.tsx @@ -21,6 +21,7 @@ export interface UsageViewSelectProps { userRole: string | null; canViewTagUsage?: boolean; isOrgAdmin?: boolean; + isTeamAdmin?: boolean; enableProjectsUI?: boolean; title?: string; description?: string; @@ -119,6 +120,7 @@ export const UsageViewSelect: React.FC = ({ userRole, canViewTagUsage = false, isOrgAdmin = false, + isTeamAdmin = false, enableProjectsUI = true, title = "Usage View", description = "Select the usage data you want to view", @@ -131,7 +133,7 @@ export const UsageViewSelect: React.FC = ({ return false; } if (option.capability) { - return hasCapability(userRole, option.capability, isOrgAdmin); + return hasCapability(userRole, option.capability, isOrgAdmin, isTeamAdmin); } if (option.value === "tag" && canViewTagUsage) { return true; diff --git a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx index caaaecf5a0f..e2c7df73224 100644 --- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx +++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx @@ -102,11 +102,6 @@ export const getFilterValue = (columnFilters: ColumnFiltersState, columnId: stri return trimmed === "" ? undefined : trimmed; }; -/** - * The Team and Project filter chips carry the id as their filter value (needed for the - * backend query and for re-selecting the right option in the filter drawer), but showing - * that id in the chip is meaningless to a reader. Resolve it back to the alias they picked. - */ export const resolveLogFilterDisplayValue = ( columnId: string, rawValue: string, diff --git a/ui/litellm-dashboard/src/utils/capabilities.test.ts b/ui/litellm-dashboard/src/utils/capabilities.test.ts index ad0b4eda3ce..eb80010c14e 100644 --- a/ui/litellm-dashboard/src/utils/capabilities.test.ts +++ b/ui/litellm-dashboard/src/utils/capabilities.test.ts @@ -92,6 +92,30 @@ describe("hasCapability for organization admins", () => { }); }); +const SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES = "Internal User"; + +describe("hasCapability for team admins", () => { + it.each(NON_ADMIN_ROLES)("grants viewProjectUsage to a team admin whose session role is %s", (role) => { + expect(hasCapability(role, "viewProjectUsage", false, true)).toBe(true); + }); + + it("leaves viewProjectUsage denied when the caller is not a team admin", () => { + expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, "viewProjectUsage", false, false)).toBe(false); + expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, "viewProjectUsage")).toBe(false); + }); + + it.each(ADMIN_ONLY_CAPABILITIES.filter((capability) => capability !== "viewProjectUsage"))( + "leaves %s denied for a team admin whose session role is not otherwise entitled", + (capability) => { + expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, capability, false, true)).toBe(false); + }, + ); + + it("does not let the team-admin allowance reopen the proxy-admin-only viewGlobalSpend gate", () => { + expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, "viewGlobalSpend", false, true)).toBe(false); + }); +}); + describe("hasCapability - viewGlobalSpend", () => { it.each(ADMIN_ROLES)("should grant it to %s", (role) => { expect(hasCapability(role, "viewGlobalSpend")).toBe(true); diff --git a/ui/litellm-dashboard/src/utils/capabilities.ts b/ui/litellm-dashboard/src/utils/capabilities.ts index 5adb88d0f46..dec6cb0d196 100644 --- a/ui/litellm-dashboard/src/utils/capabilities.ts +++ b/ui/litellm-dashboard/src/utils/capabilities.ts @@ -25,12 +25,18 @@ const ORG_ADMIN_CAPABILITIES: ReadonlySet = new Set([ "viewOrganizationUsage", ]); +const TEAM_ADMIN_CAPABILITIES: ReadonlySet = new Set(["viewProjectUsage"]); + export const hasCapability = ( userRole: string | null | undefined, capability: Capability, isOrgAdmin: boolean = false, -): boolean => - (isOrgAdmin && ORG_ADMIN_CAPABILITIES.has(capability)) || - (userRole != null && CAPABILITY_ROLES[capability].includes(userRole)); + isTeamAdmin: boolean = false, +): boolean => { + const grantedViaOrgAdmin = isOrgAdmin && ORG_ADMIN_CAPABILITIES.has(capability); + const grantedViaTeamAdmin = isTeamAdmin && TEAM_ADMIN_CAPABILITIES.has(capability); + const grantedViaRole = userRole != null && CAPABILITY_ROLES[capability].includes(userRole); + return grantedViaOrgAdmin || grantedViaTeamAdmin || grantedViaRole; +}; export const rolesWithCapability = (capability: Capability): string[] => [...CAPABILITY_ROLES[capability]];