Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Do not replace audit destinations before reading their configuration

pulse-triage[bot]72749e94ef85
diff --git a/frontend-modern/browser-verification/d26e9905378ba75b.json b/frontend-modern/browser-verification/d26e9905378ba75b.json
new file mode 100644
index 0000000000..2b7a8f65e7
--- /dev/null
+++ b/frontend-modern/browser-verification/d26e9905378ba75b.json
@@ -0,0 +1,51 @@
+{
+ "version": 1,
+ "base_sha": "9932036ca2a61d2e93fe6941c660f9d4c63fd3c0",
+ "verified_at": "2026-10-31T16:03:46Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/components/Settings/AuditWebhookPanel.tsx",
+ "frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts",
+ "frontend-modern/src/utils/auditWebhookPresentation.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/components/Settings/AuditWebhookPanel.tsx": "6e2453e780dda4cdda1b143a3f23da140e52c5c03302ebf142d0ebb9a95b9771",
+ "frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts": "4aa521570094227ff9f34d9b679dbce9e1b6f46253f6e3792516fbdde8e1bf36",
+ "frontend-modern/src/utils/auditWebhookPresentation.ts": "ea008fea62306863e0d0ac44d0582402be465395348c3168b800205826575a97"
+ },
+ "routes": [
+ "Existing Audit Webhooks settings panel, exercised via a safe /proof/index.html consumer fixture using the real Router, panel, API client, capability store, Toast and CSS"
+ ],
+ "viewports": [
+ {
+ "width": 1280,
+ "height": 1000,
+ "browser": "Chromium 141.0.7390.37"
+ },
+ {
+ "width": 320,
+ "height": 1000,
+ "browser": "WebKit 26.0",
+ "touch": true
+ }
+ ],
+ "states": [
+ "Cold service refusal is unknown, never known-empty; draft remains editable but Add and Enter cannot replace unread destinations",
+ "Pending explicit retry retains the draft without a duplicate read or mutation",
+ "Refused explicit save retains the loaded destination and draft without false success",
+ "Failed same-selection revalidation preserves labelled last-loaded destinations and disables add and removal",
+ "Separate successful read and deliberate save preserve loaded destinations and clear only the submitted draft",
+ "Accepted urls:null is known-empty; settled label and controls are readable at both widths",
+ "Invalid-organisation response does not trigger automatic default fallback; deliberate default selection remains usable",
+ "Capability refresh interrupts a pending save without assuming server cancellation or success; a read must reconcile the selection before another replacement",
+ "Read-only retry does not grant mutation capability"
+ ],
+ "interactions": [
+ "Desktop keyboard Enter and read retry; narrow touch Add and retry; repeated Enter during pending reads dispatches no mutation",
+ "Organisation switches clear peer rows/drafts, re-read the new selection and retain existing authority gates",
+ "Final-source proof contains 64 completed interaction checks across two attempts: seven desktop journeys completed before a fixture assertion counted an exiting old toast; the remaining-only supplement passes desktop interruption/read-only and all narrow journeys",
+ "Nine deliberate fixture POSTs across retained attempts, including interrupted responses, all retain selected loaded destinations; no automatic mutation replay",
+ "All eighteen final-source captures were opened with native view_image; notice text, loading, retained drafts, settled known-empty, success/warning, read-only and phone layouts inspected",
+ "Playwright 1.56.1 matches the integration lock; all 361 installed frontend lock versions and the complete copied frontend content were verified. Safe fixture proof is not an authenticated installed-service or receiver acceptance result"
+ ]
+}
diff --git a/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx b/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx
index 5e66189731..25b7c0b959 100644
--- a/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx
+++ b/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx
@@ -1,10 +1,11 @@
-import { For, Show, createSignal, type Component } from 'solid-js';
+import { For, Show, createEffect, createSignal, type Component } from 'solid-js';
import Shield from 'lucide-solid/icons/shield';
import Globe from 'lucide-solid/icons/globe';
import Plus from 'lucide-solid/icons/plus';
import Trash2 from 'lucide-solid/icons/trash-2';
import ExternalLink from 'lucide-solid/icons/external-link';
import { Card } from '@/components/shared/Card';
+import { Button } from '@/components/shared/Button';
import { Dialog } from '@/components/shared/Dialog';
import { EmptyState } from '@/components/shared/EmptyState';
import { FeatureGateSection } from '@/components/shared/FeatureGateSection';
@@ -20,6 +21,7 @@ import {
getAuditWebhookFeatureGateCopy,
getAuditWebhookLoadingState,
getAuditWebhookNotificationsSignpost,
+ getAuditWebhookReadErrorCopy,
} from '@/utils/auditWebhookPresentation';
import { pathForTab } from '@/features/alerts/types';
import { useAuditWebhookPanelState } from '@/components/Settings/useAuditWebhookPanelState';
@@ -50,11 +52,15 @@ export const AuditWebhookPanel: Component<AuditWebhookPanelProps> = (props) => {
const [urlToRemove, setUrlToRemove] = createSignal<string | null>(null);
let newUrlInputRef: HTMLInputElement | undefined;
const {
+ canEdit,
canManage,
+ fetchWebhooks,
handleAddWebhook,
handleRemoveWebhook,
isAuditLoggingEnabled,
loading,
+ loadError,
+ hasLoadedConfiguration,
newUrl,
saving,
setNewUrl,
@@ -71,161 +77,189 @@ export const AuditWebhookPanel: Component<AuditWebhookPanelProps> = (props) => {
paidRuntimeRequired: paidRuntimeRequired(),
});
const emptyStateCopy = () => getAuditWebhookEmptyStateCopy();
+ const readErrorCopy = () => getAuditWebhookReadErrorCopy(hasLoadedConfiguration());
+ createEffect(() => {
+ if (!canEdit()) setUrlToRemove(null);
+ });
- if (!isAuditLoggingEnabled()) {
- return (
- <SettingsPanel title="Audit Webhooks">
- <Show when={!loading()} fallback={<div class="text-sm text-muted">Loading...</div>}>
- <AuditWebhookNotificationsSignpost />
- <Card tone="info" padding="md" class="mt-3">
- <FeatureGateSection
- title={featureGateCopy().title}
- body={featureGateCopy().body}
- upgradeDestination={upgradeDestination()}
- showUpgradePrompts={showFeatureGateAction()}
- upgradeLabel={upgradeActionLabel()}
- upgradeButtonTone={paidRuntimeRequired() ? 'warning' : 'primary'}
- />
- </Card>
- </Show>
- </SettingsPanel>
- );
- }
+ const featureGate = () => (
+ <SettingsPanel title="Audit Webhooks">
+ <Show when={!loading()} fallback={<div class="text-sm text-muted">Loading...</div>}>
+ <AuditWebhookNotificationsSignpost />
+ <Card tone="info" padding="md" class="mt-3">
+ <FeatureGateSection
+ title={featureGateCopy().title}
+ body={featureGateCopy().body}
+ upgradeDestination={upgradeDestination()}
+ showUpgradePrompts={showFeatureGateAction()}
+ upgradeLabel={upgradeActionLabel()}
+ upgradeButtonTone={paidRuntimeRequired() ? 'warning' : 'primary'}
+ />
+ </Card>
+ </Show>
+ </SettingsPanel>
+ );
return (
- <div class="space-y-6">
- <SettingsPanel title="Audit Webhooks" noPadding bodyClass="divide-y divide-border">
- <div class="space-y-6 p-4 sm:p-6">
- <Show when={!canManage()}>
- <div class={AUDIT_WEBHOOK_READONLY_NOTICE_CLASS}>
- Audit webhook configuration is read-only for this account.
- </div>
- </Show>
+ <Show when={isAuditLoggingEnabled()} fallback={featureGate()}>
+ <div class="space-y-6">
+ <SettingsPanel title="Audit Webhooks" noPadding bodyClass="divide-y divide-border">
+ <div class="space-y-6 p-4 sm:p-6">
+ <Show when={!canManage()}>
+ <div class={AUDIT_WEBHOOK_READONLY_NOTICE_CLASS}>
+ Audit webhook configuration is read-only for this account.
+ </div>
+ </Show>
- <p class="text-sm text-muted leading-relaxed">
- Pulse can send a signed event payload whenever security-relevant activity occurs
- (logins, settings changes, RBAC updates, and similar audit events).
- </p>
- <AuditWebhookNotificationsSignpost />
+ <p class="text-sm text-muted leading-relaxed">
+ Pulse can send a signed event payload whenever security-relevant activity occurs
+ (logins, settings changes, RBAC updates, and similar audit events).
+ </p>
+ <AuditWebhookNotificationsSignpost />
- <Show
- when={!loading()}
- fallback={<p class="text-sm text-muted">{getAuditWebhookLoadingState().text}</p>}
- >
- <div class="space-y-3">
- <For each={webhookUrls()}>
- {(url) => (
- <div class={AUDIT_WEBHOOK_ENDPOINT_CARD_CLASS}>
- <div class="flex items-center gap-3 overflow-hidden min-w-0">
- <div class={AUDIT_WEBHOOK_ENDPOINT_ICON_CLASS}>
- <ExternalLink size={16} />
+ <Show when={loadError()}>
+ <Card tone="warning" padding="md">
+ <div role="alert" class="space-y-2 text-sm">
+ <p class="font-medium">{readErrorCopy().title}</p>
+ <p>{readErrorCopy().body}</p>
+ <Button onClick={() => void fetchWebhooks()} disabled={loading() || saving()}>
+ {readErrorCopy().retryLabel}
+ </Button>
+ </div>
+ </Card>
+ </Show>
+ <Show
+ when={!loading() || hasLoadedConfiguration()}
+ fallback={<p class="text-sm text-muted">{getAuditWebhookLoadingState().text}</p>}
+ >
+ <Show when={loading()}>
+ <p class="text-sm text-muted" role="status">
+ {getAuditWebhookLoadingState().text}
+ </p>
+ </Show>
+ <div class="space-y-3">
+ <For each={webhookUrls()}>
+ {(url) => (
+ <div class={AUDIT_WEBHOOK_ENDPOINT_CARD_CLASS}>
+ <div class="flex items-center gap-3 overflow-hidden min-w-0">
+ <div class={AUDIT_WEBHOOK_ENDPOINT_ICON_CLASS}>
+ <ExternalLink size={16} />
+ </div>
+ <span class="text-sm font-medium text-base-content truncate" title={url}>
+ {url}
+ </span>
</div>
- <span class="text-sm font-medium text-base-content truncate" title={url}>
- {url}
- </span>
+ <button
+ onClick={() => setUrlToRemove(url)}
+ disabled={!canEdit() || saving()}
+ class="p-2 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/25 rounded-md transition-colors"
+ title="Remove webhook endpoint"
+ >
+ <Trash2 size={16} />
+ </button>
</div>
- <button
- onClick={() => setUrlToRemove(url)}
- disabled={!canManage() || saving()}
- class="p-2 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/25 rounded-md transition-colors"
- title="Remove webhook endpoint"
- >
- <Trash2 size={16} />
- </button>
- </div>
- )}
- </For>
+ )}
+ </For>
- <Show when={webhookUrls().length === 0}>
- <EmptyState
- variant="panel"
- icon={<Globe class="h-5 w-5" />}
- title={emptyStateCopy().title}
- />
- </Show>
+ <Show
+ when={
+ hasLoadedConfiguration() &&
+ !loading() &&
+ !loadError() &&
+ webhookUrls().length === 0
+ }
+ >
+ <EmptyState
+ variant="panel"
+ icon={<Globe class="h-5 w-5" />}
+ title={emptyStateCopy().title}
+ />
+ </Show>
+ </div>
+ </Show>
+ <div class="flex flex-col gap-3 pt-4 border-t border-border sm:flex-row">
+ <input
+ ref={newUrlInputRef}
+ type="text"
+ aria-label="Audit webhook URL"
+ placeholder="https://your-api.com/webhook"
+ class={`${formControl} w-full min-w-0 flex-1`}
+ value={newUrl()}
+ onInput={(e) => setNewUrl(e.currentTarget.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleAddWebhook()}
+ disabled={!canManage()}
+ />
+ <button
+ onClick={handleAddWebhook}
+ disabled={!canEdit() || saving() || !newUrl().trim()}
+ class="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-md flex items-center justify-center gap-2 transition-colors sm:shrink-0"
+ >
+ <Plus size={18} />
+ Add Endpoint
+ </button>
</div>
- </Show>
- <div class="flex flex-col gap-3 pt-4 border-t border-border sm:flex-row">
- <input
- ref={newUrlInputRef}
- type="text"
- aria-label="Audit webhook URL"
- placeholder="https://your-api.com/webhook"
- class={`${formControl} w-full min-w-0 flex-1`}
- value={newUrl()}
- onInput={(e) => setNewUrl(e.currentTarget.value)}
- onKeyDown={(e) => e.key === 'Enter' && handleAddWebhook()}
- disabled={!canManage()}
- />
- <button
- onClick={handleAddWebhook}
- disabled={!canManage() || saving() || !newUrl().trim()}
- class="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-md flex items-center justify-center gap-2 transition-colors sm:shrink-0"
- >
- <Plus size={18} />
- Add Endpoint
- </button>
- </div>
- </div>
- </SettingsPanel>
- <Card tone="warning" class="border border-amber-200 dark:border-amber-800">
- <div class="p-5 flex gap-4">
- <div class="p-3 bg-amber-100 dark:bg-amber-900/25 rounded-md h-fit text-amber-600 dark:text-amber-300">
- <Shield size={22} />
</div>
- <div>
- <h3 class="text-base font-semibold text-amber-900 dark:text-amber-100 mb-1.5">
- {AUDIT_WEBHOOK_SECURITY_NOTE_TITLE}
- </h3>
- <p class="text-sm text-amber-800 dark:text-amber-200 leading-relaxed">
- {AUDIT_WEBHOOK_SECURITY_NOTE_BODY}
- </p>
+ </SettingsPanel>
+ <Card tone="warning" class="border border-amber-200 dark:border-amber-800">
+ <div class="p-5 flex gap-4">
+ <div class="p-3 bg-amber-100 dark:bg-amber-900/25 rounded-md h-fit text-amber-600 dark:text-amber-300">
+ <Shield size={22} />
+ </div>
+ <div>
+ <h3 class="text-base font-semibold text-amber-900 dark:text-amber-100 mb-1.5">
+ {AUDIT_WEBHOOK_SECURITY_NOTE_TITLE}
+ </h3>
+ <p class="text-sm text-amber-800 dark:text-amber-200 leading-relaxed">
+ {AUDIT_WEBHOOK_SECURITY_NOTE_BODY}
+ </p>
+ </div>
</div>
- </div>
- </Card>
+ </Card>
- {/* Remove confirmation modal — webhook removal stops audit
+ {/* Remove confirmation modal — webhook removal stops audit
deliveries to that endpoint, so guard the action behind
an explicit confirm. */}
- <Show when={urlToRemove()}>
- <Dialog
- isOpen={true}
- onClose={() => setUrlToRemove(null)}
- panelClass="max-w-md"
- ariaLabel="Remove audit webhook"
- returnFocus={() => newUrlInputRef}
- >
- <div class="w-full p-6">
- <h3 class="text-lg font-semibold text-base-content mb-2">Remove audit webhook?</h3>
- <p class="text-sm text-muted mb-4">
- This stops audit events from being delivered to{' '}
- <span class="font-medium text-base-content break-all">{urlToRemove()}</span>. Any
- external receiver using this URL will stop receiving Pulse audit traffic. You can add
- the URL back later if needed.
- </p>
- <div class="flex justify-end gap-3">
- <button
- type="button"
- onClick={() => setUrlToRemove(null)}
- class="px-4 py-2 text-sm font-medium text-base-content border border-border rounded-md hover:bg-surface-hover"
- >
- Cancel
- </button>
- <button
- type="button"
- onClick={() => {
- const url = urlToRemove();
- setUrlToRemove(null);
- if (url) void handleRemoveWebhook(url);
- }}
- class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-md hover:bg-red-700"
- >
- Remove webhook
- </button>
+ <Show when={urlToRemove()}>
+ <Dialog
+ isOpen={true}
+ onClose={() => setUrlToRemove(null)}
+ panelClass="max-w-md"
+ ariaLabel="Remove audit webhook"
+ returnFocus={() => newUrlInputRef}
+ >
+ <div class="w-full p-6">
+ <h3 class="text-lg font-semibold text-base-content mb-2">Remove audit webhook?</h3>
+ <p class="text-sm text-muted mb-4">
+ This stops audit events from being delivered to{' '}
+ <span class="font-medium text-base-content break-all">{urlToRemove()}</span>. Any
+ external receiver using this URL will stop receiving Pulse audit traffic. You can
+ add the URL back later if needed.
+ </p>
+ <div class="flex justify-end gap-3">
+ <button
+ type="button"
+ onClick={() => setUrlToRemove(null)}
+ class="px-4 py-2 text-sm font-medium text-base-content border border-border rounded-md hover:bg-surface-hover"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ disabled={!canEdit() || saving()}
+ onClick={() => {
+ const url = urlToRemove();
+ setUrlToRemove(null);
+ if (url) void handleRemoveWebhook(url);
+ }}
+ class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-md hover:bg-red-700"
+ >
+ Remove webhook
+ </button>
+ </div>
</div>
- </div>
- </Dialog>
- </Show>
- </div>
+ </Dialog>
+ </Show>
+ </div>
+ </Show>
);
};
diff --git a/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx
index 3636420acd..f6166387d2 100644
--- a/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx
@@ -1,5 +1,7 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createSignal } from 'solid-js';
+import { eventBus } from '@/stores/events';
import { AuditWebhookPanel } from '../AuditWebhookPanel';
const apiFetchJSON = vi.fn();
@@ -7,9 +9,12 @@ const showSuccess = vi.fn();
const showWarning = vi.fn();
const existingUrl = 'https://existing.example.test/events';
const addedUrl = 'https://new.example.test/events';
+let selectedOrg: string | null = 'tenant-a';
+const [enabled, setEnabled] = createSignal(true);
vi.mock('@/utils/apiClient', () => ({
apiFetchJSON: (...args: unknown[]) => apiFetchJSON(...args),
+ getOrgID: () => selectedOrg,
}));
vi.mock('@/utils/toast', () => ({
showSuccess: (...args: unknown[]) => showSuccess(...args),
@@ -18,11 +23,14 @@ vi.mock('@/utils/toast', () => ({
vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn() } }));
vi.mock('@/stores/license', () => ({
getRuntimeCapabilityBlock: () => undefined,
- hasFeature: () => true,
+ hasFeature: () => enabled(),
loadRuntimeCapabilities: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('@/stores/licenseCommercial', () => ({
- getUpgradeActionDestination: () => ({ href: '/upgrade', external: false }),
+ getUpgradeActionDestination: () => ({
+ href: 'https://plans.example.test/upgrade',
+ external: true,
+ }),
}));
vi.mock('@/stores/sessionPresentationPolicy', () => ({
presentationPolicyHidesUpgradePrompts: () => false,
@@ -37,12 +45,286 @@ const openPanel = async (canManage = true) => {
};
beforeEach(() => {
+ selectedOrg = 'tenant-a';
+ setEnabled(true);
apiFetchJSON.mockReset().mockResolvedValue({ urls: [existingUrl] });
showSuccess.mockReset();
showWarning.mockReset();
});
afterEach(cleanup);
+const defer = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+};
+
+const emptyMessage = 'No audit webhooks configured yet.';
+const readErrorMessage = 'Audit webhook configuration could not be loaded.';
+
+describe('audit webhook read admission', () => {
+ it('blocks Enter and button saves while the selected configuration has not arrived', async () => {
+ const read = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(read.promise);
+ render(() => <AuditWebhookPanel />);
+ const input = screen.getByRole('textbox', { name: 'Audit webhook URL' });
+ fireEvent.input(input, { target: { value: addedUrl } });
+ expect(screen.getByText('Loading audit webhooks…')).toBeInTheDocument();
+ expect(screen.queryByText(emptyMessage)).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(writeCalls()).toHaveLength(0);
+ read.resolve({ urls: [existingUrl] });
+ await screen.findByText(existingUrl);
+ expect(input).toHaveValue(addedUrl);
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeEnabled();
+ expect(writeCalls()).toHaveLength(0);
+ });
+
+ it('keeps failure unknown, preserves the draft and reads on explicit retry without saving', async () => {
+ apiFetchJSON.mockRejectedValueOnce(new Error('private backend text must not be rendered'));
+ render(() => <AuditWebhookPanel />);
+ await screen.findByText(readErrorMessage);
+ const input = screen.getByRole('textbox', { name: 'Audit webhook URL' });
+ fireEvent.input(input, { target: { value: ` ${addedUrl} ` } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(screen.queryByText(emptyMessage)).not.toBeInTheDocument();
+ expect(screen.getByText(/Existing destinations are unknown/)).toBeInTheDocument();
+ expect(screen.queryByText(/private backend text/)).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ expect(apiFetchJSON).toHaveBeenCalledTimes(1);
+ expect(showSuccess).not.toHaveBeenCalled();
+ const retry = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(retry.promise);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
+ eventBus.emit('org_switched', 'tenant-a');
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ expect(writeCalls()).toHaveLength(0);
+ expect(input).toHaveValue(` ${addedUrl} `);
+ retry.resolve({ urls: [existingUrl] });
+ await screen.findByText(existingUrl);
+ expect(screen.queryByText(readErrorMessage)).not.toBeInTheDocument();
+ expect(input).toHaveValue(` ${addedUrl} `);
+ expect(writeCalls()).toHaveLength(0);
+ fireEvent.click(screen.getByRole('button', { name: 'Add Endpoint' }));
+ await screen.findByText(addedUrl);
+ expect(writeCalls()).toHaveLength(1);
+ expect(JSON.parse(writeCalls()[0][1].body)).toEqual({ urls: [existingUrl, addedUrl] });
+ for (const [, options] of apiFetchJSON.mock.calls) {
+ expect(options).toMatchObject({ expectedOrgID: 'tenant-a', retry: false });
+ expect(options.signal).toBeInstanceOf(AbortSignal);
+ }
+ });
+
+ it('retains last loaded destinations and the draft across a failed same-selection refresh', async () => {
+ const input = await openPanel();
+ fireEvent.input(input, { target: { value: addedUrl } });
+ const refresh = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(refresh.promise);
+ eventBus.emit('org_switched', 'tenant-a');
+ expect(screen.getByText(existingUrl)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeDisabled();
+ fireEvent.keyDown(input, { key: 'Enter' });
+ refresh.reject(new Error('read unavailable'));
+ await screen.findByText(readErrorMessage);
+ expect(screen.getByText(/Last loaded destinations are shown below/)).toBeInTheDocument();
+ expect(screen.getByText(existingUrl)).toBeInTheDocument();
+ expect(input).toHaveValue(addedUrl);
+ expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeDisabled();
+ expect(writeCalls()).toHaveLength(0);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
+ await waitFor(() => expect(screen.queryByText(readErrorMessage)).not.toBeInTheDocument());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeEnabled());
+ expect(writeCalls()).toHaveLength(0);
+ });
+
+ it.each([[], null])(
+ 'accepts explicit known-empty %j and still requires a deliberate save',
+ async (urls) => {
+ apiFetchJSON.mockResolvedValueOnce({ urls });
+ render(() => <AuditWebhookPanel />);
+ await screen.findByText(emptyMessage);
+ const input = screen.getByRole('textbox', { name: 'Audit webhook URL' });
+ fireEvent.input(input, { target: { value: addedUrl } });
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeEnabled();
+ expect(writeCalls()).toHaveLength(0);
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await screen.findByText(addedUrl);
+ expect(JSON.parse(writeCalls()[0][1].body)).toEqual({ urls: [addedUrl] });
+ },
+ );
+
+ it.each([undefined, null, {}, { urls: false }, { urls: '' }, { urls: {} }, { urls: [false] }])(
+ 'does not mistake a malformed response for an empty selection: %j',
+ async (response) => {
+ apiFetchJSON.mockResolvedValueOnce(response);
+ render(() => <AuditWebhookPanel />);
+ await screen.findByText(readErrorMessage);
+ const input = screen.getByRole('textbox', { name: 'Audit webhook URL' });
+ fireEvent.input(input, { target: { value: addedUrl } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(screen.queryByText(emptyMessage)).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ expect(writeCalls()).toHaveLength(0);
+ },
+ );
+
+ it.each(['resolve', 'reject'] as const)(
+ 'ignores an obsolete read %s after a tenant switch and allows deliberate default recovery',
+ async (finish) => {
+ const oldRead = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(oldRead.promise);
+ render(() => <AuditWebhookPanel />);
+ selectedOrg = 'tenant-b';
+ apiFetchJSON.mockRejectedValueOnce(new Error('new tenant unavailable'));
+ eventBus.emit('org_switched', 'tenant-b');
+ await screen.findByText(readErrorMessage);
+ if (finish === 'resolve') oldRead.resolve({ urls: [existingUrl] });
+ else oldRead.reject(new Error('old tenant unavailable'));
+ await Promise.resolve();
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.getByText(readErrorMessage)).toBeInTheDocument();
+ expect(apiFetchJSON.mock.calls[0][1].signal.aborted).toBe(true);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ selectedOrg = null;
+ apiFetchJSON.mockResolvedValueOnce({ urls: [] });
+ eventBus.emit('org_switched', 'default');
+ await screen.findByText(emptyMessage);
+ expect(apiFetchJSON.mock.calls[2][1]).toMatchObject({
+ expectedOrgID: 'default',
+ retry: false,
+ });
+ const input = screen.getByRole('textbox', { name: 'Audit webhook URL' });
+ fireEvent.input(input, { target: { value: addedUrl } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await screen.findByText(addedUrl);
+ expect(writeCalls()[0][1]).toMatchObject({ expectedOrgID: 'default', retry: false });
+ expect(JSON.parse(writeCalls()[0][1].body)).toEqual({ urls: [addedUrl] });
+ },
+ );
+
+ it('rejects a stale removal confirmation when org storage changes without an event', async () => {
+ await openPanel();
+ fireEvent.click(screen.getByRole('button', { name: 'Remove webhook endpoint' }));
+ selectedOrg = 'tenant-b';
+ fireEvent.click(screen.getByRole('button', { name: 'Remove webhook' }));
+ expect(writeCalls()).toHaveLength(0);
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ await screen.findByText(readErrorMessage);
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ });
+
+ it('discards a pending save result after selection changes without replaying the mutation', async () => {
+ const input = await openPanel();
+ const save = defer<object>();
+ apiFetchJSON.mockReturnValueOnce(save.promise);
+ fireEvent.input(input, { target: { value: addedUrl } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ selectedOrg = 'tenant-b';
+ eventBus.emit('org_switched', 'tenant-b');
+ save.resolve({});
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Retry loading' })).toBeEnabled(),
+ );
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.queryByText(addedUrl)).not.toBeInTheDocument();
+ expect(input).toHaveValue('');
+ expect(showSuccess).not.toHaveBeenCalled();
+ expect(writeCalls()).toHaveLength(1);
+ expect(writeCalls()[0][1].signal.aborted).toBe(true);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ });
+
+ it('invalidates a read on capability loss and does not admit its late result', async () => {
+ const read = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(read.promise);
+ render(() => <AuditWebhookPanel />);
+ setEnabled(false);
+ read.resolve({ urls: [existingUrl] });
+ await Promise.resolve();
+ expect(apiFetchJSON.mock.calls[0][1].signal.aborted).toBe(true);
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.queryByRole('textbox', { name: 'Audit webhook URL' })).not.toBeInTheDocument();
+ expect(writeCalls()).toHaveLength(0);
+ setEnabled(true);
+ await screen.findByText(existingUrl);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps same-selection data and draft hidden during capability refresh, then revalidates them', async () => {
+ const input = await openPanel();
+ fireEvent.input(input, { target: { value: addedUrl } });
+ setEnabled(false);
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.queryByRole('textbox', { name: 'Audit webhook URL' })).not.toBeInTheDocument();
+ apiFetchJSON.mockRejectedValueOnce(new Error('read failed after capability refresh'));
+ setEnabled(true);
+ await screen.findByText(readErrorMessage);
+ expect(screen.getByText(existingUrl)).toBeInTheDocument();
+ expect(screen.getByText(/Last loaded destinations/)).toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toHaveValue(addedUrl);
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ expect(writeCalls()).toHaveLength(0);
+ });
+
+ it('requires a read after a same-selection save is interrupted by capability refresh', async () => {
+ const input = await openPanel();
+ const save = defer<object>();
+ apiFetchJSON.mockReturnValueOnce(save.promise);
+ fireEvent.input(input, { target: { value: addedUrl } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ setEnabled(false);
+ setEnabled(true);
+ save.resolve({});
+ await screen.findByText(readErrorMessage);
+ expect(screen.getByText(existingUrl)).toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toHaveValue(addedUrl);
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeDisabled();
+ expect(showSuccess).not.toHaveBeenCalled();
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ apiFetchJSON.mockResolvedValueOnce({ urls: [existingUrl, addedUrl] });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
+ await screen.findByText(addedUrl);
+ expect(writeCalls()).toHaveLength(1);
+ expect(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toHaveValue(addedUrl);
+ expect(showSuccess).not.toHaveBeenCalled();
+ });
+
+ it.each(['resolve', 'reject'] as const)(
+ 'invalidates a disposed read before its late %s',
+ async (finish) => {
+ const read = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(read.promise);
+ const panel = render(() => <AuditWebhookPanel />);
+ panel.unmount();
+ if (finish === 'resolve') read.resolve({ urls: [existingUrl] });
+ else read.reject(new Error('disposed read'));
+ await Promise.resolve();
+ eventBus.emit('org_switched', 'tenant-a');
+ expect(apiFetchJSON).toHaveBeenCalledOnce();
+ expect(apiFetchJSON.mock.calls[0][1].signal.aborted).toBe(true);
+ expect(showSuccess).not.toHaveBeenCalled();
+ },
+ );
+
+ it('allows a read-only retry but never grants write access after recovery', async () => {
+ apiFetchJSON.mockRejectedValueOnce(new Error('read refused'));
+ render(() => <AuditWebhookPanel canManage={false} />);
+ await screen.findByText(readErrorMessage);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
+ await screen.findByText(existingUrl);
+ expect(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeDisabled();
+ expect(writeCalls()).toHaveLength(0);
+ });
+});
+
describe('audit webhook entry recovery', () => {
it('preserves a refused entry and old destinations, then clears only after a successful retry', async () => {
const input = await openPanel();
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsReadOnlyPanels.test.tsx b/frontend-modern/src/components/Settings/__tests__/settingsReadOnlyPanels.test.tsx
index 9ce03cf585..c9330ff85f 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsReadOnlyPanels.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/settingsReadOnlyPanels.test.tsx
@@ -52,6 +52,7 @@ vi.mock('@/api/onboarding', () => ({
}));
vi.mock('@/utils/apiClient', () => ({
+ getOrgID: () => null,
apiFetchJSON: (...args: unknown[]) => apiFetchJSONMock(...args),
}));
diff --git a/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts b/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts
index 2bfa16d2a4..d84643fdd6 100644
--- a/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts
+++ b/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts
@@ -1,5 +1,6 @@
-import { createEffect, createSignal, onMount } from 'solid-js';
-import { apiFetchJSON } from '@/utils/apiClient';
+import { batch, createEffect, createSignal, on, onCleanup, onMount } from 'solid-js';
+import { apiFetchJSON, getOrgID } from '@/utils/apiClient';
+import { eventBus } from '@/stores/events';
import { logger } from '@/utils/logger';
import { showSuccess, showWarning } from '@/utils/toast';
import { getRuntimeCapabilityBlock, hasFeature } from '@/stores/license';
@@ -19,6 +20,14 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
const [newUrl, setNewUrl] = createSignal('');
const [saving, setSaving] = createSignal(false);
const [loading, setLoading] = createSignal(true);
+ const [loadError, setLoadError] = createSignal(false);
+ const [hasLoadedConfiguration, setHasLoadedConfiguration] = createSignal(false);
+ const currentOrg = () => getOrgID() || 'default';
+ let selectedOrg = currentOrg();
+ let request = 0;
+ let disposed = false;
+ let readController: AbortController | undefined;
+ let saveController: AbortController | undefined;
const canManage = () => canManageOverride !== false;
const auditLoggingRuntimeBlock = () => getRuntimeCapabilityBlock('audit_logging');
@@ -32,39 +41,113 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
? resolveUpgradeDestination(auditLoggingRuntimeBlock()?.action_url)
: getUpgradeActionDestination('audit_logging');
const upgradeActionLabel = () => (paidRuntimeRequired() ? 'Download Pulse Pro' : 'View plans');
+ const canEdit = () =>
+ canManage() &&
+ isAuditLoggingEnabled() &&
+ hasLoadedConfiguration() &&
+ !loading() &&
+ !loadError() &&
+ selectedOrg === currentOrg();
+
+ const invalidateRequests = () => {
+ request += 1;
+ readController?.abort();
+ readController = undefined;
+ saveController?.abort();
+ };
+
+ const selectCurrentOrg = () => {
+ if (selectedOrg === currentOrg()) return;
+ invalidateRequests();
+ selectedOrg = currentOrg();
+ batch(() => {
+ setWebhookUrls([]);
+ setHasLoadedConfiguration(false);
+ setNewUrl('');
+ setLoadError(true);
+ setLoading(false);
+ });
+ };
const fetchWebhooks = async () => {
+ selectCurrentOrg();
+ if (disposed || !isAuditLoggingEnabled() || readController || saving()) return;
+ const org = selectedOrg;
+ const thisRequest = ++request;
+ const isCurrent = () =>
+ !disposed && thisRequest === request && org === currentOrg() && isAuditLoggingEnabled();
+ readController = new AbortController();
+ setLoading(true);
+ setLoadError(false);
try {
- const data = await apiFetchJSON<{ urls: string[] }>('/api/admin/webhooks/audit');
- setWebhookUrls(data.urls || []);
+ const data = await apiFetchJSON<{ urls: string[] | null }>('/api/admin/webhooks/audit', {
+ expectedOrgID: org,
+ retry: false,
+ signal: readController.signal,
+ });
+ if (!isCurrent()) return;
+ // The server can encode a nil slice as null. Only an explicit empty
+ // selection is empty; an unexpected payload must not enable replacement.
+ if (
+ !data ||
+ (data.urls !== null &&
+ (!Array.isArray(data.urls) || data.urls.some((url) => typeof url !== 'string')))
+ ) {
+ throw new Error('Invalid audit webhook configuration');
+ }
+ setWebhookUrls(data.urls ?? []);
+ setHasLoadedConfiguration(true);
} catch (error) {
+ if (!isCurrent()) return;
+ setLoadError(true);
logger.error('[AuditWebhookPanel] Failed to fetch audit webhooks', error);
} finally {
- setLoading(false);
+ if (!disposed && thisRequest === request) {
+ readController = undefined;
+ setLoading(false);
+ selectCurrentOrg();
+ }
}
};
const saveWebhooks = async (urls: string[]) => {
+ selectCurrentOrg();
+ if (!canEdit() || saving() || disposed) return false;
+ const org = selectedOrg;
+ const thisRequest = request;
+ const isCurrent = () =>
+ !disposed && thisRequest === request && org === currentOrg() && isAuditLoggingEnabled();
+ saveController = new AbortController();
setSaving(true);
try {
await apiFetchJSON('/api/admin/webhooks/audit', {
method: 'POST',
body: JSON.stringify({ urls }),
+ expectedOrgID: org,
+ retry: false,
+ signal: saveController.signal,
});
+ if (!isCurrent()) return false;
setWebhookUrls(urls);
showSuccess(getAuditWebhookSaveSuccessMessage());
return true;
} catch (error) {
+ if (!isCurrent()) return false;
logger.error('[AuditWebhookPanel] Failed to save audit webhooks', error);
showWarning(getAuditWebhookSaveErrorMessage());
return false;
} finally {
- setSaving(false);
+ saveController = undefined;
+ if (!disposed) {
+ setSaving(false);
+ selectCurrentOrg();
+ }
}
};
const handleAddWebhook = async () => {
- if (!canManage() || saving()) return;
+ selectCurrentOrg();
+ if (!canEdit() || saving() || disposed) return;
const draft = newUrl();
const url = draft.trim();
if (!url) return;
@@ -88,7 +171,8 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
};
const handleRemoveWebhook = async (url: string) => {
- if (!canManage() || saving()) return;
+ selectCurrentOrg();
+ if (!canEdit() || saving() || disposed || !webhookUrls().includes(url)) return;
await saveWebhooks(webhookUrls().filter((existingUrl) => existingUrl !== url));
};
@@ -96,20 +180,44 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
loadRuntimeCapabilities();
});
- createEffect(() => {
- if (hasFeature('audit_logging')) {
- void fetchWebhooks();
- } else {
- setLoading(false);
- }
+ const unsubscribeOrg = eventBus.on('org_switched', () => {
+ selectCurrentOrg();
+ // Read the new selection, never replay an interrupted save.
+ void fetchWebhooks();
+ });
+
+ createEffect(
+ on(isAuditLoggingEnabled, (enabled) => {
+ if (enabled) {
+ void fetchWebhooks();
+ } else {
+ invalidateRequests();
+ // A capability refresh is not an empty configuration. Keep this
+ // selection's last accepted data hidden behind the feature gate.
+ // An interrupted save may have reached the server. Require a read
+ // before another replacement, even when the selection is unchanged.
+ if (saving()) setLoadError(true);
+ setLoading(false);
+ }
+ }),
+ );
+
+ onCleanup(() => {
+ disposed = true;
+ invalidateRequests();
+ unsubscribeOrg();
});
return {
+ canEdit,
canManage,
+ fetchWebhooks,
handleAddWebhook,
handleRemoveWebhook,
isAuditLoggingEnabled,
loading,
+ loadError,
+ hasLoadedConfiguration,
newUrl,
saving,
setNewUrl,
diff --git a/frontend-modern/src/utils/auditWebhookPresentation.ts b/frontend-modern/src/utils/auditWebhookPresentation.ts
index 1027017eac..f1940537e5 100644
--- a/frontend-modern/src/utils/auditWebhookPresentation.ts
+++ b/frontend-modern/src/utils/auditWebhookPresentation.ts
@@ -73,6 +73,16 @@ export function getAuditWebhookLoadingState() {
} as const;
}
+export function getAuditWebhookReadErrorCopy(hasLoadedConfiguration: boolean) {
+ return {
+ title: 'Audit webhook configuration could not be loaded.',
+ body: hasLoadedConfiguration
+ ? 'Last loaded destinations are shown below. Load the configuration before making changes.'
+ : 'Existing destinations are unknown. Load the configuration before making changes.',
+ retryLabel: 'Retry loading',
+ } as const;
+}
+
export function getAuditWebhookInvalidUrlMessage(): string {
return 'Please enter a valid URL';
}