Skip to content

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.

feat(authz): add dashboard permissions (#12448)

Ashwin Bhatkal206aad1acdf3
diff --git a/cmd/authz.go b/cmd/authz.go
index 6d97586695..a6f19d5b5c 100644
--- a/cmd/authz.go
+++ b/cmd/authz.go
@@ -96,6 +96,7 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceServiceAccount).String(): true,
coretypes.NewResourceRef(coretypes.ResourceRole).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorAPIKey).String(): true,
+ coretypes.NewResourceRef(coretypes.ResourceMetaResourceDashboard).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceLicense).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceSubscription).String(): true,
coretypes.NewResourceRef(coretypes.ResourceTelemetryResourceLogs).String(): true,
diff --git a/frontend/public/locales/en/dashboard.json b/frontend/public/locales/en/dashboard.json
index ecb25b0dd5..e13d24b8d7 100644
--- a/frontend/public/locales/en/dashboard.json
+++ b/frontend/public/locales/en/dashboard.json
@@ -25,11 +25,13 @@
"dashboard_has_been_updated": "Dashboard has been updated",
"do_you_want_to_refresh_the_dashboard": "Do you want to refresh the dashboard?",
"locked_dashboard_delete_tooltip_admin_author": "Dashboard is locked. Please unlock the dashboard to enable delete.",
- "locked_dashboard_delete_tooltip_editor": "Dashboard is locked. Please contact admin to delete the dashboard.",
"delete_dashboard_success": "{{name}} dashboard deleted successfully",
"dashboard_unsave_changes": "There are unsaved changes in the Query builder, please stage and run the query or the changes will be lost. Press OK to discard.",
"dashboard_save_changes": "Your graph built with {{queryTag}} query will be saved. Press OK to confirm.",
"your_graph_build_with": "Your graph built with",
"dashboard_ok_confirm": "query will be saved. Press OK to confirm.",
- "variable_name_already_exists": "Variable \"{{name}}\" already exists"
+ "variable_name_already_exists": "Variable \"{{name}}\" already exists",
+ "dashboard_locked": "This dashboard is locked",
+ "dashboard_read_only_here": "This dashboard is read-only here",
+ "lock_integration_dashboard": "An integration dashboard cannot be locked or unlocked"
}
diff --git a/frontend/src/container/RolesSettings/hooks/__tests__/useRolePermissions.test.ts b/frontend/src/container/RolesSettings/hooks/__tests__/useRolePermissions.test.ts
index b152ffb15c..b6440774f8 100644
--- a/frontend/src/container/RolesSettings/hooks/__tests__/useRolePermissions.test.ts
+++ b/frontend/src/container/RolesSettings/hooks/__tests__/useRolePermissions.test.ts
@@ -329,9 +329,10 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
it('returns all resources from RESOURCE_ORDER even with empty transaction groups', () => {
const result = transformTransactionGroupsToResourcePermissions([]);
- expect(result).toHaveLength(9);
+ expect(result).toHaveLength(10);
expect(result.map((r) => r.resourceKind)).toStrictEqual([
'factor-api-key',
+ 'dashboard',
'license',
'logs',
'meter-metrics',
@@ -420,9 +421,10 @@ describe('createEmptyRolePermissions', () => {
it('creates permissions for all resources in RESOURCE_ORDER', () => {
const result = createEmptyRolePermissions();
- expect(result).toHaveLength(9);
+ expect(result).toHaveLength(10);
expect(result.map((r) => r.resourceKind)).toStrictEqual([
'factor-api-key',
+ 'dashboard',
'license',
'logs',
'meter-metrics',
diff --git a/frontend/src/container/RolesSettings/permissions.config.ts b/frontend/src/container/RolesSettings/permissions.config.ts
index 95c1e4327e..a5876b6250 100644
--- a/frontend/src/container/RolesSettings/permissions.config.ts
+++ b/frontend/src/container/RolesSettings/permissions.config.ts
@@ -4,6 +4,7 @@ import {
DraftingCompass,
FileKey,
Gauge,
+ Grid3X3,
Key,
Logs,
Receipt,
@@ -41,6 +42,14 @@ export interface ResourcePanelConfig {
* not all of them
*/
export const RESOURCE_PANELS: Record<AuthZResource, ResourcePanelConfig> = {
+ dashboard: {
+ label: 'Dashboards',
+ description: 'Dashboards and their panels across the workspace.',
+ icon: Grid3X3,
+ selectorPlaceholder:
+ 'Type dashboard ID, separate multiple with comma or space',
+ docsAnchor: 'dashboard',
+ },
'factor-api-key': {
label: 'API Keys',
description: 'Programmatic access tokens for the workspace.',
diff --git a/frontend/src/hooks/dashboards/__tests__/useDashboardPermissions.authz.test.tsx b/frontend/src/hooks/dashboards/__tests__/useDashboardPermissions.authz.test.tsx
new file mode 100644
index 0000000000..c7776c2722
--- /dev/null
+++ b/frontend/src/hooks/dashboards/__tests__/useDashboardPermissions.authz.test.tsx
@@ -0,0 +1,137 @@
+import { AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
+import { rest } from 'msw';
+import { server } from 'mocks-server/server';
+import {
+ AUTHZ_CHECK_URL,
+ setupAuthzAdmin,
+ setupAuthzAllow,
+ setupAuthzDenyAll,
+} from 'lib/authz/utils/authz-test-utils';
+import {
+ buildDashboardReadPermission,
+ buildDashboardUpdatePermission,
+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
+
+import { useDashboardPermissions } from '../useDashboardPermissions';
+
+const DASHBOARD_ID = 'dash-1';
+
+describe('useDashboardPermissions - AuthZ', () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ server.resetHandlers();
+ });
+
+ describe('permission granted', () => {
+ it('resolves every verb when all are granted', async () => {
+ server.use(setupAuthzAdmin());
+
+ const { result } = renderHook(() => useDashboardPermissions(DASHBOARD_ID), {
+ wrapper: AllTheProviders,
+ });
+
+ await waitFor(() =>
+ expect(result.current.isReadPermissionLoading).toBe(false),
+ );
+ expect(result.current.canRead).toBe(true);
+ expect(result.current.canUpdate).toBe(true);
+ expect(result.current.canDelete).toBe(true);
+ expect(result.current.canEdit).toBe(true);
+ });
+ });
+
+ describe('permission denied', () => {
+ it('resolves every verb as false when all are denied', async () => {
+ server.use(setupAuthzDenyAll());
+
+ const { result } = renderHook(() => useDashboardPermissions(DASHBOARD_ID), {
+ wrapper: AllTheProviders,
+ });
+
+ await waitFor(() =>
+ expect(result.current.isReadPermissionLoading).toBe(false),
+ );
+ expect(result.current.canRead).toBe(false);
+ expect(result.current.canUpdate).toBe(false);
+ expect(result.current.canDelete).toBe(false);
+ expect(result.current.canEdit).toBe(false);
+ });
+ });
+
+ describe('partial', () => {
+ // Authz guide rule 2: an edit affordance needs read as well as update.
+ it('denies canEdit when update is granted but read is not', async () => {
+ server.use(setupAuthzAllow(buildDashboardUpdatePermission(DASHBOARD_ID)));
+
+ const { result } = renderHook(() => useDashboardPermissions(DASHBOARD_ID), {
+ wrapper: AllTheProviders,
+ });
+
+ await waitFor(() =>
+ expect(result.current.isReadPermissionLoading).toBe(false),
+ );
+ expect(result.current.canUpdate).toBe(true);
+ expect(result.current.canRead).toBe(false);
+ expect(result.current.canEdit).toBe(false);
+ });
+
+ it('denies canEdit when read is granted but update is not', async () => {
+ server.use(setupAuthzAllow(buildDashboardReadPermission(DASHBOARD_ID)));
+
+ const { result } = renderHook(() => useDashboardPermissions(DASHBOARD_ID), {
+ wrapper: AllTheProviders,
+ });
+
+ await waitFor(() =>
+ expect(result.current.isReadPermissionLoading).toBe(false),
+ );
+ expect(result.current.canRead).toBe(true);
+ expect(result.current.canUpdate).toBe(false);
+ expect(result.current.canEdit).toBe(false);
+ });
+ });
+
+ describe('check failure', () => {
+ // An authz outage must not read as a denial — callers fall open and let the
+ // API decide, matching AuthZGuard's onFailRenderContent default.
+ it('reports hasError and grants nothing when the check fails', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, (_req, res, ctx) => res(ctx.status(500))),
+ );
+
+ const { result } = renderHook(() => useDashboardPermissions(DASHBOARD_ID), {
+ wrapper: AllTheProviders,
+ });
+
+ // A check that cannot answer is not a grant.
+ await waitFor(() =>
+ expect(result.current.isReadPermissionLoading).toBe(false),
+ );
+ expect(result.current.canRead).toBe(false);
+ expect(result.current.canEdit).toBe(false);
+ });
+ });
+
+ describe('disabled', () => {
+ it('fires no check when disabled', async () => {
+ const onCheck = jest.fn();
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ onCheck();
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json({ data: payload, status: 'success' }),
+ );
+ }),
+ );
+
+ renderHook(() => useDashboardPermissions(DASHBOARD_ID, { enabled: false }), {
+ wrapper: AllTheProviders,
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(onCheck).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/hooks/dashboards/useDashboardCollectionPermissions.ts b/frontend/src/hooks/dashboards/useDashboardCollectionPermissions.ts
new file mode 100644
index 0000000000..db09866409
--- /dev/null
+++ b/frontend/src/hooks/dashboards/useDashboardCollectionPermissions.ts
@@ -0,0 +1,31 @@
+import {
+ DashboardCreatePermission,
+ DashboardListPermission,
+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
+import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
+
+export interface DashboardCollectionPermissions {
+ canList: boolean;
+ canCreate: boolean;
+ isLoading: boolean;
+ /**
+ * The check itself failed. Callers should fall open — behave as before authz
+ * and let the API decide — rather than treat an outage as a denial.
+ */
+ hasError: boolean;
+}
+
+// Module-level so the useQueries identity stays stable across renders.
+const CHECKS = [DashboardListPermission, DashboardCreatePermission];
+
+/** Collection-level dashboard permissions (wildcard selector). */
+export function useDashboardCollectionPermissions(): DashboardCollectionPermissions {
+ const { isGranted, isLoading, error } = useAuthZ(CHECKS);
+
+ return {
+ canList: isGranted(DashboardListPermission),
+ canCreate: isGranted(DashboardCreatePermission),
+ isLoading,
+ hasError: !!error,
+ };
+}
diff --git a/frontend/src/hooks/dashboards/useDashboardLockPermission.ts b/frontend/src/hooks/dashboards/useDashboardLockPermission.ts
new file mode 100644
index 0000000000..6411b78f2d
--- /dev/null
+++ b/frontend/src/hooks/dashboards/useDashboardLockPermission.ts
@@ -0,0 +1,42 @@
+import { useTranslation } from 'react-i18next';
+import { DashboardtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
+
+import { useDashboardPermissions } from './useDashboardPermissions';
+
+export interface DashboardLockPermission {
+ canToggleLock: boolean;
+ isLoading: boolean;
+ /** Non-permission obstacle only; empty when a permission is what's missing. */
+ disabledTooltip: string;
+}
+
+/**
+ * Needs `dashboard:update`, and the handler then rejects integration dashboards;
+ * ownership is not a factor. It rejects system dashboards too, unchecked here
+ * because the list query filters them out.
+ */
+export function useDashboardLockPermission({
+ dashboardId,
+ source,
+ enabled = true,
+}: {
+ dashboardId: string;
+ source: DashboardtypesSourceDTO;
+ enabled?: boolean;
+}): DashboardLockPermission {
+ const { t } = useTranslation('dashboard');
+ const { canEdit, areOtherPermissionsLoading } = useDashboardPermissions(
+ dashboardId,
+ { enabled },
+ );
+
+ const isLockable = source !== DashboardtypesSourceDTO.integration;
+
+ return {
+ canToggleLock: !areOtherPermissionsLoading && isLockable && canEdit,
+ isLoading: areOtherPermissionsLoading,
+ // Empty without `canEdit` so the missing permission surfaces instead.
+ disabledTooltip:
+ canEdit && !isLockable ? t('lock_integration_dashboard') : '',
+ };
+}
diff --git a/frontend/src/hooks/dashboards/useDashboardPermissions.ts b/frontend/src/hooks/dashboards/useDashboardPermissions.ts
new file mode 100644
index 0000000000..5e60480f27
--- /dev/null
+++ b/frontend/src/hooks/dashboards/useDashboardPermissions.ts
@@ -0,0 +1,76 @@
+import { useMemo } from 'react';
+import {
+ buildDashboardDeletePermission,
+ buildDashboardReadPermission,
+ buildDashboardUpdatePermission,
+} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
+import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
+import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
+
+export interface DashboardPermissions {
+ canRead: boolean;
+ canUpdate: boolean;
+ canDelete: boolean;
+ /** Per the authz guide, an edit affordance needs `read` as well as `update`. */
+ canEdit: boolean;
+ /** `read` renders the dashboard, so a page gates its mount on this alone. */
+ isReadPermissionLoading: boolean;
+ /** `update`/`delete` gate controls only; the page does not wait on them. */
+ areOtherPermissionsLoading: boolean;
+ readPermission: BrandedPermission;
+ updatePermission: BrandedPermission;
+ deletePermission: BrandedPermission;
+ /** `[read, update]`, so a denial names both. */
+ editChecks: BrandedPermission[];
+}
+
+/**
+ * Resource-level dashboard permissions. Pass `enabled: false` while the id is
+ * unknown, so no check fires against an empty selector.
+ */
+export function useDashboardPermissions(
+ dashboardId: string,
+ options?: { enabled?: boolean },
+): DashboardPermissions {
+ const enabled = options?.enabled ?? true;
+
+ const { readPermission, updatePermission, deletePermission } = useMemo(
+ () => ({
+ readPermission: buildDashboardReadPermission(dashboardId),
+ updatePermission: buildDashboardUpdatePermission(dashboardId),
+ deletePermission: buildDashboardDeletePermission(dashboardId),
+ }),
+ [dashboardId],
+ );
+
+ const checks = useMemo(
+ () => [readPermission, updatePermission, deletePermission],
+ [readPermission, updatePermission, deletePermission],
+ );
+
+ const { isGranted, isLoading } = useAuthZ(checks, { enabled });
+
+ const canRead = isGranted(readPermission);
+ const canUpdate = isGranted(updatePermission);
+ const canDelete = isGranted(deletePermission);
+
+ const editChecks = useMemo(
+ () => [readPermission, updatePermission],
+ [readPermission, updatePermission],
+ );
+
+ return {
+ canRead,
+ canUpdate,
+ canDelete,
+ canEdit: canRead && canUpdate,
+ // One request covers all three, so the two flags only differ when a page
+ // preloads `read` ahead of the rest — see `preloadChecks`.
+ isReadPermissionLoading: isLoading,
+ areOtherPermissionsLoading: isLoading,
+ readPermission,
+ updatePermission,
+ deletePermission,
+ editChecks,
+ };
+}
diff --git a/frontend/src/hooks/dashboards/useToggleDashboardLock.ts b/frontend/src/hooks/dashboards/useToggleDashboardLock.ts
new file mode 100644
index 0000000000..722e4220a7
--- /dev/null
+++ b/frontend/src/hooks/dashboards/useToggleDashboardLock.ts
@@ -0,0 +1,62 @@
+import { useMutation, useQueryClient } from 'react-query';
+import { toast } from '@signozhq/ui/sonner';
+import {
+ getGetDashboardV2QueryKey,
+ lockDashboardV2,
+ unlockDashboardV2,
+} from 'api/generated/services/dashboard';
+import type { GetDashboardV2200 } from 'api/generated/services/sigNoz.schemas';
+import APIError from 'types/api/error';
+
+interface Args {
+ dashboardId: string;
+ isLocked: boolean;
+ /** Called with the new lock state — for analytics and any extra invalidation. */
+ onSuccess?: (locked: boolean) => void;
+ /** Called on failure — for rolling back optimistic state. */
+ onError?: (error: APIError) => void;
+}
+
+export interface ToggleDashboardLock {
+ toggleLock: () => void;
+ isTogglingLock: boolean;
+}
+
+/**
+ * Toggles a dashboard's lock and patches the detail-page cache, which runs
+ * `staleTime: Infinity` + `refetchOnMount: false` and would otherwise show the
+ * stale state. Only the flag is patched: a refetch would reload every panel.
+ */
+export function useToggleDashboardLock({
+ dashboardId,
+ isLocked,
+ onSuccess,
+ onError,
+}: Args): ToggleDashboardLock {
+ const queryClient = useQueryClient();
+
+ const { mutate, isLoading } = useMutation({
+ mutationFn: () =>
+ isLocked
+ ? unlockDashboardV2({ id: dashboardId })
+ : lockDashboardV2({ id: dashboardId }),
+ onSuccess: () => {
+ const next = !isLocked;
+ toast.success(next ? 'Dashboard locked' : 'Dashboard unlocked');
+ const key = getGetDashboardV2QueryKey({ id: dashboardId });
+ const cached = queryClient.getQueryData<GetDashboardV2200>(key);
+ if (cached) {
+ queryClient.setQueryData<GetDashboardV2200>(key, {
+ ...cached,
+ data: { ...cached.data, locked: next },
+ });
+ }
+ onSuccess?.(next);
+ },
+ onError: (error: APIError) => {
+ onError?.(error);
+ },
+ });
+
+ return { toggleLock: mutate, isTogglingLock: isLoading };
+}
diff --git a/frontend/src/lib/authz/components/AuthZButton/AuthZButton.authz.test.tsx b/frontend/src/lib/authz/components/AuthZButton/AuthZButton.authz.test.tsx
index c0c4fffc26..cc07883968 100644
--- a/frontend/src/lib/authz/components/AuthZButton/AuthZButton.authz.test.tsx
+++ b/frontend/src/lib/authz/components/AuthZButton/AuthZButton.authz.test.tsx
@@ -53,22 +53,6 @@ describe('AuthZButton', () => {
});
});
- it('forwards a custom tooltipMessage', () => {
- render(
- <AuthZButton
- checks={[createPerm]}
- tooltipMessage="Ask an admin"
- testId="create-btn"
- >
- Create
- </AuthZButton>,
- );
-
- expect(mockTooltip.mock.calls[0][0]).toMatchObject({
- tooltipMessage: 'Ask an admin',
- });
- });
-
it('passes authZEnabled through as the tooltip enabled flag', () => {
render(
<AuthZButton checks={[createPerm]} authZEnabled={false} testId="create-btn">
diff --git a/frontend/src/lib/authz/components/AuthZButton/AuthZButton.tsx b/frontend/src/lib/authz/components/AuthZButton/AuthZButton.tsx
index 93dc6be68c..1865c654a5 100644
--- a/frontend/src/lib/authz/components/AuthZButton/AuthZButton.tsx
+++ b/frontend/src/lib/authz/components/AuthZButton/AuthZButton.tsx
@@ -8,13 +8,18 @@ export type AuthZButtonProps = ButtonProps & {
*/
checks: BrandedPermission[];
/**
- * Override the default denial tooltip message.
+ * Gate the permission check itself. When false, renders a plain button.
*/
+ authZEnabled?: boolean;
+ /** Replace the standard denial wording; prefer the default. */
tooltipMessage?: string;
/**
- * Gate the permission check itself. When false, renders a plain button.
+ * A non-permission block the consumer already knows about — a lock, an
+ * immutable resource. Takes precedence over `checks`, which are then skipped.
*/
- authZEnabled?: boolean;
+ disabledTooltip?: string;
+ /** Which side of the button to render the tooltip against. */
+ side?: 'top' | 'bottom' | 'left' | 'right';
/**
* Set this false when this button is used inside a modal/drawer of signozhq/ui,
* otherwise the tooltip will not have the correct z-index
@@ -24,8 +29,10 @@ export type AuthZButtonProps = ButtonProps & {
function AuthZButton({
checks,
- tooltipMessage,
authZEnabled = true,
+ tooltipMessage,
+ disabledTooltip,
+ side,
withPortal,
...buttonProps
}: AuthZButtonProps): JSX.Element {
@@ -34,6 +41,8 @@ function AuthZButton({
checks={checks}
enabled={authZEnabled}
tooltipMessage={tooltipMessage}
+ disabledTooltip={disabledTooltip}
+ side={side}
withPortal={withPortal}
>
<Button {...buttonProps} />
diff --git a/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.authz.test.tsx b/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.authz.test.tsx
index 3c981bb857..742e6e016a 100644
--- a/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.authz.test.tsx
+++ b/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.authz.test.tsx
@@ -4,6 +4,7 @@ import { buildPermission } from 'lib/authz/hooks/useAuthZ/utils';
import type {
AuthZObject,
BrandedPermission,
+ UseAuthZResult,
} from 'lib/authz/hooks/useAuthZ/types';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import AuthZTooltip from './AuthZTooltip';
@@ -11,15 +12,26 @@ import AuthZTooltip from './AuthZTooltip';
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
const mockUseAuthZ = useAuthZ as jest.MockedFunction<typeof useAuthZ>;
-const noPermissions = {
- isLoading: false,
- isFetching: false,
- error: null,
- permissions: null,
- allowed: false,
- deniedPermissions: [] as BrandedPermission[],
- refetchPermissions: jest.fn(),
-};
+// Builds a full UseAuthZResult so `isGranted` stays consistent with `permissions`
+// rather than being a stub that could drift from it.
+function authZResult(overrides: Partial<UseAuthZResult> = {}): UseAuthZResult {
+ const base: UseAuthZResult = {
+ isLoading: false,
+ isFetching: false,
+ error: null,
+ permissions: null,
+ allowed: false,
+ deniedPermissions: [] as BrandedPermission[],
+ isGranted: (): boolean => false,
+ refetchPermissions: jest.fn(),
+ ...overrides,
+ };
+ return {
+ ...base,
+ isGranted: (permission: BrandedPermission): boolean =>
+ base.permissions?.[permission]?.isGranted === true,
+ };
+}
const TestButton = (
props: React.ButtonHTMLAttributes<HTMLButtonElement>,
@@ -42,10 +54,11 @@ const attachRolePerm = buildPermission(
describe('AuthZTooltip — single check', () => {
it('renders child unchanged when permission is granted', () => {
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: { [createPerm]: { isGranted: true } },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: { [createPerm]: { isGranted: true } },
+ }),
+ );
render(
<AuthZTooltip checks={[createPerm]}>
@@ -57,10 +70,11 @@ describe('AuthZTooltip — single check', () => {
});
it('disables child when permission is denied', () => {
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: { [createPerm]: { isGranted: false } },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: { [createPerm]: { isGranted: false } },
+ }),
+ );
render(
<AuthZTooltip checks={[createPerm]}>
@@ -72,10 +86,11 @@ describe('AuthZTooltip — single check', () => {
});
it('shows formatted permission message in tooltip when denied', async () => {
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: { [createPerm]: { isGranted: false } },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: { [createPerm]: { isGranted: false } },
+ }),
+ );
render(
<AuthZTooltip checks={[createPerm]}>
@@ -95,7 +110,7 @@ describe('AuthZTooltip — single check', () => {
});
it('disables child while loading', () => {
- mockUseAuthZ.mockReturnValue({ ...noPermissions, isLoading: true });
+ mockUseAuthZ.mockReturnValue(authZResult({ isLoading: true }));
render(
<AuthZTooltip checks={[createPerm]}>
@@ -110,13 +125,14 @@ describe('AuthZTooltip — single check', () => {
describe('AuthZTooltip — multi-check (checks array)', () => {
it('renders child enabled when all checks are granted', () => {
const sa = attachSAPerm('sa-1');
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: {
- [sa]: { isGranted: true },
- [attachRolePerm]: { isGranted: true },
- },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: {
+ [sa]: { isGranted: true },
+ [attachRolePerm]: { isGranted: true },
+ },
+ }),
+ );
render(
<AuthZTooltip checks={[sa, attachRolePerm]}>
@@ -129,13 +145,14 @@ describe('AuthZTooltip — multi-check (checks array)', () => {
it('disables child when first check is denied, second granted', () => {
const sa = attachSAPerm('sa-1');
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: {
- [sa]: { isGranted: false },
- [attachRolePerm]: { isGranted: true },
- },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: {
+ [sa]: { isGranted: false },
+ [attachRolePerm]: { isGranted: true },
+ },
+ }),
+ );
render(
<AuthZTooltip checks={[sa, attachRolePerm]}>
@@ -148,13 +165,14 @@ describe('AuthZTooltip — multi-check (checks array)', () => {
it('disables child when both checks are denied and lists denied permissions in data attr', () => {
const sa = attachSAPerm('sa-1');
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: {
- [sa]: { isGranted: false },
- [attachRolePerm]: { isGranted: false },
- },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: {
+ [sa]: { isGranted: false },
+ [attachRolePerm]: { isGranted: false },
+ },
+ }),
+ );
render(
<AuthZTooltip checks={[sa, attachRolePerm]}>
@@ -173,13 +191,14 @@ describe('AuthZTooltip — multi-check (checks array)', () => {
it('shows multiple formatted permissions in tooltip when both denied', async () => {
const sa = attachSAPerm('sa-1');
- mockUseAuthZ.mockReturnValue({
- ...noPermissions,
- permissions: {
- [sa]: { isGranted: false },
- [attachRolePerm]: { isGranted: false },
- },
- });
+ mockUseAuthZ.mockReturnValue(
+ authZResult({
+ permissions: {
+ [sa]: { isGranted: false },
+ [attachRolePerm]: { isGranted: false },
+ },
+ }),
+ );
render(
<AuthZTooltip checks={[sa, attachRolePerm]}>
diff --git a/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.module.scss b/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.module.scss
deleted file mode 100644
index cc26b43271..0000000000
--- a/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.module.scss
+++ /dev/null
@@ -1,10 +0,0 @@
-.errorContent {
- background: var(--callout-error-background) !important;
- border-color: var(--callout-error-border) !important;
- backdrop-filter: blur(15px);
- border-radius: 4px !important;
- color: var(--foreground) !important;
- font-style: normal;
- font-weight: 400;
- white-space: nowrap;
-}
diff --git a/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.tsx b/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.tsx
index f9b38b4a90..d8d5115350 100644
--- a/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.tsx
+++ b/frontend/src/lib/authz/components/AuthZTooltip/AuthZTooltip.tsx
@@ -1,4 +1,12 @@
-import { cloneElement, CSSProperties, ReactElement, useMemo } from 'react';
+import {
+ cloneElement,
+ CSSProperties,
+ ReactElement,
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import {
TooltipContent,
TooltipProvider,
@@ -9,7 +17,9 @@ import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { formatPermission } from 'lib/authz/hooks/useAuthZ/utils';
import { useAppContext } from 'providers/App/App';
-import styles from './AuthZTooltip.module.scss';
+import cx from 'classnames';
+
+import styles from '../tooltipContent.module.scss';
const DISABLED_STYLE: CSSProperties = {
pointerEvents: 'all',
@@ -22,7 +32,23 @@ interface AuthZTooltipProps {
checks: BrandedPermission[];
children: ReactElement;
enabled?: boolean;
+ /**
+ * Replace the standard denial wording. Prefer the default — it names the exact
+ * scopes — and reach for this only when a surface genuinely needs its own.
+ */
tooltipMessage?: string;
+ /**
+ * A block the consumer already knows about that is not a permission — a lock,
+ * an immutable resource, a forced read-only mount.
+ *
+ * It takes precedence over the checks, which are skipped entirely: the control
+ * is unavailable either way, so running them would only cost a request. Set it
+ * only when the non-permission block is the real obstacle, so a missing
+ * permission still surfaces its own message.
+ */
+ disabledTooltip?: string;
+ /** Which side of the control to render against. Defaults to the top. */
+ side?: 'top' | 'bottom' | 'left' | 'right';
/**
* Set this false when this button is used inside a modal/drawer of signozhq/ui,
* otherwise the tooltip will not have the correct z-index
@@ -47,10 +73,17 @@ function AuthZTooltip({
children,
enabled = true,
tooltipMessage,
+ disabledTooltip,
+ side,
withPortal,
}: AuthZTooltipProps): JSX.Element {
const { user } = useAppContext();
- const shouldCheck = enabled && checks.length > 0;
+ const isPointerOverRef = useRef(false);
+ const [isOpen, setIsOpen] = useState(false);
+
+ // The block the consumer passed is already decisive, so the check is not run.
+ const isBlocked = !!disabledTooltip;
+ const shouldCheck = enabled && checks.length > 0 && !isBlocked;
const { permissions, isLoading } = useAuthZ(checks, { enabled: shouldCheck });
@@ -61,6 +94,20 @@ function AuthZTooltip({
return checks.filter((p) => permissions[p]?.isGranted === false);
}, [checks, permissions]);
+ /**
+ * Radix closes the tooltip on pointerdown and on click, and merges its own
+ * handlers after the trigger's regardless of `preventDefault`, so the close is
+ * filtered here. Clicking a dead control does nothing, which is exactly when
+ * its reason is still wanted, so a close is ignored while the pointer remains
+ * on it. Everything else stays Radix's to decide.
+ */
+ const handleOpenChange = useCallback((next: boolean): void => {
+ if (!next && isPointerOverRef.current) {
+ return;
+ }
+ setIsOpen(next);
+ }, []);
+
if (shouldCheck && isLoading) {
return cloneElement(children, {
disabled: true,
@@ -71,7 +118,7 @@ function AuthZTooltip({
});
}
- if (!shouldCheck || deniedPermissions.length === 0) {
+ if (!isBlocked && (!shouldCheck || deniedPermissions.length === 0)) {
return children;
}
@@ -79,7 +126,7 @@ function AuthZTooltip({
return (
<TooltipProvider>
- <TooltipRoot>
+ <TooltipRoot open={isOpen} onOpenChange={handleOpenChange}>
<TooltipTrigger asChild testId={childTestId}>
{cloneElement(children, {
disabled: true,
@@ -87,11 +134,31 @@ function AuthZTooltip({
onClick: noOp,
onMouseDown: noOp,
onPointerDown: noOp,
- 'data-denied-permissions': deniedPermissions.join(','),
+ onPointerEnter: (): void => {
+ isPointerOverRef.current = true;
+ },
+ onPointerLeave: (): void => {
+ isPointerOverRef.current = false;
+ },
+ ...(isBlocked
+ ? {}
+ : { 'data-denied-permissions': deniedPermissions.join(',') }),
})}
</TooltipTrigger>
- <TooltipContent className={styles.errorContent} withPortal={withPortal}>
- {formatDeniedMessage(deniedPermissions, user.id, tooltipMessage)}
+ <TooltipContent
+ side={side}
+ // A denial has no arrow; a state the user can act on is not an error
+ // and reads as a normal tooltip.
+ arrow={isBlocked}
+ className={cx(
+ isBlocked ? styles.blockedContent : styles.errorContent,
+ styles.aboveOverlay,
+ )}
+ withPortal={withPortal}
+ >
+ {isBlocked
+ ? disabledTooltip
+ : formatDeniedMessage(deniedPermissions, user.id, tooltipMessage)}
</TooltipContent>
</TooltipRoot>
</TooltipProvider>
diff --git a/frontend/src/lib/authz/components/tooltipContent.module.scss b/frontend/src/lib/authz/components/tooltipContent.module.scss
new file mode 100644
index 0000000000..7db2a51687
--- /dev/null
+++ b/frontend/src/lib/authz/components/tooltipContent.module.scss
@@ -0,0 +1,42 @@
+// Shared presentation for every "you can't use this, here's why" tooltip, so the
+// explanation looks the same wherever it surfaces.
+//
+// These drive the bubble AND the arrow: @signozhq/ui paints both from
+// --tooltip-background / --tooltip-border-color, so setting the variables keeps
+// them in step. Overriding `background`/`border-color` directly styles only the
+// bubble and leaves the arrow on the default fill.
+.errorContent {
+ --tooltip-background: var(--callout-error-background);
+ --tooltip-border-color: var(--callout-error-border);
+ --tooltip-foreground: var(--foreground);
+
+ backdrop-filter: blur(15px);
+ border-radius: 4px;
+ font-style: normal;
+ font-weight: 400;
+ // Reasons naming two permissions run long; wrap rather than stretch the
+ // bubble across the viewport.
+ max-width: 260px;
+ white-space: normal;
+}
+
+// A block the user can act on themselves — a lock, an integration-owned or
+// legacy dashboard — reads as state, not as an access error.
+.blockedContent {
+ --tooltip-background: var(--l2-background);
+ --tooltip-border-color: var(--l2-border);
+ --tooltip-foreground: var(--l1-foreground);
+
+ backdrop-filter: blur(15px);
+ border-radius: 4px;
+ font-style: normal;
+ font-weight: 400;
+ max-width: 260px;
+ white-space: normal;
+}
+
+.aboveOverlay {
+ // Lift above the dropdown menu (z 50) and the antd Drawer (z 1000) so the
+ // tooltip is never clipped behind them. The arrow reads this too.
+ --tooltip-z-index: 1100;
+}
diff --git a/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx b/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx
index 79986c71e1..fb0a425aad 100644
--- a/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx
+++ b/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx
@@ -6,6 +6,7 @@ import {
} from 'react-router-dom';
import type { AuthZGuardProps } from 'lib/authz/components/AuthZGuard/AuthZGuard';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
+import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
export type RouterContext = {
/**
@@ -45,6 +46,18 @@ export type WithAuthZOptions<P> = {
checks:
| BrandedPermission[]
| ((props: P, router: RouterContext) => BrandedPermission[]);
+ /**
+ * Extra permissions to fetch in the same batch as `checks`, without gating on
+ * them. `useAuthZ` coalesces everything requested in the same tick into one
+ * request and caches per permission, so a component below the guard that
+ * needs these resolves from cache instead of firing a second round trip and
+ * flipping its controls once it lands.
+ *
+ * Never affects whether the content renders — a denial here is ignored.
+ */
+ preloadChecks?:
+ | BrandedPermission[]
+ | ((props: P, router: RouterContext) => BrandedPermission[]);
fallback?: AuthZGuardProps['fallback'];
fallbackOnLoading?: AuthZGuardProps['fallbackOnLoading'];
failOpenOnError?: AuthZGuardProps['onFailRenderContent'];
@@ -86,12 +99,21 @@ export function createAuthZHOC<P extends object>(
Component: ComponentType<P>,
opts: WithAuthZOptions<P>,
): ComponentType<P> {
- const { checks, ...guardProps } = opts;
+ const { checks, preloadChecks, ...guardProps } = opts;
function Wrapped(props: P): ReactElement | null {
const router = useRouterContext();
const resolvedChecks =
typeof checks === 'function' ? checks(props, router) : checks;
+ const resolvedPreload =
+ typeof preloadChecks === 'function'
+ ? preloadChecks(props, router)
+ : preloadChecks;
+
+ // Requested here rather than through the guard: `useAuthZ` coalesces
+ // everything asked for in the same tick into one request, so this rides
+ // along with the guard's own checks without being able to gate rendering.
+ useAuthZ(resolvedPreload ?? [], { enabled: !!resolvedPreload?.length });
return (
<Guard checks={resolvedChecks} {...guardProps}>
diff --git a/frontend/src/lib/authz/hooks/useAuthZ/permissions.type.ts b/frontend/src/lib/authz/hooks/useAuthZ/permissions.type.ts
index b0770fda7f..75ece140a5 100644
--- a/frontend/src/lib/authz/hooks/useAuthZ/permissions.type.ts
+++ b/frontend/src/lib/authz/hooks/useAuthZ/permissions.type.ts
@@ -3,6 +3,11 @@ export default {
status: 'success',
data: {
resources: [
+ {
+ kind: 'dashboard',
+ type: 'metaresource',
+ allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
+ },
{
kind: 'factor-api-key',
type: 'metaresource',
diff --git a/frontend/src/lib/authz/hooks/useAuthZ/permissions/dashboard.permissions.ts b/frontend/src/lib/authz/hooks/useAuthZ/permissions/dashboard.permissions.ts
new file mode 100644
index 0000000000..5f33158fb4
--- /dev/null
+++ b/frontend/src/lib/authz/hooks/useAuthZ/permissions/dashboard.permissions.ts
@@ -0,0 +1,18 @@
+import { buildPermission } from '../utils';
+import type { BrandedPermission } from '../types';
+
+// Collection-level — wildcard selector required for correct response key matching.
+// `list` also covers pin/unpin and saved-view CRUD, which the backend gates on it.
+export const DashboardListPermission = buildPermission('list', 'dashboard:*');
+export const DashboardCreatePermission = buildPermission(
+ 'create',
+ 'dashboard:*',
+);
+
+// Resource-level — require a specific dashboard id
+export const buildDashboardReadPermission = (id: string): BrandedPermission =>
+ buildPermission('read', `dashboard:${id}`);
+export const buildDashboardUpdatePermission = (id: string): BrandedPermission =>
+ buildPermission('update', `dashboard:${id}`);
+export const buildDashboardDeletePermission = (id: string): BrandedPermission =>
+ buildPermission('delete', `dashboard:${id}`);
diff --git a/frontend/src/lib/authz/hooks/useAuthZ/types.ts b/frontend/src/lib/authz/hooks/useAuthZ/types.ts
index 9f7d2d9f35..49cf4407d9 100644
--- a/frontend/src/lib/authz/hooks/useAuthZ/types.ts
+++ b/frontend/src/lib/authz/hooks/useAuthZ/types.ts
@@ -97,5 +97,9 @@ export type UseAuthZResult = {
* Checks that resolved as not granted (empty while loading/error).
*/
deniedPermissions: BrandedPermission[];
+ /**
+ * Use this to check if a specific permission is granted, false while loading or on error.
+ */
+ isGranted: (permission: BrandedPermission) => boolean;
refetchPermissions: () => void;
};
diff --git a/frontend/src/lib/authz/hooks/useAuthZ/useAuthZ.tsx b/frontend/src/lib/authz/hooks/useAuthZ/useAuthZ.tsx
index 3949b7214a..979c8c717a 100644
--- a/frontend/src/lib/authz/hooks/useAuthZ/useAuthZ.tsx
+++ b/frontend/src/lib/authz/hooks/useAuthZ/useAuthZ.tsx
@@ -240,6 +240,12 @@ export function useAuthZ(
return permissions.every((check) => data[check]?.isGranted === true);
}, [permissions, data, isLoading, error]);
+ const isGranted = useCallback(
+ (permission: BrandedPermission): boolean =>
+ data?.[permission]?.isGranted === true,
+ [data],
+ );
+
const deniedPermissions = useMemo(() => {
if (!data) {
return [];
@@ -254,6 +260,7 @@ export function useAuthZ(
permissions: data ?? null,
allowed,
deniedPermissions,
+ isGranted,
refetchPermissions,
};
}
diff --git a/frontend/src/lib/authz/utils/authz-test-utils.ts b/frontend/src/lib/authz/utils/authz-test-utils.ts
index e6d741b165..36ce3a48a6 100644
--- a/frontend/src/lib/authz/utils/authz-test-utils.ts
+++ b/frontend/src/lib/authz/utils/authz-test-utils.ts
@@ -170,6 +170,7 @@ export function mockUseAuthZGrantAll(
) as UseAuthZResult['permissions'],
allowed: true,
deniedPermissions: [],
+ isGranted: (): boolean => true,
refetchPermissions: jest.fn(),
};
}
@@ -187,6 +188,7 @@ export function mockUseAuthZDenyAll(
) as UseAuthZResult['permissions'],
allowed: false,
deniedPermissions: permissions,
+ isGranted: (): boolean => false,
refetchPermissions: jest.fn(),
};
}
@@ -213,6 +215,8 @@ export function mockUseAuthZGrantByPrefix(
) as UseAuthZResult['permissions'],
allowed: denied.length === 0,
deniedPermissions: denied,
+ isGranted: (permission): boolean =>
+ prefixes.some((prefix) => permission.startsWith(prefix)),
refetchPermissions: jest.fn(),
};
};