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]

fix(ui): gate organization and agent usage views behind capabilities

Yuneng Jiang6a540a1bf848
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx
index 82ca66b10c0..11528117f1e 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import * as networking from "@/components/networking";
import EntityUsage from "./EntityUsage";
@@ -856,6 +856,47 @@ describe("EntityUsage", () => {
expect(logo.getAttribute("src")).toContain("openai_small");
});
+ describe("capability gating", () => {
+ it.each([
+ ["organization", () => mockOrganizationDailyActivityCall, "Organization Spend Overview"],
+ ["agent", () => mockAgentDailyActivityCall, "Agent Spend Overview"],
+ ] as const)("fetches %s activity for an admin but not for an internal user", async (entityType, call, heading) => {
+ render(<EntityUsage {...defaultProps} entityType={entityType} />);
+ await waitFor(() => {
+ expect(call()).toHaveBeenCalled();
+ });
+
+ cleanup();
+ call().mockClear();
+
+ render(<EntityUsage {...defaultProps} entityType={entityType} userRole="Internal User" />);
+ expect(await screen.findByText(heading)).toBeInTheDocument();
+ expect(call()).not.toHaveBeenCalled();
+ });
+
+ it("keeps the team breakdown but drops its agent sub-fetch for an internal user", async () => {
+ render(<EntityUsage {...defaultProps} entityType="team" userRole="Internal User" />);
+
+ await waitFor(() => {
+ expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ });
+ expect(screen.getByText("Team Spend Overview")).toBeInTheDocument();
+
+ expect(mockAgentDailyActivityCall).not.toHaveBeenCalled();
+ expect(screen.queryByText("Agent Activity")).not.toBeInTheDocument();
+ expect(screen.queryByText("Top Agents Driving Spend")).not.toBeInTheDocument();
+ });
+
+ it("keeps the tag breakdown for an internal user", async () => {
+ render(<EntityUsage {...defaultProps} entityType="tag" userRole="Internal User" />);
+
+ await waitFor(() => {
+ expect(mockTagDailyActivityCall).toHaveBeenCalled();
+ });
+ expect(screen.getByText("Tag Spend Overview")).toBeInTheDocument();
+ });
+ });
+
it("renders a letter avatar instead of an img for an unknown provider slug", async () => {
const spendDataUnknownProvider = {
...mockSpendData,
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx
index 4d44791d1a9..5a0f2abf15b 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx
@@ -2,6 +2,7 @@ import useTeams from "@/app/(dashboard)/hooks/useTeams";
import { BarChart, DonutChart } from "@/components/shared/charts";
import { MoneyCell } from "@/components/shared/table_cells";
import { Card as ShadcnCard, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { hasCapability, type Capability } from "@/utils/capabilities";
import { formatNumberWithCommas } from "@/utils/dataUtils";
import {
Card,
@@ -108,7 +109,19 @@ const ENTITY_FETCH_FNS: Record<EntityType, (...args: any[]) => Promise<any>> = {
user: userDailyActivityCall,
};
-const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, entityId, entityList, dateValue }) => {
+const ENTITY_CAPABILITIES: Partial<Record<EntityType, Capability>> = {
+ organization: "viewOrganizationUsage",
+ agent: "viewAgentUsage",
+};
+
+const EntityUsage: React.FC<EntityUsageProps> = ({
+ accessToken,
+ entityType,
+ entityId,
+ entityList,
+ userRole,
+ dateValue,
+}) => {
const { teams } = useTeams();
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [modelViewType, setModelViewType] = useState<ModelViewType>("groups");
@@ -125,7 +138,11 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
}, [entityType, selectedTags]);
const fetchFn = ENTITY_FETCH_FNS[entityType];
- const enabled = !!accessToken && !!startTime && !!endTime;
+ const entityCapability = ENTITY_CAPABILITIES[entityType];
+ const canViewEntity = entityCapability === undefined || hasCapability(userRole, entityCapability);
+ const showAgentBreakdown = entityType === "team" && hasCapability(userRole, "viewAgentUsage");
+ const hasRequestWindow = !!accessToken && !!startTime && !!endTime;
+ const enabled = hasRequestWindow && canViewEntity;
const {
data: spendDataRaw,
@@ -150,7 +167,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
} = usePaginatedDailyActivity({
fetchFn: agentDailyActivityCall,
args: [accessToken, startTime, endTime, null],
- enabled: enabled && entityType === "team",
+ enabled: enabled && showAgentBreakdown,
});
const agentSpendData = agentSpendDataRaw as unknown as EntitySpendData;
@@ -158,7 +175,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
const modelBreakdownKey = modelViewType === "groups" ? "model_groups" : "models";
const modelMetrics = processActivityData(spendData, modelBreakdownKey, teams || []);
const keyMetrics = processActivityData(spendData, "api_keys", teams || []);
- const agentMetrics = entityType === "team" ? processActivityData(agentSpendData, "entities", teams || []) : {};
+ const agentMetrics = showAgentBreakdown ? processActivityData(agentSpendData, "entities", teams || []) : {};
const getTopModels = () => {
const modelSpend: { [key: string]: any } = {};
@@ -621,8 +638,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
</Card>
</Col>
- {/* Top Agents - only for team entity type */}
- {entityType === "team" && (
+ {showAgentBreakdown && (
<Col numColSpan={2}>
<Card>
<Title>Top Agents Driving Spend</Title>
@@ -708,7 +724,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
</>
),
},
- ...(entityType === "team"
+ ...(showAgentBreakdown
? [{ key: "agents", label: "Agent Activity", content: <ActivityMetrics modelMetrics={agentMetrics} /> }]
: []),
{
@@ -757,7 +773,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
}
/>
)}
- {agentIsFetchingMore && entityType === "team" && (
+ {agentIsFetchingMore && showAgentBreakdown && (
<Alert
banner
type="warning"
@@ -781,7 +797,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti
}
/>
)}
- {agentCancelled && entityType === "team" && (
+ {agentCancelled && showAgentBreakdown && (
<Alert
banner
type="info"
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 0ded7d195d0..841f0fda573 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
@@ -502,6 +502,8 @@ describe("UsagePage", () => {
userId: "user-123",
userEmail: "[email protected]",
userRole: "Internal User",
+ userRoleLabel: "Internal User",
+ isViewOnly: false,
premiumUser: true,
disabledPersonalKeyCreation: false,
showSSOBanner: false,
@@ -861,6 +863,29 @@ describe("UsagePage", () => {
});
});
+ // The select hides both views from a non-admin, so this drives the section
+ // gate directly through the mocked select, which always offers every option.
+ it.each(["organization", "agent"])("should not render the %s usage view for an internal user", async (usageView) => {
+ mockUseAuthorized.mockReturnValue(nonAdminSession);
+
+ renderWithProviders(<UsagePage {...defaultProps} organizations={mockOrganizations} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ const usageSelect = screen.getByTestId("usage-view-select");
+ act(() => {
+ fireEvent.change(usageSelect, { target: { value: "team" } });
+ });
+ expect(screen.getAllByText("Entity Usage").length).toBeGreaterThan(0);
+
+ act(() => {
+ fireEvent.change(usageSelect, { target: { value: usageView } });
+ });
+ expect(screen.queryByText("Entity Usage")).not.toBeInTheDocument();
+ });
+
describe("admin user selector", () => {
it("should render user selector for admin users in global view", async () => {
renderWithProviders(<UsagePage {...defaultProps} />);
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 c3645d6371e..494df313ac0 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
@@ -33,6 +33,7 @@ import { useCustomers } from "@/app/(dashboard)/hooks/customers/useCustomers";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser";
import { useInfiniteUsers } from "@/app/(dashboard)/hooks/users/useUsers";
+import { hasCapability } from "@/utils/capabilities";
import { formatNumberWithCommas } from "@/utils/dataUtils";
import { all_admin_roles, internalUserRoles } from "@/utils/roles";
import { ActivityMetrics, processActivityData } from "@/components/activity_metrics";
@@ -109,6 +110,8 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
const { data: currentUser } = useCurrentUser();
const isAdmin = all_admin_roles.includes(userRole || "");
const canViewTagUsage = isAdmin || internalUserRoles.includes(userRole || "");
+ const canViewOrganizationUsage = hasCapability(userRole, "viewOrganizationUsage");
+ const canViewAgentUsage = hasCapability(userRole, "viewAgentUsage");
// Debounced search for user selector
const [userSearchInput, setUserSearchInput] = useState("");
@@ -513,7 +516,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
<UsageViewSelect
value={usageView}
onChange={(value) => setUsageView(value)}
- isAdmin={isAdmin}
+ userRole={userRole}
canViewTagUsage={canViewTagUsage}
/>
<AdvancedDatePicker value={dateValue} onValueChange={handleDateChange} />
@@ -950,7 +953,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
)}
{/* Organization Usage Panel */}
- {usageView === "organization" && (
+ {usageView === "organization" && canViewOrganizationUsage && (
<EntityUsage
accessToken={accessToken}
entityType="organization"
@@ -1033,7 +1036,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
/>
</>
)}
- {usageView === "agent" && (
+ {usageView === "agent" && canViewAgentUsage && (
<EntityUsage
accessToken={accessToken}
entityType="agent"
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 aa9ff921ee1..9bc4bd81302 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
@@ -90,15 +90,16 @@ describe("UsageViewSelect", () => {
});
it("should render", () => {
- render(<UsageViewSelect value="global" onChange={mockOnChange} isAdmin={false} />);
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Internal User" />);
expect(screen.getByText("Usage View")).toBeInTheDocument();
expect(screen.getByText("Select the usage data you want to view")).toBeInTheDocument();
expect(screen.getByRole("combobox")).toBeInTheDocument();
+ expect(screen.getByRole("option", { name: "Your Usage" })).toBeInTheDocument();
});
it("should call onChange when value changes", () => {
- render(<UsageViewSelect value="global" onChange={mockOnChange} isAdmin={true} />);
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Admin" />);
const select = screen.getByRole("combobox");
act(() => {
@@ -109,14 +110,34 @@ describe("UsageViewSelect", () => {
});
it("should show Tag Usage for non-admin users with tag usage permission", () => {
- render(<UsageViewSelect value="global" onChange={mockOnChange} isAdmin={false} canViewTagUsage={true} />);
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Internal User" canViewTagUsage={true} />);
expect(screen.getByRole("option", { name: "Tag Usage" })).toBeInTheDocument();
});
it("should hide Tag Usage for non-admin users without tag usage permission", () => {
- render(<UsageViewSelect value="global" onChange={mockOnChange} isAdmin={false} />);
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Internal User" />);
expect(screen.queryByRole("option", { name: "Tag Usage" })).not.toBeInTheDocument();
});
+
+ it.each(["Organization Usage", "Agent Usage (A2A)"])("should show %s to an admin", (optionName) => {
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Admin" />);
+
+ expect(screen.getByRole("option", { name: optionName })).toBeInTheDocument();
+ });
+
+ // Neither /organization/daily/activity nor /agent/daily/activity admits an
+ // internal user, so the option that fires them must not be selectable.
+ it.each(["Organization Usage", "Agent Usage (A2A)"])("should hide %s from an internal user", (optionName) => {
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Internal User" canViewTagUsage={true} />);
+
+ expect(screen.queryByRole("option", { name: optionName })).not.toBeInTheDocument();
+ });
+
+ it.each(["Team Usage", "Tag Usage"])("should keep %s available to an internal user", (optionName) => {
+ render(<UsageViewSelect value="global" onChange={mockOnChange} userRole="Internal User" canViewTagUsage={true} />);
+
+ expect(screen.getByRole("option", { name: optionName })).toBeInTheDocument();
+ });
});
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 94b483cb539..54c1d5ab7cc 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
@@ -11,6 +11,8 @@ import {
} from "@ant-design/icons";
import { Badge, Select } from "antd";
import React from "react";
+import { hasCapability, type Capability } from "@/utils/capabilities";
+import { all_admin_roles } from "@/utils/roles";
export type UsageOption =
| "global"
| "my-usage"
@@ -24,7 +26,7 @@ export type UsageOption =
export interface UsageViewSelectProps {
value: UsageOption;
onChange: (value: UsageOption) => void;
- isAdmin: boolean;
+ userRole: string | null;
canViewTagUsage?: boolean;
title?: string;
description?: string;
@@ -35,6 +37,7 @@ interface OptionConfig {
label: string;
description: string;
icon: React.ReactNode;
+ capability?: Capability;
adminOnly?: boolean;
showForAdmin?: string;
showForNonAdmin?: string;
@@ -63,12 +66,9 @@ const OPTIONS: OptionConfig[] = [
{
value: "organization",
label: "Organization Usage",
- showForAdmin: "Organization Usage",
- showForNonAdmin: "Your Organization Usage",
- description: "View organization-level usage",
- descriptionForAdmin: "View usage across all organizations",
- descriptionForNonAdmin: "View your organization's usage",
+ description: "View usage across all organizations",
icon: <BankOutlined style={{ fontSize: "16px" }} />,
+ capability: "viewOrganizationUsage",
},
{
value: "team",
@@ -95,7 +95,7 @@ const OPTIONS: OptionConfig[] = [
label: "Agent Usage (A2A)",
description: "View usage by AI agents",
icon: <RobotOutlined style={{ fontSize: "16px" }} />,
- adminOnly: true,
+ capability: "viewAgentUsage",
},
{
value: "user",
@@ -115,14 +115,18 @@ const OPTIONS: OptionConfig[] = [
export const UsageViewSelect: React.FC<UsageViewSelectProps> = ({
value,
onChange,
- isAdmin,
+ userRole,
canViewTagUsage = false,
title = "Usage View",
description = "Select the usage data you want to view",
"data-id": dataId,
}) => {
+ const isAdmin = all_admin_roles.includes(userRole ?? "");
const getFilteredOptions = () => {
return OPTIONS.filter((option) => {
+ if (option.capability) {
+ return hasCapability(userRole, option.capability);
+ }
if (option.value === "tag" && canViewTagUsage) {
return true;
}
diff --git a/ui/litellm-dashboard/src/utils/capabilities.test.ts b/ui/litellm-dashboard/src/utils/capabilities.test.ts
index f48609b0b9d..3f5a8ac81fb 100644
--- a/ui/litellm-dashboard/src/utils/capabilities.test.ts
+++ b/ui/litellm-dashboard/src/utils/capabilities.test.ts
@@ -1,21 +1,31 @@
import { describe, expect, it } from "vitest";
-import { hasCapability, rolesWithCapability } from "./capabilities";
+import { hasCapability, rolesWithCapability, type Capability } from "./capabilities";
+
+const ADMIN_ROLES = ["Admin", "Admin Viewer", "proxy_admin", "proxy_admin_viewer"];
+const NON_ADMIN_ROLES = [
+ "Internal User",
+ "Internal Viewer",
+ "App User",
+ "Org Admin",
+ "Unknown Role",
+ "",
+ null,
+ undefined,
+];
+
+const ADMIN_ONLY_CAPABILITIES: Capability[] = ["viewToolPolicies", "viewOrganizationUsage", "viewAgentUsage"];
describe("hasCapability", () => {
- it.each(["Admin", "Admin Viewer", "proxy_admin", "proxy_admin_viewer"])(
- "should grant viewToolPolicies to %s",
- (role) => {
- expect(hasCapability(role, "viewToolPolicies")).toBe(true);
- },
- );
+ describe.each(ADMIN_ONLY_CAPABILITIES)("%s", (capability) => {
+ it.each(ADMIN_ROLES)("should grant it to %s", (role) => {
+ expect(hasCapability(role, capability)).toBe(true);
+ });
- it.each(["Internal User", "Internal Viewer", "App User", "Org Admin", "Unknown Role", "", null, undefined])(
- "should deny viewToolPolicies to %s",
- (role) => {
- expect(hasCapability(role, "viewToolPolicies")).toBe(false);
- },
- );
+ it.each(NON_ADMIN_ROLES)("should deny it to %s", (role) => {
+ expect(hasCapability(role, capability)).toBe(false);
+ });
+ });
});
describe("rolesWithCapability", () => {
diff --git a/ui/litellm-dashboard/src/utils/capabilities.ts b/ui/litellm-dashboard/src/utils/capabilities.ts
index 77ead2568fb..c4d878b81a5 100644
--- a/ui/litellm-dashboard/src/utils/capabilities.ts
+++ b/ui/litellm-dashboard/src/utils/capabilities.ts
@@ -2,6 +2,8 @@ import { all_admin_roles } from "./roles";
const CAPABILITY_ROLES = {
viewToolPolicies: all_admin_roles,
+ viewOrganizationUsage: all_admin_roles,
+ viewAgentUsage: all_admin_roles,
} as const satisfies Record<string, readonly string[]>;
export type Capability = keyof typeof CAPABILITY_ROLES;