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.

6.8 KB
Raw Blame
import { toast } from '@signozhq/ui/sonner';
import type { ServiceaccounttypesGettableFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
import {
	AUTHZ_CHECK_URL,
	setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { submitImplicitly } from 'tests/submitImplicitly';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';

import EditKeyModal from '../EditKeyModal';

jest.mock('lib/authz/components/AuthZTooltip/AuthZTooltip', () => ({
	__esModule: true,
	default: ({
		children,
	}: {
		children: React.ReactElement;
	}): React.ReactElement => children,
}));

jest.mock('@signozhq/ui/sonner', () => ({
	...jest.requireActual('@signozhq/ui/sonner'),
	toast: { success: jest.fn(), error: jest.fn() },
}));

const mockToast = jest.mocked(toast);

const SA_KEY_ENDPOINT = '*/api/v1/service_accounts/sa-1/keys/key-1';

const mockKey: ServiceaccounttypesGettableFactorAPIKeyDTO = {
	id: 'key-1',
	name: 'Original Key Name',
	expiresAt: 0,
	lastObservedAt: null as unknown as string,
	serviceAccountId: 'sa-1',
};

function renderModal(
	keyItem: ServiceaccounttypesGettableFactorAPIKeyDTO | null = mockKey,
	searchParams: Record<string, string> = {
		account: 'sa-1',
		'edit-key': 'key-1',
	},
	onUrlUpdate?: jest.Mock,
): ReturnType<typeof render> {
	return render(
		<NuqsTestingAdapter
			searchParams={searchParams}
			hasMemory
			onUrlUpdate={onUrlUpdate}
		>
			<EditKeyModal keyItem={keyItem} />
		</NuqsTestingAdapter>,
	);
}

describe('EditKeyModal (URL-controlled)', () => {
	beforeEach(() => {
		jest.clearAllMocks();
		server.use(
			rest.put(SA_KEY_ENDPOINT, (_, res, ctx) =>
				res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
			),
			rest.delete(SA_KEY_ENDPOINT, (_, res, ctx) =>
				res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
			),
			setupAuthzAdmin(),
		);
	});

	afterEach(() => {
		server.resetHandlers();
	});

	it('renders nothing when edit-key param is absent', () => {
		renderModal(null, { account: 'sa-1' });

		expect(screen.queryByTestId('edit-key-modal')).not.toBeInTheDocument();
	});

	it('renders key data from prop when edit-key param is set', async () => {
		renderModal();

		await expect(
			screen.findByDisplayValue('Original Key Name'),
		).resolves.toBeInTheDocument();
		expect(screen.getByRole('button', { name: /Save Changes/i })).toHaveAttribute(
			'aria-disabled',
			'true',
		);
	});

	it('does not show the denial tooltip while the permission check is pending', async () => {
		server.use(
			rest.post(AUTHZ_CHECK_URL, (_req, res, ctx) => res(ctx.delay('infinite'))),
		);
		renderModal();

		await screen.findByText('key-1');

		expect(
			screen.queryByText('You do not have permission to update this key'),
		).not.toBeInTheDocument();
	});

	it('save calls update API, shows toast, and closes modal', async () => {
		const user = userEvent.setup({ pointerEventsCheck: 0 });
		renderModal();

		const nameInput = await screen.findByPlaceholderText(/Enter key name/i);
		await user.clear(nameInput);
		await user.type(nameInput, 'Updated Key Name');

		await user.click(screen.getByRole('button', { name: /Save Changes/i }));

		await waitFor(() => {
			expect(mockToast.success).toHaveBeenCalledWith('Key updated successfully');
		});

		await waitFor(() => {
			expect(screen.queryByTestId('edit-key-modal')).not.toBeInTheDocument();
		});
	});

	it('pressing Enter again while saving sends one request', async () => {
		const user = userEvent.setup({ pointerEventsCheck: 0 });
		let requests = 0;
		server.use(
			rest.put(SA_KEY_ENDPOINT, (_, res, ctx) => {
				requests += 1;
				return res(
					ctx.delay(100),
					ctx.status(200),
					ctx.json({ status: 'success', data: {} }),
				);
			}),
		);
		renderModal();

		const nameInput =
			await screen.findByPlaceholderText<HTMLInputElement>(/Enter key name/i);
		await user.clear(nameInput);
		await user.type(nameInput, 'Updated Key Name');
		const saveBtn = screen.getByRole('button', { name: /Save Changes/i });

		submitImplicitly(nameInput);
		await waitFor(() => expect(saveBtn).toHaveAttribute('aria-busy', 'true'));
		submitImplicitly(nameInput);

		await waitFor(() => {
			expect(mockToast.success).toHaveBeenCalledWith('Key updated successfully');
		});
		expect(requests).toBe(1);
	});

	it('pressing Enter without changes does not save', async () => {
		let requests = 0;
		server.use(
			rest.put(SA_KEY_ENDPOINT, (_, res, ctx) => {
				requests += 1;
				return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
			}),
		);
		renderModal();

		const nameInput =
			await screen.findByDisplayValue<HTMLInputElement>('Original Key Name');
		submitImplicitly(nameInput);

		await act(() => new Promise((resolve) => setTimeout(resolve, 200)));
		expect(requests).toBe(0);
		expect(screen.getByTestId('edit-key-modal')).toBeInTheDocument();
	});

	it('cancel clears edit-key param and closes modal', async () => {
		const user = userEvent.setup({ pointerEventsCheck: 0 });
		const onUrlUpdate = jest.fn();
		renderModal(mockKey, undefined, onUrlUpdate);

		await screen.findByDisplayValue('Original Key Name');
		await user.click(screen.getByRole('button', { name: /Cancel/i }));

		await waitFor(() => {
			expect(onUrlUpdate).toHaveBeenCalled();
		});

		const latestUrlUpdate =
			onUrlUpdate.mock.calls[onUrlUpdate.mock.calls.length - 1]?.[0];
		expect(latestUrlUpdate).toStrictEqual(
			expect.objectContaining({
				queryString: expect.any(String),
			}),
		);
		expect(latestUrlUpdate.queryString).toContain('account=sa-1');
		expect(latestUrlUpdate.queryString).not.toContain('edit-key=');

		await waitFor(() => {
			expect(screen.queryByTestId('edit-key-modal')).not.toBeInTheDocument();
		});
	});

	it('revoke flow: clicking Revoke Key shows confirmation inside same dialog', async () => {
		const user = userEvent.setup({ pointerEventsCheck: 0 });
		renderModal();

		await screen.findByDisplayValue('Original Key Name');
		await user.click(screen.getByRole('button', { name: /Revoke Key/i }));

		// Same dialog, now showing revoke confirmation
		expect(screen.getByTestId('edit-key-modal')).toBeInTheDocument();
		expect(
			screen.getByText(/Revoking this key will permanently invalidate it/i),
		).toBeInTheDocument();
	});

	it('revoke flow: confirming revoke shows toast and closes modal', async () => {
		const user = userEvent.setup({ pointerEventsCheck: 0 });
		renderModal();

		await screen.findByDisplayValue('Original Key Name');
		await user.click(screen.getByRole('button', { name: /Revoke Key/i }));

		const confirmBtn = await screen.findByRole('button', {
			name: /^Revoke Key$/i,
		});
		await user.click(confirmBtn);

		await waitFor(() => {
			expect(mockToast.success).toHaveBeenCalledWith('Key revoked successfully');
		});

		await waitFor(() => {
			expect(screen.queryByTestId('edit-key-modal')).not.toBeInTheDocument();
		});
	});
});