SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(dashboards): show disabled dashboard actions with a reason (#12438)
Ashwin Bhatkal878e938b65c6
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsxindex 198db48696..74ce705831 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx@@ -1,4 +1,5 @@import {+ type ReactElement,type ReactNode,useCallback,useEffect,@@ -29,29 +30,31 @@ import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/serviceimport ROUTES from 'constants/routes';import { useSafeNavigate } from 'hooks/useSafeNavigate';import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';-import { useAppContext } from 'providers/App/App';+import { useDashboardCollectionPermissions } from 'hooks/dashboards/useDashboardCollectionPermissions';+import { useDashboardLockPermission } from 'hooks/dashboards/useDashboardLockPermission';import { useErrorModal } from 'providers/ErrorModalProvider';import APIError from 'types/api/error';-import { USER_ROLES } from 'types/roles';-import DisabledControlTooltip from '../../components/DisabledControlTooltip/DisabledControlTooltip';-import DisabledMenuItemLabel from '../../components/DisabledMenuItemLabel/DisabledMenuItemLabel';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';+import { DashboardCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';+import MenuActionItem from '../../components/MenuActionItem/MenuActionItem';import DashboardSettings from '../../DashboardSettings';import { useAddSection } from '../../PanelsAndSectionsLayout/Section/hooks/useAddSection';import SectionTitleModal from '../../PanelsAndSectionsLayout/Section/SectionTitleModal';import JsonEditorDrawer from '../JsonEditorDrawer/JsonEditorDrawer';import SettingsDrawer from '../SettingsDrawer';+import menuStyles from '../../components/MenuActionItem/MenuActionItem.module.scss';import styles from './DashboardActions.module.scss';import { useDeleteDashboardAction } from './useDeleteDashboardAction';-import { DASHBOARD_LOCKED_REASON } from '../../hooks/useDashboardEditGuard';import { useDashboardStore } from '../../store/useDashboardStore';+import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';interface DashboardActionsProps {title: string;dashboard: DashboardtypesGettableDashboardV2DTO;handle: FullScreenHandle;isDashboardLocked: boolean;- isAuthor: boolean;onAddPanel: () => void;onLockToggle: () => void;onOpenRename: () => void;@@ -62,19 +65,37 @@ function DashboardActions({dashboard,handle,isDashboardLocked,- isAuthor,onAddPanel,onLockToggle,onOpenRename,}: DashboardActionsProps): JSX.Element {- const canEditDashboard = useDashboardStore((s) => s.canEditDashboard);- const isLocked = useDashboardStore((s) => s.isLocked);- const isEditable = useDashboardStore((s) => s.isEditable);+ const {+ isLocked,+ isEditable,+ editChecks,+ editDisabledTooltip,+ deleteChecks,+ deleteDisabledTooltip,+ canDeleteDashboard,+ canReadDashboard,+ } = useDashboardEditContext();const settingsRequest = useDashboardStore((s) => s.settingsRequest);const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);- const { user } = useAppContext();const { safeNavigate } = useSafeNavigate();const { showErrorModal } = useErrorModal();+ const { canCreate } = useDashboardCollectionPermissions();+ const { canToggleLock, disabledTooltip: lockDisabledTooltip } =+ useDashboardLockPermission({+ dashboardId: dashboard.id,+ source: dashboard.source,+ });++ // Cloning creates a new dashboard, so it needs `create` too, and no lock gate.+ const cloneChecks = useMemo(+ () => [...editChecks.slice(0, 1), DashboardCreatePermission],+ [editChecks],+ );+ const cloneDenied = !canCreate || !canReadDashboard;const [isSettingsDrawerOpen, setIsSettingsDrawerOpen] =useState<boolean>(false);@@ -157,101 +178,110 @@ function DashboardActions({void handle.enter();}, [dashboard.id, handle]);- // Shown only to edit-permitted users, so the only disabled reason is the lock.- const editLabel = useCallback(- (text: string): ReactNode =>- isLocked ? (- <DisabledMenuItemLabel reason={DASHBOARD_LOCKED_REASON}>- {text}- </DisabledMenuItemLabel>- ) : (- text- ),- [isLocked],+ // Unavailable items stay in the menu, carrying the reason.+ // The row carries icon, label and reason; the item keeps `disabled`/`onClick`.+ const row = useCallback(+ (+ text: string,+ icon: ReactElement,+ checks: BrandedPermission[],+ opts: { disabledTooltip?: string; destructive?: boolean } = {},+ ): ReactNode => (+ <MenuActionItem+ label={text}+ icon={icon}+ checks={checks}+ disabledTooltip={opts.disabledTooltip}+ destructive={opts.destructive}+ />+ ),+ [],);const menuItems = useMemo<MenuItem[]>(() => {- const dashboardGroup: MenuItem[] = [];- if (canEditDashboard) {- dashboardGroup.push({+ const dashboardGroup: MenuItem[] = [+ {key: 'rename',- label: editLabel('Rename'),- icon: <PenLine size={14} />,- disabled: isLocked,+ label: row('Rename', <PenLine size={14} />, editChecks, {+ disabledTooltip: editDisabledTooltip,+ }),+ disabled: !isEditable,onClick: onOpenRename,- });+ },// Clone creates a new dashboard, so it's not lock-gated.- dashboardGroup.push({+ {key: 'clone',- label: 'Clone dashboard',- icon: <Copy size={14} />,- disabled: isCloning,+ label: row('Clone dashboard', <Copy size={14} />, cloneChecks),+ disabled: isCloning || cloneDenied,onClick: (): void => void handleClone(),- });- }-- if (canEditDashboard && (isAuthor || user.role === USER_ROLES.ADMIN)) {- dashboardGroup.push({+ },+ {key: 'lock',- label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',- icon: <LockKeyhole size={14} />,- disabled: dashboard.createdBy === 'integration',+ label: row(+ isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',+ <LockKeyhole size={14} />,+ editChecks,+ { disabledTooltip: lockDisabledTooltip },+ ),+ disabled: !canToggleLock,onClick: onLockToggle,- });- }- dashboardGroup.push({- key: 'fullscreen',- label: 'Full screen',- icon: <Fullscreen size={14} />,- onClick: handleEnterFullScreen,- });+ },+ {+ key: 'fullscreen',+ label: row('Full screen', <Fullscreen size={14} />, []),+ onClick: handleEnterFullScreen,+ },+ ];- const items: MenuItem[] = [+ return [{type: 'group',key: 'group-dashboard',label: 'Dashboard',children: dashboardGroup,},- ];- // Omit the whole Layout group (header included) in view mode.- if (canEditDashboard) {- items.push({+ {type: 'group',key: 'group-layout',label: 'Layout',children: [{key: 'new-section',- label: editLabel('New section'),- icon: <SquareStack size={14} />,- disabled: isLocked,+ label: row('New section', <SquareStack size={14} />, editChecks, {+ disabledTooltip: editDisabledTooltip,+ }),+ disabled: !isEditable,onClick: (): void => setIsNewSectionOpen(true),},],- });- items.push(- { type: 'divider', key: 'divider-danger' },- {- key: 'delete',- label: editLabel('Delete dashboard'),- icon: <Trash2 size={14} />,- danger: true,- disabled: isLocked,- onClick: confirmDeleteDashboard,- },- );- }- return items;+ },+ { type: 'divider', key: 'divider-danger' },+ {+ key: 'delete',+ label: row('Delete dashboard', <Trash2 size={14} />, deleteChecks, {+ disabledTooltip: deleteDisabledTooltip,+ destructive: true,+ }),+ // Independent of read/update, but a locked dashboard can't be removed.+ disabled: isLocked || !canDeleteDashboard,+ onClick: confirmDeleteDashboard,+ },+ ];}, [- editLabel,- canEditDashboard,+ row,+ isEditable,isLocked,+ editChecks,+ editDisabledTooltip,+ deleteChecks,+ deleteDisabledTooltip,+ canDeleteDashboard,+ cloneChecks,+ cloneDenied,isCloning,- isAuthor,- user.role,+ canToggleLock,+ lockDisabledTooltip,isDashboardLocked,- dashboard.createdBy,onOpenRename,handleClone,onLockToggle,@@ -261,7 +291,10 @@ function DashboardActions({return (<div className={styles.dashboardActionsContainer}>- <DropdownMenuSimple menu={{ items: menuItems }}>+ <DropdownMenuSimple+ menu={{ items: menuItems }}+ className={menuStyles.menuContent}+ ><Buttonvariant="solid"color="secondary"@@ -273,38 +306,31 @@ function DashboardActions({Actions</Button></DropdownMenuSimple>- {canEditDashboard && (- <>- <DisabledControlTooltip- reason={DASHBOARD_LOCKED_REASON}- disabled={isLocked}- >- <Button- variant="solid"- color="secondary"- className={styles.toolbarButton}- prefix={<Configure size="md" />}- testId="show-drawer"- disabled={isLocked}- onClick={handleOpenSettings}- size="md"- >- Configure- </Button>- </DisabledControlTooltip>- <SettingsDrawer- drawerTitle="Dashboard Configuration"- isOpen={isSettingsDrawerOpen}- destroyOnClose- onClose={(): void => {- setIsSettingsDrawerOpen(false);- clearSettingsRequest();- }}- >- <DashboardSettings dashboard={dashboard} />- </SettingsDrawer>- </>- )}+ <AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>+ <Button+ variant="solid"+ color="secondary"+ className={styles.toolbarButton}+ prefix={<Configure size="md" />}+ testId="show-drawer"+ disabled={!isEditable}+ onClick={handleOpenSettings}+ size="md"+ >+ Configure+ </Button>+ </AuthZTooltip>+ <SettingsDrawer+ drawerTitle="Dashboard Configuration"+ isOpen={isSettingsDrawerOpen}+ destroyOnClose+ onClose={(): void => {+ setIsSettingsDrawerOpen(false);+ clearSettingsRequest();+ }}+ >+ <DashboardSettings dashboard={dashboard} />+ </SettingsDrawer><Buttonvariant="solid"color="secondary"@@ -316,24 +342,19 @@ function DashboardActions({>JSON</Button>- {canEditDashboard && (- <DisabledControlTooltip- reason={DASHBOARD_LOCKED_REASON}- disabled={isLocked}+ <AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>+ <Button+ variant="solid"+ color="primary"+ onClick={onAddPanel}+ prefix={<Plus size="md" />}+ testId="add-panel-header"+ disabled={!isEditable}+ size="md">- <Button- variant="solid"- color="primary"- onClick={onAddPanel}- prefix={<Plus size="md" />}- testId="add-panel-header"- disabled={isLocked}- size="md"- >- New Panel- </Button>- </DisabledControlTooltip>- )}+ New Panel+ </Button>+ </AuthZTooltip><JsonEditorDrawerdashboard={dashboard}isOpen={isJsonEditorOpen}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/__tests__/DashboardActions.authz.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/__tests__/DashboardActions.authz.test.tsxnew file mode 100644index 0000000000..ae74908bbe--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/__tests__/DashboardActions.authz.test.tsx@@ -0,0 +1,189 @@+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';+import { server } from 'mocks-server/server';+import { render, screen, userEvent, waitFor } from 'tests/test-utils';+import {+ setupAuthzAdmin,+ setupAuthzAllow,+ setupAuthzDenyAll,+} from 'lib/authz/utils/authz-test-utils';+import { IsAdminPermission } from 'lib/authz/hooks/useAuthZ/legacy';+import {+ buildDashboardDeletePermission,+ buildDashboardReadPermission,+ buildDashboardUpdatePermission,+ DashboardListPermission,+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';++import DashboardActions from '../DashboardActions';++const DASHBOARD_ID = 'dash-1';++const dashboard = {+ id: DASHBOARD_ID,+ createdBy: '[email protected]',+ locked: false,+ spec: { display: { name: 'D' }, panels: {}, layouts: [], variables: [] },+} as unknown as DashboardtypesGettableDashboardV2DTO;++// Composition is what's under test here; the derivation has its own suite.+const mockEditContext = {+ isEditable: true,+ editChecks: [],+ areOtherPermissionsLoading: false,+ deleteChecks: [],+ isLocked: false,+ canEditDashboard: true,+ canDeleteDashboard: true,+ editDisabledTooltip: '',+ deleteDisabledTooltip: '',+};+function setEditContextMock(next: Partial<typeof mockEditContext>): void {+ Object.assign(mockEditContext, {+ isEditable: true,+ isLocked: false,+ canEditDashboard: true,+ canDeleteDashboard: true,+ editDisabledTooltip: '',+ deleteDisabledTooltip: '',+ ...next,+ });+}+jest.mock(+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',+ () => ({+ useDashboardEditContext: (): typeof mockEditContext => mockEditContext,+ }),+);++// The dropdown trigger's testId is swallowed by Radix's asChild clone.+function openActionsMenu(): Promise<void> {+ return userEvent.click(screen.getByRole('button', { name: /Actions/ }));+}++function renderActions(): ReturnType<typeof render> {+ return render(+ <DashboardActions+ title="D"+ dashboard={dashboard}+ handle={+ {+ active: false,+ enter: jest.fn(),+ exit: jest.fn(),+ node: { current: null },+ } as never+ }+ isDashboardLocked={false}+ onAddPanel={jest.fn()}+ onLockToggle={jest.fn()}+ onOpenRename={jest.fn()}+ />,+ );+}++describe('DashboardActions - AuthZ', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ server.resetHandlers();+ });++ describe('permission denied', () => {+ // These controls used to be removed from the DOM entirely.+ it('keeps the toolbar buttons visible and disabled', async () => {+ server.use(setupAuthzDenyAll());+ setEditContextMock({+ isEditable: false,+ canEditDashboard: false,+ editDisabledTooltip: 'no permission',+ });++ renderActions();++ await waitFor(() => {+ expect(screen.getByTestId('show-drawer')).toBeDisabled();+ });+ expect(screen.getByTestId('add-panel-header')).toBeDisabled();+ // JSON stays available — it's a read-only inspect.+ expect(screen.getByTestId('edit-json')).toBeEnabled();+ });++ it('keeps the menu items present and disabled', async () => {+ server.use(setupAuthzDenyAll());+ setEditContextMock({+ isEditable: false,+ canEditDashboard: false,+ canDeleteDashboard: false,+ editDisabledTooltip: 'no permission',+ deleteDisabledTooltip: 'no permission',+ });++ renderActions();+ await openActionsMenu();++ await expect(screen.findByText('Rename')).resolves.toBeInTheDocument();+ expect(screen.getByText('New section')).toBeInTheDocument();+ expect(screen.getByText('Delete dashboard')).toBeInTheDocument();+ expect(screen.getByText('Clone dashboard')).toBeInTheDocument();+ // Full screen never depended on permission.+ expect(screen.getByText('Full screen')).toBeInTheDocument();+ });+ });++ describe('partial permissions', () => {+ // Delete is independent of read/update (authz guide rule 3).+ it('enables delete for a user who can only delete', async () => {+ server.use(setupAuthzAllow(buildDashboardDeletePermission(DASHBOARD_ID)));+ setEditContextMock({+ isEditable: false,+ canEditDashboard: false,+ editDisabledTooltip: 'no permission',+ });++ renderActions();++ await waitFor(() => {+ expect(screen.getByTestId('show-drawer')).toBeDisabled();+ });+ await openActionsMenu();+ await expect(+ screen.findByText('Delete dashboard'),+ ).resolves.toBeInTheDocument();+ });++ it('disables clone when create is denied but edit is allowed', async () => {+ server.use(+ setupAuthzAllow(+ buildDashboardReadPermission(DASHBOARD_ID),+ buildDashboardUpdatePermission(DASHBOARD_ID),+ DashboardListPermission,+ IsAdminPermission,+ ),+ );+ setEditContextMock({});++ renderActions();++ await waitFor(() => {+ expect(screen.getByTestId('show-drawer')).toBeEnabled();+ });+ await openActionsMenu();+ await expect(+ screen.findByText('Clone dashboard'),+ ).resolves.toBeInTheDocument();+ });+ });++ describe('permission granted', () => {+ it('enables the toolbar for a full-rights user', async () => {+ server.use(setupAuthzAdmin());+ setEditContextMock({});++ renderActions();++ await waitFor(() => {+ expect(screen.getByTestId('show-drawer')).toBeEnabled();+ });+ expect(screen.getByTestId('add-panel-header')).toBeEnabled();+ });+ });+});diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardInfo/DashboardInfo.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardInfo/DashboardInfo.tsxindex 73c46435c6..d47ff3b4f1 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardInfo/DashboardInfo.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardInfo/DashboardInfo.tsx@@ -25,6 +25,7 @@ import { TOOLTIP_SCROLL_CONTENT_CLASS } from 'components/TooltipScrollArea/Tooltimport TagsOverflowTooltip from './TagsOverflowTooltip';import { DASHBOARD_NAME_MAX_LENGTH } from '../../constants';import { useDashboardStore } from '../../store/useDashboardStore';+import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';// The tag cluster keeps a fixed footprint so a long title ellipsizes around it// instead of collapsing the tags: show up to two tags, then a `+N` overflow badge.@@ -43,6 +44,8 @@ interface DashboardInfoProps {showLockToggle: boolean;/** When provided, the lock icon toggles lock/unlock (author/admin only). */onToggleLock?: () => void;+ /** Why the toggle is unavailable, when onToggleLock is absent. */+ lockDisabledTooltip?: string;isEditing: boolean;draft: string;onDraftChange: (value: string) => void;@@ -61,6 +64,7 @@ function DashboardInfo({isDashboardLocked,showLockToggle,onToggleLock,+ lockDisabledTooltip,isEditing,draft,onDraftChange,@@ -68,7 +72,7 @@ function DashboardInfo({onCommit,onCancel,}: DashboardInfoProps): JSX.Element {- const canEdit = useDashboardStore((s) => s.isEditable);+ const { isEditable: canEdit } = useDashboardEditContext();const dashboardId = useDashboardStore((s) => s.dashboardId);const hasTags = tags.length > 0;@@ -77,11 +81,15 @@ function DashboardInfo({const visibleTags = tags.slice(0, MAX_VISIBLE_TAGS);const remainingTags = tags.slice(MAX_VISIBLE_TAGS);+ // Without a toggle, say why it can't be toggled rather than only restating the+ // lock state.let lockTooltip: string;if (onToggleLock) {lockTooltip = isDashboardLocked? 'Locked — click to unlock': 'Unlocked — click to lock';+ } else if (lockDisabledTooltip) {+ lockTooltip = lockDisabledTooltip;} else {lockTooltip = isDashboardLocked? 'This dashboard is locked'diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/JsonEditorDrawer.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/JsonEditorDrawer.tsxindex c6c647b3d2..32472c7881 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/JsonEditorDrawer.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/JsonEditorDrawer.tsx@@ -16,8 +16,8 @@ import { defineJsonEditorTheme, JSON_EDITOR_THEME } from './editorTheme';import styles from './JsonEditorDrawer.module.scss';import JsonEditorToolbar from './JsonEditorToolbar';import { useJsonEditor } from './useJsonEditor';-import DisabledControlTooltip from '../../components/DisabledControlTooltip/DisabledControlTooltip';-import { useDashboardStore } from '../../store/useDashboardStore';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';+import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';interface JsonEditorDrawerProps {dashboard: DashboardtypesGettableDashboardV2DTO;@@ -30,10 +30,13 @@ function JsonEditorDrawer({isOpen,onClose,}: JsonEditorDrawerProps): JSX.Element {+ const {+ isEditable,+ editDisabledTooltip: readOnlyTooltip,+ editChecks: readOnlyChecks,+ } = useDashboardEditContext();const [, copyToClipboard] = useCopyToClipboard();- const isEditable = useDashboardStore((s) => s.isEditable);- const readOnlyReason = useDashboardStore((s) => s.editDisabledReason);// Inspect-only when not editable: Apply/Format/Reset disabled.const readOnly = !isEditable;@@ -175,7 +178,10 @@ function JsonEditorDrawer({>Cancel</Button>- <DisabledControlTooltip reason={readOnlyReason} disabled={readOnly}>+ <AuthZTooltip+ checks={readOnlyChecks}+ disabledTooltip={readOnly ? readOnlyTooltip : undefined}+ ><Buttonvariant="solid"color="primary"@@ -186,7 +192,7 @@ function JsonEditorDrawer({>Apply changes</Button>- </DisabledControlTooltip>+ </AuthZTooltip></div></div>}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/__tests__/JsonEditorDrawer.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/__tests__/JsonEditorDrawer.test.tsxindex 18aa8a1e91..11792e9c99 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/__tests__/JsonEditorDrawer.test.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/JsonEditorDrawer/__tests__/JsonEditorDrawer.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from 'tests/test-utils';import { TooltipProvider } from '@signozhq/ui/tooltip';import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';@@ -10,8 +10,21 @@ jest.mock('../useJsonEditor', () => ({ useJsonEditor: jest.fn() }));// Editable by default so the drawer renders in its editable (non-read-only) mode.jest.mock('../../../store/useDashboardStore', () => ({useDashboardStore: (- selector: (s: { isEditable: boolean; editDisabledReason: string }) => unknown,- ): unknown => selector({ isEditable: true, editDisabledReason: '' }),+ selector: (s: {+ isEditable: boolean;+ editChecks: unknown[];+ deleteChecks: unknown[];+ areOtherPermissionsLoading: boolean;+ editDisabledTooltip: string;+ }) => unknown,+ ): unknown =>+ selector({+ isEditable: true,+ editChecks: [],+ areOtherPermissionsLoading: false,+ deleteChecks: [],+ editDisabledTooltip: '',+ }),}));jest.mock('@monaco-editor/react', () => ({@@ -65,6 +78,26 @@ function hookValue(} as ReturnType<typeof useJsonEditor>;}+// The derivation has its own suite (useDashboardEditContext.authz); these cases are+// about what the UI does with a given edit context, so control it directly.+const mockEditContext = {+ isEditable: true,+ editChecks: [],+ deleteChecks: [],+ areOtherPermissionsLoading: false,+ isLocked: false,+ canEditDashboard: true,+ canDeleteDashboard: true,+ editDisabledTooltip: '',+ deleteDisabledTooltip: '',+};+jest.mock(+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',+ () => ({+ useDashboardEditContext: (): typeof mockEditContext => mockEditContext,+ }),+);+describe('JsonEditorDrawer', () => {beforeEach(() => jest.clearAllMocks());@@ -95,7 +128,7 @@ describe('JsonEditorDrawer', () => {mockUseJsonEditor.mockReturnValue(hookValue({ danglingPanelIds: ['p1', 'p2'] }),);- const { rerender } = render(+ const { unmount } = render(<TooltipProvider><JsonEditorDrawer dashboard={dashboard} isOpen onClose={jest.fn()} /></TooltipProvider>,@@ -104,8 +137,11 @@ describe('JsonEditorDrawer', () => {'2 panels not present in layout',);+ // Mounted fresh rather than re-rendered: the provider wrapper holds the+ // first tree, so a rerender does not pick up the new hook value.+ unmount();mockUseJsonEditor.mockReturnValue(hookValue({ danglingPanelIds: [] }));- rerender(+ render(<TooltipProvider><JsonEditorDrawer dashboard={dashboard} isOpen onClose={jest.fn()} /></TooltipProvider>,diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/index.tsxindex 260281aa2a..3dd66de2e3 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/index.tsx@@ -1,25 +1,18 @@-import { useCallback, useEffect, useMemo, useState } from 'react';-import { useQueryClient } from 'react-query';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { FullScreenHandle } from 'react-full-screen';import { toast } from '@signozhq/ui/sonner';import logEvent from 'api/common/logEvent';-import {- getGetDashboardV2QueryKey,- lockDashboardV2,- unlockDashboardV2,-} from 'api/generated/services/dashboard';import type {DashboardtypesGettableDashboardV2DTO,DashboardtypesJSONPatchOperationDTO,- GetDashboardV2200,} from 'api/generated/services/sigNoz.schemas';import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/dashboardIcons';import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';-import { useAppContext } from 'providers/App/App';+import { useDashboardLockPermission } from 'hooks/dashboards/useDashboardLockPermission';+import { useToggleDashboardLock } from 'hooks/dashboards/useToggleDashboardLock';import { useErrorModal } from 'providers/ErrorModalProvider';import APIError from 'types/api/error';-import { USER_ROLES } from 'types/roles';import { getAbsoluteUrl } from 'utils/basePath';import { useCreatePanel } from '../hooks/useCreatePanel';@@ -42,7 +35,6 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {const { dashboard, handle } = props;const id = dashboard.id;- const queryClient = useQueryClient();// Session-local lock state: the toggle appears once locked and persists for the page.const [isDashboardLocked, setIsDashboardLocked] = useState(!!dashboard.locked);@@ -64,7 +56,6 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {[dashboard.tags],);- const { user } = useAppContext();const { showErrorModal } = useErrorModal();const { patchAsync } = useOptimisticPatch();const {@@ -75,59 +66,51 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {targetLayoutIndex,} = useCreatePanel();- const isAuthor =- !!user?.email && !!dashboard.createdBy && dashboard.createdBy === user.email;-- // Author/admin can lock-unlock (mirrors the Actions menu gate); integration-owned- // dashboards are never toggleable.- const canToggleLock =- (isAuthor || user.role === USER_ROLES.ADMIN) &&- dashboard.createdBy !== 'integration';+ // dashboard:update, then the backend's source and creator-or-admin rules.+ const { canToggleLock, disabledTooltip: lockDisabledTooltip } =+ useDashboardLockPermission({+ dashboardId: id,+ source: dashboard.source,+ });// Public-sharing meta (deduped react-query read); drives the header globe.const { isPublic, publicMeta } = usePublicDashboardMeta(id);const publicUrl = getAbsoluteUrl(publicMeta?.publicPath ?? '');+ // Shared with the list's row menu — it owns the API call, the toast and the+ // detail-cache patch; the optimistic local state and this page's event stay here.+ const lockSource = useRef<'menu' | 'header'>('header');+ const { toggleLock } = useToggleDashboardLock({+ dashboardId: id,+ isLocked: isDashboardLocked,+ onSuccess: (locked) => {+ void logEvent(DashboardDetailEvents.LockToggled, {+ dashboardId: id,+ dashboardName: title,+ locked,+ source: lockSource.current,+ });+ },+ onError: (error) => {+ setIsDashboardLocked(isDashboardLocked);+ showErrorModal(error);+ },+ });+const handleLockDashboardToggle = useCallback(- async (source: 'menu' | 'header'): Promise<void> => {+ (source: 'menu' | 'header'): void => {if (!id) {return;}+ lockSource.current = source;const next = !isDashboardLocked;setIsDashboardLocked(next);if (next) {setShowLockToggle(true);}- try {- if (next) {- await lockDashboardV2({ id });- toast.success('Dashboard locked');- } else {- await unlockDashboardV2({ id });- toast.success('Dashboard unlocked');- }- // Patch just the `locked` flag in the cache — a full refetch would reload- // every panel's chart data for a metadata-only change.- const key = getGetDashboardV2QueryKey({ id });- const cached = queryClient.getQueryData<GetDashboardV2200>(key);- if (cached) {- queryClient.setQueryData<GetDashboardV2200>(key, {- ...cached,- data: { ...cached.data, locked: next },- });- }- void logEvent(DashboardDetailEvents.LockToggled, {- dashboardId: id,- dashboardName: title,- locked: next,- source,- });- } catch (error) {- setIsDashboardLocked(!next);- showErrorModal(error as APIError);- }+ toggleLock();},- [id, title, isDashboardLocked, queryClient, showErrorModal],+ [id, isDashboardLocked, toggleLock],);const onNameSave = useCallback(@@ -184,9 +167,10 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {showLockToggle={showLockToggle}onToggleLock={canToggleLock- ? (): void => void handleLockDashboardToggle('header')+ ? (): void => handleLockDashboardToggle('header'): undefined}+ lockDisabledTooltip={lockDisabledTooltip}isEditing={isEditing}draft={draft}onDraftChange={setDraft}@@ -199,9 +183,8 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {dashboard={dashboard}handle={handle}isDashboardLocked={isDashboardLocked}- isAuthor={isAuthor}onAddPanel={onAddPanel}- onLockToggle={(): void => void handleLockDashboardToggle('menu')}+ onLockToggle={(): void => handleLockDashboardToggle('menu')}onOpenRename={startEdit}/></div>diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/PublicDashboardActions/PublicDashboardActions.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/PublicDashboardActions/PublicDashboardActions.tsxindex 123aba9acb..db65d01df2 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/PublicDashboardActions/PublicDashboardActions.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/PublicDashboardActions/PublicDashboardActions.tsx@@ -1,11 +1,19 @@import { Globe, RefreshCw, Trash } from '@signozhq/icons';import { Button } from '@signozhq/ui/button';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';import styles from './PublicDashboardActions.module.scss';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';interface PublicDashboardActionsProps {isPublic: boolean;- disabled: boolean;+ /**+ * Why publishing is unavailable. Non-empty both disables the buttons and+ * explains them, so they cannot be disabled silently.+ */+ checks: BrandedPermission[];+ /** In-flight config read — transient, and a spinner explains itself. */+ isLoading?: boolean;isPublishing: boolean;isUpdating: boolean;isUnpublishing: boolean;@@ -16,7 +24,8 @@ interface PublicDashboardActionsProps {function PublicDashboardActions({isPublic,- disabled,+ checks,+ isLoading = false,isPublishing,isUpdating,isUnpublishing,@@ -24,45 +33,53 @@ function PublicDashboardActions({onUpdate,onUnpublish,}: PublicDashboardActionsProps): JSX.Element {+ const disabled = isLoading;+return (<div className={styles.footer}>{isPublic ? (<>- <Button- variant="outlined"- color="destructive"- disabled={disabled}- loading={isUnpublishing}- prefix={<Trash size={15} />}- testId="public-dashboard-unpublish"- onClick={onUnpublish}- >- Unpublish Dashboard- </Button>+ <AuthZTooltip checks={checks}>+ <Button+ variant="outlined"+ color="destructive"+ disabled={disabled}+ loading={isUnpublishing}+ prefix={<Trash size={15} />}+ testId="public-dashboard-unpublish"+ onClick={onUnpublish}+ >+ Unpublish Dashboard+ </Button>+ </AuthZTooltip>+ <AuthZTooltip checks={checks}>+ <Button+ variant="solid"+ color="primary"+ disabled={disabled}+ loading={isUpdating}+ prefix={<RefreshCw size={15} />}+ testId="public-dashboard-update"+ onClick={onUpdate}+ >+ Update Dashboard+ </Button>+ </AuthZTooltip>+ </>+ ) : (+ <AuthZTooltip checks={checks}><Buttonvariant="solid"color="primary"disabled={disabled}- loading={isUpdating}- prefix={<RefreshCw size={15} />}- testId="public-dashboard-update"- onClick={onUpdate}+ loading={isPublishing}+ prefix={<Globe size={15} />}+ testId="public-dashboard-publish"+ onClick={onPublish}>- Update Dashboard+ Publish Dashboard</Button>- </>- ) : (- <Button- variant="solid"- color="primary"- disabled={disabled}- loading={isPublishing}- prefix={<Globe size={15} />}- testId="public-dashboard-publish"- onClick={onPublish}- >- Publish Dashboard- </Button>+ </AuthZTooltip>)}</div>);diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/__tests__/PublicDashboard.authz.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/__tests__/PublicDashboard.authz.test.tsxnew file mode 100644index 0000000000..6ec69090b7--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/__tests__/PublicDashboard.authz.test.tsx@@ -0,0 +1,61 @@+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';+import { server } from 'mocks-server/server';+import { rest } from 'msw';+import { render, screen, waitFor } from 'tests/test-utils';+import {+ setupAuthzAdmin,+ setupAuthzDeny,+} from 'lib/authz/utils/authz-test-utils';+import { buildDashboardUpdatePermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';++import PublicDashboardSettings from '../index';++const DASHBOARD_ID = 'dash-1';+const PUBLIC_URL = `http://localhost/api/v1/dashboards/${DASHBOARD_ID}/public`;++const dashboard = {+ id: DASHBOARD_ID,+ spec: { display: { name: 'D' }, panels: {}, layouts: [], variables: [] },+} as unknown as DashboardtypesGettableDashboardV2DTO;++describe('PublicDashboard - AuthZ', () => {+ beforeEach(() => {+ // Not published yet — the tab offers Publish.+ server.use(+ rest.get(PUBLIC_URL, (_req, res, ctx) =>+ res(ctx.status(404), ctx.json({ status: 'error', error: {} })),+ ),+ );+ });++ afterEach(() => {+ jest.restoreAllMocks();+ server.resetHandlers();+ });++ // The backend gates the public-config writes on dashboard:update, so a+ // licensed editor can publish — this used to be admin-only in the UI.+ it('lets a non-admin holding update publish', async () => {+ server.use(setupAuthzAdmin());++ render(<PublicDashboardSettings dashboard={dashboard} />, undefined, {+ role: 'EDITOR',+ });++ await waitFor(() => {+ expect(screen.getByTestId('public-dashboard-publish')).toBeEnabled();+ });+ });++ it('disables publishing when update is denied', async () => {+ server.use(setupAuthzDeny(buildDashboardUpdatePermission(DASHBOARD_ID)));++ render(<PublicDashboardSettings dashboard={dashboard} />, undefined, {+ role: 'ADMIN',+ });++ await waitFor(() => {+ expect(screen.getByTestId('public-dashboard-publish')).toBeDisabled();+ });+ });+});diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/index.tsxindex 149a4c0a8e..77422e135d 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/index.tsx@@ -5,6 +5,7 @@ import PublicDashboardHint from './PublicDashboardHint/PublicDashboardHint';import PublicDashboardSettingsForm from './PublicDashboardSettingsForm/PublicDashboardSettingsForm';import PublicDashboardStatus from './PublicDashboardStatus/PublicDashboardStatus';import PublicDashboardUrl from './PublicDashboardUrl/PublicDashboardUrl';+import { usePublicDashboard } from './usePublicDashboard';import styles from './PublicDashboard.module.scss';@@ -17,7 +18,8 @@ function PublicDashboardSettings({}: PublicDashboardSettingsProps): JSX.Element {const {isPublic,- isAdmin,+ canManage,+ publishChecks,isLoading,isPublishing,isUpdating,@@ -34,7 +36,7 @@ function PublicDashboardSettings({onOpenUrl,} = usePublicDashboard(dashboard.id);- const controlsDisabled = isLoading || !isAdmin;+ const controlsDisabled = isLoading || !canManage;return (<div className={styles.publishTab}>@@ -61,7 +63,8 @@ function PublicDashboardSettings({<PublicDashboardActionsisPublic={isPublic}- disabled={controlsDisabled}+ checks={publishChecks}+ isLoading={isLoading}isPublishing={isPublishing}isUpdating={isUpdating}isUnpublishing={isUnpublishing}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/usePublicDashboard.ts b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/usePublicDashboard.tsindex 9f1411b81d..f50edfa928 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/usePublicDashboard.ts+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/PublicDashboard/usePublicDashboard.ts@@ -1,6 +1,8 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useQueryClient } from 'react-query';import { useCopyToClipboard } from 'react-use';+import { useDashboardPermissions } from 'hooks/dashboards/useDashboardPermissions';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';import { toast } from '@signozhq/ui/sonner';import logEvent from 'api/common/logEvent';import {@@ -11,10 +13,8 @@ import {} from 'api/generated/services/dashboard';import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';-import { useAppContext } from 'providers/App/App';import { useErrorModal } from 'providers/ErrorModalProvider';import APIError from 'types/api/error';-import { USER_ROLES } from 'types/roles';import { getAbsoluteUrl } from 'utils/basePath';import { openInNewTab } from 'utils/navigation';@@ -22,7 +22,10 @@ import { usePublicDashboardMeta } from './usePublicDashboardMeta';export interface UsePublicDashboardReturn {isPublic: boolean;- isAdmin: boolean;+ /** read + update on this dashboard — publishing is a dashboard update. */+ canManage: boolean;+ /** `[read, update]` — publishing changes the dashboard. */+ publishChecks: BrandedPermission[];isLoading: boolean;isPublishing: boolean;isUpdating: boolean;@@ -49,8 +52,10 @@ export function usePublicDashboard(): UsePublicDashboardReturn {const queryClient = useQueryClient();const { showErrorModal } = useErrorModal();- const { user } = useAppContext();- const isAdmin = user?.role === USER_ROLES.ADMIN;+ // The backend gates the public-config writes on dashboard:update, not on the+ // admin role, so a licensed editor can publish.+ const { canEdit: canManage, editChecks: publishChecks } =+ useDashboardPermissions(dashboardId);const [, copyToClipboard] = useCopyToClipboard();const [timeRangeEnabled, setTimeRangeEnabled] = useState<boolean>(true);@@ -196,7 +201,8 @@ export function usePublicDashboard(return {isPublic,- isAdmin,+ canManage,+ publishChecks,isLoading,isPublishing,isUpdating,diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/AddVariableButton.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/AddVariableButton.tsxindex 63fcb6f315..ed04ed4100 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/AddVariableButton.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/AddVariableButton.tsx@@ -1,26 +1,28 @@import { Plus } from '@signozhq/icons';-import { Button } from '@signozhq/ui/button';+import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';const AddVariableButton = ({- isEditable,+ checks,+ disabledTooltip,setIsEditing,}: {- isEditable: boolean;+ checks: BrandedPermission[];+ disabledTooltip?: string;setIsEditing: (state: { type: 'new' }) => void;-}): JSX.Element => {- return (- <Button- variant="solid"- color="primary"- prefix={<Plus size={14} />}- size="md"- onClick={(): void => setIsEditing({ type: 'new' })}- testId="add-variable"- disabled={!isEditable}- >- Add variable- </Button>- );-};+}): JSX.Element => (+ <AuthZButton+ checks={checks}+ disabledTooltip={disabledTooltip}+ variant="solid"+ color="primary"+ prefix={<Plus size={14} />}+ size="md"+ onClick={(): void => setIsEditing({ type: 'new' })}+ testId="add-variable"+ >+ Add variable+ </AuthZButton>+);export default AddVariableButton;diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/NoVariablesCard/NoVariablesCard.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/NoVariablesCard/NoVariablesCard.tsxindex 537ecf9cfe..4207253cfa 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/NoVariablesCard/NoVariablesCard.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/components/NoVariablesCard/NoVariablesCard.tsx@@ -2,12 +2,15 @@ import { Typography } from '@signozhq/ui/typography';import AddVariableButton from '../AddVariableButton';import { EditingState } from '../../types';import styles from './NoVariables.module.scss';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';const NoVariablesCard = ({- isEditable,+ checks,+ disabledTooltip,setIsEditing,}: {- isEditable: boolean;+ checks: BrandedPermission[];+ disabledTooltip?: string;setIsEditing: React.Dispatch<React.SetStateAction<EditingState | null>>;}): JSX.Element => {return (@@ -20,7 +23,11 @@ const NoVariablesCard = ({Create a variable to parameterize your panel queries.</Typography.Text></div>- <AddVariableButton isEditable={isEditable} setIsEditing={setIsEditing} />+ <AddVariableButton+ checks={checks}+ disabledTooltip={disabledTooltip}+ setIsEditing={setIsEditing}+ /></div>);};diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/index.tsxindex bec82bc793..82fb2759f3 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/index.tsx@@ -20,13 +20,15 @@ import styles from './Variables.module.scss';import AddVariableButton from './components/AddVariableButton';import NoVariablesCard from './components/NoVariablesCard/NoVariablesCard';import { EditingState } from './types';+import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';interface VariablesSettingsProps {dashboard: DashboardtypesGettableDashboardV2DTO;}function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {- const isEditable = useDashboardStore((s) => s.isEditable);+ const { isEditable, editChecks, editDisabledTooltip } =+ useDashboardEditContext();// The drawer destroys on close, so reading this once on mount is enough to// open the add-form when deep-linked (e.g. the bar's "Add variable" button).const openAddOnMount = useDashboardStore(@@ -127,7 +129,11 @@ function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {return (<div className={cx(styles.container, settingsStyles.settingsCard)}>{variables.length === 0 ? (- <NoVariablesCard isEditable={isEditable} setIsEditing={setIsEditing} />+ <NoVariablesCard+ checks={editChecks}+ disabledTooltip={editDisabledTooltip}+ setIsEditing={setIsEditing}+ />) : (<><VariablesList@@ -143,7 +149,11 @@ function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {appliedToAllNames={appliedToAllNames}/><div className={styles.footer}>- <AddVariableButton isEditable={isEditable} setIsEditing={setIsEditing} />+ <AddVariableButton+ checks={editChecks}+ disabledTooltip={editDisabledTooltip}+ setIsEditing={setIsEditing}+ /></div></>)}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/__tests__/DashboardSettings.authz.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/__tests__/DashboardSettings.authz.test.tsxnew file mode 100644index 0000000000..69909a7200--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/__tests__/DashboardSettings.authz.test.tsx@@ -0,0 +1,75 @@+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';+import { server } from 'mocks-server/server';+import { render, screen, waitFor } from 'tests/test-utils';+import {+ setupAuthzAdmin,+ setupAuthzDenyAll,+} from 'lib/authz/utils/authz-test-utils';++import DashboardSettings from '../index';++const DASHBOARD_ID = 'dash-1';++const dashboard = {+ id: DASHBOARD_ID,+ spec: { display: { name: 'D' }, panels: {}, layouts: [], variables: [] },+} as unknown as DashboardtypesGettableDashboardV2DTO;++let isCloudUser = true;+jest.mock('hooks/useGetTenantLicense', () => ({+ useGetTenantLicense: (): {+ isCloudUser: boolean;+ isEnterpriseSelfHostedUser: boolean;+ } => ({ isCloudUser, isEnterpriseSelfHostedUser: false }),+}));++describe('DashboardSettings - AuthZ', () => {+ beforeEach(() => {+ isCloudUser = true;+ });++ afterEach(() => {+ jest.restoreAllMocks();+ server.resetHandlers();+ });++ it('renders a trigger per tab', async () => {+ server.use(setupAuthzAdmin());++ render(<DashboardSettings dashboard={dashboard} />);++ await waitFor(() => {+ expect(screen.getByRole('tab', { name: /Overview/ })).toBeInTheDocument();+ });+ expect(screen.getByRole('tab', { name: /Variables/ })).toBeInTheDocument();+ expect(screen.getByRole('tab', { name: /Publish/ })).toBeInTheDocument();+ });++ // The triggers used to be rendered from the TabKeys enum rather than the+ // items list, so Publish appeared on OSS and landed on an empty body.+ it('omits the Publish tab when public dashboards are unavailable', async () => {+ isCloudUser = false;+ server.use(setupAuthzAdmin());++ render(<DashboardSettings dashboard={dashboard} />);++ await waitFor(() => {+ expect(screen.getByRole('tab', { name: /Overview/ })).toBeInTheDocument();+ });+ expect(+ screen.queryByRole('tab', { name: /Publish/ }),+ ).not.toBeInTheDocument();+ });++ // Reading the publish config only needs read; the writes inside gate on update.+ it('keeps the Publish tab reachable for a non-admin', async () => {+ server.use(setupAuthzDenyAll());++ render(<DashboardSettings dashboard={dashboard} />);++ await waitFor(() => {+ expect(screen.getByRole('tab', { name: /Publish/ })).toBeInTheDocument();+ });+ expect(screen.getByRole('tab', { name: /Publish/ })).toBeEnabled();+ });+});diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/index.tsxindex f7fa4871a7..cb65b07b2c 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/index.tsx@@ -13,9 +13,7 @@ import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/serviceimport Overview from './Overview';import PublicDashboardSettings from './PublicDashboard';import VariablesSettings from './Variables';-import { useAppContext } from 'providers/App/App';import { useGetTenantLicense } from 'hooks/useGetTenantLicense';-import { USER_ROLES } from 'types/roles';import { useDashboardStore } from '../store/useDashboardStore';import styles from './DashboardSettings.module.scss';@@ -37,7 +35,6 @@ const prefixIcons: Record<TabKeys, JSX.Element> = {};function DashboardSettings({ dashboard }: DashboardSettingsProps): JSX.Element {- const { user } = useAppContext();const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();// Opened once per drawer mount (the drawer destroys on close); a deep-link// request lands us on the right tab.@@ -58,27 +55,28 @@ function DashboardSettings({ dashboard }: DashboardSettingsProps): JSX.Element {children: <VariablesSettings dashboard={dashboard} />,prefixIcon: <Braces size={14} />,},+ // Readable by anyone who can open the dashboard; the controls inside+ // gate on update....(enablePublicDashboard? [{key: TabKeys.PUBLISH,label: TabKeys.PUBLISH,children: <PublicDashboardSettings dashboard={dashboard} />,- disabled: user?.role !== USER_ROLES.ADMIN,},]: []),],- [enablePublicDashboard, dashboard, user?.role],+ [enablePublicDashboard, dashboard],);return (<TabsRoot defaultValue={settingsRequest?.tab ?? TabKeys.OVERVIEW}><TabsList variant="primary">- {Object.values(TabKeys).map((key) => (- <TabsTrigger value={key} key={key}>- {prefixIcons[key]}- {key}+ {items.map((item) => (+ <TabsTrigger value={item.key} key={item.key} disabled={item.disabled}>+ {prefixIcons[item.key as TabKeys]}+ {item.label}</TabsTrigger>))}</TabsList>diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/Header.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/Header.tsxindex ea9861e336..36c4dbaba6 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/Header.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/Header.tsx@@ -8,10 +8,12 @@ import { Typography } from '@signozhq/ui/typography';import logEvent from 'api/common/logEvent';import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';import { useConfirmableAction } from 'hooks/useConfirmableAction';+import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';-import DisabledControlTooltip from '../../components/DisabledControlTooltip/DisabledControlTooltip';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';import styles from './Header.module.scss';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';interface HeaderProps {/** Unsaved edits exist — shows the "Unsaved Changes" badge and gates the discard confirmation on close (not the Save button). */@@ -20,7 +22,9 @@ interface HeaderProps {showSwitchToView?: boolean;/** Locked/no-permission dashboard — Save is disabled with a reason. */readOnly?: boolean;- readOnlyReason?: string;+ /** Present when saving is unavailable — the Save button explains itself with it. */+ readOnlyChecks?: BrandedPermission[];+ readOnlyTooltip?: string;onSave: () => void;onSwitchToView?: () => void;onClose: () => void;@@ -31,7 +35,8 @@ function Header({isSaving,showSwitchToView = false,readOnly = false,- readOnlyReason,+ readOnlyChecks = [],+ readOnlyTooltip,onSave,onSwitchToView,onClose,@@ -90,7 +95,10 @@ function Header({Switch to View Mode</Button>)}- <DisabledControlTooltip reason={readOnlyReason ?? ''} disabled={readOnly}>+ <AuthZTooltip+ checks={readOnlyChecks}+ disabledTooltip={readOnly ? readOnlyTooltip : undefined}+ ><Buttonvariant="solid"color="primary"@@ -101,7 +109,7 @@ function Header({>Save changes</Button>- </DisabledControlTooltip>+ </AuthZTooltip></div><DialogWrapperdiff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsxindex ed747e7f3e..106bf4fc6f 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx@@ -1,6 +1,6 @@import type { ComponentProps } from 'react';import { MemoryRouter } from 'react-router-dom';-import { render, screen } from '@testing-library/react';+import { render, screen } from 'tests/test-utils';import { TooltipProvider } from '@signozhq/ui/tooltip';import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';@@ -82,7 +82,11 @@ describe('PanelEditor Header', () => {it('disables Save only while read-only or saving', () => {mockUseIsAIAssistantEnabled.mockReturnValue(false);- renderHeader({ isDirty: true, readOnly: true, readOnlyReason: 'Locked' });+ renderHeader({+ isDirty: true,+ readOnly: true,+ readOnlyTooltip: 'Locked',+ });expect(screen.getByTestId('panel-editor-v2-save')).toBeDisabled();});diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/PanelEditorContainer.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/PanelEditorContainer.test.tsxindex f73d691589..96893cc62d 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/PanelEditorContainer.test.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/PanelEditorContainer.test.tsx@@ -6,6 +6,26 @@ import { PANEL_TYPES } from 'constants/queryBuilder';import { getPanelDefinition } from 'pages/DashboardPage/DashboardContainer/Panels/registry';import PanelEditorContainer from '../index';++// The editor reads its edit context from the loaded dashboard subtree, which+// these composition cases don't stand up; the derivation has its own suite.+const mockEditContext = {+ isEditable: true,+ editChecks: [],+ areOtherPermissionsLoading: false,+ deleteChecks: [],+ isLocked: false,+ canEditDashboard: true,+ canDeleteDashboard: true,+ editDisabledTooltip: '',+ deleteDisabledTooltip: '',+};+jest.mock(+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',+ () => ({+ useDashboardEditContext: (): typeof mockEditContext => mockEditContext,+ }),+);import { useScrollIntoViewStore } from '../../store/useScrollIntoViewStore';/**@@ -172,8 +192,6 @@ function makePanel(const baseProps = {dashboardId: 'dash-1',panelId: 'panel-1',- isEditable: true,- editDisabledReason: '',onClose: jest.fn(),onSaved: jest.fn(),};diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/index.tsxindex 32a132fe94..33f0b321a5 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/index.tsx@@ -21,6 +21,7 @@ import {import { getBuilderQueries } from 'pages/DashboardPage/DashboardContainer/Panels/utils/getBuilderQueries';import { useErrorModal } from 'providers/ErrorModalProvider';+import { useDashboardEditContext } from '../hooks/useDashboardEditContext';import { getExecStats } from '../queryV5/v5ResponseData';import { usePanelInteractions } from '../PanelsAndSectionsLayout/Panel/hooks/usePanelInteractions';import { useScrollIntoViewStore } from '../store/useScrollIntoViewStore';@@ -63,10 +64,6 @@ interface PanelEditorContainerProps {isNew?: boolean;/** Target section for a new panel; falls back to the last/new section. */layoutIndex?: number;- /** The dashboard can be edited (unlocked + permission); gates Save. */- isEditable: boolean;- /** Why Save is disabled (locked / no permission); '' when editable. */- editDisabledReason: string;/** Leave the editor (navigate back to the dashboard) without saving. */onClose: () => void;/** Called after a successful save — navigates back to the dashboard. */@@ -85,11 +82,14 @@ function PanelEditorContainer({savedPanel,isNew = false,layoutIndex,- isEditable,- editDisabledReason,onClose,onSaved,}: PanelEditorContainerProps): JSX.Element {+ // Read here rather than taken as props: this renders inside a loaded dashboard+ // subtree, so it resolves the same context every other consumer does.+ const { isEditable, editChecks, editDisabledTooltip } =+ useDashboardEditContext();+// Shared editing pipeline (draft + query + staged-query sync + kind switch). A new// panel always serializes its seed query and seeds the builder's default signal.const {@@ -280,7 +280,8 @@ function PanelEditorContainer({isSaving={isSaving}showSwitchToView={!isNew}readOnly={!isEditable}- readOnlyReason={editDisabledReason}+ readOnlyChecks={editChecks}+ readOnlyTooltip={editDisabledTooltip}onSave={onSave}onSwitchToView={switchToViewMode}onClose={onCloseEditor}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/DashboardEmptyState/DashboardEmptyState.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/DashboardEmptyState/DashboardEmptyState.tsxindex 39a2548b0b..bfe8d05171 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/DashboardEmptyState/DashboardEmptyState.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/DashboardEmptyState/DashboardEmptyState.tsx@@ -6,9 +6,11 @@ import dashboardEmojiUrl from '@/assets/Icons/dashboard_emoji.svg';import landscapeUrl from '@/assets/Icons/landscape.svg';import { useCreatePanel } from '../../hooks/useCreatePanel';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';import { useDashboardStore } from '../../store/useDashboardStore';import PanelTypeSelectionModal from '../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';import styles from './DashboardEmptyState.module.scss';+import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';interface DashboardEmptyStateProps {canAddPanel: boolean;@@ -17,9 +19,10 @@ interface DashboardEmptyStateProps {function DashboardEmptyState({canAddPanel,}: DashboardEmptyStateProps): JSX.Element {+ const { isEditable, editChecks, editDisabledTooltip } =+ useDashboardEditContext();const { isPickerOpen, openPicker, closePicker, createPanel } =useCreatePanel();- const isEditable = useDashboardStore((s) => s.isEditable);const requestSettings = useDashboardStore((s) => s.requestSettings);return (@@ -48,17 +51,18 @@ function DashboardEmptyState({</Typography.Text></div></div>- {isEditable && (+ <AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}><Buttonvariant="solid"color="secondary"prefix={<Configure size="md" />}+ disabled={!isEditable}onClick={(): void => requestSettings({ tab: 'Overview' })}testId="empty-configure">Configure</Button>- )}+ </AuthZTooltip></div><div className={styles.step}>@@ -73,16 +77,17 @@ function DashboardEmptyState({</Typography.Text></div></div>- {canAddPanel && (+ <AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}><Buttoncolor="primary"prefix={<Plus size="md" />}+ disabled={!canAddPanel}onClick={(): void => openPicker()}testId="add-panel">New Panel</Button>- )}+ </AuthZTooltip></div></div></div>diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/PanelActionsMenu.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/PanelActionsMenu.tsxindex 1ec6678bf8..526957ea7f 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/PanelActionsMenu.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/PanelActionsMenu.tsx@@ -7,6 +7,7 @@ import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/querimport ConfirmDeleteDialog from '../../../components/ConfirmDeleteDialog/ConfirmDeleteDialog';import type { PanelActionsConfig } from '../Panel';import { usePanelActionItems } from './usePanelActionItems';+import menuStyles from '../../../components/MenuActionItem/MenuActionItem.module.scss';import styles from './PanelActionsMenu.module.scss';interface PanelActionsMenuProps {@@ -43,7 +44,11 @@ function PanelActionsMenu({return (<>- <DropdownMenuSimple menu={{ items }} align="end">+ <DropdownMenuSimple+ menu={{ items }}+ align="end"+ className={menuStyles.menuContent}+ ><Buttontype="button"variant="ghost"diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsxindex 39dbbc7d2e..184a9cddf7 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsx@@ -1,13 +1,42 @@import { act, renderHook } from '@testing-library/react';import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';-import type { ROLES } from 'types/roles';import type { DashboardSection } from '../../../../utils';-import { useDashboardStore } from '../../../../store/useDashboardStore';import { usePanelActionItems } from '../usePanelActionItems';/** Keys of the disabled items, in order. */+// The derivation has its own suite (useDashboardEditContext.authz); these cases are+// about what the UI does with a given edit context, so control it directly.+const mockEditContext = {+ isEditable: true,+ editChecks: [],+ areOtherPermissionsLoading: false,+ deleteChecks: [],+ isLocked: false,+ canEditDashboard: true,+ canDeleteDashboard: true,+ editDisabledTooltip: '',+ deleteDisabledTooltip: '',+};+function setEditContextMock(next: Partial<typeof mockEditContext>): void {+ Object.assign(mockEditContext, {+ isEditable: true,+ isLocked: false,+ canEditDashboard: true,+ canDeleteDashboard: true,+ editDisabledTooltip: '',+ deleteDisabledTooltip: '',+ ...next,+ });+}+jest.mock(+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',+ () => ({+ useDashboardEditContext: (): typeof mockEditContext => mockEditContext,+ }),+);+function disabledKeys(result: ReturnType<typeof usePanelActionItems>,): unknown[] {@@ -64,15 +93,6 @@ jest.mock('../../hooks/useDownloadPanelImage', () => ({}),}));-// Role is the only thing read off the app context; useComponentPermission runs-// for real so the tests exercise the actual role → permission mapping.-let mockRole: ROLES = 'ADMIN';-jest.mock('providers/App/App', () => ({- useAppContext: (): { user: { role: ROLES } } => ({- user: { role: mockRole },- }),-}));-function section(layoutIndex: number,title: string | undefined,@@ -133,11 +153,10 @@ function itemKeys(result: ReturnType<typeof usePanelActionItems>): unknown[] {describe('usePanelActionItems', () => {beforeEach(() => {jest.clearAllMocks();- mockRole = 'ADMIN';- useDashboardStore.setState({ canEditDashboard: true, isLocked: false });+ setEditContextMock({});});- it('ADMIN on an editable dashboard with a known kind gets the full V1-parity set, divider-separated', () => {+ it('an editable dashboard with a known kind gets the full set, divider-separated', () => {const { result } = renderHook(() => usePanelActionItems(baseArgs));expect(itemKeys(result.current)).toStrictEqual(['view-panel',@@ -155,11 +174,20 @@ describe('usePanelActionItems', () => {// it's present for every renderable kind.});- it('AUTHOR loses edit and clone (edit_widget excludes AUTHOR) but keeps the rest', () => {- mockRole = 'AUTHOR';- const { result } = renderHook(() => usePanelActionItems(baseArgs));+ // These used to be dropped from the menu, leaving no trace of why.+ it('without edit rights keeps the edit actions visible but disabled', () => {+ setEditContextMock({+ isEditable: false,+ canEditDashboard: false,+ editDisabledTooltip: 'no permission',+ });+ const { result } = renderHook(() =>+ usePanelActionItems({ ...baseArgs, panelActions: undefined }),+ );expect(itemKeys(result.current)).toStrictEqual(['view-panel',+ 'edit-panel',+ 'clone-panel','divider','download','create-alert',@@ -168,34 +196,20 @@ describe('usePanelActionItems', () => {'divider','delete-panel',]);- });-- it('VIEWER keeps only the role-ungated actions (view, download, create-alert)', () => {- mockRole = 'VIEWER';- const { result } = renderHook(() => usePanelActionItems(baseArgs));- expect(itemKeys(result.current)).toStrictEqual([- 'view-panel',- 'divider',- 'download',- 'create-alert',- ]);- });-- it('no edit permission (view mode) hides the edit actions entirely', () => {- useDashboardStore.setState({ canEditDashboard: false });- const { result } = renderHook(() =>- usePanelActionItems({ ...baseArgs, panelActions: undefined }),- );- expect(itemKeys(result.current)).toStrictEqual([- 'view-panel',- 'divider',- 'download',- 'create-alert',+ expect(disabledKeys(result.current)).toStrictEqual([+ 'edit-panel',+ 'clone-panel',+ 'move',+ 'delete-panel',]);});it('locked (edit mode) keeps the edit actions visible but disabled', () => {- useDashboardStore.setState({ canEditDashboard: true, isLocked: true });+ setEditContextMock({+ isEditable: false,+ isLocked: true,+ editDisabledTooltip: 'locked',+ });// A locked dashboard mounts panels without layout context (no panelActions).const { result } = renderHook(() =>usePanelActionItems({ ...baseArgs, panelActions: undefined }),diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta.ts b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta.tsindex 6a9807a5bd..9f962af8b6 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta.ts+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta.ts@@ -1,5 +1,4 @@import type { PanelActionCapabilities } from 'pages/DashboardPage/DashboardContainer/Panels/types/panelDefinition';-import type { ComponentTypes } from 'utils/permission';/*** Every action the panel menu can offer: per-kind gated capabilities (minus@@ -14,12 +13,6 @@ export type PanelActionId =| 'delete';export interface PanelActionMeta {- /**- * Role gate: componentPermission key checked against the current user.- * Absent = available to every role (V1 parity: view, download and- * create-alerts were never role-gated).- */- permission?: ComponentTypes;/*** Kind gate: the PanelActionCapabilities flag this action requires.* Chrome actions (move/clone/delete) are layout concerns available for@@ -29,19 +22,19 @@ export interface PanelActionMeta {}/**- * Single source of truth for how each panel action is gated, mirroring V1's- * WidgetHeader rules. The third gate — context (editable, target sections) — is- * runtime state resolved in `usePanelActionItems`, not declarable here.+ * Single source of truth for the kind gate on each panel action. Whether the+ * user may take it (dashboard edit rights) and whether the context allows it+ * (target sections present) are runtime state resolved in `usePanelActionItems`.*/export const PANEL_ACTION_META: Record<PanelActionId, PanelActionMeta> = {view: { capability: 'view' },- edit: { permission: 'edit_widget', capability: 'edit' },- clone: { permission: 'edit_widget' },- // Single entry for every export format (CSV/PNG/SVG); like view it isn't- // role-gated (V1 parity). The per-format options live in usePanelActionItems.+ edit: { capability: 'edit' },+ clone: {},+ // Single entry for every export format (CSV/PNG/SVG); the per-format options+ // live in usePanelActionItems.download: { capability: 'download' },createAlert: { capability: 'createAlert' },// Moving a panel between sections mutates the dashboard layout.- move: { permission: 'edit_dashboard' },- delete: { permission: 'delete_widget' },+ move: {},+ delete: {},};diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsxindex 6ecab5694a..7d7dea4ff3 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsx@@ -1,4 +1,4 @@-import { type ReactNode, useCallback, useMemo } from 'react';+import { type ReactElement, type ReactNode, useCallback, useMemo } from 'react';import {Bell,Copy,@@ -9,7 +9,6 @@ import {} from '@signozhq/icons';import type { MenuItem } from '@signozhq/ui/dropdown-menu';import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';-import useComponentPermission from 'hooks/useComponentPermission';import {type ConfirmableAction,useConfirmableAction,@@ -17,8 +16,6 @@ import {import { getPanelDefinition } from 'pages/DashboardPage/DashboardContainer/Panels/registry';import { useOpenPanelEditor } from 'pages/DashboardPage/DashboardContainer/hooks/useOpenPanelEditor';import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';-import { useDashboardStore } from 'pages/DashboardPage/DashboardContainer/store/useDashboardStore';-import { useAppContext } from 'providers/App/App';import type { DashboardSection } from '../../../utils';import type { PanelActionsConfig } from '../Panel';@@ -29,9 +26,9 @@ import { useDownloadPanelMenuItem } from '../hooks/useDownloadPanelMenuItem';import { useMovePanelToSection } from '../hooks/useMovePanelToSection';import { useViewPanel } from '../hooks/useViewPanel';import { buildMoveItems } from '../utils/buildMoveItems';-import { PANEL_ACTION_META } from './panelActionMeta';-import DisabledMenuItemLabel from '../../../components/DisabledMenuItemLabel/DisabledMenuItemLabel';-import { DASHBOARD_LOCKED_REASON } from '../../../hooks/useDashboardEditGuard';+import MenuActionItem from '../../../components/MenuActionItem/MenuActionItem';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';+import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';// Stable fallback so renders without layout context don't churn the mutation// hooks' deps (a fresh [] each render would re-create their callbacks).@@ -54,10 +51,10 @@ export interface PanelActionItems {}/**- * Resolves the panel actions menu items. Each action passes three gates before- * it appears: kind (PanelDefinition.actions), role (useComponentPermission) and- * context (dashboard editable + layout config present). View and Download stay- * available on read-only dashboards, as in V1.+ * Resolves the panel actions menu items. Panels live in the dashboard spec and+ * have no authz kind, so every mutating action maps to the dashboard's edit+ * rights, while PanelDefinition.actions still decides which make sense at all.+ * View, Download and Create Alerts never mutate, so they are always available.*/export function usePanelActionItems({panelId,@@ -66,18 +63,8 @@ export function usePanelActionItems({panelActions,}: UsePanelActionItemsArgs): PanelActionItems {const panelKind = panel.spec.plugin.kind;- const { user } = useAppContext();- const [canEditWidget, canMove, canDelete] = useComponentPermission(- [- // edit_widget gates both Edit and Clone, exactly as in V1.- PANEL_ACTION_META.edit.permission ?? 'edit_widget',- PANEL_ACTION_META.move.permission ?? 'edit_dashboard',- PANEL_ACTION_META.delete.permission ?? 'delete_widget',- ],- user.role,- );- const canEditDashboard = useDashboardStore((s) => s.canEditDashboard);- const isLocked = useDashboardStore((s) => s.isLocked);+ const { isEditable, editChecks, editDisabledTooltip } =+ useDashboardEditContext();const openPanelEditor = useOpenPanelEditor();const createAlert = useCreateAlertFromPanel();const { openView } = useViewPanel();@@ -112,43 +99,43 @@ export function usePanelActionItems({const { request: requestDelete } = deleteConfirm;const items = useMemo<MenuItem[]>(() => {- // Edit actions are shown only to edit-permitted users; the lock is their only- // disabled state, surfaced as a hover tooltip on the row.- const canEdit = canEditDashboard;- const label = (text: string): ReactNode =>- isLocked ? (- <DisabledMenuItemLabel reason={DASHBOARD_LOCKED_REASON}>- {text}- </DisabledMenuItemLabel>- ) : (- text- );+ // The row is a button carrying its own icon and reason; the item hosts it.+ const row = (+ text: string,+ icon: ReactElement,+ opts: { checks?: BrandedPermission[]; destructive?: boolean } = {},+ ): ReactNode => (+ <MenuActionItem+ label={text}+ icon={icon}+ checks={opts.checks ?? editChecks}+ disabledTooltip={editDisabledTooltip}+ destructive={opts.destructive}+ />+ );const panelGroup: MenuItem[] = [];if (panelCapabilities.view) {panelGroup.push({key: 'view-panel',- label: 'View',- icon: <Fullscreen size={14} />,+ label: row('View', <Fullscreen size={14} />, { checks: [] }),onClick: (): void => openView(panelId, panel),});}- if (canEdit && canEditWidget && panelCapabilities.edit) {+ if (panelCapabilities.edit) {panelGroup.push({key: 'edit-panel',- label: label('Edit panel'),- icon: <PenLine size={14} />,- disabled: isLocked,+ label: row('Edit panel', <PenLine size={14} />),+ disabled: !isEditable,onClick: (): void => openPanelEditor(panelId, { panel }),});}- if (canEdit && canEditWidget && panelCapabilities.clone) {+ if (panelCapabilities.clone) {// Needs section context to place the copy; disabled without it.panelGroup.push({key: 'clone-panel',- label: label('Clone'),- icon: <Copy size={14} />,- disabled: isLocked || !panelActions,+ label: row('Clone', <Copy size={14} />),+ disabled: !isEditable || !panelActions,onClick: (): void => {if (panelActions) {void clonePanel({@@ -170,45 +157,35 @@ export function usePanelActionItems({if (panelCapabilities.createAlert) {dataGroup.push({key: 'create-alert',- label: 'Create Alerts',- icon: <Bell size={14} />,+ label: row('Create Alerts', <Bell size={14} />, { checks: [] }),onClick: (): void => createAlert(panel, panelId),});}- let moveGroup: MenuItem[] = [];- if (canEdit && canMove) {- moveGroup =- !isLocked && panelActions- ? buildMoveItems({- sections,- currentLayoutIndex: panelActions.currentLayoutIndex,- panelId,- movePanel,- })- : [- {- key: 'move',- label: label('Move to section'),- icon: <FolderInput size={14} />,- disabled: true,- },- ];- }-- const deleteGroup: MenuItem[] =- canEdit && canDelete- ? [+ const moveGroup: MenuItem[] =+ isEditable && panelActions+ ? buildMoveItems({+ sections,+ currentLayoutIndex: panelActions.currentLayoutIndex,+ panelId,+ movePanel,+ })+ : [{- key: 'delete-panel',- danger: true,- icon: <Trash2 size={14} />,- label: label('Delete panel'),- disabled: isLocked || !panelActions,- onClick: (): void => requestDelete(),+ key: 'move',+ label: row('Move to section', <FolderInput size={14} />),+ disabled: true,},- ]- : [];+ ];++ const deleteGroup: MenuItem[] = [+ {+ key: 'delete-panel',+ label: row('Delete panel', <Trash2 size={14} />, { destructive: true }),+ disabled: !isEditable || !panelActions,+ onClick: (): void => requestDelete(),+ },+ ];return [panelGroup, dataGroup, moveGroup, deleteGroup].filter((group) => group.length > 0)@@ -216,11 +193,9 @@ export function usePanelActionItems({index === 0 ? group : [{ type: 'divider' as const }, ...group],);}, [- canEditDashboard,- isLocked,- canEditWidget,- canMove,- canDelete,+ isEditable,+ editChecks,+ editDisabledTooltip,panelCapabilities,panel,panelActions,diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/ViewPanelModal/ViewPanelModalHeader.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/ViewPanelModal/ViewPanelModalHeader.tsxindex 39cb655161..d6ac7fcf07 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/ViewPanelModal/ViewPanelModalHeader.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/ViewPanelModal/ViewPanelModalHeader.tsx@@ -13,7 +13,8 @@ import type { PanelKind } from 'pages/DashboardPage/DashboardContainer/Panels/tyimport type { EQueryType } from 'types/common/dashboard';import styles from './ViewPanelModal.module.scss';-import { useDashboardStore } from 'pages/DashboardPage/DashboardContainer/store/useDashboardStore';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';+import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';interface ViewPanelModalHeaderProps {selectedInterval: Time | CustomTimeType;@@ -62,13 +63,14 @@ function ViewPanelModalHeader({onChangePanelKind,onResetQuery,}: ViewPanelModalHeaderProps): JSX.Element {+ const {+ isEditable: canSwitchToEdit,+ editChecks,+ editDisabledTooltip,+ } = useDashboardEditContext();// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).const panelTypeItems = usePanelTypeSelectItems({ queryType, signal });- const canEditDashboard = useDashboardStore((s) => s.canEditDashboard);- const isLocked = useDashboardStore((s) => s.isLocked);-- const canSwitchToEdit = canEditDashboard && !isLocked;return (<div className={styles.toolbar}>@@ -80,17 +82,18 @@ function ViewPanelModalHeader({onChange={onChangePanelKind}/></div>- {canSwitchToEdit && (+ <AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}><Buttonvariant="outlined"color="secondary"prefix={<PenLine />}+ disabled={!canSwitchToEdit}onClick={onSwitchToEdit}data-testid="view-panel-switch-to-edit">Switch to Edit Mode</Button>- )}+ </AuthZTooltip><Buttonvariant="link"color="primary"diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/Section/Section.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/Section/Section.tsxindex dcd8760700..b909f3e68a 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/Section/Section.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/Section/Section.tsx@@ -3,12 +3,10 @@ import { Plus } from '@signozhq/icons';import { Button } from '@signozhq/ui/button';import ConfirmDeleteDialog from '../../../components/ConfirmDeleteDialog/ConfirmDeleteDialog';-import DisabledControlTooltip from '../../../components/DisabledControlTooltip/DisabledControlTooltip';-import { DASHBOARD_LOCKED_REASON } from '../../../hooks/useDashboardEditGuard';+import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';import { useCreatePanel } from '../../../hooks/useCreatePanel';import type { DashboardSection } from '../../../utils';import PanelTypeSelectionModal from '../../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';-import { useDashboardStore } from '../../../store/useDashboardStore';import { useCloneSection } from '../hooks/useCloneSection';import { useDeleteSection } from '../hooks/useDeleteSection';import { useRenameSection } from '../hooks/useRenameSection';@@ -20,6 +18,7 @@ import SectionHeader, {type SectionDragHandle,} from '../SectionHeader/SectionHeader';import styles from './Section.module.scss';+import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';interface SectionProps {section: DashboardSection;@@ -30,8 +29,8 @@ interface SectionProps {}function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {- const canEditDashboard = useDashboardStore((s) => s.canEditDashboard);- const isLocked = useDashboardStore((s) => s.isLocked);+ const { isEditable, editChecks, editDisabledTooltip } =+ useDashboardEditContext();const {isPickerOpen,openPicker,@@ -104,43 +103,34 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {onToggle={toggle}repeatVariable={section.repeatVariable}dragHandle={dragHandle}- disabledReason={isLocked ? DASHBOARD_LOCKED_REASON : ''}- actions={- canEditDashboard- ? {- onRename: (): void => setIsRenaming(true),- onAddPanel: (): void => openPicker(section.layoutIndex),- onCloneSection: (): void => void cloneSection(section),- onDeleteSection: (): void => setIsDeleteOpen(true),- }- : undefined- }+ disabledChecks={editChecks}+ disabledTooltip={editDisabledTooltip}+ actions={{+ onRename: (): void => setIsRenaming(true),+ onAddPanel: (): void => openPicker(section.layoutIndex),+ onCloneSection: (): void => void cloneSection(section),+ onDeleteSection: (): void => setIsDeleteOpen(true),+ }}/>{open &&(section.items.length > 0 ? (grid) : (<div className={styles.emptySection}>- {canEditDashboard && (- <DisabledControlTooltip- reason={DASHBOARD_LOCKED_REASON}- disabled={isLocked}+ <AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>+ <Button+ type="button"+ variant="dashed"+ color="secondary"+ prefix={<Plus size="md" />}+ onClick={+ isEditable ? (): void => openPicker(section.layoutIndex) : undefined+ }+ testId={`section-add-panel-${section.id}`}>- <Button- type="button"- variant="dashed"- color="secondary"- prefix={<Plus size="md" />}- disabled={isLocked}- onClick={- isLocked ? undefined : (): void => openPicker(section.layoutIndex)- }- testId={`section-add-panel-${section.id}`}- >- New Panel- </Button>- </DisabledControlTooltip>- )}+ New Panel+ </Button>+ </AuthZTooltip></div>))}<SectionTitleModaldiff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionActionsMenu/SectionActionsMenu.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionActionsMenu/SectionActionsMenu.tsxindex 2962fa1d60..2e590e15cb 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionActionsMenu/SectionActionsMenu.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionActionsMenu/SectionActionsMenu.tsx@@ -1,16 +1,20 @@-import { type ReactNode, useMemo } from 'react';+import { type ReactElement, type ReactNode, useMemo } from 'react';import { Copy, EllipsisVertical, PenLine, Plus, Trash2 } from '@signozhq/icons';import { Button } from '@signozhq/ui/button';import { DropdownMenuSimple } from '@signozhq/ui/dropdown-menu';import type { MenuItem } from '@signozhq/ui/dropdown-menu';-import DisabledMenuItemLabel from '../../../components/DisabledMenuItemLabel/DisabledMenuItemLabel';+import MenuActionItem from '../../../components/MenuActionItem/MenuActionItem';+import menuStyles from '../../../components/MenuActionItem/MenuActionItem.module.scss';import styles from './SectionActionsMenu.module.scss';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';interface SectionActionsMenuProps {sectionId: string;- /** Non-empty when edits are unavailable — items render disabled with this reason. */- disabledReason?: string;+ /** Present when edits are unavailable — items render disabled with its reason. */+ disabledChecks?: BrandedPermission[];+ disabledTooltip?: string;+ disabled?: boolean;onAddPanel?: () => void;onRename?: () => void;onCloneSection?: () => void;@@ -19,28 +23,35 @@ interface SectionActionsMenuProps {function SectionActionsMenu({sectionId,- disabledReason = '',+ disabledChecks = [],+ disabledTooltip,+ disabled = false,onAddPanel,onRename,onCloneSection,onDeleteSection,}: SectionActionsMenuProps): JSX.Element {const items = useMemo<MenuItem[]>(() => {- const disabled = !!disabledReason;- const label = (text: string): ReactNode =>- disabled ? (- <DisabledMenuItemLabel reason={disabledReason}>- {text}- </DisabledMenuItemLabel>- ) : (- text- );+ // The row is a button, so it carries its own icon, disabled state and+ // reason — the dropdown item just hosts it.+ const row = (+ text: string,+ icon: ReactElement,+ opts: { destructive?: boolean } = {},+ ): ReactNode => (+ <MenuActionItem+ label={text}+ icon={icon}+ checks={disabledChecks}+ disabledTooltip={disabledTooltip}+ destructive={opts.destructive}+ />+ );const result: MenuItem[] = [];if (onAddPanel) {result.push({key: 'add-panel',- icon: <Plus size={14} />,- label: label('Add panel'),+ label: row('Add panel', <Plus size={14} />),disabled,onClick: onAddPanel,});@@ -48,8 +59,7 @@ function SectionActionsMenu({if (onRename) {result.push({key: 'rename',- icon: <PenLine size={14} />,- label: label('Rename section'),+ label: row('Rename section', <PenLine size={14} />),disabled,onClick: onRename,});@@ -57,8 +67,7 @@ function SectionActionsMenu({if (onCloneSection) {result.push({key: 'clone-section',- icon: <Copy size={14} />,- label: label('Clone section'),+ label: row('Clone section', <Copy size={14} />),disabled,onClick: onCloneSection,});@@ -68,19 +77,27 @@ function SectionActionsMenu({{ type: 'divider' },{key: 'delete-section',- danger: true,- icon: <Trash2 size={14} />,- label: label('Delete section'),+ label: row('Delete section', <Trash2 size={14} />, {+ destructive: true,+ }),disabled,onClick: onDeleteSection,},);}return result;- }, [disabledReason, onAddPanel, onRename, onCloneSection, onDeleteSection]);+ }, [+ disabled,+ disabledChecks,+ disabledTooltip,+ onAddPanel,+ onRename,+ onCloneSection,+ onDeleteSection,+ ]);return (- <DropdownMenuSimple menu={{ items }}>+ <DropdownMenuSimple menu={{ items }} className={menuStyles.menuContent}><Buttontype="button"variant="ghost"diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionGrid/SectionGrid.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionGrid/SectionGrid.tsxindex 874cbfcbee..2019bf68cb 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionGrid/SectionGrid.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionGrid/SectionGrid.tsx@@ -2,10 +2,10 @@ import { useMemo } from 'react';import GridLayout, { WidthProvider, type Layout } from 'react-grid-layout';import type { DashboardSection } from '../../../utils';-import { useDashboardStore } from '../../../store/useDashboardStore';import { usePersistLayout } from '../hooks/usePersistLayout';import SectionGridItem from './SectionGridItem';import styles from './SectionGrid.module.scss';+import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';const ResponsiveGridLayout = WidthProvider(GridLayout);@@ -21,7 +21,7 @@ function SectionGrid({layoutIndex,sections,}: SectionGridProps): JSX.Element {- const isEditable = useDashboardStore((s) => s.isEditable);+ const { isEditable } = useDashboardEditContext();const rglLayout = useMemo<Layout[]>(() =>diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionHeader/SectionHeader.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionHeader/SectionHeader.tsxindex e420137b26..f7418958a1 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionHeader/SectionHeader.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionHeader/SectionHeader.tsx@@ -6,7 +6,9 @@ import { Typography } from '@signozhq/ui/typography';import cx from 'classnames';import SectionActionsMenu from '../SectionActionsMenu/SectionActionsMenu';+import styles from './SectionHeader.module.scss';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';export interface SectionDragHandle {attributes: DraggableAttributes;@@ -32,8 +34,9 @@ interface SectionHeaderProps {dragHandle?: SectionDragHandle;/** Present for edit-permitted users; absent (no menu) in view mode. */actions?: SectionHeaderActions;- /** Non-empty when locked — actions render disabled with this reason. */- disabledReason?: string;+ /** Present when edits are unavailable — actions render disabled with its reason. */+ disabledChecks?: BrandedPermission[];+ disabledTooltip?: string;}function SectionHeader({@@ -44,7 +47,8 @@ function SectionHeader({repeatVariable,dragHandle,actions,- disabledReason = '',+ disabledChecks = [],+ disabledTooltip,}: SectionHeaderProps): JSX.Element {return (<div className={cx(styles.header, { [styles.headerOpen]: open })}>@@ -83,7 +87,8 @@ function SectionHeader({{actions ? (<SectionActionsMenusectionId={sectionId}- disabledReason={disabledReason}+ disabledChecks={disabledChecks}+ disabledTooltip={disabledTooltip}onAddPanel={actions.onAddPanel}onRename={actions.onRename}onCloneSection={actions.onCloneSection}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionList.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionList.tsxindex dfdee9e65b..88846d80a9 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionList.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SectionList.tsx@@ -11,11 +11,11 @@ import {import type { DashboardtypesLayoutDTO } from 'api/generated/services/sigNoz.schemas';import type { DashboardSection } from '../../utils';-import { useDashboardStore } from '../../store/useDashboardStore';import { useSectionDragReorder } from './hooks/useSectionDragReorder';import Section from './Section/Section';import SectionDragPreview from './SectionDragPreview/SectionDragPreview';import SortableSection from './SortableSection';+import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';interface SectionListProps {sections: DashboardSection[];@@ -23,7 +23,7 @@ interface SectionListProps {}function SectionList({ sections, layouts }: SectionListProps): JSX.Element {- const isEditable = useDashboardStore((s) => s.isEditable);+ const { isEditable } = useDashboardEditContext();const {sensors,@@ -41,16 +41,9 @@ function SectionList({ sections, layouts }: SectionListProps): JSX.Element {[orderedSections],);- if (!isEditable) {- return (- <>- {sections.map((section) => (- <Section key={section.id} section={section} />- ))}- </>- );- }-+ // The DnD tree stays mounted whether or not the user can reorder: permissions+ // resolve asynchronously, and swapping the subtree shape on that transition+ // would remount every section and its panels.return (<DndContextsensors={sensors}@@ -63,7 +56,12 @@ function SectionList({ sections, layouts }: SectionListProps): JSX.Element {<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>{orderedSections.map((section) =>section.title ? (- <SortableSection key={section.id} section={section} sections={sections} />+ <SortableSection+ key={section.id}+ section={section}+ sections={sections}+ disabled={!isEditable}+ />) : (<Section key={section.id} section={section} sections={sections} />),diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SortableSection.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SortableSection.tsxindex c1489dc3e6..107e118f0a 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SortableSection.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Section/SortableSection.tsx@@ -1,3 +1,4 @@+import { useMemo } from 'react';import { useSortable } from '@dnd-kit/sortable';import { CSS } from '@dnd-kit/utilities';@@ -7,11 +8,14 @@ import Section from './Section/Section';interface SortableSectionProps {section: DashboardSection;sections: DashboardSection[];+ /** Reordering needs edit rights; the section still renders without them. */+ disabled?: boolean;}function SortableSection({section,sections,+ disabled = false,}: SortableSectionProps): JSX.Element {const {attributes,@@ -21,7 +25,14 @@ function SortableSection({transform,transition,isDragging,- } = useSortable({ id: section.id });+ } = useSortable({ id: section.id, disabled });++ // dnd-kit re-renders this on every drag frame, so keep the handle identity+ // stable rather than handing Section a fresh object each time.+ const handle = useMemo(+ () => (disabled ? undefined : { attributes, listeners, setActivatorNodeRef }),+ [disabled, attributes, listeners, setActivatorNodeRef],+ );// dnd-kit drives the drag transform per-frame, so this must be an inline// style — there is no static-stylesheet equivalent for a live transform.@@ -35,11 +46,7 @@ function SortableSection({return (<div ref={setNodeRef} style={style}>- <Section- section={section}- sections={sections}- dragHandle={{ attributes, listeners, setActivatorNodeRef }}- />+ <Section section={section} sections={sections} dragHandle={handle} /></div>);}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/index.tsxindex 04ab5ea21a..9df71ac306 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/index.tsx@@ -5,7 +5,6 @@ import type {DashboardtypesPanelDTO,} from 'api/generated/services/sigNoz.schemas';-import { useDashboardStore } from '../store/useDashboardStore';import { layoutsToSections } from '../utils';import DashboardEmptyState from './DashboardEmptyState/DashboardEmptyState';import { useViewPanel } from './Panel/hooks/useViewPanel';@@ -16,6 +15,7 @@ import styles from './PanelsAndSectionsLayout.module.scss';import 'react-grid-layout/css/styles.css';import 'react-resizable/css/styles.css';+import { useDashboardEditContext } from '../hooks/useDashboardEditContext';interface PanelsAndSectionsLayoutProps {layouts: DashboardtypesLayoutDTO[];@@ -26,7 +26,7 @@ function PanelsAndSectionsLayout({layouts,panels,}: PanelsAndSectionsLayoutProps): JSX.Element {- const isEditable = useDashboardStore((s) => s.isEditable);+ const { isEditable } = useDashboardEditContext();// Single View-modal host for the whole dashboard, driven by the URL// (`expandedWidgetId`). One mounted modal beats one-per-panel: no N locationdiff --git a/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/VariablesBar.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/VariablesBar.tsxindex b2e87d9914..10205368e6 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/VariablesBar.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/VariablesBar.tsx@@ -16,6 +16,7 @@ import { useVariableSelection } from './hooks/useVariableSelection';import { resolveDefaultSelection } from './utils/resolveVariableSelection';import VariableSelector from './components/VariableSelector/VariableSelector';import styles from './VariablesBar.module.scss';+import { useDashboardEditContext } from '../hooks/useDashboardEditContext';interface VariablesBarProps {dashboard: DashboardtypesGettableDashboardV2DTO;@@ -32,9 +33,10 @@ interface VariablesBarProps {*/function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {const dashboardId = dashboard.id ?? '';+ const { isEditable, editChecks, editDisabledTooltip } =+ useDashboardEditContext();const { variables, selection, setSelection, autoSelect } =useVariableSelection(dashboard);- const isEditable = useDashboardStore((s) => s.isEditable);// Persisted per dashboard so the full/collapsed view survives reloads.const expanded = useDashboardStore(selectVariablesExpanded(dashboardId));const setVariablesExpanded = useDashboardStore((s) => s.setVariablesExpanded);@@ -131,11 +133,13 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {{/* After the more/less trigger, in every state. Kept inline (not block)so the row still flows under the floated time selector, and alwaysmounted so measuring never toggles it. */}- {isEditable && (- <span className={styles.addSlot}>- <AddVariableIcon />- </span>- )}+ <span className={styles.addSlot}>+ <AddVariableIcon+ checks={editChecks}+ disabledTooltip={editDisabledTooltip}+ isEditable={isEditable}+ />+ </span></div></div>);diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/components/AddVariable/AddVariableIcon.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/components/AddVariable/AddVariableIcon.tsxindex 2f6485a3d1..96f845889e 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/components/AddVariable/AddVariableIcon.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/VariablesBar/components/AddVariable/AddVariableIcon.tsx@@ -1,34 +1,70 @@import { Plus } from '@signozhq/icons';import { Button } from '@signozhq/ui/button';import { TooltipSimple } from '@signozhq/ui/tooltip';+import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';import { useDashboardStore } from '../../../store/useDashboardStore';import styles from './AddVariable.module.scss';+interface AddVariableIconProps {+ /** Permissions the control needs; reported in the standard wording when denied. */+ checks: BrandedPermission[];+ /** A non-permission block, which outranks the checks. */+ disabledTooltip?: string;+ /** Whether editing is available at all, so the label is shown instead. */+ isEditable: boolean;+}+/*** Compact "+" trigger (label on hover) shown after the variable pills once at* least one variable exists. Opens the Variables settings tab with the add form* primed.*/-function AddVariableIcon(): JSX.Element {+function AddVariableIcon({+ checks,+ disabledTooltip,+ isEditable,+}: AddVariableIconProps): JSX.Element {const requestSettings = useDashboardStore((s) => s.requestSettings);+ const onClick = (): void =>+ requestSettings({ tab: 'Variables', addVariable: true });++ // An available trigger shows its label; an unavailable one is disabled and+ // explained by the authz button itself.+ if (isEditable) {+ return (+ <TooltipSimple side="top" title="Add variable">+ <Button+ variant="outlined"+ color="secondary"+ size="icon"+ className={styles.addVariableIcon}+ aria-label="Add variable"+ testId="dashboard-variables-add"+ onClick={onClick}+ >+ <Plus size={14} />+ </Button>+ </TooltipSimple>+ );+ }+return (- <TooltipSimple side="top" title="Add variable">- <Button- variant="outlined"- color="secondary"- size="icon"- className={styles.addVariableIcon}- aria-label="Add variable"- testId="dashboard-variables-add"- onClick={(): void =>- requestSettings({ tab: 'Variables', addVariable: true })- }- >- <Plus size={14} />- </Button>- </TooltipSimple>+ <AuthZButton+ checks={checks}+ disabledTooltip={disabledTooltip}+ variant="outlined"+ color="secondary"+ size="icon"+ className={styles.addVariableIcon}+ aria-label="Add variable"+ testId="dashboard-variables-add"+ onClick={onClick}+ >+ <Plus size={14} />+ </AuthZButton>);}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledControlTooltip/DisabledControlTooltip.module.scss b/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledControlTooltip/DisabledControlTooltip.module.scssdeleted file mode 100644index 2a72edc7bd..0000000000--- a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledControlTooltip/DisabledControlTooltip.module.scss+++ /dev/null@@ -1,9 +0,0 @@-.trigger {- display: inline-flex;-}--.aboveOverlay {- // Lift the tooltip above the dropdown menu (z 50) and the antd Drawer (z 1000)- // so it is never clipped behind them. The tooltip content reads this variable.- --tooltip-z-index: 1100;-}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledControlTooltip/DisabledControlTooltip.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledControlTooltip/DisabledControlTooltip.tsxdeleted file mode 100644index 2a72fa8941..0000000000--- a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledControlTooltip/DisabledControlTooltip.tsx+++ /dev/null@@ -1,33 +0,0 @@-import type { ReactNode } from 'react';-import { TooltipSimple } from '@signozhq/ui/tooltip';--import styles from './DisabledControlTooltip.module.scss';--interface DisabledControlTooltipProps {- reason: string;- disabled: boolean;- children: ReactNode;-}--// A disabled button swallows hover, so the wrapping span is the tooltip trigger.-function DisabledControlTooltip({- reason,- disabled,- children,-}: DisabledControlTooltipProps): JSX.Element {- if (!disabled) {- return <>{children}</>;- }- return (- <TooltipSimple- title={reason}- arrow- disableHoverableContent- tooltipContentProps={{ className: styles.aboveOverlay }}- >- <span className={styles.trigger}>{children}</span>- </TooltipSimple>- );-}--export default DisabledControlTooltip;diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledMenuItemLabel/DisabledMenuItemLabel.module.scss b/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledMenuItemLabel/DisabledMenuItemLabel.module.scssdeleted file mode 100644index 1c665285cf..0000000000--- a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledMenuItemLabel/DisabledMenuItemLabel.module.scss+++ /dev/null@@ -1,10 +0,0 @@-.label {- // Re-enable pointer events so the tooltip fires while the disabled row- // (pointer-events: none) suppresses selection.- pointer-events: auto;-}--.aboveOverlay {- // Lift the tooltip above the dropdown menu (z 50) and the antd Drawer (z 1000).- --tooltip-z-index: 1100;-}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledMenuItemLabel/DisabledMenuItemLabel.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledMenuItemLabel/DisabledMenuItemLabel.tsxdeleted file mode 100644index 9563da41d0..0000000000--- a/frontend/src/pages/DashboardPage/DashboardContainer/components/DisabledMenuItemLabel/DisabledMenuItemLabel.tsx+++ /dev/null@@ -1,28 +0,0 @@-import type { ReactNode } from 'react';-import { TooltipSimple } from '@signozhq/ui/tooltip';--import styles from './DisabledMenuItemLabel.module.scss';--interface DisabledMenuItemLabelProps {- reason: string;- children: ReactNode;-}--// A disabled row has pointer-events: none, so the label re-enables them to catch hover.-function DisabledMenuItemLabel({- reason,- children,-}: DisabledMenuItemLabelProps): JSX.Element {- return (- <TooltipSimple- title={reason}- arrow- disableHoverableContent- tooltipContentProps={{ className: styles.aboveOverlay }}- >- <span className={styles.label}>{children}</span>- </TooltipSimple>- );-}--export default DisabledMenuItemLabel;diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/MenuActionItem/MenuActionItem.module.scss b/frontend/src/pages/DashboardPage/DashboardContainer/components/MenuActionItem/MenuActionItem.module.scssnew file mode 100644index 0000000000..7f3bf049ab--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/components/MenuActionItem/MenuActionItem.module.scss@@ -0,0 +1,28 @@+.menuActionItem {+ /* The item owns the row's height, font, gap, hover and dimming, so anything+ the button would size, paint or dim for itself is handed back. Without this+ the two compound: a highlight inset in the row, 0.6 opacity on top of 0.5.+ Colour stays the button's, from `color`, as on the list rows. */+ --button-padding: var(--spacing-5, 10px) var(--spacing-6, 12px);+ --button-height: auto;+ --button-font-size: inherit;+ --button-line-height: inherit;+ --button-gap: var(--spacing-4, 8px);+ --button-variant-ghost-background-color: transparent;+ --button-variant-ghost-hover-background-color: transparent;+ --button-internal-hover-state-background-color: transparent;+ --button-disabled-opacity: 1;++ /* Padding is the exception: it belongs to the button, which is what the+ tooltip anchors to. Left on the item, the anchor is inset from the menu's+ edge and the tooltip opens under the panel. */+ width: 100%;+ justify-content: flex-start;+}++/* The other half: the menu hands its padding to the rows, so a row's box reaches+ the panel edge, as the list popover's rows do. */+.menuContent {+ --dropdown-menu-content-padding: 0;+ --dropdown-menu-item-padding: 0;+}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/MenuActionItem/MenuActionItem.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/components/MenuActionItem/MenuActionItem.tsxnew file mode 100644index 0000000000..f90cfa5578--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/components/MenuActionItem/MenuActionItem.tsx@@ -0,0 +1,47 @@+import type { ReactElement, ReactNode } from 'react';+import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';++import styles from './MenuActionItem.module.scss';++interface MenuActionItemProps {+ label: ReactNode;+ icon: ReactElement;+ /** Permissions the row needs. Empty for a row that needs none. */+ checks: BrandedPermission[];+ /** A non-permission block, which outranks the checks (see AuthZTooltip). */+ disabledTooltip?: string;+ destructive?: boolean;+}++/**+ * A row in a dashboard dropdown. The button fills the row, so the tooltip+ * anchors to the whole row and lands clear of the menu.+ *+ * Takes no `onClick` or `disabled`: the item keeps both, because Radix reads+ * `disabled` off it for keyboard navigation and only marks a row `clickable` —+ * the pointer cursor — when the item carries the handler.+ */+function MenuActionItem({+ label,+ icon,+ checks,+ disabledTooltip,+ destructive = false,+}: MenuActionItemProps): JSX.Element {+ return (+ <AuthZButton+ checks={checks}+ disabledTooltip={disabledTooltip}+ side="left"+ variant="ghost"+ color={destructive ? 'destructive' : 'secondary'}+ className={styles.menuActionItem}+ prefix={icon}+ >+ {label}+ </AuthZButton>+ );+}++export default MenuActionItem;diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/__tests__/useDashboardEditContext.authz.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/__tests__/useDashboardEditContext.authz.test.tsxnew file mode 100644index 0000000000..397d5cc9e7--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/__tests__/useDashboardEditContext.authz.test.tsx@@ -0,0 +1,133 @@+import { server } from 'mocks-server/server';+import { AllTheProviders, renderHook, waitFor } from 'tests/test-utils';+import {+ setupAuthzAdmin,+ setupAuthzAllow,+ setupAuthzDenyAll,+} from 'lib/authz/utils/authz-test-utils';+import {+ buildDashboardDeletePermission,+ buildDashboardReadPermission,+ buildDashboardUpdatePermission,+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';++import { useDashboardEditContext } from '../useDashboardEditContext';++const DASHBOARD_ID = 'dash-1';+// The copy lives in the dashboard i18n bundle, which the test env does not load,+// so `t` yields the key — which is the part worth asserting anyway.+const LOCKED_COPY = 'dashboard_locked';++let lockedDashboard = false;++// The hook reads the dashboard from the loaded subtree, which a bare renderHook+// has no root page to establish — stand in for it so these cases stay about the+// permissions and the derivation.+jest.mock('../useDashboardFetchRequired', () => ({+ useDashboardFetchRequired: (): { dashboard: unknown } => ({+ dashboard: { id: DASHBOARD_ID, locked: lockedDashboard },+ }),+}));++function renderGuard(+ locked = false,+): ReturnType<+ typeof renderHook<ReturnType<typeof useDashboardEditContext>, void>+> {+ lockedDashboard = locked;+ return renderHook(() => useDashboardEditContext(), {+ wrapper: AllTheProviders,+ });+}++describe('useDashboardEditContext - AuthZ', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ server.resetHandlers();+ });++ describe('permission granted', () => {+ it('is editable when unlocked', async () => {+ server.use(setupAuthzAdmin());++ const { result } = renderGuard();++ await waitFor(() => expect(result.current.isEditable).toBe(true));+ expect(result.current.editDisabledTooltip).toBe('');+ expect(result.current.deleteDisabledTooltip).toBe('');+ });++ // An edit-capable user gets the lock: it's the thing they can act on.+ it('reports the lock when locked', async () => {+ server.use(setupAuthzAdmin());++ const { result } = renderGuard(true);++ // Settle on the resolved grant: the in-flight state has canEdit false, so+ // a non-empty reason is not enough to know the check has landed.+ await waitFor(() => expect(result.current.canEditDashboard).toBe(true));+ expect(result.current.isEditable).toBe(false);+ expect(result.current.editDisabledTooltip).toBe(LOCKED_COPY);+ expect(result.current.deleteDisabledTooltip).toBe(LOCKED_COPY);+ });+ });++ describe('permission denied', () => {+ // Access before state: a lock would send them asking for the wrong thing.+ it('reports the permission, not the lock, when both apply', async () => {+ server.use(setupAuthzDenyAll());++ const { result } = renderGuard(true);++ await waitFor(() => expect(result.current.editDisabledTooltip).toBe(''));+ expect(result.current.deleteDisabledTooltip).toBe('');+ expect(result.current.editDisabledTooltip).toBe('');+ });++ it('reports the permission when unlocked', async () => {+ server.use(setupAuthzDenyAll());++ const { result } = renderGuard();++ await waitFor(() => expect(result.current.canEditDashboard).toBe(false));+ expect(result.current.canEditDashboard).toBe(false);+ expect(result.current.editDisabledTooltip).toBe('');+ expect(result.current.deleteDisabledTooltip).toBe('');+ });++ // Authz guide rule 2 — update alone is not enough to offer an edit affordance.+ it('is not editable with update but no read', async () => {+ server.use(setupAuthzAllow(buildDashboardUpdatePermission(DASHBOARD_ID)));++ const { result } = renderGuard();++ await waitFor(() => expect(result.current.canEditDashboard).toBe(false));+ expect(result.current.canEditDashboard).toBe(false);+ expect(result.current.editDisabledTooltip).toBe('');+ });++ // Authz guide rule 3 — delete stands on its own.+ it('keeps delete available without read or update', async () => {+ server.use(setupAuthzAllow(buildDashboardDeletePermission(DASHBOARD_ID)));++ const { result } = renderGuard();++ await waitFor(() => expect(result.current.canDeleteDashboard).toBe(true));+ expect(result.current.deleteDisabledTooltip).toBe('');+ expect(result.current.canEditDashboard).toBe(false);+ });++ it('is editable with read and update together', async () => {+ server.use(+ setupAuthzAllow(+ buildDashboardReadPermission(DASHBOARD_ID),+ buildDashboardUpdatePermission(DASHBOARD_ID),+ ),+ );++ const { result } = renderGuard();++ await waitFor(() => expect(result.current.isEditable).toBe(true));+ });+ });+});diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/dashboardEditContext.ts b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/dashboardEditContext.tsnew file mode 100644index 0000000000..437b56dd54--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/dashboardEditContext.ts@@ -0,0 +1,79 @@+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';++/** Copy for the two non-permission blocks, resolved by the caller so this stays pure. */+export interface EditContextReasons {+ locked: string;+ readOnly: string;+}++export interface DashboardEditContext {+ isEditable: boolean;+ isLocked: boolean;+ canReadDashboard: boolean;+ canEditDashboard: boolean;+ canDeleteDashboard: boolean;+ /** `[read, update]`, for an authz component's `checks`. */+ editChecks: BrandedPermission[];+ deleteChecks: BrandedPermission[];+ /** Non-permission obstacle for `disabledTooltip`; empty when a permission is what's missing. */+ editDisabledTooltip: string;+ deleteDisabledTooltip: string;+ /** `update`/`delete` are still resolving; `read` gates the page itself. */+ areOtherPermissionsLoading: boolean;+}++/**+ * Precedence is `update` → lock → `read`: the lock is only reported to a caller+ * who holds `update` and can act on it. A forced read-only mount outranks both,+ * since no check can lift it.+ */+export function deriveEditContext({+ isLocked,+ canRead,+ canEdit,+ canDelete,+ editChecks,+ deleteChecks,+ areOtherPermissionsLoading,+ reasons,+ readOnlyOverride = false,+}: {+ isLocked: boolean;+ canRead: boolean;+ canEdit: boolean;+ canDelete: boolean;+ editChecks: BrandedPermission[];+ deleteChecks: BrandedPermission[];+ areOtherPermissionsLoading: boolean;+ reasons: EditContextReasons;+ /** Mount forced view-only regardless of permissions (see pulse-pod#283). */+ readOnlyOverride?: boolean;+}): DashboardEditContext {+ if (readOnlyOverride) {+ return {+ isEditable: false,+ isLocked,+ canReadDashboard: canRead,+ canEditDashboard: false,+ canDeleteDashboard: false,+ editChecks,+ deleteChecks,+ editDisabledTooltip: reasons.readOnly,+ deleteDisabledTooltip: reasons.readOnly,+ areOtherPermissionsLoading: false,+ };+ }++ return {+ isEditable: canEdit && !isLocked,+ isLocked,+ canReadDashboard: canRead,+ canEditDashboard: canEdit,+ canDeleteDashboard: canDelete,+ editChecks,+ deleteChecks,+ editDisabledTooltip: canEdit && isLocked ? reasons.locked : '',+ deleteDisabledTooltip: canDelete && isLocked ? reasons.locked : '',+ areOtherPermissionsLoading,+ };+}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext.ts b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext.tsnew file mode 100644index 0000000000..db3e7cf9f6--- /dev/null+++ b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext.ts@@ -0,0 +1,49 @@+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { useDashboardPermissions } from 'hooks/dashboards/useDashboardPermissions';++import { useDashboardStore } from '../store/useDashboardStore';++import {+ type DashboardEditContext,+ deriveEditContext,+} from './dashboardEditContext';+import { useDashboardFetchRequired } from './useDashboardFetchRequired';++/**+ * Edit context for components inside a loaded dashboard subtree. The dashboard+ * and the permissions come from their shared caches, keyed off the store's+ * `dashboardId`; nothing derived is stored, to avoid a second source of truth.+ */+export function useDashboardEditContext(): DashboardEditContext {+ const { dashboard } = useDashboardFetchRequired();+ const {+ canRead,+ canEdit,+ canDelete,+ editChecks,+ deletePermission,+ areOtherPermissionsLoading,+ } = useDashboardPermissions(dashboard.id);+ const { t } = useTranslation('dashboard');+ const readOnlyOverride = useDashboardStore(+ (s) => s.canEditDashboardOverride === false,+ );++ const deleteChecks = useMemo(() => [deletePermission], [deletePermission]);++ return deriveEditContext({+ isLocked: !!dashboard.locked,+ canRead,+ canEdit,+ canDelete,+ editChecks,+ deleteChecks,+ areOtherPermissionsLoading,+ reasons: {+ locked: t('dashboard_locked'),+ readOnly: t('dashboard_read_only_here'),+ },+ readOnlyOverride,+ });+}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useDashboardEditGuard.ts b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useDashboardEditGuard.tsdeleted file mode 100644index f441531419..0000000000--- a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useDashboardEditGuard.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';-import useComponentPermission from 'hooks/useComponentPermission';-import { useAppContext } from 'providers/App/App';--import {- DASHBOARD_LOCKED_REASON,- DASHBOARD_NO_EDIT_PERMISSION_REASON,-} from '../store/slices/editContextSlice';--// Re-exported from the (dependency-light) slice so leaf modules / tests can import-// the reason strings without pulling this hook's provider chain.-export {- DASHBOARD_LOCKED_REASON,- DASHBOARD_NO_EDIT_PERMISSION_REASON,-} from '../store/slices/editContextSlice';--export interface DashboardEditGuard {- isEditable: boolean;- isLocked: boolean;- canEditDashboard: boolean;- editDisabledReason: string;-}--// Editability + reason, derived from the dashboard (used where the store is cold,-// e.g. the panel-editor route reached by direct URL).-export function useDashboardEditGuard(- dashboard: DashboardtypesGettableDashboardV2DTO | undefined,-): DashboardEditGuard {- const { user } = useAppContext();- const [editDashboardPermission] = useComponentPermission(- ['edit_dashboard'],- user.role,- );- const canEditDashboard = !!editDashboardPermission;- const isLocked = !!dashboard?.locked;- let editDisabledReason = '';- if (isLocked) {- editDisabledReason = DASHBOARD_LOCKED_REASON;- } else if (!canEditDashboard) {- editDisabledReason = DASHBOARD_NO_EDIT_PERMISSION_REASON;- }- return {- isEditable: canEditDashboard && !isLocked,- isLocked,- canEditDashboard,- editDisabledReason,- };-}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch.ts b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch.tsindex 739c5bbe80..b55d9679ff 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch.ts+++ b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch.ts@@ -12,8 +12,8 @@ import type {import APIError from 'types/api/error';import { applyJsonPatch } from '../optimistic/applyJsonPatch';-import { DASHBOARD_LOCKED_REASON } from '../store/slices/editContextSlice';import { useDashboardStore } from '../store/useDashboardStore';+import { useTranslation } from 'react-i18next';/** Cached dashboard snapshot, kept for rollback on error. */interface OptimisticPatchContext {@@ -37,8 +37,8 @@ export function useOptimisticPatch(dashboardIdOverride?: string,): UseOptimisticPatch {const storeDashboardId = useDashboardStore((s) => s.dashboardId);- const storeIsEditable = useDashboardStore((s) => s.isEditable);const dashboardId = dashboardIdOverride ?? storeDashboardId;+ const { t } = useTranslation('dashboard');const queryClient = useQueryClient();const queryKey = getGetDashboardV2QueryKey({ id: dashboardId });@@ -78,12 +78,16 @@ export function useOptimisticPatch(const { mutateAsync } = mutation;const patchAsync = useCallback((ops: DashboardtypesJSONPatchOperationDTO[]): Promise<unknown> => {- if (storeDashboardId === dashboardId && !storeIsEditable) {- return Promise.reject(new Error(DASHBOARD_LOCKED_REASON));+ // Defense-in-depth against a lock, read straight from the cache this hook+ // already owns. Permission is enforced by the UI and, definitively, by the+ // backend — checking it here would drag authz into every mutation.+ const cached = queryClient.getQueryData<GetDashboardV2200>(queryKey);+ if (cached?.data?.locked) {+ return Promise.reject(new Error(t('dashboard_locked')));}return mutateAsync(ops);},- [storeDashboardId, dashboardId, storeIsEditable, mutateAsync],+ [queryClient, queryKey, mutateAsync],);return {diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/index.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/index.tsxindex e5b5392d8c..5e1be7737d 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/index.tsx+++ b/frontend/src/pages/DashboardPage/DashboardContainer/index.tsx@@ -6,7 +6,6 @@ import AutoRefreshTicker from 'container/TopNav/AutoRefreshV2/AutoRefreshTicker'import DashboardPageToolbar from './DashboardPageToolbar';import PanelsAndSectionsLayout from './PanelsAndSectionsLayout';-import { useDashboardEditGuard } from './hooks/useDashboardEditGuard';import { useResolvedVariables } from './hooks/useResolvedVariables';import { useSyncVariablesForSuggestions } from './hooks/useSyncVariablesForSuggestions';import { useDashboardStore } from './store/useDashboardStore';@@ -50,17 +49,13 @@ function DashboardContainer({const fullScreenHandle = useFullScreenHandle();- const { isLocked, canEditDashboard } = useDashboardEditGuard(dashboard);-// Seed during render (not an effect) so the first Panel render already sees the id —// useDashboardFetchRequired throws on a missing id. setEditContext self-guards.const setEditContext = useDashboardStore((s) => s.setEditContext);-setEditContext({dashboardId: dashboard.id,- isLocked,- canEditDashboard: canEditDashboardOverride ?? canEditDashboard,refetch,+ canEditDashboardOverride,});// Resolve the variable selection into the V5 query payload and publish it to@@ -88,7 +83,7 @@ function DashboardContainer({</>)}<PanelsAndSectionsLayout layouts={spec.layouts} panels={spec.panels} />- {isLocked && <LockedIndicator />}+ {!!dashboard.locked && <LockedIndicator />}<DashboardChangedDialogopen={staleCheck.showPrompt}onReload={staleCheck.reload}diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/store/slices/editContextSlice.ts b/frontend/src/pages/DashboardPage/DashboardContainer/store/slices/editContextSlice.tsindex 981035be33..f8d98a0db8 100644--- a/frontend/src/pages/DashboardPage/DashboardContainer/store/slices/editContextSlice.ts+++ b/frontend/src/pages/DashboardPage/DashboardContainer/store/slices/editContextSlice.ts@@ -2,25 +2,23 @@ import type { StateCreator } from 'zustand';import type { DashboardStore } from '../useDashboardStore';-export const DASHBOARD_LOCKED_REASON = 'This dashboard is locked';-export const DASHBOARD_NO_EDIT_PERMISSION_REASON =- 'You don’t have permission to edit this dashboard';--// Edit context shared across the V2 dashboard tree, set once by DashboardContainer.+/**+ * The one piece of page context the subtree can't derive for itself: which+ * dashboard is open, and how to refetch it. Editability is deliberately absent —+ * `useDashboardEditContext` derives it from the caches.+ */export interface EditContextSlice {dashboardId: string;- // canEditDashboard && !isLocked.- isEditable: boolean;- isLocked: boolean;- canEditDashboard: boolean;- // Locked / no-permission reason for tooltips; '' when editable.- editDisabledReason: string;refetch: () => void;+ /**+ * @deprecated Forces a view-only mount regardless of permissions. Used only by+ * LLM Observability; see SigNoz/pulse-pod#283.+ */+ canEditDashboardOverride?: boolean;setEditContext: (ctx: {dashboardId: string;- isLocked: boolean;- canEditDashboard: boolean;refetch: () => void;+ canEditDashboardOverride?: boolean;}) => void;}@@ -31,37 +29,22 @@ export const createEditContextSlice: StateCreator<EditContextSlice> = (set, get) => ({dashboardId: '',- isEditable: false,- isLocked: false,- canEditDashboard: false,- editDisabledReason: '',refetch: (): void => undefined,+ canEditDashboardOverride: undefined,// Idempotent (no-op when unchanged) so it's safe to call during render.setEditContext: (ctx): void => {- const isEditable = ctx.canEditDashboard && !ctx.isLocked;- let editDisabledReason = '';- if (ctx.isLocked) {- editDisabledReason = DASHBOARD_LOCKED_REASON;- } else if (!ctx.canEditDashboard) {- editDisabledReason = DASHBOARD_NO_EDIT_PERMISSION_REASON;- }const prev = get();if (prev.dashboardId === ctx.dashboardId &&- prev.isEditable === isEditable &&- prev.isLocked === ctx.isLocked &&- prev.canEditDashboard === ctx.canEditDashboard &&- prev.refetch === ctx.refetch+ prev.refetch === ctx.refetch &&+ prev.canEditDashboardOverride === ctx.canEditDashboardOverride) {return;}set({dashboardId: ctx.dashboardId,- isEditable,- isLocked: ctx.isLocked,- canEditDashboard: ctx.canEditDashboard,- editDisabledReason,refetch: ctx.refetch,+ canEditDashboardOverride: ctx.canEditDashboardOverride,});},});diff --git a/frontend/src/pages/DashboardPage/DashboardPage.tsx b/frontend/src/pages/DashboardPage/DashboardPage.tsxindex dbe3f575a5..cc3cc06590 100644--- a/frontend/src/pages/DashboardPage/DashboardPage.tsx+++ b/frontend/src/pages/DashboardPage/DashboardPage.tsx@@ -4,6 +4,12 @@ import { useParams } from 'react-router-dom';import { Typography } from '@signozhq/ui/typography';import logEvent from 'api/common/logEvent';import Spinner from 'components/Spinner';+import { withAuthZPage } from 'lib/authz/components/withAuthZ/withAuthZPage';+import {+ buildDashboardDeletePermission,+ buildDashboardReadPermission,+ buildDashboardUpdatePermission,+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';import DashboardContainer from './DashboardContainer';@@ -49,4 +55,15 @@ function DashboardPage(): JSX.Element {return <DashboardContainer dashboard={dashboard} refetch={refetch} />;}-export default DashboardPage;+// Typed explicitly: the route lazy-loads this, and Loadable needs indexable props.+export default withAuthZPage<Record<string, unknown>>(DashboardPage, {+ checks: (_props, router) => [+ buildDashboardReadPermission(router.params.dashboardId ?? ''),+ ],+ // Same batch as `checks`, so the controls below resolve from cache.+ preloadChecks: (_props, router) => [+ buildDashboardUpdatePermission(router.params.dashboardId ?? ''),+ buildDashboardDeletePermission(router.params.dashboardId ?? ''),+ ],+ fallbackOnLoading: <Spinner tip="Loading dashboard..." />,+});diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsxindex 81aec5567d..b32ecdd372 100644--- a/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx@@ -10,9 +10,14 @@ import Spinner from 'components/Spinner';import ROUTES from 'constants/routes';import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';import { useSafeNavigate } from 'hooks/useSafeNavigate';+import { withAuthZPage } from 'lib/authz/components/withAuthZ/withAuthZPage';+import {+ buildDashboardDeletePermission,+ buildDashboardReadPermission,+ buildDashboardUpdatePermission,+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';import { useDashboardFetch } from '../DashboardContainer/hooks/useDashboardFetch';-import { useDashboardEditGuard } from '../DashboardContainer/hooks/useDashboardEditGuard';import { useResolvedVariables } from '../DashboardContainer/hooks/useResolvedVariables';import PanelEditorContainer from '../DashboardContainer/PanelEditor';import type { PanelEditorHandoffState } from '../DashboardContainer/PanelEditor/panelEditorHandoff';@@ -47,22 +52,12 @@ function PanelEditorPage(): JSX.Element {const { dashboard, isLoading, isError, error, refetch } =useDashboardFetch(dashboardId);- // Derived here (not from the store) because the editor route doesn't mount- // DashboardContainer, so the store's edit context may be cold on a direct URL.- const { isEditable, isLocked, canEditDashboard, editDisabledReason } =- useDashboardEditGuard(dashboard);-// On a refresh/direct URL this route is the only mount, so seed the edit// context the way DashboardContainer does — during render, so the subtree's// first render already sees the id (useDashboardFetchRequired throws without it).const setEditContext = useDashboardStore((s) => s.setEditContext);if (dashboard?.id) {- setEditContext({- dashboardId: dashboard.id,- isLocked,- canEditDashboard,- refetch,- });+ setEditContext({ dashboardId: dashboard.id, refetch });}// No variables bar on this route: seed the selection and publish the resolved@@ -143,12 +138,21 @@ function PanelEditorPage(): JSX.Element {savedPanel={existingPanel}isNew={!!newKind}layoutIndex={layoutIndex}- isEditable={isEditable}- editDisabledReason={editDisabledReason}onClose={backToDashboard}onSaved={backToDashboard}/>);}-export default PanelEditorPage;+// Typed explicitly: the route lazy-loads this, and Loadable needs indexable props.+export default withAuthZPage<Record<string, unknown>>(PanelEditorPage, {+ checks: (_props, router) => [+ buildDashboardReadPermission(router.params.dashboardId ?? ''),+ ],+ // Same batch as `checks`, so the controls below resolve from cache.+ preloadChecks: (_props, router) => [+ buildDashboardUpdatePermission(router.params.dashboardId ?? ''),+ buildDashboardDeletePermission(router.params.dashboardId ?? ''),+ ],+ fallbackOnLoading: <Spinner tip="Loading dashboard..." />,+});diff --git a/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsx b/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsxnew file mode 100644index 0000000000..5c5646e2c1--- /dev/null+++ b/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsx@@ -0,0 +1,154 @@+import { server } from 'mocks-server/server';+import { rest } from 'msw';+import { render, screen, waitFor } from 'tests/test-utils';+import {+ AUTHZ_CHECK_URL,+ setupAuthzAdmin,+ setupAuthzDenyAll,+} from 'lib/authz/utils/authz-test-utils';++import DashboardPage from '../DashboardPage';++const DASHBOARD_ID = 'dash-1';+const DASHBOARD_URL = `http://localhost/api/v2/dashboards/${DASHBOARD_ID}`;++jest.mock('react-router-dom', () => ({+ ...jest.requireActual('react-router-dom'),+ useParams: (): { dashboardId: string } => ({ dashboardId: DASHBOARD_ID }),+}));++describe('DashboardPage - AuthZ', () => {+ beforeEach(() => {+ server.use(setupAuthzAdmin());+ });++ afterEach(() => {+ jest.restoreAllMocks();+ server.resetHandlers();+ });++ // The list is collection-scoped, so an unreadable row is expected, not a failure.+ it('blocks the page when the read check is denied', async () => {+ server.use(setupAuthzDenyAll());++ render(<DashboardPage />);++ await expect(+ screen.findByText('Uh-oh! You are not authorized'),+ ).resolves.toBeInTheDocument();+ expect(+ screen.getByText(`read:dashboard:${DASHBOARD_ID}`),+ ).toBeInTheDocument();+ expect(+ screen.queryByText('Failed to load dashboard'),+ ).not.toBeInTheDocument();+ });++ // The check is the only authority; a 403 from the GET is an API failure.+ it('shows the generic load error for a 403 from the dashboard request', async () => {+ server.use(+ rest.get(DASHBOARD_URL, (_req, res, ctx) =>+ res(+ ctx.status(403),+ ctx.json({+ status: 'error',+ error: {+ type: 'forbidden',+ code: 'authz_forbidden',+ message: 'user/x is not authorized to perform dashboard:read',+ },+ }),+ ),+ ),+ );++ render(<DashboardPage />);++ await expect(+ screen.findByText('Failed to load dashboard'),+ ).resolves.toBeInTheDocument();+ expect(+ screen.queryByText('Uh-oh! You are not authorized'),+ ).not.toBeInTheDocument();+ });++ // The page must not paint controls and then disable them once the check lands.+ it('holds the page on the spinner until the permission check resolves', async () => {+ server.use(+ rest.post(AUTHZ_CHECK_URL, (_req, res, ctx) => res(ctx.delay('infinite'))),+ rest.get(DASHBOARD_URL, (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: {+ id: DASHBOARD_ID,+ spec: {+ display: { name: 'Checkout' },+ panels: {},+ layouts: [],+ variables: [],+ },+ },+ }),+ ),+ ),+ );++ render(<DashboardPage />);++ // Dashboard data has arrived, but the tree stays unmounted.+ await expect(screen.findByLabelText('loading')).resolves.toBeInTheDocument();+ expect(screen.queryByTestId('show-drawer')).not.toBeInTheDocument();+ expect(screen.queryByTestId('add-panel-header')).not.toBeInTheDocument();+ });++ // An authz outage must not make every dashboard look forbidden.+ it('renders the dashboard when the permission check itself fails', async () => {+ server.use(+ rest.post(AUTHZ_CHECK_URL, (_req, res, ctx) => res(ctx.status(500))),+ rest.get(DASHBOARD_URL, (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: {+ id: DASHBOARD_ID,+ spec: {+ display: { name: 'Checkout' },+ panels: {},+ layouts: [],+ variables: [],+ },+ },+ }),+ ),+ ),+ );++ render(<DashboardPage />);++ await waitFor(() => {+ expect(+ screen.queryByText('Uh-oh! You are not authorized'),+ ).not.toBeInTheDocument();+ });+ });++ it('still shows the generic error for a server failure', async () => {+ server.use(+ rest.get(DASHBOARD_URL, (_req, res, ctx) =>+ res(ctx.status(500), ctx.json({ status: 'error', error: {} })),+ ),+ );++ render(<DashboardPage />);++ await expect(+ screen.findByText('Failed to load dashboard'),+ ).resolves.toBeInTheDocument();+ expect(+ screen.queryByText('Uh-oh! You are not authorized'),+ ).not.toBeInTheDocument();+ });+});