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
fix(rbac): restore admin-viewer read parity for Logs page + settings reads
Yuneng Jiangb1ee9c4fc537
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 92c920ca594..522bb47936d 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -717,20 +717,56 @@ class LiteLLMRoutes(enum.Enum):]# Routes accessible by Admin Viewer (read-only admin access)- admin_viewer_routes = [- "/user/list",- "/user/available_users",- "/user/available_roles",- "/user/daily/activity",- "/team/daily/activity",- "/tag/daily/activity",- "/tag/list",- "/audit",- "/audit/{id}",- "/global/activity",- "/global/activity/model",- "/global/activity/cache_hits",- ] + info_routes+ #+ # Admin Viewer follows a read-parity-with-Proxy-Admin rule: anything Proxy+ # Admin can read/list/get, Admin Viewer can too (no writes, no cost-incurring+ # actions). When extending this list, the only valid exclusions are write+ # endpoints and cost-incurring endpoints (e.g. /chat/completions, the+ # Playground). Pure GET/list/info endpoints belong here.+ admin_viewer_routes = (+ [+ "/user/list",+ "/user/available_users",+ "/user/available_roles",+ "/user/daily/activity",+ "/team/daily/activity",+ "/tag/daily/activity",+ "/tag/list",+ "/audit",+ "/audit/{id}",+ "/global/activity",+ "/global/activity/model",+ "/global/activity/cache_hits",+ # Customer / end-user listing (handlers already gate on+ # PROXY_ADMIN_VIEW_ONLY — the route gate must match).+ "/customer/list",+ "/customer/info",+ # UI Logs page detail drawer (single + session). The list endpoint+ # `/spend/logs/ui` is covered via spend_tracking_routes below.+ "/spend/logs/ui/{logId}",+ "/spend/logs/session/ui",+ # Settings / observability read endpoints exposed in admin-only+ # sidebar groups (Logging & Alerts, Admin Settings, Budgets,+ # Invitations).+ "/callbacks/list",+ "/callbacks/configs",+ "/get/config/callbacks",+ "/alerting/settings",+ "/config/list",+ "/config/field/info",+ "/budget/list",+ "/budget/settings",+ # Model cost map maintenance views (read-only status / source).+ "/schedule/model_cost_map_reload/status",+ "/model/cost_map/source",+ ]+ # Spend tracking reads (/spend/logs, /spend/logs/ui, /spend/keys,+ # /spend/users, /spend/tags, /spend/calculate, /cost/estimate). Admin+ # Viewer can already read /global/spend/* via global_spend_tracking_routes;+ # the per-tenant /spend/* views were the missing peer.+ + spend_tracking_routes+ + info_routes+ )# All routes accesible by an Org Adminorg_admin_allowed_routes = (diff --git a/litellm/proxy/management_endpoints/budget_management_endpoints.py b/litellm/proxy/management_endpoints/budget_management_endpoints.pyindex 90c0d02d1e0..81b133e6c81 100644--- a/litellm/proxy/management_endpoints/budget_management_endpoints.py+++ b/litellm/proxy/management_endpoints/budget_management_endpoints.py@@ -17,6 +17,7 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom litellm.proxy.common_utils.timezone_utils import get_budget_reset_timefrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.management_endpoints.common_utils import _user_has_admin_viewfrom litellm.proxy.utils import jsonify_objectrouter = APIRouter()@@ -238,7 +239,7 @@ async def budget_settings(detail={"error": CommonProxyErrors.db_not_connected_error.value},)- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=400,detail={@@ -305,7 +306,7 @@ async def list_budget(detail={"error": CommonProxyErrors.db_not_connected_error.value},)- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=400,detail={diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 870ea78f17a..6450a16df53 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -358,6 +358,7 @@ from litellm.proxy.management_endpoints.callback_management_endpoints import ()from litellm.proxy.management_endpoints.common_utils import (_user_has_admin_privileges,+ _user_has_admin_view,admin_can_invite_user,)from litellm.proxy.management_endpoints.compliance_endpoints import (@@ -11499,7 +11500,7 @@ async def alerting_settings(detail={"error": CommonProxyErrors.db_not_connected_error.value},)- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=400,detail={@@ -12485,7 +12486,7 @@ async def invitation_info(detail={"error": CommonProxyErrors.db_not_connected_error.value},)- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=400,detail={@@ -12917,7 +12918,7 @@ async def get_config_general_settings(detail={"error": CommonProxyErrors.db_not_connected_error.value},)- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=400,detail={"error": CommonProxyErrors.not_allowed_access.value},@@ -12981,7 +12982,7 @@ async def get_config_list(detail={"error": CommonProxyErrors.db_not_connected_error.value},)- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=400,detail={@@ -13693,8 +13694,8 @@ async def get_model_cost_map_reload_status(Get the status of the scheduled model cost map reload job."""- # Check if user is admin- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ # Read-only status check — admin viewers can read.+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=403,detail=f"Access denied. Admin role required. Current role: {user_api_key_dict.user_role}",@@ -13796,7 +13797,8 @@ async def get_model_cost_map_source(- fallback_reason: human-readable reason why remote failed (null on success)- model_count: number of models in the currently loaded cost map"""- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ # Read-only source info — admin viewers can read.+ if not _user_has_admin_view(user_api_key_dict):raise HTTPException(status_code=403,detail=f"Access denied. Admin role required. Current role: {user_api_key_dict.user_role}",diff --git a/tests/test_litellm/proxy/auth/test_admin_viewer_handler_access.py b/tests/test_litellm/proxy/auth/test_admin_viewer_handler_access.pynew file mode 100644index 00000000000..b0d2595e48c--- /dev/null+++ b/tests/test_litellm/proxy/auth/test_admin_viewer_handler_access.py@@ -0,0 +1,168 @@+"""+Handler-level admin viewer parity tests.++These tests assert that PROXY_ADMIN_VIEW_ONLY callers are NOT blocked at the+handler level for read-only admin endpoints. The route_checks layer is tested+separately in `test_route_checks.py`; here we verify each individual endpoint+function has been updated to use `_user_has_admin_view()` rather than a bare+`user_role != PROXY_ADMIN` check.++The principle (see Admin Viewer role doc): anything Proxy Admin can read,+Admin Viewer can read. No writes, no cost-incurring actions.+"""++import os+import sys+import types+from unittest.mock import AsyncMock, MagicMock++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, os.path.abspath("../../../"))++import litellm.proxy.proxy_server as ps+from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.proxy_server import app+++def _make_admin_viewer_auth() -> UserAPIKeyAuth:+ return UserAPIKeyAuth(+ user_id="viewer_user",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,+ )+++def _override_auth(role: LitellmUserRoles) -> None:+ fake_user = UserAPIKeyAuth(user_id="viewer_user", user_role=role)+ app.dependency_overrides[ps.user_api_key_auth] = lambda: fake_user+++def _clear_overrides() -> None:+ app.dependency_overrides.clear()+++def admin_viewer_client(monkeypatch):+ """TestClient where auth always returns PROXY_ADMIN_VIEW_ONLY + a mocked Prisma."""+ mock_prisma = MagicMock()++ # Common DB tables touched by the read endpoints under test.+ mock_budget_table = MagicMock()+ mock_budget_table.find_many = AsyncMock(return_value=[])+ mock_budget_table.find_first = AsyncMock(return_value=None)++ mock_invitation_table = MagicMock()+ mock_invitation_table.find_unique = AsyncMock(return_value=None)++ mock_config_table = MagicMock()+ mock_config_table.find_first = AsyncMock(return_value=None)++ mock_prisma.db = types.SimpleNamespace(+ litellm_budgettable=mock_budget_table,+ litellm_invitationlink=mock_invitation_table,+ litellm_config=mock_config_table,+ )++ monkeypatch.setattr(ps, "prisma_client", mock_prisma)+ _override_auth(LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY)++ yield TestClient(app)++ _clear_overrides()+++def _assert_not_role_blocked(response) -> None:+ """The endpoint must not return a role-block error.++ Detects both the 400 ``not_allowed_access`` pattern (used by most+ management endpoints) and the 403 ``Admin role required`` pattern+ (used by model cost map endpoints).+ """+ if response.status_code in (400, 401, 403):+ body = response.json()+ detail = body.get("detail", body)+ if isinstance(detail, dict):+ err = detail.get("error", "")+ else:+ err = str(detail)+ err_lower = err.lower()+ role_block_signals = (+ "your role=",+ "not allowed to access",+ "admin role required",+ "admin-only endpoint",+ )+ for signal in role_block_signals:+ assert (+ signal not in err_lower+ ), f"endpoint blocked PROXY_ADMIN_VIEW_ONLY at handler level: {err}"+++def test_budget_list_allows_admin_viewer(admin_viewer_client):+ """`/budget/list` is read-only and must be accessible to Admin Viewer."""+ resp = admin_viewer_client.get("/budget/list")+ _assert_not_role_blocked(resp)+ assert resp.status_code == 200, resp.text+++def test_budget_settings_allows_admin_viewer(admin_viewer_client):+ """`/budget/settings` describes a budget's fields; read-only."""+ resp = admin_viewer_client.get("/budget/settings", params={"budget_id": "b1"})+ _assert_not_role_blocked(resp)+ assert resp.status_code == 200, resp.text+++def test_alerting_settings_allows_admin_viewer(admin_viewer_client):+ """`/alerting/settings` describes alerting params; read-only."""+ resp = admin_viewer_client.get("/alerting/settings")+ _assert_not_role_blocked(resp)+ # Endpoint may 400 for *config* reasons (no proxy config loaded), but it+ # must not 400 because of role.+ assert resp.status_code != 403, resp.text+++def test_get_config_field_info_allows_admin_viewer(admin_viewer_client):+ """`/config/field/info` describes a single general-settings field; read-only."""+ resp = admin_viewer_client.get(+ "/config/field/info", params={"field_name": "alerting"}+ )+ _assert_not_role_blocked(resp)+++def test_get_config_list_allows_admin_viewer(admin_viewer_client):+ """`/config/list` lists configurable params for a config_type; read-only."""+ resp = admin_viewer_client.get(+ "/config/list", params={"config_type": "general_settings"}+ )+ _assert_not_role_blocked(resp)+++def test_get_config_callbacks_allows_admin_viewer(admin_viewer_client):+ """`/get/config/callbacks` lists current callbacks; read-only."""+ resp = admin_viewer_client.get("/get/config/callbacks")+ _assert_not_role_blocked(resp)+++def test_invitation_info_allows_admin_viewer(admin_viewer_client):+ """`/invitation/info` reads a single invitation; read-only.++ The invitation lookup will return 400 because no invitation exists in our+ mock DB — that's fine. We only assert it doesn't hit the role-block path.+ """+ resp = admin_viewer_client.get(+ "/invitation/info", params={"invitation_id": "nonexistent"}+ )+ _assert_not_role_blocked(resp)+++def test_model_cost_map_reload_status_allows_admin_viewer(admin_viewer_client):+ """`/schedule/model_cost_map_reload/status` is read-only operations status."""+ resp = admin_viewer_client.get("/schedule/model_cost_map_reload/status")+ _assert_not_role_blocked(resp)+++def test_model_cost_map_source_allows_admin_viewer(admin_viewer_client):+ """`/model/cost_map/source` reads the configured cost map source URL."""+ resp = admin_viewer_client.get("/model/cost_map/source")+ _assert_not_role_blocked(resp)diff --git a/tests/test_litellm/proxy/auth/test_route_checks.py b/tests/test_litellm/proxy/auth/test_route_checks.pyindex a5d405cfc2d..4c8832dee60 100644--- a/tests/test_litellm/proxy/auth/test_route_checks.py+++ b/tests/test_litellm/proxy/auth/test_route_checks.py@@ -1198,6 +1198,170 @@ def test_proxy_admin_viewer_can_access_audit_logs(route):)+# ── Admin Viewer parity: Logs page endpoints ──────────────────────────────────+#+# The Admin Viewer (PROXY_ADMIN_VIEW_ONLY) role is documented as+# "view all keys, view all spend" and follows a read-parity-with-Proxy-Admin+# rule. The UI Logs page is the most user-visible failure mode: filtering and+# log details break entirely when these routes are blocked at the route_checks+# layer, even though the underlying handlers already gate on PROXY_ADMIN_VIEW_ONLY.+#+# Each route below corresponds to a network call made by the Logs page+# (ui/litellm-dashboard/src/components/view_logs/) — see the comment on each.+ADMIN_VIEWER_LOGS_PAGE_ROUTES = [+ # Main paginated log list — uiSpendLogsCall in log_filter_logic.tsx & index.tsx+ "/spend/logs/ui",+ # Single-log detail drawer — fetched on row click in LogDetailsDrawer+ "/spend/logs/ui/abc-request-id",+ # Multi-call session drawer — sessionSpendLogsCall in LogDetailsDrawer+ "/spend/logs/session/ui",+ # End User filter dropdown — allEndUsersCall in index.tsx+ "/customer/list",+ "/customer/info",+ # Cost estimation — used by some log views+ "/cost/estimate",+ # Public spend logs / spend tracking routes that admin viewer should read+ "/spend/logs",+ "/spend/keys",+ "/spend/users",+ "/spend/tags",+ "/spend/calculate",+]++[email protected]("route", ADMIN_VIEWER_LOGS_PAGE_ROUTES)+def test_proxy_admin_viewer_can_access_logs_page_endpoints(route):+ """+ PROXY_ADMIN_VIEW_ONLY must pass route_checks for every endpoint the UI+ Logs page depends on. Without these, the page renders empty / errors.+ """+ user_obj = LiteLLM_UserTable(+ user_id="viewer_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )+ valid_token = UserAPIKeyAuth(+ user_id="viewer_user",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )+ request = MagicMock(spec=Request)+ request.query_params = {}++ try:+ RouteChecks.non_proxy_admin_allowed_routes_check(+ user_obj=user_obj,+ _user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ route=route,+ request=request,+ valid_token=valid_token,+ request_data={},+ )+ except Exception as e:+ pytest.fail(+ f"proxy_admin_viewer should be able to access {route}. Got error: {str(e)}"+ )++[email protected]("route", ADMIN_VIEWER_LOGS_PAGE_ROUTES)+def test_internal_user_blocked_from_admin_viewer_logs_routes(route):+ """+ The Logs-page route opening above must NOT also widen access for+ INTERNAL_USER. Plain internal users still see only their own logs and+ must be blocked from proxy-wide spend tracking + customer routes.+ """+ user_obj = LiteLLM_UserTable(+ user_id="internal_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.INTERNAL_USER.value,+ )+ valid_token = UserAPIKeyAuth(+ user_id="internal_user",+ user_role=LitellmUserRoles.INTERNAL_USER.value,+ )+ request = MagicMock(spec=Request)+ request.query_params = {}++ # Routes already in `spend_tracking_routes` (which is part of+ # `internal_user_routes`) are intentionally accessible to internal users+ # for their own scoped spend — those handlers enforce per-user filtering.+ # /cost/estimate is similarly per-user. The /customer/* routes are+ # admin-only.+ INTERNAL_USER_BLOCKED_SUBSET = {+ "/customer/list",+ "/customer/info",+ }+ if route not in INTERNAL_USER_BLOCKED_SUBSET:+ return++ with pytest.raises(Exception) as exc_info:+ RouteChecks.non_proxy_admin_allowed_routes_check(+ user_obj=user_obj,+ _user_role=LitellmUserRoles.INTERNAL_USER.value,+ route=route,+ request=request,+ valid_token=valid_token,+ request_data={},+ )+ assert "Only proxy admin" in str(exc_info.value)+++# ── Admin Viewer parity: Settings/observability read endpoints ────────────────+#+# These are GET endpoints accessible to PROXY_ADMIN that the UI exposes to+# admin viewers via sidebar items gated by `all_admin_roles` (which includes+# proxy_admin_viewer). Without these, the Logging & Alerts, Caching, Budgets,+# and Admin Settings pages break for admin viewers.+ADMIN_VIEWER_SETTINGS_ROUTES = [+ # Logging & Alerts page+ "/callbacks/list",+ "/callbacks/configs",+ "/get/config/callbacks",+ "/alerting/settings",+ # Admin Settings / Router Settings pages+ "/config/list",+ "/config/field/info",+ # Budgets page+ "/budget/list",+ "/budget/settings",+ # Model cost map (read-only status / source)+ "/schedule/model_cost_map_reload/status",+ "/model/cost_map/source",+]++[email protected]("route", ADMIN_VIEWER_SETTINGS_ROUTES)+def test_proxy_admin_viewer_can_access_settings_read_endpoints(route):+ """+ PROXY_ADMIN_VIEW_ONLY must pass route_checks for the read-only+ settings/observability endpoints exposed in admin-only sidebar groups.+ """+ user_obj = LiteLLM_UserTable(+ user_id="viewer_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )+ valid_token = UserAPIKeyAuth(+ user_id="viewer_user",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )+ request = MagicMock(spec=Request)+ request.query_params = {}++ try:+ RouteChecks.non_proxy_admin_allowed_routes_check(+ user_obj=user_obj,+ _user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ route=route,+ request=request,+ valid_token=valid_token,+ request_data={},+ )+ except Exception as e:+ pytest.fail(+ f"proxy_admin_viewer should be able to access {route}. Got error: {str(e)}"+ )++class TestModelsRouteExemptFromDisableLLMEndpoints:"""Test that /models and /v1/models are exempt from DISABLE_LLM_API_ENDPOINTS.diff --git a/ui/litellm-dashboard/src/components/leftnav.test.tsx b/ui/litellm-dashboard/src/components/leftnav.test.tsxindex c168ffa21e0..b8f30084127 100644--- a/ui/litellm-dashboard/src/components/leftnav.test.tsx+++ b/ui/litellm-dashboard/src/components/leftnav.test.tsx@@ -5,10 +5,11 @@ import Sidebar from "./leftnav";vi.mock("../utils/roles", () => {return {- all_admin_roles: ["admin"],+ all_admin_roles: ["admin", "admin_viewer"],internalUserRoles: ["internal"],rolesWithWriteAccess: ["admin", "internal"],- isAdminRole: (role: string) => role === "admin",+ rolesAllowedToViewWriteScopedPages: ["admin", "internal", "admin_viewer"],+ isAdminRole: (role: string) => role === "admin" || role === "admin_viewer",isUserTeamAdminForAnyTeam: () => false,};});@@ -135,6 +136,46 @@ describe("Sidebar (leftnav)", () => {expect(duplicates).toHaveLength(0);});+ describe("Admin Viewer parity", () => {+ // Admin Viewer follows a "read parity with Proxy Admin, no writes, no+ // cost-incurring actions" rule. Playground stays hidden (incurs LLM+ // cost); Models + Endpoints and Agents must be visible read-only.+ const adminViewerAuth = {+ userId: "admin-viewer-user-id",+ accessToken: "test-access-token",+ userRole: "admin_viewer",+ token: "test-token",+ userEmail: "[email protected]",+ premiumUser: false,+ disabledPersonalKeyCreation: false,+ showSSOBanner: false,+ };++ it("hides Playground from Admin Viewer (cost-incurring action)", () => {+ mockUseAuthorized.mockReturnValueOnce(adminViewerAuth);+ renderWithProviders(<Sidebar {...defaultProps} />);+ expect(screen.queryByText("Playground")).not.toBeInTheDocument();+ });++ it("shows Models + Endpoints to Admin Viewer (read-only)", () => {+ mockUseAuthorized.mockReturnValueOnce(adminViewerAuth);+ renderWithProviders(<Sidebar {...defaultProps} />);+ expect(screen.getByText("Models + Endpoints")).toBeInTheDocument();+ });++ it("shows Agents to Admin Viewer (read-only)", () => {+ mockUseAuthorized.mockReturnValueOnce(adminViewerAuth);+ renderWithProviders(<Sidebar {...defaultProps} />);+ expect(screen.getByText("Agents")).toBeInTheDocument();+ });++ it("shows Logs to Admin Viewer", () => {+ mockUseAuthorized.mockReturnValueOnce(adminViewerAuth);+ renderWithProviders(<Sidebar {...defaultProps} />);+ expect(screen.getByText("Logs")).toBeInTheDocument();+ });+ });+it("should show Organizations tab for organization admins", () => {mockUseAuthorized.mockReturnValueOnce({userId: "org-admin-user-id",diff --git a/ui/litellm-dashboard/src/components/leftnav.tsx b/ui/litellm-dashboard/src/components/leftnav.tsxindex c340b65496c..029bdc49b5d 100644--- a/ui/litellm-dashboard/src/components/leftnav.tsx+++ b/ui/litellm-dashboard/src/components/leftnav.tsx@@ -31,7 +31,14 @@ import {import type { MenuProps } from "antd";import { ConfigProvider, Layout, Menu } from "antd";import { useMemo } from "react";-import { all_admin_roles, internalUserRoles, isAdminRole, isUserTeamAdminForAnyTeam, rolesWithWriteAccess } from "../utils/roles";+import {+ all_admin_roles,+ internalUserRoles,+ isAdminRole,+ isUserTeamAdminForAnyTeam,+ rolesAllowedToViewWriteScopedPages,+ rolesWithWriteAccess,+} from "../utils/roles";import NewBadge from "./common_components/NewBadge";import type { Organization } from "./networking";import UsageIndicator from "./UsageIndicator";@@ -117,14 +124,16 @@ const menuGroups: MenuGroup[] = [page: "models",label: "Models + Endpoints",icon: <BlockOutlined />,- roles: rolesWithWriteAccess,+ // Admin Viewer can view models read-only (write actions are+ // hidden inside the page); Playground above stays write-only.+ roles: rolesAllowedToViewWriteScopedPages,},{key: "agents",page: "agents",label: "Agents",icon: <RobotOutlined />,- roles: rolesWithWriteAccess,+ roles: rolesAllowedToViewWriteScopedPages,},{key: "mcp-servers",diff --git a/ui/litellm-dashboard/src/components/model_add/credentials.test.tsx b/ui/litellm-dashboard/src/components/model_add/credentials.test.tsxindex 2504b2a9789..6d555621ca8 100644--- a/ui/litellm-dashboard/src/components/model_add/credentials.test.tsx+++ b/ui/litellm-dashboard/src/components/model_add/credentials.test.tsx@@ -30,7 +30,7 @@ const createQueryClient = () =>describe("CredentialsPanel", () => {it("should render", () => {- mockUseAuthorized.mockReturnValue({ accessToken: "test-token" });+ mockUseAuthorized.mockReturnValue({ accessToken: "test-token", userRole: "Admin" });mockUseCredentials.mockReturnValue({data: { credentials: [] },refetch: vi.fn(),@@ -54,7 +54,7 @@ describe("CredentialsPanel", () => {},];- mockUseAuthorized.mockReturnValue({ accessToken: "test-token" });+ mockUseAuthorized.mockReturnValue({ accessToken: "test-token", userRole: "Admin" });mockUseCredentials.mockReturnValue({data: { credentials },refetch: vi.fn(),@@ -70,7 +70,7 @@ describe("CredentialsPanel", () => {});it("should display empty state when no credentials are provided", () => {- mockUseAuthorized.mockReturnValue({ accessToken: "test-token" });+ mockUseAuthorized.mockReturnValue({ accessToken: "test-token", userRole: "Admin" });mockUseCredentials.mockReturnValue({data: { credentials: [] },refetch: vi.fn(),@@ -86,7 +86,7 @@ describe("CredentialsPanel", () => {});it("should open add modal when add button is clicked", async () => {- mockUseAuthorized.mockReturnValue({ accessToken: "test-token" });+ mockUseAuthorized.mockReturnValue({ accessToken: "test-token", userRole: "Admin" });mockUseCredentials.mockReturnValue({data: { credentials: [] },refetch: vi.fn(),@@ -108,4 +108,63 @@ describe("CredentialsPanel", () => {expect(screen.getByText("Add New Credential")).toBeInTheDocument();});});++ describe("Admin Viewer write-action gating", () => {+ // Admin Viewer can VIEW credentials but must not be able to add / edit /+ // delete them. The page shows the credential list read-only.+ const credentials: CredentialItem[] = [+ {+ credential_name: "openai-key",+ credential_values: {},+ credential_info: { custom_llm_provider: "openai" },+ },+ ];++ it("hides the Add Credential button for Admin Viewer", () => {+ mockUseAuthorized.mockReturnValue({+ accessToken: "test-token",+ userRole: "Admin Viewer",+ });+ mockUseCredentials.mockReturnValue({+ data: { credentials },+ refetch: vi.fn(),+ });++ render(+ <QueryClientProvider client={createQueryClient()}>+ <CredentialsPanel uploadProps={DEFAULT_UPLOAD_PROPS} />+ </QueryClientProvider>,+ );++ // Credential row still renders (read parity).+ expect(screen.getByText("openai-key")).toBeInTheDocument();+ // But no Add Credential button (write blocked).+ expect(+ screen.queryByRole("button", { name: /add credential/i }),+ ).not.toBeInTheDocument();+ });++ it("hides Edit / Delete buttons on existing credentials for Admin Viewer", () => {+ mockUseAuthorized.mockReturnValue({+ accessToken: "test-token",+ userRole: "Admin Viewer",+ });+ mockUseCredentials.mockReturnValue({+ data: { credentials },+ refetch: vi.fn(),+ });++ const { container } = render(+ <QueryClientProvider client={createQueryClient()}>+ <CredentialsPanel uploadProps={DEFAULT_UPLOAD_PROPS} />+ </QueryClientProvider>,+ );++ // The Actions cell should be empty (no edit/delete buttons rendered).+ // We rely on the row being visible but containing no `<button>`s in+ // the actions column — easier-to-read assertion: the entire panel+ // contains zero buttons in admin-viewer mode.+ expect(container.querySelectorAll("button").length).toBe(0);+ });+ });});diff --git a/ui/litellm-dashboard/src/components/model_add/credentials.tsx b/ui/litellm-dashboard/src/components/model_add/credentials.tsxindex af3c757955e..e7bf85bbe48 100644--- a/ui/litellm-dashboard/src/components/model_add/credentials.tsx+++ b/ui/litellm-dashboard/src/components/model_add/credentials.tsx@@ -26,12 +26,15 @@ import AddCredentialsTab from "./AddCredentialModal";import EditCredentialsModal from "./EditCredentialModal";import { useCredentials } from "@/app/(dashboard)/hooks/credentials/useCredentials";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";+import { isProxyAdminRole } from "@/utils/roles";interface CredentialsPanelProps {uploadProps: UploadProps;}const CredentialsPanel: React.FC<CredentialsPanelProps> = ({ uploadProps }) => {- const { accessToken } = useAuthorized();+ const { accessToken, userRole } = useAuthorized();+ // Admin Viewer follows the read-parity rule: see credentials, do not modify.+ const canModifyCredentials = isProxyAdminRole(userRole ?? "");const { data: credentialsResponse, refetch: refetchCredentials } = useCredentials();const credentialList = credentialsResponse?.credentials || [];@@ -137,7 +140,9 @@ const CredentialsPanel: React.FC<CredentialsPanelProps> = ({ uploadProps }) => {return (<div className="w-full mx-auto flex-auto overflow-y-auto p-2">- <Button onClick={() => setIsAddModalOpen(true)}>Add Credential</Button>+ {canModifyCredentials && (+ <Button onClick={() => setIsAddModalOpen(true)}>Add Credential</Button>+ )}<div className="flex justify-between items-center mt-4 mb-4"><Text>Configured credentials for different AI providers. Add and manage your API credentials.</Text></div>@@ -166,22 +171,26 @@ const CredentialsPanel: React.FC<CredentialsPanelProps> = ({ uploadProps }) => {{renderProviderBadge((credential.credential_info?.custom_llm_provider as string) || "-")}</TableCell><TableCell>- <Button- icon={PencilAltIcon}- variant="light"- size="sm"- onClick={() => {- setSelectedCredential(credential);- setIsUpdateModalOpen(true);- }}- />- <Button- icon={TrashIcon}- variant="light"- size="sm"- onClick={() => openDeleteModal(credential)}- className="ml-2"- />+ {canModifyCredentials ? (+ <>+ <Button+ icon={PencilAltIcon}+ variant="light"+ size="sm"+ onClick={() => {+ setSelectedCredential(credential);+ setIsUpdateModalOpen(true);+ }}+ />+ <Button+ icon={TrashIcon}+ variant="light"+ size="sm"+ onClick={() => openDeleteModal(credential)}+ className="ml-2"+ />+ </>+ ) : null}</TableCell></TableRow>))diff --git a/ui/litellm-dashboard/src/utils/roles.test.ts b/ui/litellm-dashboard/src/utils/roles.test.tsindex 38343094b94..954a86d4194 100644--- a/ui/litellm-dashboard/src/utils/roles.test.ts+++ b/ui/litellm-dashboard/src/utils/roles.test.ts@@ -1,5 +1,12 @@import { describe, it, expect } from "vitest";-import { isAdminRole, isProxyAdminRole, isUserTeamAdminForAnyTeam, isUserTeamAdminForSingleTeam } from "./roles";+import {+ isAdminRole,+ isProxyAdminRole,+ isUserTeamAdminForAnyTeam,+ isUserTeamAdminForSingleTeam,+ rolesAllowedToViewWriteScopedPages,+ rolesWithWriteAccess,+} from "./roles";import { Team } from "@/components/networking";describe("roles", () => {@@ -144,4 +151,27 @@ describe("roles", () => {expect(isUserTeamAdminForAnyTeam([], "user-1")).toBe(false);});});++ describe("rolesAllowedToViewWriteScopedPages", () => {+ it("includes Admin Viewer (both display and stored forms)", () => {+ // Admin Viewer follows the read-parity rule — they must be able to+ // see Models + Endpoints and Agents read-only.+ expect(rolesAllowedToViewWriteScopedPages).toContain("Admin Viewer");+ expect(rolesAllowedToViewWriteScopedPages).toContain("proxy_admin_viewer");+ });++ it("includes everything in rolesWithWriteAccess (read parity is a superset)", () => {+ for (const role of rolesWithWriteAccess) {+ expect(rolesAllowedToViewWriteScopedPages).toContain(role);+ }+ });++ it("is a strict superset of rolesWithWriteAccess", () => {+ // Admin Viewer is added on top — the new set must be larger than+ // the write-only set, otherwise the constant has no purpose.+ expect(rolesAllowedToViewWriteScopedPages.length).toBeGreaterThan(+ rolesWithWriteAccess.length,+ );+ });+ });});diff --git a/ui/litellm-dashboard/src/utils/roles.ts b/ui/litellm-dashboard/src/utils/roles.tsindex 608a54ae143..11e31fd369c 100644--- a/ui/litellm-dashboard/src/utils/roles.ts+++ b/ui/litellm-dashboard/src/utils/roles.ts@@ -8,6 +8,15 @@ export const all_admin_roles = [...old_admin_roles, ...v2_admin_role_names];export const internalUserRoles = ["Internal User", "Internal Viewer"];export const rolesAllowedToSeeUsage = ["Admin", "Admin Viewer", "Internal User", "Internal Viewer"];export const rolesWithWriteAccess = ["Internal User", "Admin", "proxy_admin"];+// Admin-tier read parity: Admin Viewer sees Models + Endpoints, Agents, and+// other pages whose primary purpose is configuration/management read-only.+// Per the Admin Viewer principle: read parity with Proxy Admin, no writes,+// no cost-incurring actions (Playground stays gated by `rolesWithWriteAccess`).+export const rolesAllowedToViewWriteScopedPages = [+ ...rolesWithWriteAccess,+ "Admin Viewer",+ "proxy_admin_viewer",+];// Helper function to check if a role is in all_admin_rolesexport const isAdminRole = (role: string): boolean => {