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.

5.5 KB
Raw Blame
import type {
	AuthtypesGettableTransactionDTO,
	AuthtypesTransactionDTO,
} from 'api/generated/services/sigNoz.schemas';
import { ENVIRONMENT } from 'constants/env';
import { gettableTransactionToPermission } from 'lib/authz/hooks/useAuthZ/utils';
import type {
	BrandedPermission,
	UseAuthZOptions,
	UseAuthZResult,
} from 'lib/authz/hooks/useAuthZ/types';
import { rest } from 'msw';
import type { RestHandler } from 'msw';
import {
	LicenseEvent,
	LicensePlatform,
	type LicenseResModel,
	LicenseState,
	LicenseStatus,
} from 'types/api/licensesV3/getActive';

export const AUTHZ_CHECK_URL = `${ENVIRONMENT.baseURL || ''}/api/v1/authz/check`;

export 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',
	};
}

export function setupAuthzAdmin(): RestHandler {
	return rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
		const payload = (await req.json()) as AuthtypesTransactionDTO[];
		return res(
			ctx.status(200),
			ctx.json(
				authzMockResponse(
					payload,
					payload.map(() => true),
				),
			),
		);
	});
}

/** Denies all permission checks. */
export function setupAuthzDenyAll(): RestHandler {
	return rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
		const payload = (await req.json()) as AuthtypesTransactionDTO[];
		return res(
			ctx.status(200),
			ctx.json(
				authzMockResponse(
					payload,
					payload.map(() => false),
				),
			),
		);
	});
}

/** Grants all permissions except the ones listed — matched precisely by relation + object. */
export function setupAuthzDeny(
	...permissions: BrandedPermission[]
): RestHandler {
	const denied = new Set<BrandedPermission>(permissions);
	return rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
		const payload = (await req.json()) as AuthtypesTransactionDTO[];
		return res(
			ctx.status(200),
			ctx.json(
				authzMockResponse(
					payload,
					payload.map((txn) => !denied.has(gettableTransactionToPermission(txn))),
				),
			),
		);
	});
}

/** Denies all permissions except the ones listed — matched precisely by relation + object. */
export function setupAuthzAllow(
	...permissions: BrandedPermission[]
): RestHandler {
	const allowed = new Set<BrandedPermission>(permissions);
	return rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
		const payload = (await req.json()) as AuthtypesTransactionDTO[];
		return res(
			ctx.status(200),
			ctx.json(
				authzMockResponse(
					payload,
					payload.map((txn) => allowed.has(gettableTransactionToPermission(txn))),
				),
			),
		);
	});
}

/** Grants permissions that start with any of the given prefixes. */
export function setupAuthzGrantByPrefix(...prefixes: string[]): RestHandler {
	return rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
		const payload = (await req.json()) as AuthtypesTransactionDTO[];
		return res(
			ctx.status(200),
			ctx.json(
				authzMockResponse(
					payload,
					payload.map((txn) => {
						const perm = gettableTransactionToPermission(txn);
						return prefixes.some((prefix) => perm.startsWith(prefix));
					}),
				),
			),
		);
	});
}

export function buildLicense(
	overrides?: Partial<LicenseResModel>,
): LicenseResModel {
	return {
		id: 'test-license-id',
		status: LicenseStatus.VALID,
		state: LicenseState.ACTIVATED,
		platform: LicensePlatform.CLOUD,
		eventQueue: {
			createdAt: '0',
			event: LicenseEvent.NO_EVENT,
			scheduledAt: '0',
			status: '',
			updatedAt: '0',
		},
		plan: {
			id: '0',
			createdAt: '0',
			description: '',
			isActive: true,
			name: '',
			updatedAt: '0',
		},
		freeUntil: '0',
		updatedAt: '0',
		validFrom: 0,
		validUntil: 0,
		createdAt: '0',
		...overrides,
	};
}

export const invalidLicense = buildLicense({ status: LicenseStatus.INVALID });

export function mockUseAuthZGrantAll(
	permissions: BrandedPermission[],
	_options?: UseAuthZOptions,
): UseAuthZResult {
	return {
		isLoading: false,
		isFetching: false,
		error: null,
		permissions: Object.fromEntries(
			permissions.map((p) => [p, { isGranted: true }]),
		) as UseAuthZResult['permissions'],
		allowed: true,
		deniedPermissions: [],
		isGranted: (): boolean => true,
		refetchPermissions: jest.fn(),
	};
}

export function mockUseAuthZDenyAll(
	permissions: BrandedPermission[],
	_options?: UseAuthZOptions,
): UseAuthZResult {
	return {
		isLoading: false,
		isFetching: false,
		error: null,
		permissions: Object.fromEntries(
			permissions.map((p) => [p, { isGranted: false }]),
		) as UseAuthZResult['permissions'],
		allowed: false,
		deniedPermissions: permissions,
		isGranted: (): boolean => false,
		refetchPermissions: jest.fn(),
	};
}

export function mockUseAuthZGrantByPrefix(
	...prefixes: string[]
): (
	permissions: BrandedPermission[],
	options?: UseAuthZOptions,
) => UseAuthZResult {
	return (permissions, _options) => {
		const denied = permissions.filter(
			(p) => !prefixes.some((prefix) => p.startsWith(prefix)),
		);
		return {
			isLoading: false,
			isFetching: false,
			error: null,
			permissions: Object.fromEntries(
				permissions.map((p) => [
					p,
					{ isGranted: prefixes.some((prefix) => p.startsWith(prefix)) },
				]),
			) as UseAuthZResult['permissions'],
			allowed: denied.length === 0,
			deniedPermissions: denied,
			isGranted: (permission): boolean =>
				prefixes.some((prefix) => permission.startsWith(prefix)),
			refetchPermissions: jest.fn(),
		};
	};
}