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): migrate authorization to authz instead of user.role (#10486)

Vinicius Lourençoce5499d5a798
diff --git a/frontend/src/api/index.ts b/frontend/src/api/index.ts
index 338fcc8b12..01e22aeb38 100644
--- a/frontend/src/api/index.ts
+++ b/frontend/src/api/index.ts
@@ -81,7 +81,8 @@ export const interceptorRejected = async (
response.config.url !== '/sessions/email_password' &&
!(
response.config.url === '/sessions' && response.config.method === 'delete'
- )
+ ) &&
+ response.config.url !== '/authz/check'
) {
try {
const accessToken = getLocalStorageApi(LOCALSTORAGE.AUTH_TOKEN);
diff --git a/frontend/src/api/interceptors.test.ts b/frontend/src/api/interceptors.test.ts
new file mode 100644
index 0000000000..130572602e
--- /dev/null
+++ b/frontend/src/api/interceptors.test.ts
@@ -0,0 +1,152 @@
+import axios, { AxiosHeaders, AxiosResponse } from 'axios';
+
+import { interceptorRejected } from './index';
+
+jest.mock('api/browser/localstorage/get', () => ({
+ __esModule: true,
+ default: jest.fn(() => 'mock-token'),
+}));
+
+jest.mock('api/v2/sessions/rotate/post', () => ({
+ __esModule: true,
+ default: jest.fn(() =>
+ Promise.resolve({
+ data: { accessToken: 'new-token', refreshToken: 'new-refresh' },
+ }),
+ ),
+}));
+
+jest.mock('AppRoutes/utils', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+jest.mock('axios', () => {
+ const actualAxios = jest.requireActual('axios');
+ const mockAxios = jest.fn().mockResolvedValue({ data: 'success' });
+
+ return {
+ ...actualAxios,
+ default: Object.assign(mockAxios, {
+ ...actualAxios.default,
+ isAxiosError: jest.fn().mockReturnValue(true),
+ create: actualAxios.create,
+ }),
+ __esModule: true,
+ };
+});
+
+describe('interceptorRejected', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ ((axios as unknown) as jest.Mock).mockResolvedValue({ data: 'success' });
+ ((axios.isAxiosError as unknown) as jest.Mock).mockReturnValue(true);
+ });
+
+ it('should preserve array payload structure when retrying a 401 request', async () => {
+ const arrayPayload = [
+ { relation: 'assignee', object: { resource: { name: 'role' } } },
+ { relation: 'assignee', object: { resource: { name: 'editor' } } },
+ ];
+
+ const error = ({
+ response: {
+ status: 401,
+ config: {
+ url: '/some-endpoint',
+ method: 'POST',
+ baseURL: 'http://localhost/',
+ headers: new AxiosHeaders(),
+ data: JSON.stringify(arrayPayload),
+ },
+ },
+ config: {
+ url: '/some-endpoint',
+ method: 'POST',
+ baseURL: 'http://localhost/',
+ headers: new AxiosHeaders(),
+ data: JSON.stringify(arrayPayload),
+ },
+ } as unknown) as AxiosResponse;
+
+ try {
+ await interceptorRejected(error);
+ } catch {
+ // Expected to reject after retry
+ }
+
+ const mockAxiosFn = (axios as unknown) as jest.Mock;
+ expect(mockAxiosFn.mock.calls.length).toBe(1);
+ const retryCallConfig = mockAxiosFn.mock.calls[0][0];
+ expect(Array.isArray(JSON.parse(retryCallConfig.data))).toBe(true);
+ expect(JSON.parse(retryCallConfig.data)).toEqual(arrayPayload);
+ });
+
+ it('should preserve object payload structure when retrying a 401 request', async () => {
+ const objectPayload = { key: 'value', nested: { data: 123 } };
+
+ const error = ({
+ response: {
+ status: 401,
+ config: {
+ url: '/some-endpoint',
+ method: 'POST',
+ baseURL: 'http://localhost/',
+ headers: new AxiosHeaders(),
+ data: JSON.stringify(objectPayload),
+ },
+ },
+ config: {
+ url: '/some-endpoint',
+ method: 'POST',
+ baseURL: 'http://localhost/',
+ headers: new AxiosHeaders(),
+ data: JSON.stringify(objectPayload),
+ },
+ } as unknown) as AxiosResponse;
+
+ try {
+ await interceptorRejected(error);
+ } catch {
+ // Expected to reject after retry
+ }
+
+ const mockAxiosFn = (axios as unknown) as jest.Mock;
+ expect(mockAxiosFn.mock.calls.length).toBe(1);
+ const retryCallConfig = mockAxiosFn.mock.calls[0][0];
+ expect(JSON.parse(retryCallConfig.data)).toEqual(objectPayload);
+ });
+
+ it('should handle undefined data gracefully when retrying', async () => {
+ const error = ({
+ response: {
+ status: 401,
+ config: {
+ url: '/some-endpoint',
+ method: 'GET',
+ baseURL: 'http://localhost/',
+ headers: new AxiosHeaders(),
+ data: undefined,
+ },
+ },
+ config: {
+ url: '/some-endpoint',
+ method: 'GET',
+ baseURL: 'http://localhost/',
+ headers: new AxiosHeaders(),
+ data: undefined,
+ },
+ } as unknown) as AxiosResponse;
+
+ try {
+ await interceptorRejected(error);
+ } catch {
+ // Expected to reject after retry
+ }
+
+ const mockAxiosFn = (axios as unknown) as jest.Mock;
+ expect(mockAxiosFn.mock.calls.length).toBe(1);
+ const retryCallConfig = mockAxiosFn.mock.calls[0][0];
+ expect(retryCallConfig.data).toBeUndefined();
+ });
+});
diff --git a/frontend/src/assets/UnAuthorized.tsx b/frontend/src/assets/UnAuthorized.tsx
index 93cfb48d1e..4eacd78571 100644
--- a/frontend/src/assets/UnAuthorized.tsx
+++ b/frontend/src/assets/UnAuthorized.tsx
@@ -1,8 +1,14 @@
-function UnAuthorized(): JSX.Element {
+function UnAuthorized({
+ width = 137,
+ height = 137,
+}: {
+ height?: number;
+ width?: number;
+}): JSX.Element {
return (
<svg
- width="137"
- height="137"
+ width={width}
+ height={height}
viewBox="0 0 137 137"
fill="none"
xmlns="http://www.w3.org/2000/svg"
diff --git a/frontend/src/components/ShiftOverlay/ShiftHoldOverlayController.tsx b/frontend/src/components/ShiftOverlay/ShiftHoldOverlayController.tsx
index d7960ed4f8..46504c6502 100644
--- a/frontend/src/components/ShiftOverlay/ShiftHoldOverlayController.tsx
+++ b/frontend/src/components/ShiftOverlay/ShiftHoldOverlayController.tsx
@@ -1,13 +1,13 @@
import { createShortcutActions } from '../../constants/shortcutActions';
import { useCmdK } from '../../providers/cmdKProvider';
+import { ROLES } from '../../types/roles';
import { ShiftOverlay } from './ShiftOverlay';
import { useShiftHoldOverlay } from './useShiftHoldOverlay';
-type UserRole = 'ADMIN' | 'EDITOR' | 'AUTHOR' | 'VIEWER';
export function ShiftHoldOverlayController({
userRole,
}: {
- userRole: UserRole;
+ userRole: ROLES;
}): JSX.Element | null {
const { open: isCmdKOpen } = useCmdK();
const noop = (): void => undefined;
diff --git a/frontend/src/components/ShiftOverlay/ShiftOverlay.tsx b/frontend/src/components/ShiftOverlay/ShiftOverlay.tsx
index 6ab6595b70..4f0b810852 100644
--- a/frontend/src/components/ShiftOverlay/ShiftOverlay.tsx
+++ b/frontend/src/components/ShiftOverlay/ShiftOverlay.tsx
@@ -1,18 +1,18 @@
import { useMemo } from 'react';
import ReactDOM from 'react-dom';
+import { ROLES } from 'types/roles';
import { formatShortcut } from './formatShortcut';
import './shiftOverlay.scss';
-export type UserRole = 'ADMIN' | 'EDITOR' | 'AUTHOR' | 'VIEWER';
export type CmdAction = {
id: string;
name: string;
shortcut?: string[];
keywords?: string;
section?: string;
- roles?: UserRole[];
+ roles?: ROLES[];
perform: () => void;
};
@@ -33,7 +33,7 @@ function Shortcut({ label, keyHint }: ShortcutProps): JSX.Element {
interface ShiftOverlayProps {
visible: boolean;
actions: CmdAction[];
- userRole: UserRole;
+ userRole: ROLES;
}
export function ShiftOverlay({
diff --git a/frontend/src/components/cmdKPalette/cmdKPalette.tsx b/frontend/src/components/cmdKPalette/cmdKPalette.tsx
index 689fcb2ce6..032af7ba25 100644
--- a/frontend/src/components/cmdKPalette/cmdKPalette.tsx
+++ b/frontend/src/components/cmdKPalette/cmdKPalette.tsx
@@ -11,6 +11,7 @@ import {
import logEvent from 'api/common/logEvent';
import { useThemeMode } from 'hooks/useDarkMode';
import history from 'lib/history';
+import { ROLES as UserRole } from 'types/roles';
import { createShortcutActions } from '../../constants/shortcutActions';
import { useCmdK } from '../../providers/cmdKProvider';
@@ -28,7 +29,6 @@ type CmdAction = {
perform: () => void;
};
-type UserRole = 'ADMIN' | 'EDITOR' | 'AUTHOR' | 'VIEWER';
export function CmdKPalette({
userRole,
}: {
diff --git a/frontend/src/constants/shortcutActions.tsx b/frontend/src/constants/shortcutActions.tsx
index ef74b8e1c0..7530612a96 100644
--- a/frontend/src/constants/shortcutActions.tsx
+++ b/frontend/src/constants/shortcutActions.tsx
@@ -18,8 +18,7 @@ import {
TowerControl,
Workflow,
} from 'lucide-react';
-
-export type UserRole = 'ADMIN' | 'EDITOR' | 'AUTHOR' | 'VIEWER';
+import { ROLES } from 'types/roles';
export type CmdAction = {
id: string;
@@ -28,7 +27,7 @@ export type CmdAction = {
keywords?: string;
section?: string;
icon?: React.ReactNode;
- roles?: UserRole[];
+ roles?: ROLES[];
perform: () => void;
};
diff --git a/frontend/src/hooks/useAuthZ/constants.ts b/frontend/src/hooks/useAuthZ/constants.ts
new file mode 100644
index 0000000000..b956048a2a
--- /dev/null
+++ b/frontend/src/hooks/useAuthZ/constants.ts
@@ -0,0 +1,2 @@
+export const SINGLE_FLIGHT_WAIT_TIME_MS = 50;
+export const AUTHZ_CACHE_TIME = 20_000;
diff --git a/frontend/src/hooks/useAuthZ/legacy.ts b/frontend/src/hooks/useAuthZ/legacy.ts
new file mode 100644
index 0000000000..719f7dfe86
--- /dev/null
+++ b/frontend/src/hooks/useAuthZ/legacy.ts
@@ -0,0 +1,18 @@
+import { buildPermission } from './utils';
+
+export const IsAdminPermission = buildPermission(
+ 'assignee',
+ 'role:signoz-admin',
+);
+export const IsEditorPermission = buildPermission(
+ 'assignee',
+ 'role:signoz-editor',
+);
+export const IsViewerPermission = buildPermission(
+ 'assignee',
+ 'role:signoz-viewer',
+);
+export const IsAnonymousPermission = buildPermission(
+ 'assignee',
+ 'role:signoz-anonymous',
+);
diff --git a/frontend/src/hooks/useAuthZ/types.ts b/frontend/src/hooks/useAuthZ/types.ts
index 03728d9315..a8d78c0b23 100644
--- a/frontend/src/hooks/useAuthZ/types.ts
+++ b/frontend/src/hooks/useAuthZ/types.ts
@@ -14,7 +14,7 @@ type ResourceTypeMap = {
type RelationName = keyof RelationsByType;
-type ResourcesForRelation<R extends RelationName> = Extract<
+export type ResourcesForRelation<R extends RelationName> = Extract<
Resource,
{ type: RelationsByType[R][number] }
>['name'];
@@ -50,8 +50,26 @@ export type AuthZCheckResponse = Record<
}
>;
+export type UseAuthZOptions = {
+ /**
+ * If false, the query/permissions will not be fetched.
+ * Useful when you want to disable the query/permissions for a specific use case, like logout.
+ *
+ * @default true
+ */
+ enabled?: boolean;
+};
+
export type UseAuthZResult = {
+ /**
+ * If query is cached, and refetch happens in background, this is false.
+ */
isLoading: boolean;
+ /**
+ * If query is fetching, even if happens in background, this is true.
+ */
+ isFetching: boolean;
error: Error | null;
permissions: AuthZCheckResponse | null;
+ refetchPermissions: () => void;
};
diff --git a/frontend/src/hooks/useAuthZ/useAuthZ.tsx b/frontend/src/hooks/useAuthZ/useAuthZ.tsx
index aebc85af4e..74d7930edf 100644
--- a/frontend/src/hooks/useAuthZ/useAuthZ.tsx
+++ b/frontend/src/hooks/useAuthZ/useAuthZ.tsx
@@ -1,4 +1,4 @@
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { useQueries } from 'react-query';
import { authzCheck } from 'api/generated/services/authz';
import type {
@@ -6,7 +6,13 @@ import type {
AuthtypesTransactionDTO,
} from 'api/generated/services/sigNoz.schemas';
-import { AuthZCheckResponse, BrandedPermission, UseAuthZResult } from './types';
+import { AUTHZ_CACHE_TIME, SINGLE_FLIGHT_WAIT_TIME_MS } from './constants';
+import {
+ AuthZCheckResponse,
+ BrandedPermission,
+ UseAuthZOptions,
+ UseAuthZResult,
+} from './types';
import {
gettableTransactionToPermission,
permissionToTransactionDto,
@@ -14,8 +20,6 @@ import {
let ctx: Promise<AuthZCheckResponse> | null;
let pendingPermissions: BrandedPermission[] = [];
-const SINGLE_FLIGHT_WAIT_TIME_MS = 50;
-const AUTHZ_CACHE_TIME = 20_000;
function dispatchPermission(
permission: BrandedPermission,
@@ -70,7 +74,12 @@ async function fetchManyPermissions(
}, {} as AuthZCheckResponse);
}
-export function useAuthZ(permissions: BrandedPermission[]): UseAuthZResult {
+export function useAuthZ(
+ permissions: BrandedPermission[],
+ options?: UseAuthZOptions,
+): UseAuthZResult {
+ const { enabled } = options ?? { enabled: true };
+
const queryResults = useQueries(
permissions.map((permission) => {
return {
@@ -80,6 +89,7 @@ export function useAuthZ(permissions: BrandedPermission[]): UseAuthZResult {
refetchIntervalInBackground: false,
refetchOnWindowFocus: false,
refetchOnReconnect: true,
+ enabled,
queryFn: async (): Promise<AuthZCheckResponse> => {
const response = await dispatchPermission(permission);
@@ -96,6 +106,10 @@ export function useAuthZ(permissions: BrandedPermission[]): UseAuthZResult {
const isLoading = useMemo(() => queryResults.some((q) => q.isLoading), [
queryResults,
]);
+ const isFetching = useMemo(() => queryResults.some((q) => q.isFetching), [
+ queryResults,
+ ]);
+
const error = useMemo(
() =>
!isLoading
@@ -121,9 +135,17 @@ export function useAuthZ(permissions: BrandedPermission[]): UseAuthZResult {
}, {} as AuthZCheckResponse);
}, [isLoading, error, queryResults]);
+ const refetchPermissions = useCallback(() => {
+ for (const query of queryResults) {
+ query.refetch();
+ }
+ }, [queryResults]);
+
return {
isLoading,
+ isFetching,
error,
permissions: data ?? null,
+ refetchPermissions,
};
}
diff --git a/frontend/src/hooks/useAuthZ/utils.ts b/frontend/src/hooks/useAuthZ/utils.ts
index a379fd0794..8ea5806006 100644
--- a/frontend/src/hooks/useAuthZ/utils.ts
+++ b/frontend/src/hooks/useAuthZ/utils.ts
@@ -3,9 +3,9 @@ import permissionsType from './permissions.type';
import {
AuthZObject,
AuthZRelation,
- AuthZResource,
BrandedPermission,
ResourceName,
+ ResourcesForRelation,
ResourceType,
} from './types';
@@ -19,11 +19,10 @@ export function buildPermission<R extends AuthZRelation>(
return `${relation}${PermissionSeparator}${object}` as BrandedPermission;
}
-export function buildObjectString(
- resource: AuthZResource,
- objectId: string,
-): `${AuthZResource}${typeof ObjectSeparator}${string}` {
- return `${resource}${ObjectSeparator}${objectId}` as const;
+export function buildObjectString<
+ R extends 'delete' | 'read' | 'update' | 'assignee'
+>(resource: ResourcesForRelation<R>, objectId: string): AuthZObject<R> {
+ return `${resource}${ObjectSeparator}${objectId}` as AuthZObject<R>;
}
export function parsePermission(
diff --git a/frontend/src/pages/UnAuthorized/index.styles.scss b/frontend/src/pages/UnAuthorized/index.styles.scss
new file mode 100644
index 0000000000..b1666088de
--- /dev/null
+++ b/frontend/src/pages/UnAuthorized/index.styles.scss
@@ -0,0 +1,5 @@
+.unauthorized-page {
+ &__description {
+ text-align: center;
+ }
+}
diff --git a/frontend/src/pages/UnAuthorized/index.tsx b/frontend/src/pages/UnAuthorized/index.tsx
index cec1409fb6..43ef920b01 100644
--- a/frontend/src/pages/UnAuthorized/index.tsx
+++ b/frontend/src/pages/UnAuthorized/index.tsx
@@ -1,20 +1,51 @@
+import { useCallback } from 'react';
import { Space, Typography } from 'antd';
import UnAuthorized from 'assets/UnAuthorized';
-import { Button, Container } from 'components/NotFound/styles';
-import ROUTES from 'constants/routes';
+import { Container } from 'components/NotFound/styles';
+import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
+import { useQueryState } from 'nuqs';
+import { handleContactSupport } from 'pages/Integrations/utils';
+
+import { useAppContext } from '../../providers/App/App';
+import { USER_ROLES } from '../../types/roles';
+
+import './index.styles.scss';
function UnAuthorizePage(): JSX.Element {
+ const [debugCurrentRole] = useQueryState('currentRole');
+ const { user } = useAppContext();
+ const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
+
+ const userIsAnonymous =
+ debugCurrentRole === USER_ROLES.ANONYMOUS ||
+ user.role === USER_ROLES.ANONYMOUS;
+ const mistakeMessage = userIsAnonymous
+ ? 'If you believe this is a mistake, please contact your administrator or'
+ : 'Please contact your administrator.';
+
+ const handleContactSupportClick = useCallback((): void => {
+ handleContactSupport(isCloudUserVal);
+ }, [isCloudUserVal]);
+
return (
- <Container>
+ <Container className="unauthorized-page">
<Space align="center" direction="vertical">
- <UnAuthorized />
- <Typography.Title level={3}>
- Oops.. you don&apos;t have permission to view this page
- </Typography.Title>
-
- <Button to={ROUTES.HOME} tabIndex={0} className="periscope-btn primary">
- Return To Home
- </Button>
+ <UnAuthorized width={64} height={64} />
+ <Typography.Title level={3}>Access Restricted</Typography.Title>
+
+ <p className="unauthorized-page__description">
+ It looks like you don&lsquo;t have permission to view this page. <br />
+ {mistakeMessage}
+ {userIsAnonymous ? (
+ <Typography.Link
+ className="contact-support-link"
+ onClick={handleContactSupportClick}
+ >
+ {' '}
+ reach out to us.
+ </Typography.Link>
+ ) : null}
+ </p>
</Space>
</Container>
);
diff --git a/frontend/src/providers/App/App.tsx b/frontend/src/providers/App/App.tsx
index d43bede202..8fc9d6a56f 100644
--- a/frontend/src/providers/App/App.tsx
+++ b/frontend/src/providers/App/App.tsx
@@ -19,6 +19,12 @@ import getUserVersion from 'api/v1/version/get';
import { LOCALSTORAGE } from 'constants/localStorage';
import dayjs from 'dayjs';
import useActiveLicenseV3 from 'hooks/useActiveLicenseV3/useActiveLicenseV3';
+import {
+ IsAdminPermission,
+ IsEditorPermission,
+ IsViewerPermission,
+} from 'hooks/useAuthZ/legacy';
+import { useAuthZ } from 'hooks/useAuthZ/useAuthZ';
import { useGetFeatureFlag } from 'hooks/useGetFeatureFlag';
import { useGlobalEventListener } from 'hooks/useGlobalEventListener';
import { ChangelogSchema } from 'types/api/changelog/getChangelogByVersion';
@@ -34,7 +40,7 @@ import {
UserPreference,
} from 'types/api/preferences/preference';
import { Organization } from 'types/api/user/getOrganization';
-import { USER_ROLES } from 'types/roles';
+import { ROLES, USER_ROLES } from 'types/roles';
import { IAppContext, IUser } from './types';
import { getUserDefaults } from './utils';
@@ -43,7 +49,7 @@ export const AppContext = createContext<IAppContext | undefined>(undefined);
export function AppProvider({ children }: PropsWithChildren): JSX.Element {
// on load of the provider set the user defaults with access token , refresh token from local storage
- const [user, setUser] = useState<IUser>(() => getUserDefaults());
+ const [defaultUser, setDefaultUser] = useState<IUser>(() => getUserDefaults());
const [activeLicense, setActiveLicense] = useState<LicenseResModel | null>(
null,
);
@@ -70,18 +76,51 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
// if logged out and trying to hit any route none of these calls will trigger
const {
data: userData,
- isFetching: isFetchingUser,
- error: userFetchError,
+ isFetching: isFetchingUserData,
+ error: userFetchDataError,
} = useQuery({
queryFn: get,
queryKey: ['/api/v1/user/me'],
enabled: isLoggedIn,
});
+ const {
+ permissions: permissionsResult,
+ isFetching: isFetchingPermissions,
+ error: errorOnPermissions,
+ refetchPermissions,
+ } = useAuthZ([IsAdminPermission, IsEditorPermission, IsViewerPermission], {
+ enabled: isLoggedIn,
+ });
+
+ const isFetchingUser = isFetchingUserData || isFetchingPermissions;
+ const userFetchError = userFetchDataError || errorOnPermissions;
+
+ const userRole = useMemo(() => {
+ if (permissionsResult?.[IsAdminPermission]?.isGranted) {
+ return USER_ROLES.ADMIN;
+ }
+ if (permissionsResult?.[IsEditorPermission]?.isGranted) {
+ return USER_ROLES.EDITOR;
+ }
+ if (permissionsResult?.[IsViewerPermission]?.isGranted) {
+ return USER_ROLES.VIEWER;
+ }
+ // if none of the permissions, so anonymous
+ return USER_ROLES.ANONYMOUS;
+ }, [permissionsResult]);
+
+ const user: IUser = useMemo(() => {
+ return {
+ ...defaultUser,
+ role: userRole as ROLES,
+ };
+ }, [defaultUser, userRole]);
+
useEffect(() => {
if (!isFetchingUser && userData && userData.data) {
setLocalStorageApi(LOCALSTORAGE.LOGGED_IN_USER_EMAIL, userData.data.email);
- setUser((prev) => ({
+ setDefaultUser((prev) => ({
...prev,
...userData.data,
}));
@@ -203,7 +242,7 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
}, [userPreferencesData, isFetchingUserPreferences, isLoggedIn]);
function updateUser(user: IUser): void {
- setUser((prev) => ({
+ setDefaultUser((prev) => ({
...prev,
...user,
}));
@@ -244,7 +283,7 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
...org.slice(orgIndex + 1, org.length),
];
setOrg(updatedOrg);
- setUser((prev) => {
+ setDefaultUser((prev) => {
if (prev.orgId === orgId) {
return {
...prev,
@@ -272,7 +311,7 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
// global event listener for AFTER_LOGIN event to start the user fetch post all actions are complete
useGlobalEventListener('AFTER_LOGIN', (event) => {
if (event.detail) {
- setUser((prev) => ({
+ setDefaultUser((prev) => ({
...prev,
accessJwt: event.detail.accessJWT,
refreshJwt: event.detail.refreshJWT,
@@ -280,12 +319,14 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
}));
setIsLoggedIn(true);
}
+
+ refetchPermissions();
});
// global event listener for LOGOUT event to clean the app context state
useGlobalEventListener('LOGOUT', () => {
setIsLoggedIn(false);
- setUser(getUserDefaults());
+ setDefaultUser(getUserDefaults());
setActiveLicense(null);
setTrialInfo(null);
setFeatureFlags(null);
diff --git a/frontend/src/providers/App/__tests__/App.test.tsx b/frontend/src/providers/App/__tests__/App.test.tsx
new file mode 100644
index 0000000000..1d61c6cb9c
--- /dev/null
+++ b/frontend/src/providers/App/__tests__/App.test.tsx
@@ -0,0 +1,273 @@
+import { ReactElement } from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { renderHook, waitFor } from '@testing-library/react';
+import setLocalStorageApi from 'api/browser/localstorage/set';
+import {
+ AuthtypesGettableTransactionDTO,
+ AuthtypesTransactionDTO,
+} from 'api/generated/services/sigNoz.schemas';
+import { LOCALSTORAGE } from 'constants/localStorage';
+import { SINGLE_FLIGHT_WAIT_TIME_MS } from 'hooks/useAuthZ/constants';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { USER_ROLES } from 'types/roles';
+
+import { AppProvider, useAppContext } from '../App';
+
+const AUTHZ_CHECK_URL = 'http://localhost/api/v1/authz/check';
+
+jest.mock('constants/env', () => ({
+ ENVIRONMENT: { baseURL: 'http://localhost', wsURL: '' },
+}));
+
+/**
+ * Since we are mocking the check permissions, this is needed
+ */
+const waitForSinglePreflightToFinish = async (): Promise<void> =>
+ await new Promise((r) => setTimeout(r, SINGLE_FLIGHT_WAIT_TIME_MS));
+
+function authzMockResponse(
+ payload: AuthtypesTransactionDTO[],
+ authorizedByIndex: boolean[],
+): { data: AuthtypesGettableTransactionDTO[]; status: string } {
+ return {
+ data: payload.map((txn, i) => ({
+ relation: txn.relation,
+ object: txn.object,
+ authorized: authorizedByIndex[i] ?? false,
+ })),
+ status: 'success',
+ };
+}
+
+const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ refetchOnWindowFocus: false,
+ retry: false,
+ },
+ },
+});
+
+function createWrapper(): ({
+ children,
+}: {
+ children: ReactElement;
+}) => ReactElement {
+ return function Wrapper({
+ children,
+ }: {
+ children: ReactElement;
+ }): ReactElement {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <AppProvider>{children}</AppProvider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+describe('AppProvider user.role from permissions', () => {
+ beforeEach(() => {
+ queryClient.clear();
+ setLocalStorageApi(LOCALSTORAGE.IS_LOGGED_IN, 'true');
+ });
+
+ it('sets user.role to ADMIN and hasEditPermission to true when admin permission is granted', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [true, false, false])),
+ );
+ }),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.user.role).toBe(USER_ROLES.ADMIN);
+ expect(result.current.hasEditPermission).toBe(true);
+ },
+ { timeout: 2000 },
+ );
+ });
+
+ it('sets user.role to EDITOR and hasEditPermission to true when only editor permission is granted', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [false, true, false])),
+ );
+ }),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.user.role).toBe(USER_ROLES.EDITOR);
+ expect(result.current.hasEditPermission).toBe(true);
+ },
+ { timeout: 2000 },
+ );
+ });
+
+ it('sets user.role to VIEWER and hasEditPermission to false when only viewer permission is granted', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [false, false, true])),
+ );
+ }),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.user.role).toBe(USER_ROLES.VIEWER);
+ expect(result.current.hasEditPermission).toBe(false);
+ },
+ { timeout: 2000 },
+ );
+ });
+
+ it('sets user.role to ANONYMOUS and hasEditPermission to false when no role permission is granted', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [false, false, false])),
+ );
+ }),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.user.role).toBe(USER_ROLES.ANONYMOUS);
+ expect(result.current.hasEditPermission).toBe(false);
+ },
+ { timeout: 2000 },
+ );
+ });
+
+ /**
+ * This is expected to not happen, but we'll test it just in case.
+ */
+ describe('when multiple role permissions are granted', () => {
+ it('prefers ADMIN over EDITOR and VIEWER when multiple role permissions are granted', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [true, true, true])),
+ );
+ }),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitFor(
+ () => {
+ expect(result.current.user.role).toBe(USER_ROLES.ADMIN);
+ expect(result.current.hasEditPermission).toBe(true);
+ },
+ { timeout: 300 },
+ );
+ });
+
+ it('prefers EDITOR over VIEWER when editor and viewer permissions are granted', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [false, true, true])),
+ );
+ }),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.user.role).toBe(USER_ROLES.EDITOR);
+ expect(result.current.hasEditPermission).toBe(true);
+ },
+ { timeout: 2000 },
+ );
+ });
+ });
+});
+
+describe('AppProvider when authz/check fails', () => {
+ beforeEach(() => {
+ queryClient.clear();
+ setLocalStorageApi(LOCALSTORAGE.IS_LOGGED_IN, 'true');
+ });
+
+ it('sets userFetchError when authz/check returns 500 (same as user fetch error)', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, (_, res, ctx) =>
+ res(ctx.status(500), ctx.json({ error: 'Internal Server Error' })),
+ ),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.userFetchError).toBeTruthy();
+ },
+ { timeout: 2000 },
+ );
+ });
+
+ it('sets userFetchError when authz/check fails with network error (same as user fetch error)', async () => {
+ server.use(
+ rest.post(AUTHZ_CHECK_URL, (_, res) => res.networkError('Network error')),
+ );
+
+ const wrapper = createWrapper();
+ const { result } = renderHook(() => useAppContext(), { wrapper });
+
+ await waitForSinglePreflightToFinish();
+
+ await waitFor(
+ () => {
+ expect(result.current.userFetchError).toBeTruthy();
+ },
+ { timeout: 2000 },
+ );
+ });
+});
diff --git a/frontend/src/types/api/user/getUser.ts b/frontend/src/types/api/user/getUser.ts
index 3030336c6e..de15453565 100644
--- a/frontend/src/types/api/user/getUser.ts
+++ b/frontend/src/types/api/user/getUser.ts
@@ -13,6 +13,9 @@ export interface UserResponse {
displayName: string;
orgId: string;
organization: string;
+ /**
+ * @deprecated This will be removed in the future releases in favor of new AuthZ framework
+ */
role: ROLES;
updatedAt?: number;
}
diff --git a/frontend/src/types/roles.ts b/frontend/src/types/roles.ts
index 38ddef0cf3..c7c54f163b 100644
--- a/frontend/src/types/roles.ts
+++ b/frontend/src/types/roles.ts
@@ -2,14 +2,16 @@ export type ADMIN = 'ADMIN';
export type VIEWER = 'VIEWER';
export type EDITOR = 'EDITOR';
export type AUTHOR = 'AUTHOR';
+export type ANONYMOUS = 'ANONYMOUS';
-export type ROLES = ADMIN | VIEWER | EDITOR | AUTHOR;
+export type ROLES = ADMIN | VIEWER | EDITOR | AUTHOR | ANONYMOUS;
export const USER_ROLES = {
ADMIN: 'ADMIN',
VIEWER: 'VIEWER',
EDITOR: 'EDITOR',
AUTHOR: 'AUTHOR',
+ ANONYMOUS: 'ANONYMOUS',
};
export enum RoleType {
diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.ts
index 31ae963106..ed7a3828f4 100644
--- a/frontend/src/utils/permission/index.ts
+++ b/frontend/src/utils/permission/index.ts
@@ -69,7 +69,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
ALERT_OVERVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],
LOGIN: ['ADMIN', 'EDITOR', 'VIEWER'],
FORGOT_PASSWORD: ['ADMIN', 'EDITOR', 'VIEWER'],
- NOT_FOUND: ['ADMIN', 'VIEWER', 'EDITOR'],
+ NOT_FOUND: ['ADMIN', 'VIEWER', 'EDITOR', 'ANONYMOUS'],
PASSWORD_RESET: ['ADMIN', 'EDITOR', 'VIEWER'],
SERVICE_METRICS: ['ADMIN', 'EDITOR', 'VIEWER'],
SETTINGS: ['ADMIN', 'EDITOR', 'VIEWER'],
@@ -77,7 +77,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
TRACES_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
TRACE: ['ADMIN', 'EDITOR', 'VIEWER'],
TRACE_DETAIL: ['ADMIN', 'EDITOR', 'VIEWER'],
- UN_AUTHORIZED: ['ADMIN', 'EDITOR', 'VIEWER'],
+ UN_AUTHORIZED: ['ADMIN', 'EDITOR', 'VIEWER', 'ANONYMOUS'],
USAGE_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
VERSION: ['ADMIN', 'EDITOR', 'VIEWER'],
LOGS: ['ADMIN', 'EDITOR', 'VIEWER'],
@@ -101,7 +101,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
ROLE_DETAILS: ['ADMIN'],
MEMBERS_SETTINGS: ['ADMIN'],
BILLING: ['ADMIN'],
- SUPPORT: ['ADMIN', 'EDITOR', 'VIEWER'],
+ SUPPORT: ['ADMIN', 'EDITOR', 'VIEWER', 'ANONYMOUS'],
SOMETHING_WENT_WRONG: ['ADMIN', 'EDITOR', 'VIEWER'],
LOGS_SAVE_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],
TRACES_SAVE_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],