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
import { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
import { act, render, screen, waitFor } from '@testing-library/react';
import { LOCALSTORAGE } from 'constants/localStorage';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
import { AppContext } from 'providers/App/App';
import { IAppContext, IUser } from 'providers/App/types';
import {
LicenseEvent,
LicensePlatform,
LicenseResModel,
LicenseState,
LicenseStatus,
TrialInfo,
} from 'types/api/licensesV3/getActive';
import { OrgPreference } from 'types/api/preferences/preference';
import { ROLES, USER_ROLES } from 'types/roles';
import { routeWithInitialAuthZSupport } from 'utils/permission';
import PrivateRoute from '../Private';
// Mock localStorage APIs
const mockLocalStorage: Record<string, string> = {};
jest.mock('api/browser/localstorage/get', () => ({
__esModule: true,
default: (key: string): string | null => mockLocalStorage[key] || null,
}));
jest.mock('api/browser/localstorage/set', () => ({
__esModule: true,
default: (key: string, value: string): void => {
mockLocalStorage[key] = value;
},
}));
// Mock useGetTenantLicense hook
let mockIsCloudUser = true;
jest.mock('hooks/useGetTenantLicense', () => ({
useGetTenantLicense: (): {
isCloudUser: boolean;
isEnterpriseSelfHostedUser: boolean;
isCommunityUser: boolean;
isCommunityEnterpriseUser: boolean;
} => ({
isCloudUser: mockIsCloudUser,
isEnterpriseSelfHostedUser: !mockIsCloudUser,
isCommunityUser: false,
isCommunityEnterpriseUser: false,
}),
}));
// Mock react-query for users fetch
let mockUsersData: { email: string }[] = [];
jest.mock('api/generated/services/users', () => ({
...jest.requireActual('api/generated/services/users'),
useListUsers: jest.fn(() => ({
data: { data: mockUsersData },
isFetching: false,
})),
}));
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: false,
},
},
});
// Component to capture current location for assertions
function LocationDisplay(): ReactElement {
const location = useLocation();
return (
<>
<div data-testid="location-display">{location.pathname}</div>
<div data-testid="location-search">{location.search}</div>
<div data-testid="location-hash">{location.hash}</div>
</>
);
}
// Helper to create mock user
function createMockUser(overrides: Partial<IUser> = {}): IUser {
return {
accessJwt: 'test-token',
refreshJwt: 'test-refresh-token',
id: 'user-id',
email: '[email protected]',
displayName: 'Test User',
createdAt: 1732544623,
organization: 'Test Org',
orgId: 'org-id',
role: USER_ROLES.ADMIN as ROLES,
...overrides,
};
}
// Helper to create mock license
function createMockLicense(
overrides: Partial<LicenseResModel> = {},
): LicenseResModel {
return {
id: 'test-license-id',
eventQueue: {
createdAt: '0',
event: LicenseEvent.NO_EVENT,
scheduledAt: '0',
status: '',
updatedAt: '0',
},
state: LicenseState.ACTIVATED,
status: LicenseStatus.VALID,
platform: LicensePlatform.CLOUD,
createdAt: '0',
plan: {
id: '0',
createdAt: '0',
description: '',
isActive: true,
name: '',
updatedAt: '0',
},
freeUntil: '0',
updatedAt: '0',
validFrom: 0,
validUntil: 0,
...overrides,
};
}
// Helper to create mock trial info
function createMockTrialInfo(overrides: Partial<TrialInfo> = {}): TrialInfo {
return {
trialStart: -1,
trialEnd: -1,
onTrial: false,
workSpaceBlock: false,
trialConvertedToSubscription: false,
gracePeriodEnd: -1,
...overrides,
};
}
// Helper to create mock org preferences
function createMockOrgPreferences(onboardingComplete = true): OrgPreference[] {
return [
{
name: ORG_PREFERENCES.ORG_ONBOARDING,
description: 'Organisation Onboarding',
valueType: 'boolean',
defaultValue: false,
allowedValues: ['true', 'false'],
allowedScopes: ['org'],
value: onboardingComplete,
},
];
}
// Helper to create mock app context
function createMockAppContext(
overrides: Partial<IAppContext> = {},
): IAppContext {
return {
user: createMockUser(),
activeLicense: createMockLicense(),
trialInfo: createMockTrialInfo(),
featureFlags: [],
orgPreferences: createMockOrgPreferences(),
userPreferences: [],
hostsData: null,
isLoggedIn: true,
isPreflightLoading: false,
org: [{ createdAt: 0, id: 'org-id', displayName: 'Test Org' }],
isFetchingUser: false,
isFetchingActiveLicense: false,
isFetchingHosts: false,
isFetchingFeatureFlags: false,
isFetchingOrgPreferences: false,
isFetchingUserPreferences: false,
userFetchError: null,
activeLicenseFetchError: null,
hostsFetchError: null,
featureFlagsFetchError: null,
orgPreferencesFetchError: null,
changelog: null,
showChangelogModal: false,
activeLicenseRefetch: jest.fn(),
updateUser: jest.fn(),
updateOrgPreferences: jest.fn(),
updateUserPreferenceInContext: jest.fn(),
updateOrg: jest.fn(),
updateChangelog: jest.fn(),
toggleChangelogModal: jest.fn(),
versionData: { version: '1.0.0', ee: 'Y', setupCompleted: true },
hasEditPermission: true,
...overrides,
};
}
// Roles that no authz-aware route grants through the legacy routePermission table
const DENIED_ROLES: ROLES[] = [
USER_ROLES.ANONYMOUS as ROLES,
USER_ROLES.AUTHOR as ROLES,
];
const PERMITTED_ROLES: ROLES[] = [
USER_ROLES.ADMIN as ROLES,
USER_ROLES.EDITOR as ROLES,
USER_ROLES.VIEWER as ROLES,
];
interface AuthzRouteCase {
path: string;
deniedRoles: ROLES[];
}
interface RenderPrivateRouteOptions {
initialRoute?: string;
appContext?: Partial<IAppContext>;
isCloudUser?: boolean;
}
function buildPrivateRouteTree(
options: RenderPrivateRouteOptions,
): ReactElement {
const { initialRoute = ROUTES.HOME, appContext = {} } = options;
const contextValue = createMockAppContext({
...appContext,
});
return (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialRoute]}>
<AppContext.Provider value={contextValue}>
<PrivateRoute>
<Switch>
<Route path="*">
<div data-testid="children-rendered">Content</div>
<LocationDisplay />
</Route>
</Switch>
</PrivateRoute>
</AppContext.Provider>
</MemoryRouter>
</QueryClientProvider>
);
}
function renderPrivateRoute(options: RenderPrivateRouteOptions = {}): void {
mockIsCloudUser = options.isCloudUser ?? true;
render(buildPrivateRouteTree(options));
}
// Generic assertion helpers for navigation behavior
// Using location-based assertions since Private.tsx now uses Redirect component
async function assertRedirectsTo(targetRoute: string): Promise<void> {
await waitFor(() => {
expect(screen.getByTestId('location-display')).toHaveTextContent(targetRoute);
});
}
function assertStaysOnRoute(expectedRoute: string): void {
expect(screen.getByTestId('location-display')).toHaveTextContent(
expectedRoute,
);
}
function assertRendersChildren(): void {
expect(screen.getByTestId('children-rendered')).toBeInTheDocument();
}
describe('PrivateRoute', () => {
beforeEach(() => {
jest.clearAllMocks();
queryClient.clear();
Object.keys(mockLocalStorage).forEach((key) => delete mockLocalStorage[key]);
mockIsCloudUser = true;
mockUsersData = [];
});
describe('Old Routes Handling', () => {
it('should redirect /pipelines to /logs/pipelines preserving search params', () => {
renderPrivateRoute({ initialRoute: '/pipelines?foo=bar' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
'/logs/pipelines',
);
});
it('should redirect /logs-explorer to /logs/logs-explorer', () => {
renderPrivateRoute({ initialRoute: '/logs-explorer' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
'/logs/logs-explorer',
);
});
it.each([
['/logs-save-views', ROUTES.LOGS_EXPLORER],
['/traces-save-views', ROUTES.TRACES_EXPLORER],
['/logs/saved-views', ROUTES.LOGS_EXPLORER],
['/traces/saved-views', ROUTES.TRACES_EXPLORER],
['/metrics-explorer/views', ROUTES.METRICS_EXPLORER_EXPLORER],
['/meter/explorer/views', ROUTES.METER_EXPLORER],
])('should redirect the old views route %s to %s', (from, to) => {
renderPrivateRoute({ initialRoute: from });
expect(screen.getByTestId('location-display').textContent).toBe(to);
});
it('should redirect /settings/access-tokens to /settings/service-accounts', () => {
renderPrivateRoute({ initialRoute: '/settings/access-tokens' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
'/settings/service-accounts',
);
});
it('should redirect /settings/api-keys to /settings/service-accounts', () => {
renderPrivateRoute({ initialRoute: '/settings/api-keys' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
'/settings/service-accounts',
);
});
it('should redirect /messaging-queues to /messaging-queues/overview', () => {
renderPrivateRoute({ initialRoute: '/messaging-queues' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
'/messaging-queues/overview',
);
});
it('should redirect /alerts/edit to /alerts/overview', () => {
renderPrivateRoute({ initialRoute: '/alerts/edit' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
'/alerts/overview',
);
});
});
describe('Public Dashboard Route', () => {
it('should render children for public dashboard route without redirecting when not logged in', () => {
renderPrivateRoute({
initialRoute: '/public/dashboard/abc123',
appContext: { isLoggedIn: false },
});
assertRendersChildren();
assertStaysOnRoute('/public/dashboard/abc123');
});
it('should render children for public dashboard route when logged in without redirecting', () => {
renderPrivateRoute({
initialRoute: '/public/dashboard/abc123',
appContext: { isLoggedIn: true },
});
assertRendersChildren();
// Critical: without the isPublicDashboard early return, logged-in users
// would be redirected to HOME due to the non-private route handling
assertStaysOnRoute('/public/dashboard/abc123');
});
});
describe('Private Routes - User Not Logged In', () => {
it('should redirect to login when accessing private route without authentication', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: { isLoggedIn: false },
});
await assertRedirectsTo(ROUTES.LOGIN);
});
it('should save current pathname to localStorage before redirecting to login', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ALL_DASHBOARD,
appContext: { isLoggedIn: false },
});
await waitFor(() => {
expect(mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT]).toBe(
ROUTES.ALL_DASHBOARD,
);
});
await assertRedirectsTo(ROUTES.LOGIN);
});
it('should redirect to login for /services route when not logged in', async () => {
renderPrivateRoute({
initialRoute: ROUTES.APPLICATION,
appContext: { isLoggedIn: false },
});
await assertRedirectsTo(ROUTES.LOGIN);
});
it('should redirect to login for /alerts route when not logged in', async () => {
renderPrivateRoute({
initialRoute: ROUTES.LIST_ALL_ALERT,
appContext: { isLoggedIn: false },
});
await assertRedirectsTo(ROUTES.LOGIN);
});
});
describe('Private Routes - User Logged In', () => {
it('should render children when logged in user has correct permissions for route', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertRendersChildren();
assertStaysOnRoute(ROUTES.HOME);
});
it('should redirect to unauthorized when VIEWER tries to access admin-only route /alerts/new', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ALERTS_NEW,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
});
it('should not redirect VIEWER from /settings/org-settings since it matches SETTINGS route which allows all roles', () => {
// Note: ORG_SETTINGS is not a standalone route in routes.ts
// It's handled by the SETTINGS route (exact: false) which allows all roles
// The actual permission check happens inside SettingsPage component
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
// VIEWER can access since SETTINGS route allows all roles
assertRendersChildren();
});
it('should allow ADMIN to access /settings/org-settings', () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertRendersChildren();
});
it('should allow EDITOR to access /alerts/new route', () => {
renderPrivateRoute({
initialRoute: ROUTES.ALERTS_NEW,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.EDITOR as ROLES }),
},
});
assertRendersChildren();
});
it('should allow VIEWER to access /dashboard route', () => {
renderPrivateRoute({
initialRoute: '/dashboard/test-id',
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
assertRendersChildren();
});
});
describe('Non-Private Routes - User Logged In', () => {
it('should redirect to saved route from localStorage when logging in', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] =
ROUTES.ALL_DASHBOARD;
renderPrivateRoute({
initialRoute: ROUTES.LOGIN,
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
});
it('should clear localStorage after redirecting to saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] = ROUTES.HOME;
renderPrivateRoute({
initialRoute: ROUTES.LOGIN,
appContext: { isLoggedIn: true },
});
await waitFor(() => {
expect(mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT]).toBe('');
});
});
it('should redirect to home when logged in user visits login page with no saved route', async () => {
renderPrivateRoute({
initialRoute: ROUTES.LOGIN,
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.HOME);
});
it('should not redirect when on /something-went-wrong page even when logged in', () => {
renderPrivateRoute({
initialRoute: ROUTES.SOMETHING_WENT_WRONG,
appContext: { isLoggedIn: true },
});
assertStaysOnRoute(ROUTES.SOMETHING_WENT_WRONG);
});
});
describe('Non-Private Routes - User Not Logged In', () => {
it('should not redirect when not logged in user visits login page', () => {
renderPrivateRoute({
initialRoute: ROUTES.LOGIN,
appContext: { isLoggedIn: false },
});
// Should not redirect - login page handles its own routing
assertStaysOnRoute(ROUTES.LOGIN);
});
it('should not redirect when not logged in user visits signup page', () => {
renderPrivateRoute({
initialRoute: ROUTES.SIGN_UP,
appContext: { isLoggedIn: false },
});
assertStaysOnRoute(ROUTES.SIGN_UP);
});
it('should not redirect when not logged in user visits password reset page', () => {
renderPrivateRoute({
initialRoute: ROUTES.PASSWORD_RESET,
appContext: { isLoggedIn: false },
});
assertStaysOnRoute(ROUTES.PASSWORD_RESET);
});
it('should not redirect when not logged in user visits forgot password page', () => {
renderPrivateRoute({
initialRoute: ROUTES.FORGOT_PASSWORD,
appContext: { isLoggedIn: false },
});
assertStaysOnRoute(ROUTES.FORGOT_PASSWORD);
});
});
describe('Unknown Routes', () => {
it('should redirect to home when logged in and visiting unknown route', async () => {
renderPrivateRoute({
initialRoute: '/unknown-route-that-does-not-exist',
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.HOME);
});
it('should redirect to login when not logged in and visiting unknown route', async () => {
renderPrivateRoute({
initialRoute: '/unknown-route-that-does-not-exist',
appContext: { isLoggedIn: false },
});
await assertRedirectsTo(ROUTES.LOGIN);
});
it('should save unknown route to localStorage before redirecting to login', async () => {
const unknownRoute = '/some-unknown-page';
renderPrivateRoute({
initialRoute: unknownRoute,
appContext: { isLoggedIn: false },
});
await waitFor(() => {
expect(mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT]).toBe(
unknownRoute,
);
});
});
it('should redirect to saved route when logged in user visits unknown route with fromPathname in localStorage', async () => {
// This tests the branch where:
// - currentRoute is null (unknown route)
// - isLoggedInState is true
// - fromPathname exists in localStorage
// Expected: redirect to savedRoute and clear localStorage
const savedRoute = ROUTES.ALL_DASHBOARD;
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] = savedRoute;
renderPrivateRoute({
initialRoute: '/unknown-route-that-does-not-exist',
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(savedRoute);
await waitFor(() => {
expect(mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT]).toBe('');
});
});
});
describe('Workspace Blocked - Trial Expired (Cloud Users)', () => {
it('should redirect to workspace locked when workSpaceBlock is true for cloud users', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should allow ADMIN to access /settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
// Admin should be able to access settings even when workspace is blocked
assertStaysOnRoute(ROUTES.SETTINGS);
});
it('should allow ADMIN to access /settings/billing when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.BILLING,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.BILLING);
});
it('should allow ADMIN to access /settings/org-settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
});
it('should allow ADMIN to access /settings/members when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.MEMBERS_SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
});
it('should allow ADMIN to access /settings/my-settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.MY_SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.MY_SETTINGS);
});
it('should allow VIEWER to access /settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.SETTINGS);
});
it('should allow VIEWER to access /settings/billing when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.BILLING,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.BILLING);
});
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should redirect VIEWER to workspace locked when trying to access members settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.MEMBERS_SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should redirect VIEWER to workspace locked when trying to access my-settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.MY_SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should allow EDITOR to access /settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.EDITOR as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.SETTINGS);
});
it('should not redirect when already on workspace locked page', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_LOCKED,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_LOCKED);
});
it('should keep a custom role (ANONYMOUS) on workspace locked instead of bouncing to unauthorized', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_LOCKED,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ANONYMOUS as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_LOCKED);
});
it('should not redirect self-hosted users to workspace locked even when workSpaceBlock is true', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.SELF_HOSTED,
}),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
},
isCloudUser: false,
});
assertStaysOnRoute(ROUTES.HOME);
});
});
describe('Workspace Access Restricted - License Terminated/Expired/Cancelled (Cloud Users)', () => {
it('should redirect to workspace access restricted when license is TERMINATED', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.TERMINATED,
}),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
});
it('should redirect to workspace access restricted when license is EXPIRED', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.EXPIRED,
}),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
});
it('should redirect to workspace access restricted when license is CANCELLED', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.CANCELLED,
}),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
});
it('should not redirect when already on workspace access restricted page', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_ACCESS_RESTRICTED,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.TERMINATED,
}),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
});
it('should not redirect self-hosted users to workspace access restricted when license is terminated', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.SELF_HOSTED,
state: LicenseState.TERMINATED,
}),
},
isCloudUser: false,
});
assertStaysOnRoute(ROUTES.HOME);
});
it('should not redirect when license is ACTIVE', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.ACTIVATED,
}),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.HOME);
});
it('should not redirect when license is EVALUATING', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.EVALUATING,
}),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.HOME);
});
});
describe('Workspace Suspended - License Defaulted (Cloud Users)', () => {
it('should redirect to workspace suspended when license is DEFAULTED', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.DEFAULTED,
}),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_SUSPENDED);
});
it('should not redirect when already on workspace suspended page', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_SUSPENDED,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.DEFAULTED,
}),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_SUSPENDED);
});
it('should keep a custom role (ANONYMOUS) on workspace suspended instead of bouncing to unauthorized', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_SUSPENDED,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.DEFAULTED,
}),
user: createMockUser({ role: USER_ROLES.ANONYMOUS as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_SUSPENDED);
});
it('should not redirect self-hosted users to workspace suspended when license is defaulted', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.SELF_HOSTED,
state: LicenseState.DEFAULTED,
}),
},
isCloudUser: false,
});
assertStaysOnRoute(ROUTES.HOME);
});
});
describe('Onboarding Flow (Cloud Users)', () => {
it('should redirect to onboarding when first user has not completed onboarding', async () => {
// Set up exactly one user (not [email protected]) to trigger first user check
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false), // Onboarding NOT complete
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
// Wait for the users query to complete and trigger re-render
await act(async () => {
await Promise.resolve();
});
await assertRedirectsTo(ROUTES.ONBOARDING);
});
it('should not redirect to onboarding when org preferences are still fetching', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: true,
orgPreferences: null,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.HOME);
});
it('should not redirect to onboarding when onboarding is already complete', async () => {
// Set up first user condition - this ensures the ONLY reason we don't redirect
// is because isOnboardingComplete is true
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(true), // Onboarding complete
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
// Wait for async operations (useQuery, useEffect) to settle
await act(async () => {
await Promise.resolve();
});
// Critical: if isOnboardingComplete check is broken (always false),
// this test would fail because all other conditions for redirect ARE met
assertStaysOnRoute(ROUTES.HOME);
});
it('should not redirect to onboarding for non-cloud users', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false), // Onboarding not complete
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: false,
});
assertStaysOnRoute(ROUTES.HOME);
});
it('should not redirect to onboarding when on /workspace-locked route', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_LOCKED,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_LOCKED);
});
it('should not redirect to onboarding when on /workspace-suspended route', () => {
renderPrivateRoute({
initialRoute: ROUTES.WORKSPACE_SUSPENDED,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.WORKSPACE_SUSPENDED);
});
it('should not redirect to onboarding when workspace is blocked and accessing billing', async () => {
// This tests the scenario where admin tries to access billing to fix payment
// while workspace is blocked and onboarding is not complete
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.BILLING,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
isFetchingActiveLicense: false,
orgPreferences: createMockOrgPreferences(false), // Onboarding NOT complete
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
// Should NOT redirect to onboarding - user needs to access billing to fix payment
assertStaysOnRoute(ROUTES.BILLING);
});
it('should not redirect to onboarding when workspace is blocked and accessing settings', async () => {
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.SETTINGS,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
isFetchingActiveLicense: false,
orgPreferences: createMockOrgPreferences(false),
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
assertStaysOnRoute(ROUTES.SETTINGS);
});
it('should not redirect to onboarding when workspace is suspended (DEFAULTED)', async () => {
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
isFetchingActiveLicense: false,
orgPreferences: createMockOrgPreferences(false), // Onboarding NOT complete
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.DEFAULTED,
}),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
// Should redirect to WORKSPACE_SUSPENDED, not ONBOARDING
await assertRedirectsTo(ROUTES.WORKSPACE_SUSPENDED);
});
it('should not redirect to onboarding when workspace is access restricted (TERMINATED)', async () => {
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
isFetchingActiveLicense: false,
orgPreferences: createMockOrgPreferences(false), // Onboarding NOT complete
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.TERMINATED,
}),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
// Should redirect to WORKSPACE_ACCESS_RESTRICTED, not ONBOARDING
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
});
it('should not redirect to onboarding when workspace is access restricted (EXPIRED)', async () => {
mockUsersData = [{ email: '[email protected]' }];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
isFetchingActiveLicense: false,
orgPreferences: createMockOrgPreferences(false),
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.EXPIRED,
}),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
await assertRedirectsTo(ROUTES.WORKSPACE_ACCESS_RESTRICTED);
});
});
describe('Loading States', () => {
it('should not redirect while license is still being fetched', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: true,
activeLicense: null,
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
},
});
assertStaysOnRoute(ROUTES.HOME);
});
it('should not fetch users when org data is not available', () => {
// This tests the queryFn branch where orgData is undefined
// so the users fetch returns undefined instead of calling getAll()
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
org: [], // Empty org array means orgData won't be set
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertRendersChildren();
});
it('should not fetch users when org id is undefined', () => {
// This tests the queryFn branch where orgData exists but id is undefined
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
// @ts-expect-error - intentionally passing undefined id to test edge case
org: [{ createdAt: 0, id: undefined, displayName: 'Test Org' }],
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertRendersChildren();
});
it('should not check workspace states when activeLicense is null', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: null,
},
});
assertStaysOnRoute(ROUTES.HOME);
});
});
describe('Role-based Route Access', () => {
it('should allow ADMIN to access /licenses route', () => {
renderPrivateRoute({
initialRoute: ROUTES.LIST_LICENSES,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertRendersChildren();
});
it('should redirect VIEWER away from /licenses route', async () => {
renderPrivateRoute({
initialRoute: ROUTES.LIST_LICENSES,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
});
it('should redirect EDITOR away from /licenses route', async () => {
renderPrivateRoute({
initialRoute: ROUTES.LIST_LICENSES,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.EDITOR as ROLES }),
},
});
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
});
it('should allow ADMIN to access /services route', () => {
renderPrivateRoute({
initialRoute: ROUTES.APPLICATION,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertStaysOnRoute(ROUTES.APPLICATION);
});
it('should allow EDITOR to access /services route', () => {
renderPrivateRoute({
initialRoute: ROUTES.APPLICATION,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.EDITOR as ROLES }),
},
});
assertStaysOnRoute(ROUTES.APPLICATION);
});
it('should allow VIEWER to access /services route', () => {
renderPrivateRoute({
initialRoute: ROUTES.APPLICATION,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
assertStaysOnRoute(ROUTES.APPLICATION);
});
it('should redirect VIEWER from /onboarding route (admin only)', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ONBOARDING,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
});
it('lets a VIEWER reach /alerts/channels/new, which authz then gates', () => {
// CHANNELS_NEW runs on fine-grained authz, so the router no longer decides
// on the role: the page's own guard denies when `create` is not granted.
renderPrivateRoute({
initialRoute: ROUTES.CHANNELS_NEW,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
});
assertStaysOnRoute(ROUTES.CHANNELS_NEW);
});
it('should allow EDITOR to access /get-started-with-signoz-cloud route', () => {
renderPrivateRoute({
initialRoute: ROUTES.GET_STARTED_WITH_CLOUD,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.EDITOR as ROLES }),
},
});
assertStaysOnRoute(ROUTES.GET_STARTED_WITH_CLOUD);
});
it.each([...PERMITTED_ROLES, ...DENIED_ROLES])(
'should render the unauthorized page for a %s instead of bouncing off it',
(role) => {
// routePermission.UN_AUTHORIZED must grant every role: a role denied here
// is redirected to /un-authorized and then redirected away from it again,
// which loops until React bails out with a blank screen.
renderPrivateRoute({
initialRoute: ROUTES.UN_AUTHORIZED,
appContext: {
isLoggedIn: true,
user: createMockUser({ role }),
},
});
assertStaysOnRoute(ROUTES.UN_AUTHORIZED);
assertRendersChildren();
},
);
});
describe('Edge Cases', () => {
it('should handle route with query parameters correctly for private routes', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] = '';
renderPrivateRoute({
initialRoute: `${ROUTES.ALL_DASHBOARD}?tab=metrics`,
appContext: { isLoggedIn: false },
});
await assertRedirectsTo(ROUTES.LOGIN);
});
it('should render children when all conditions pass', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({
platform: LicensePlatform.CLOUD,
state: LicenseState.ACTIVATED,
}),
trialInfo: createMockTrialInfo({ workSpaceBlock: false }),
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
});
assertRendersChildren();
});
it('should handle ANONYMOUS role by redirecting from private routes', async () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ANONYMOUS as ROLES }),
},
});
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
});
});
describe('AuthZ Support (routeWithInitialAuthZSupport)', () => {
// Routes in routeWithInitialAuthZSupport always bypass legacy role check
const AUTHZ_ROUTE_CASES: Record<
keyof typeof routeWithInitialAuthZSupport,
AuthzRouteCase
> = {
CHANNELS_NEW: { path: ROUTES.CHANNELS_NEW, deniedRoles: DENIED_ROLES },
CHANNELS_EDIT: {
path: ROUTES.CHANNELS_EDIT.replace(':channelId', 'channel-id-1'),
deniedRoles: DENIED_ROLES,
},
ALL_DASHBOARD: { path: ROUTES.ALL_DASHBOARD, deniedRoles: DENIED_ROLES },
DASHBOARD: {
path: ROUTES.DASHBOARD.replace(':dashboardId', 'dashboard-id-1'),
deniedRoles: DENIED_ROLES,
},
DASHBOARD_PANEL_EDITOR: {
path: ROUTES.DASHBOARD_PANEL_EDITOR.replace(
':dashboardId',
'dashboard-id-1',
).replace(':panelId', 'panel-id-1'),
deniedRoles: DENIED_ROLES,
},
// Everything under /settings resolves to the non-exact SETTINGS route
SETTINGS: { path: ROUTES.SETTINGS, deniedRoles: DENIED_ROLES },
MY_SETTINGS: { path: ROUTES.MY_SETTINGS, deniedRoles: DENIED_ROLES },
ROLES_SETTINGS: { path: ROUTES.ROLES_SETTINGS, deniedRoles: DENIED_ROLES },
ROLE_CREATE: { path: ROUTES.ROLE_CREATE, deniedRoles: DENIED_ROLES },
ROLE_DETAILS: {
path: ROUTES.ROLE_DETAILS.replace(':roleId', 'role-id-1'),
deniedRoles: DENIED_ROLES,
},
ROLE_EDIT: {
path: ROUTES.ROLE_EDIT.replace(':roleId', 'role-id-1'),
deniedRoles: DENIED_ROLES,
},
SERVICE_ACCOUNTS_SETTINGS: {
path: ROUTES.SERVICE_ACCOUNTS_SETTINGS,
deniedRoles: DENIED_ROLES,
},
TRACES_EXPLORER: { path: ROUTES.TRACES_EXPLORER, deniedRoles: DENIED_ROLES },
TRACE_DETAIL: {
path: ROUTES.TRACE_DETAIL.replace(':id', 'trace-id-1'),
deniedRoles: DENIED_ROLES,
},
// LOGS and LOGS_EXPLORER share a path - matchPath resolves it to whichever
// route definition comes last, and both keys are authz-aware either way.
LOGS: { path: ROUTES.LOGS, deniedRoles: DENIED_ROLES },
LOGS_EXPLORER: { path: ROUTES.LOGS_EXPLORER, deniedRoles: DENIED_ROLES },
METRICS_EXPLORER: {
path: ROUTES.METRICS_EXPLORER,
deniedRoles: DENIED_ROLES,
},
METRICS_EXPLORER_EXPLORER: {
path: ROUTES.METRICS_EXPLORER_EXPLORER,
deniedRoles: DENIED_ROLES,
},
METRICS_EXPLORER_VOLUME_CONTROL: {
path: ROUTES.METRICS_EXPLORER_VOLUME_CONTROL,
deniedRoles: DENIED_ROLES,
},
METER: { path: ROUTES.METER, deniedRoles: DENIED_ROLES },
METER_EXPLORER: { path: ROUTES.METER_EXPLORER, deniedRoles: DENIED_ROLES },
// SUPPORT already grants ANONYMOUS in routePermission, so only AUTHOR
// exercises the redirect branch here.
SUPPORT: {
path: ROUTES.SUPPORT,
deniedRoles: [USER_ROLES.AUTHOR as ROLES],
},
WORKSPACE_LOCKED: {
path: ROUTES.WORKSPACE_LOCKED,
deniedRoles: DENIED_ROLES,
},
WORKSPACE_SUSPENDED: {
path: ROUTES.WORKSPACE_SUSPENDED,
deniedRoles: DENIED_ROLES,
},
WORKSPACE_ACCESS_RESTRICTED: {
path: ROUTES.WORKSPACE_ACCESS_RESTRICTED,
deniedRoles: DENIED_ROLES,
},
BILLING: { path: ROUTES.BILLING, deniedRoles: DENIED_ROLES },
};
const authzRouteRolePairs: [string, string, ROLES][] = Object.entries(
AUTHZ_ROUTE_CASES,
).flatMap(([name, { path, deniedRoles }]) =>
deniedRoles.map((role): [string, string, ROLES] => [name, path, role]),
);
// Routes with no authz check - legacy role check still applies
const NON_AUTHZ_ROUTE_CASES: [string, string, ROLES][] = [
['ALERTS_NEW', ROUTES.ALERTS_NEW, USER_ROLES.VIEWER as ROLES],
['LIST_LICENSES', ROUTES.LIST_LICENSES, USER_ROLES.EDITOR as ROLES],
['ONBOARDING', ROUTES.ONBOARDING, USER_ROLES.VIEWER as ROLES],
['APPLICATION', ROUTES.APPLICATION, USER_ROLES.ANONYMOUS as ROLES],
];
it.each(authzRouteRolePairs)(
'should not redirect %s (%s) for role %s - authz routes bypass legacy role check',
(_name, path, role) => {
// Routes in routeWithInitialAuthZSupport always bypass the legacy role check.
// Authorization is handled by downstream components via fine-grained authz.
renderPrivateRoute({
initialRoute: path,
appContext: {
isLoggedIn: true,
user: createMockUser({ role }),
},
});
assertStaysOnRoute(path);
assertRendersChildren();
},
);
it.each([...PERMITTED_ROLES, ...DENIED_ROLES])(
'should not redirect a %s from an authz-aware route',
(role) => {
// All roles pass through - authorization handled downstream
renderPrivateRoute({
initialRoute: ROUTES.LOGS_EXPLORER,
appContext: {
isLoggedIn: true,
user: createMockUser({ role }),
},
});
assertStaysOnRoute(ROUTES.LOGS_EXPLORER);
assertRendersChildren();
},
);
it.each(NON_AUTHZ_ROUTE_CASES)(
'should redirect %s (%s) for role %s - non-authz routes use legacy role check',
async (_name, path, role) => {
// Routes NOT in routeWithInitialAuthZSupport still use legacy role check
renderPrivateRoute({
initialRoute: path,
appContext: {
isLoggedIn: true,
user: createMockUser({ role }),
},
});
await assertRedirectsTo(ROUTES.UN_AUTHORIZED);
},
);
it.each(authzRouteRolePairs)(
'should still redirect unauthenticated users away from %s (%s) with role %s',
async (_name, path, role) => {
// The authz bypass only relaxes the role check, never the login check.
renderPrivateRoute({
initialRoute: path,
appContext: {
isLoggedIn: false,
user: createMockUser({ role }),
},
});
await assertRedirectsTo(ROUTES.LOGIN);
},
);
it('should still redirect to workspace locked from an authz-aware route', async () => {
// Workspace guards run before the role check and must not be bypassed.
renderPrivateRoute({
initialRoute: ROUTES.LOGS_EXPLORER,
appContext: {
isLoggedIn: true,
isFetchingActiveLicense: false,
activeLicense: createMockLicense({ platform: LicensePlatform.CLOUD }),
trialInfo: createMockTrialInfo({ workSpaceBlock: true }),
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
});
describe('Old channel route redirects', () => {
it.each([
['/settings/channels', '/alerts', 'tab=Channels'],
['/settings/channels/new', '/alerts/channels/new', ''],
])(
'should redirect %s to %s',
async (oldRoute, expectedPath, expectedSearch) => {
renderPrivateRoute({
initialRoute: oldRoute,
appContext: { isLoggedIn: true },
});
await waitFor(() => {
expect(screen.getByTestId('location-display')).toHaveTextContent(
expectedPath,
);
});
if (expectedSearch) {
const search = screen.getByTestId('location-search').textContent ?? '';
const params = new URLSearchParams(search);
new URLSearchParams(expectedSearch).forEach((value, name) => {
expect(params.get(name)).toBe(value);
});
} else {
expect(screen.getByTestId('location-search')).toHaveTextContent('');
}
},
);
it('should redirect dynamic channel edit route preserving the channel id', async () => {
renderPrivateRoute({
initialRoute: '/settings/channels/edit/abc123',
appContext: { isLoggedIn: true },
});
await assertRedirectsTo('/alerts/channels/edit/abc123');
});
it('should merge incoming query params with the embedded query of the target', async () => {
renderPrivateRoute({
initialRoute: '/settings/channels?foo=bar',
appContext: { isLoggedIn: true },
});
await waitFor(() => {
expect(screen.getByTestId('location-display')).toHaveTextContent('/alerts');
});
const search = screen.getByTestId('location-search').textContent ?? '';
const params = new URLSearchParams(search);
expect(params.get('tab')).toBe('Channels');
expect(params.get('foo')).toBe('bar');
});
});
});