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.

Keep audit webhook configuration within its current reader

pulse-triage[bot]68ef53046fbb
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index d0dff23c08..a9e6bc2cb6 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -15,6 +15,39 @@
## Purpose
+### Audit destinations belong to their current reader
+
+The existing Audit Webhooks panel receives the live principal and explicit
+read/write capabilities from Settings. Accepted endpoint URLs, unsaved entries,
+removal confirmation and inline feedback belong to that reader, selected
+organisation and audit-logging entitlement. A principal, read/write authority
+or entitlement change, organisation switch or disposal aborts outstanding work
+and erases that state. Returning to the same principal or organisation does not
+readmit an old response. Equal-reader status refreshes retain the current draft.
+
+A new admitted reader loads configuration before any replacement. Failed and
+malformed reads remain unknown, not an empty destination list. A failed refresh
+within the same reader retains their last accepted destinations and draft, but
+blocks edits until an explicit read-only Retry succeeds. Read-only readers can
+recover without acquiring write access. Storage drift noticed at an action or
+completion withdraws old state rather than dispatching that action in another
+organisation. Reads and writes keep the existing expected-organisation, abort
+signal and no-automatic-retry client contract; backend enforcement is unchanged.
+
+Only accepted current inventory enables add/removal. Mutations are serialised,
+and removal requires the current in-page confirmation. Refused additions retain
+the draft; refused removals retain the confirmation with fixed inline feedback.
+Only explicit retry repeats a write. An obsolete success/refusal/completion
+cannot finish a newer read or write, restore old URLs, clear a later draft,
+close another confirmation or publish global feedback. Client cancellation
+cannot undo a server-applied change; recovery reads its actual configuration.
+
+Registered `AuditWebhookPanel` and registry-context tests cover reader changes,
+authority loss/recovery, malformed/refused reads, storage drift, disposal and
+late read/write results. Actual App browser proof at desktop and narrow widths
+exercises the producer through Settings, its registry, API client and dialogs.
+Synthetic proof is not native receiver delivery, IdP or original tenant recovery.
+
### Role administration belongs to the current reader
The existing Roles screen binds its accepted role inventory, unsaved permissions,
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 96e8a5da87..34c0d7d71d 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,26 @@
## Purpose
+### Audit webhook configuration withdraws with its reader
+
+The Settings Audit Webhooks consumer treats endpoint addresses and new URL
+drafts as reader-owned data. Changes of principal, selected organisation,
+read/write authority or audit entitlement, and panel disposal, cancel requests
+and erase inventory, draft, confirmation and local feedback. Old completions
+cannot enter a later reader, including after the same identifiers return.
+The registry passes explicit current read/write capabilities; read withdrawal
+permits no configuration read or mutation. Read-only recovery never grants write
+access. Unchanged-reader status refreshes preserve their current draft.
+
+This tightens consumer lifetime, not backend authentication, tenant boundaries,
+audit event redaction, SSRF validation or delivery. The existing API client still
+binds expected organisation, cancellation and disabled automatic retries. Failed
+reads do not imply no destinations; failed mutations remain explicit and locally
+recoverable. No response error payload or endpoint address enters global action
+feedback. Registered `AuditWebhookPanel`/registry tests and actual-App browser
+proof cover withdrawal and current-reader recovery; they are not evidence of
+installed recipient delivery or original administrator/IdP recovery.
+
### Configuration writes own their temporary files
Ordinary shared configuration writes, their retained credential backups and
diff --git a/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx b/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx
index 25b7c0b959..2eafe7916a 100644
--- a/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx
+++ b/frontend-modern/src/components/Settings/AuditWebhookPanel.tsx
@@ -1,4 +1,4 @@
-import { For, Show, createEffect, createSignal, type Component } from 'solid-js';
+import { For, Show, 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';
@@ -24,11 +24,10 @@ import {
getAuditWebhookReadErrorCopy,
} from '@/utils/auditWebhookPresentation';
import { pathForTab } from '@/features/alerts/types';
-import { useAuditWebhookPanelState } from '@/components/Settings/useAuditWebhookPanelState';
-
-interface AuditWebhookPanelProps {
- canManage?: boolean;
-}
+import {
+ useAuditWebhookPanelState,
+ type AuditWebhookPanelProps,
+} from '@/components/Settings/useAuditWebhookPanelState';
const AuditWebhookNotificationsSignpost: Component = () => {
// A plain anchor: the app Router intercepts same-origin links, and the
@@ -49,10 +48,12 @@ const AuditWebhookNotificationsSignpost: Component = () => {
};
export const AuditWebhookPanel: Component<AuditWebhookPanelProps> = (props) => {
- const [urlToRemove, setUrlToRemove] = createSignal<string | null>(null);
let newUrlInputRef: HTMLInputElement | undefined;
const {
+ actionError,
canEdit,
+ canRead,
+ closeRemoveWebhook,
canManage,
fetchWebhooks,
handleAddWebhook,
@@ -62,15 +63,18 @@ export const AuditWebhookPanel: Component<AuditWebhookPanelProps> = (props) => {
loadError,
hasLoadedConfiguration,
newUrl,
+ openRemoveWebhook,
+ pendingRemoval,
saving,
setNewUrl,
+ successNotice,
showUpgradePrompts,
showFeatureGateAction,
upgradeDestination,
upgradeActionLabel,
paidRuntimeRequired,
webhookUrls,
- } = useAuditWebhookPanelState(props.canManage);
+ } = useAuditWebhookPanelState(props);
const featureGateCopy = () =>
getAuditWebhookFeatureGateCopy({
showCommercialCopy: showUpgradePrompts(),
@@ -78,9 +82,6 @@ export const AuditWebhookPanel: Component<AuditWebhookPanelProps> = (props) => {
});
const emptyStateCopy = () => getAuditWebhookEmptyStateCopy();
const readErrorCopy = () => getAuditWebhookReadErrorCopy(hasLoadedConfiguration());
- createEffect(() => {
- if (!canEdit()) setUrlToRemove(null);
- });
const featureGate = () => (
<SettingsPanel title="Audit Webhooks">
@@ -102,164 +103,191 @@ export const AuditWebhookPanel: Component<AuditWebhookPanelProps> = (props) => {
return (
<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).
+ <Show
+ when={canRead()}
+ fallback={
+ <SettingsPanel title="Audit Webhooks">
+ <p role="status" class="text-sm text-muted">
+ Audit webhook access is unavailable for this account.
</p>
- <AuditWebhookNotificationsSignpost />
-
- <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>
+ </SettingsPanel>
+ }
+ >
+ <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>
- </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}
+ </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 />
+
+ <Show when={successNotice()}>
+ <p role="status" class="text-sm text-green-700 dark:text-green-300">
+ {successNotice()}
</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} />
+ <Show when={actionError() && !pendingRemoval()}>
+ <p role="alert" class="text-sm text-red-700 dark:text-red-300">
+ {actionError()}
+ </p>
+ </Show>
+ <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={() => openRemoveWebhook(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={!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>
- )}
- </For>
+ )}
+ </For>
- <Show
- when={
- hasLoadedConfiguration() &&
- !loading() &&
- !loadError() &&
- webhookUrls().length === 0
- }
+ <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"
>
- <EmptyState
- variant="panel"
- icon={<Globe class="h-5 w-5" />}
- title={emptyStateCopy().title}
- />
- </Show>
+ <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={!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>
- </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"
- 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>
- </Dialog>
- </Show>
- </div>
+ <Show when={pendingRemoval()} keyed>
+ {(url) => (
+ <Dialog
+ isOpen={true}
+ onClose={closeRemoveWebhook}
+ 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">{url}</span>. Any external
+ receiver using this URL will stop receiving Pulse audit traffic. You can add the
+ URL back later if needed.
+ </p>
+ <Show when={actionError()}>
+ <p role="alert" class="mb-4 text-sm text-red-700 dark:text-red-300">
+ {actionError()}
+ </p>
+ </Show>
+ <div class="flex justify-end gap-3">
+ <button
+ type="button"
+ disabled={saving()}
+ onClick={closeRemoveWebhook}
+ 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={() => void handleRemoveWebhook()}
+ 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>
+ </Dialog>
+ )}
+ </Show>
+ </div>
+ </Show>
</Show>
);
};
diff --git a/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx
index f6166387d2..aad8bb5e3c 100644
--- a/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AuditWebhookPanel.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createSignal } from 'solid-js';
import { eventBus } from '@/stores/events';
import { AuditWebhookPanel } from '../AuditWebhookPanel';
+import { useAuditWebhookPanelState } from '../useAuditWebhookPanelState';
const apiFetchJSON = vi.fn();
const showSuccess = vi.fn();
@@ -226,18 +227,17 @@ describe('audit webhook read admission', () => {
fireEvent.input(input, { target: { value: addedUrl } });
fireEvent.keyDown(input, { key: 'Enter' });
selectedOrg = 'tenant-b';
+ apiFetchJSON.mockResolvedValueOnce({ urls: [] });
eventBus.emit('org_switched', 'tenant-b');
save.resolve({});
- await waitFor(() =>
- expect(screen.getByRole('button', { name: 'Retry loading' })).toBeEnabled(),
- );
+ await screen.findByText(emptyMessage);
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);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(3);
});
it('invalidates a read on capability loss and does not admit its late result', async () => {
@@ -256,7 +256,7 @@ describe('audit webhook read admission', () => {
expect(apiFetchJSON).toHaveBeenCalledTimes(2);
});
- it('keeps same-selection data and draft hidden during capability refresh, then revalidates them', async () => {
+ it('withdraws same-selection data and draft on capability loss and requires a fresh read', async () => {
const input = await openPanel();
fireEvent.input(input, { target: { value: addedUrl } });
setEnabled(false);
@@ -265,9 +265,9 @@ describe('audit webhook read admission', () => {
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.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.getByText(/Existing destinations are unknown/)).toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toHaveValue('');
expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
expect(writeCalls()).toHaveLength(0);
});
@@ -279,20 +279,23 @@ describe('audit webhook read admission', () => {
fireEvent.input(input, { target: { value: addedUrl } });
fireEvent.keyDown(input, { key: 'Enter' });
setEnabled(false);
+ apiFetchJSON.mockRejectedValueOnce(new Error('fresh read unavailable'));
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.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toHaveValue('');
expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
- expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeDisabled();
+ expect(
+ screen.queryByRole('button', { name: 'Remove webhook endpoint' }),
+ ).not.toBeInTheDocument();
expect(showSuccess).not.toHaveBeenCalled();
- expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(3);
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(screen.getByRole('textbox', { name: 'Audit webhook URL' })).toHaveValue('');
expect(showSuccess).not.toHaveBeenCalled();
});
@@ -331,9 +334,8 @@ describe('audit webhook entry recovery', () => {
apiFetchJSON.mockRejectedValueOnce(new Error('save refused')).mockResolvedValueOnce({});
fireEvent.input(input, { target: { value: ` ${addedUrl} ` } });
fireEvent.keyDown(input, { key: 'Enter' });
- await waitFor(() =>
- expect(showWarning).toHaveBeenCalledWith('Failed to save webhook configuration'),
- );
+ await screen.findByRole('alert');
+ expect(screen.getByRole('alert')).toHaveTextContent('Failed to save webhook configuration');
expect(input).toHaveValue(` ${addedUrl} `);
expect(screen.getByText(existingUrl)).toBeInTheDocument();
expect(screen.queryByText(addedUrl)).not.toBeInTheDocument();
@@ -342,7 +344,8 @@ describe('audit webhook entry recovery', () => {
fireEvent.click(screen.getByRole('button', { name: 'Add Endpoint' }));
await screen.findByText(addedUrl);
expect(input).toHaveValue('');
- expect(showSuccess).toHaveBeenCalledOnce();
+ await screen.findByText('Audit webhooks updated');
+ expect(showSuccess).not.toHaveBeenCalled();
expect(writeCalls().map(([, options]) => JSON.parse(options.body))).toEqual([
{ urls: [existingUrl, addedUrl] },
{ urls: [existingUrl, addedUrl] },
@@ -383,10 +386,10 @@ describe('audit webhook entry recovery', () => {
apiFetchJSON.mockRejectedValueOnce(new Error('save refused')).mockResolvedValueOnce({});
fireEvent.click(screen.getByRole('button', { name: 'Remove webhook endpoint' }));
fireEvent.click(screen.getByRole('button', { name: 'Remove webhook' }));
- await waitFor(() => expect(showWarning).toHaveBeenCalledOnce());
- expect(screen.getByText(existingUrl)).toBeInTheDocument();
+ await screen.findByRole('alert');
+ expect(screen.getByRole('dialog', { name: 'Remove audit webhook' })).toBeInTheDocument();
+ expect(screen.getAllByText(existingUrl)).toHaveLength(2);
expect(input).toHaveValue(addedUrl);
- fireEvent.click(screen.getByRole('button', { name: 'Remove webhook endpoint' }));
fireEvent.click(screen.getByRole('button', { name: 'Remove webhook' }));
await waitFor(() => expect(screen.queryByText(existingUrl)).not.toBeInTheDocument());
expect(input).toHaveValue(addedUrl);
@@ -402,7 +405,10 @@ describe('audit webhook entry recovery', () => {
const input = await openPanel();
fireEvent.input(input, { target: { value: draft } });
fireEvent.keyDown(input, { key: 'Enter' });
- expect(showWarning).toHaveBeenCalledOnce();
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ draft === existingUrl ? 'This URL is already configured' : 'Please enter a valid URL',
+ );
+ expect(showWarning).not.toHaveBeenCalled();
expect(writeCalls()).toHaveLength(0);
expect(input).toHaveValue(draft);
},
@@ -417,3 +423,216 @@ describe('audit webhook entry recovery', () => {
expect(writeCalls()).toHaveLength(0);
});
});
+
+describe('audit webhook reader lifetime', () => {
+ it('never reads or exposes configuration without read admission, and recovers read-only', async () => {
+ const [read, setRead] = createSignal(false);
+ render(() => <AuditWebhookPanel currentUser="reader" canRead={read()} canManage={false} />);
+ expect(
+ screen.getByText('Audit webhook access is unavailable for this account.'),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
+ expect(apiFetchJSON).not.toHaveBeenCalled();
+ setRead(true);
+ await screen.findByText(existingUrl);
+ const input = screen.getByRole('textbox', { name: 'Audit webhook URL' });
+ expect(input).toBeDisabled();
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(writeCalls()).toHaveLength(0);
+ setRead(false);
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
+ expect(apiFetchJSON).toHaveBeenCalledOnce();
+ });
+
+ it.each(['resolve', 'reject'] as const)(
+ 'rejects an old principal read %s even after that name returns',
+ async (finish) => {
+ const oldRead = defer<{ urls: string[] }>();
+ const currentRead = defer<{ urls: string[] }>();
+ const [user, setUser] = createSignal<string | undefined>('first');
+ apiFetchJSON.mockReturnValueOnce(oldRead.promise);
+ render(() => <AuditWebhookPanel currentUser={user()} />);
+ apiFetchJSON.mockResolvedValueOnce({ urls: ['https://second.example.test/events'] });
+ setUser('second');
+ await screen.findByText('https://second.example.test/events');
+ apiFetchJSON.mockReturnValueOnce(currentRead.promise);
+ setUser('first');
+ expect(screen.queryByText('https://second.example.test/events')).not.toBeInTheDocument();
+ if (finish === 'resolve') oldRead.resolve({ urls: [existingUrl] });
+ else oldRead.reject(new Error('private obsolete read error'));
+ await Promise.resolve();
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.getByText('Loading audit webhooks…')).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(apiFetchJSON.mock.calls[0][1].signal.aborted).toBe(true);
+ currentRead.resolve({ urls: [] });
+ await screen.findByText(emptyMessage);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(3);
+ },
+ );
+
+ it('withdraws a draft, confirmation and endpoint on write withdrawal before read-only recovery', async () => {
+ const [manage, setManage] = createSignal(true);
+ render(() => <AuditWebhookPanel currentUser="reader" canManage={manage()} />);
+ await screen.findByText(existingUrl);
+ fireEvent.input(screen.getByRole('textbox'), { target: { value: addedUrl } });
+ fireEvent.click(screen.getByRole('button', { name: 'Remove webhook endpoint' }));
+ const read = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(read.promise);
+ setManage(false);
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox')).toHaveValue('');
+ expect(screen.getByRole('textbox')).toBeDisabled();
+ read.resolve({ urls: [existingUrl] });
+ await screen.findByText(existingUrl);
+ expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeDisabled();
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
+ expect(writeCalls()).toHaveLength(0);
+ setManage(true);
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Remove webhook endpoint' })).toBeEnabled(),
+ );
+ expect(screen.getByRole('textbox')).toHaveValue('');
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(apiFetchJSON).toHaveBeenCalledTimes(3);
+ });
+
+ it.each(['resolve', 'reject'] as const)(
+ 'ignores an obsolete save %s without finishing a new reader read or erasing their draft',
+ async (finish) => {
+ const [user, setUser] = createSignal('first');
+ render(() => <AuditWebhookPanel currentUser={user()} />);
+ await screen.findByText(existingUrl);
+ const save = defer<object>();
+ apiFetchJSON.mockReturnValueOnce(save.promise);
+ fireEvent.input(screen.getByRole('textbox'), { target: { value: addedUrl } });
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
+ expect(writeCalls()).toHaveLength(1);
+ const nextRead = defer<{ urls: string[] }>();
+ apiFetchJSON.mockReturnValueOnce(nextRead.promise);
+ setUser('second');
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox')).toHaveValue('');
+ fireEvent.input(screen.getByRole('textbox'), { target: { value: addedUrl } });
+ if (finish === 'resolve') save.resolve({});
+ else save.reject(new Error('private obsolete write refusal'));
+ await Promise.resolve();
+ expect(screen.getByText('Loading audit webhooks…')).toBeInTheDocument();
+ expect(screen.getByRole('textbox')).toHaveValue(addedUrl);
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.queryByText('Audit webhooks updated')).not.toBeInTheDocument();
+ nextRead.resolve({ urls: [] });
+ await screen.findByText(emptyMessage);
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeEnabled();
+ expect(writeCalls()[0][1].signal.aborted).toBe(true);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(3);
+ expect(showSuccess).not.toHaveBeenCalled();
+ expect(showWarning).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['resolve', 'reject'] as const)(
+ 'withdraws an obsolete save %s when org storage drifts without an event',
+ async (finish) => {
+ 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';
+ if (finish === 'resolve') save.resolve({});
+ else save.reject(new Error('private stale save failure'));
+ await screen.findByText(readErrorMessage);
+ expect(screen.queryByText(existingUrl)).not.toBeInTheDocument();
+ expect(input).toHaveValue('');
+ expect(screen.queryByText('Audit webhooks updated')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Add Endpoint' })).toBeDisabled();
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ expect(showSuccess).not.toHaveBeenCalled();
+ expect(showWarning).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps an unchanged-reader draft and confirmation through copied status props', async () => {
+ const [reader, setReader] = createSignal({
+ currentUser: 'reader',
+ canRead: true,
+ canManage: true,
+ });
+ render(() => <AuditWebhookPanel {...reader()} />);
+ await screen.findByText(existingUrl);
+ fireEvent.input(screen.getByRole('textbox'), { target: { value: addedUrl } });
+ fireEvent.click(screen.getByRole('button', { name: 'Remove webhook endpoint' }));
+ setReader({ ...reader() });
+ expect(screen.getByRole('dialog', { name: 'Remove audit webhook' })).toBeInTheDocument();
+ expect(screen.getByRole('textbox')).toHaveValue(addedUrl);
+ expect(apiFetchJSON).toHaveBeenCalledOnce();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(writeCalls()).toHaveLength(0);
+ });
+
+ it.each(['resolve', 'reject'] as const)(
+ 'erases owned state on disposal and ignores a late save %s',
+ async (finish) => {
+ let state!: ReturnType<typeof useAuditWebhookPanelState>;
+ const panel = render(() => {
+ state = useAuditWebhookPanelState({ currentUser: 'reader' });
+ return null;
+ });
+ await waitFor(() => expect(state.webhookUrls()).toEqual([existingUrl]));
+ state.setNewUrl(addedUrl);
+ state.openRemoveWebhook(existingUrl);
+ const save = defer<object>();
+ apiFetchJSON.mockReturnValueOnce(save.promise);
+ const pending = state.handleRemoveWebhook();
+ panel.unmount();
+ expect(state.webhookUrls()).toEqual([]);
+ expect(state.newUrl()).toBe('');
+ expect(state.pendingRemoval()).toBeNull();
+ expect(state.actionError()).toBeNull();
+ expect(state.successNotice()).toBeNull();
+ expect(state.saving()).toBe(false);
+ expect(state.hasLoadedConfiguration()).toBe(false);
+ expect(state.canEdit()).toBe(false);
+ expect(writeCalls()[0][1].signal.aborted).toBe(true);
+ if (finish === 'resolve') save.resolve({});
+ else save.reject(new Error('disposed write refusal'));
+ await pending;
+ state.setNewUrl(addedUrl);
+ state.openRemoveWebhook(existingUrl);
+ await state.handleAddWebhook();
+ await state.fetchWebhooks();
+ eventBus.emit('org_switched', 'tenant-b');
+ expect(state.webhookUrls()).toEqual([]);
+ expect(state.newUrl()).toBe('');
+ expect(state.successNotice()).toBeNull();
+ expect(state.actionError()).toBeNull();
+ expect(apiFetchJSON).toHaveBeenCalledTimes(2);
+ expect(showSuccess).not.toHaveBeenCalled();
+ expect(showWarning).not.toHaveBeenCalled();
+ },
+ );
+
+ it('withdraws local validation and success feedback with the principal', async () => {
+ const [user, setUser] = createSignal('first');
+ render(() => <AuditWebhookPanel currentUser={user()} />);
+ await screen.findByText(existingUrl);
+ fireEvent.input(screen.getByRole('textbox'), { target: { value: existingUrl } });
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
+ expect(screen.getByRole('alert')).toHaveTextContent('This URL is already configured');
+ setUser('second');
+ await screen.findByText(existingUrl);
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ fireEvent.input(screen.getByRole('textbox'), { target: { value: addedUrl } });
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
+ await screen.findByText('Audit webhooks updated');
+ setUser('third');
+ await screen.findByText(existingUrl);
+ expect(screen.queryByText('Audit webhooks updated')).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox')).toHaveValue('');
+ expect(showSuccess).not.toHaveBeenCalled();
+ expect(showWarning).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
index 0c835f802c..6a5617547a 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
@@ -150,6 +150,42 @@ describe('buildSettingsPanelRegistryContext', () => {
expect(context.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: undefined });
expect(context.getApiAccessPanelProps()).toMatchObject({ currentUser: undefined });
});
+ it('binds audit webhooks to the live principal and explicit read/write capabilities', () => {
+ const [status, setStatus] = createSignal<SecurityStatus | null>(null);
+ const context = buildSettingsPanelRegistryContext({
+ ...buildParams(null),
+ securityStatus: status,
+ });
+ expect(context.getAuditWebhookPanelProps()).toEqual({
+ currentUser: undefined,
+ canRead: false,
+ canManage: false,
+ });
+ setStatus({
+ currentUsername: 'audit-reader',
+ settingsCapabilities: { auditWebhooksRead: true, auditWebhooksWrite: false },
+ } as SecurityStatus);
+ expect(context.getAuditWebhookPanelProps()).toEqual({
+ currentUser: 'audit-reader',
+ canRead: true,
+ canManage: false,
+ });
+ setStatus({
+ currentUsername: 'audit-writer',
+ settingsCapabilities: { auditWebhooksRead: true, auditWebhooksWrite: true },
+ } as SecurityStatus);
+ expect(context.getAuditWebhookPanelProps()).toEqual({
+ currentUser: 'audit-writer',
+ canRead: true,
+ canManage: true,
+ });
+ setStatus({ currentUsername: '', settingsCapabilities: {} } as SecurityStatus);
+ expect(context.getAuditWebhookPanelProps()).toEqual({
+ currentUser: '',
+ canRead: false,
+ canManage: false,
+ });
+ });
it('binds Roles to the live principal and explicit roles capability', () => {
const [status, setStatus] = createSignal<SecurityStatus | null>(null);
const context = buildSettingsPanelRegistryContext({
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index 6324a08f1b..091b075ae6 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -125,6 +125,8 @@ export function buildSettingsPanelRegistryContext(
canManage: settingsCapabilities()?.relayWrite === true,
}),
getAuditWebhookPanelProps: () => ({
+ currentUser: currentUser(),
+ canRead: settingsCapabilities()?.auditWebhooksRead === true,
canManage: settingsCapabilities()?.auditWebhooksWrite === true,
}),
getRolesPanelProps: () => ({
diff --git a/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts b/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts
index d84643fdd6..41d9474b98 100644
--- a/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts
+++ b/frontend-modern/src/components/Settings/useAuditWebhookPanelState.ts
@@ -1,12 +1,9 @@
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';
+import { getRuntimeCapabilityBlock, hasFeature, loadRuntimeCapabilities } from '@/stores/license';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentationPolicy';
-import { loadRuntimeCapabilities } from '@/stores/license';
import { resolveUpgradeDestination } from '@/utils/upgradeNavigation';
import {
getAuditWebhookDuplicateUrlMessage,
@@ -15,79 +12,123 @@ import {
getAuditWebhookSaveSuccessMessage,
} from '@/utils/auditWebhookPresentation';
-export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
+export interface AuditWebhookPanelProps {
+ currentUser?: string;
+ canRead?: boolean;
+ canManage?: boolean;
+}
+
+export const useAuditWebhookPanelState = (props: AuditWebhookPanelProps) => {
const [webhookUrls, setWebhookUrls] = createSignal<string[]>([]);
const [newUrl, setNewUrl] = createSignal('');
const [saving, setSaving] = createSignal(false);
const [loading, setLoading] = createSignal(true);
const [loadError, setLoadError] = createSignal(false);
+ const [actionError, setActionError] = createSignal<string | null>(null);
+ const [successNotice, setSuccessNotice] = createSignal<string | null>(null);
const [hasLoadedConfiguration, setHasLoadedConfiguration] = createSignal(false);
+ const [pendingRemoval, setPendingRemoval] = createSignal<string | null>(null);
const currentOrg = () => getOrgID() || 'default';
- let selectedOrg = currentOrg();
- let request = 0;
+ const canRead = () => props.canRead !== false;
+ const canManage = () => canRead() && props.canManage !== false;
+ const isAuditLoggingEnabled = () => hasFeature('audit_logging');
+ const snapshot = () => ({
+ org: currentOrg(),
+ user: props.currentUser,
+ read: canRead(),
+ write: canManage(),
+ enabled: isAuditLoggingEnabled(),
+ });
+ const [context, setContext] = createSignal(snapshot());
let disposed = false;
let readController: AbortController | undefined;
let saveController: AbortController | undefined;
+ const contextIsCurrent = () => {
+ const current = snapshot();
+ const accepted = context();
+ return (
+ !disposed &&
+ current.org === accepted.org &&
+ current.user === accepted.user &&
+ current.read === accepted.read &&
+ current.write === accepted.write &&
+ current.enabled === accepted.enabled
+ );
+ };
- const canManage = () => canManageOverride !== false;
const auditLoggingRuntimeBlock = () => getRuntimeCapabilityBlock('audit_logging');
const paidRuntimeRequired = () => auditLoggingRuntimeBlock()?.reason === 'paid_runtime_required';
const showUpgradePrompts = () =>
!paidRuntimeRequired() && !presentationPolicyHidesUpgradePrompts();
const showFeatureGateAction = () => paidRuntimeRequired() || showUpgradePrompts();
- const isAuditLoggingEnabled = () => hasFeature('audit_logging');
const upgradeDestination = () =>
paidRuntimeRequired()
? resolveUpgradeDestination(auditLoggingRuntimeBlock()?.action_url)
: getUpgradeActionDestination('audit_logging');
const upgradeActionLabel = () => (paidRuntimeRequired() ? 'Download Pulse Pro' : 'View plans');
const canEdit = () =>
+ contextIsCurrent() &&
canManage() &&
isAuditLoggingEnabled() &&
hasLoadedConfiguration() &&
!loading() &&
!loadError() &&
- selectedOrg === currentOrg();
+ !saving();
- const invalidateRequests = () => {
- request += 1;
+ const resetContext = () => {
readController?.abort();
- readController = undefined;
saveController?.abort();
- };
-
- const selectCurrentOrg = () => {
- if (selectedOrg === currentOrg()) return;
- invalidateRequests();
- selectedOrg = currentOrg();
+ readController = saveController = undefined;
batch(() => {
+ // Replacing the snapshot invalidates old completions even if an ID is reused.
+ setContext(snapshot());
setWebhookUrls([]);
setHasLoadedConfiguration(false);
setNewUrl('');
- setLoadError(true);
+ setPendingRemoval(null);
+ setActionError(null);
+ setSuccessNotice(null);
+ setSaving(false);
+ setLoadError(false);
setLoading(false);
});
};
+ const ensureCurrentContext = () => {
+ if (contextIsCurrent()) return true;
+ if (!disposed) {
+ resetContext();
+ // Storage can change without an org event. Withdraw first; require a read,
+ // never turn the interrupted action into a replacement in another org.
+ setLoadError(true);
+ }
+ return false;
+ };
const fetchWebhooks = async () => {
- selectCurrentOrg();
- if (disposed || !isAuditLoggingEnabled() || readController || saving()) return;
- const org = selectedOrg;
- const thisRequest = ++request;
+ if (disposed) return;
+ ensureCurrentContext();
+ if (!canRead() || !isAuditLoggingEnabled() || readController || saveController) return;
+ const reader = context();
+ const controller = new AbortController();
+ readController = controller;
const isCurrent = () =>
- !disposed && thisRequest === request && org === currentOrg() && isAuditLoggingEnabled();
- readController = new AbortController();
- setLoading(true);
- setLoadError(false);
+ contextIsCurrent() && reader === context() && readController === controller;
+ batch(() => {
+ setPendingRemoval(null);
+ setActionError(null);
+ setSuccessNotice(null);
+ setLoading(true);
+ setLoadError(false);
+ });
try {
const data = await apiFetchJSON<{ urls: string[] | null }>('/api/admin/webhooks/audit', {
- expectedOrgID: org,
+ expectedOrgID: reader.org,
retry: false,
- signal: readController.signal,
+ signal: controller.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.
+ // Only a known empty selection is empty. Unknown configuration must not
+ // enable replacing destinations; the server encodes a nil slice as null.
if (
!data ||
(data.urls !== null &&
@@ -95,122 +136,141 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
) {
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);
+ batch(() => {
+ setWebhookUrls(data.urls ?? []);
+ setHasLoadedConfiguration(true);
+ });
+ } catch {
+ if (isCurrent()) setLoadError(true);
} finally {
- if (!disposed && thisRequest === request) {
+ if (isCurrent()) {
readController = undefined;
setLoading(false);
- selectCurrentOrg();
+ } else if (!disposed && reader === context() && !contextIsCurrent()) {
+ ensureCurrentContext();
}
}
};
const saveWebhooks = async (urls: string[]) => {
- selectCurrentOrg();
- if (!canEdit() || saving() || disposed) return false;
- const org = selectedOrg;
- const thisRequest = request;
+ if (!ensureCurrentContext() || !canEdit()) return false;
+ const reader = context();
+ const controller = new AbortController();
+ saveController = controller;
const isCurrent = () =>
- !disposed && thisRequest === request && org === currentOrg() && isAuditLoggingEnabled();
- saveController = new AbortController();
- setSaving(true);
+ contextIsCurrent() && reader === context() && saveController === controller;
+ batch(() => {
+ setSaving(true);
+ setActionError(null);
+ setSuccessNotice(null);
+ });
try {
await apiFetchJSON('/api/admin/webhooks/audit', {
method: 'POST',
body: JSON.stringify({ urls }),
- expectedOrgID: org,
+ expectedOrgID: reader.org,
retry: false,
- signal: saveController.signal,
+ signal: controller.signal,
});
if (!isCurrent()) return false;
- setWebhookUrls(urls);
- showSuccess(getAuditWebhookSaveSuccessMessage());
+ batch(() => {
+ setWebhookUrls(urls);
+ setSuccessNotice(getAuditWebhookSaveSuccessMessage());
+ });
return true;
- } catch (error) {
- if (!isCurrent()) return false;
- logger.error('[AuditWebhookPanel] Failed to save audit webhooks', error);
- showWarning(getAuditWebhookSaveErrorMessage());
+ } catch {
+ if (isCurrent()) setActionError(getAuditWebhookSaveErrorMessage());
return false;
} finally {
- saveController = undefined;
- if (!disposed) {
+ if (isCurrent()) {
+ saveController = undefined;
setSaving(false);
- selectCurrentOrg();
+ } else if (!disposed && reader === context() && !contextIsCurrent()) {
+ ensureCurrentContext();
}
}
};
const handleAddWebhook = async () => {
- selectCurrentOrg();
- if (!canEdit() || saving() || disposed) return;
+ if (!ensureCurrentContext() || !canEdit()) return;
const draft = newUrl();
const url = draft.trim();
if (!url) return;
-
+ setSuccessNotice(null);
try {
new URL(url);
} catch {
- showWarning(getAuditWebhookInvalidUrlMessage());
+ setActionError(getAuditWebhookInvalidUrlMessage());
return;
}
-
if (webhookUrls().includes(url)) {
- showWarning(getAuditWebhookDuplicateUrlMessage());
+ setActionError(getAuditWebhookDuplicateUrlMessage());
return;
}
-
+ const reader = context();
const saved = await saveWebhooks([...webhookUrls(), url]);
- // Leave failed entries available for correction/retry, and do not erase
- // a different draft typed while the submitted entry was saving.
- if (saved && newUrl() === draft) setNewUrl('');
+ // An obsolete completion cannot erase a later reader's matching draft.
+ if (saved && contextIsCurrent() && context() === reader && newUrl() === draft) setNewUrl('');
};
- const handleRemoveWebhook = async (url: string) => {
- selectCurrentOrg();
- if (!canEdit() || saving() || disposed || !webhookUrls().includes(url)) return;
- await saveWebhooks(webhookUrls().filter((existingUrl) => existingUrl !== url));
+ const openRemoveWebhook = (url: string) => {
+ if (!ensureCurrentContext() || !canEdit() || !webhookUrls().includes(url)) return;
+ batch(() => {
+ setActionError(null);
+ setSuccessNotice(null);
+ setPendingRemoval(url);
+ });
+ };
+ const closeRemoveWebhook = () => {
+ if (saving()) return;
+ setPendingRemoval(null);
+ setActionError(null);
+ };
+ const handleRemoveWebhook = async () => {
+ if (!ensureCurrentContext() || !canEdit()) return;
+ const url = pendingRemoval();
+ if (!url || !webhookUrls().includes(url)) return;
+ const reader = context();
+ const saved = await saveWebhooks(webhookUrls().filter((existingUrl) => existingUrl !== url));
+ if (saved && contextIsCurrent() && context() === reader) setPendingRemoval(null);
+ };
+ const updateNewUrl = (url: string) => {
+ if (!ensureCurrentContext() || !canManage() || !isAuditLoggingEnabled()) return;
+ setNewUrl(url);
+ if (!pendingRemoval() && !saving()) setActionError(null);
};
onMount(() => {
- loadRuntimeCapabilities();
- });
-
- const unsubscribeOrg = eventBus.on('org_switched', () => {
- selectCurrentOrg();
- // Read the new selection, never replay an interrupted save.
- void fetchWebhooks();
+ void loadRuntimeCapabilities();
});
-
createEffect(
- on(isAuditLoggingEnabled, (enabled) => {
- if (enabled) {
+ on(
+ [isAuditLoggingEnabled, canRead, canManage, () => props.currentUser],
+ (current, previous) => {
+ // A copied status object is not a new reader: keep their current draft.
+ if (previous && current.every((value, index) => value === previous[index])) return;
+ resetContext();
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);
- }
- }),
+ },
+ ),
);
-
+ const unsubscribeOrg = eventBus.on('org_switched', () => {
+ if (!contextIsCurrent()) resetContext();
+ // A same-reader refresh retains accepted destinations/draft on failure.
+ void fetchWebhooks();
+ });
onCleanup(() => {
disposed = true;
- invalidateRequests();
unsubscribeOrg();
+ resetContext();
});
return {
+ actionError,
canEdit,
canManage,
+ canRead,
+ closeRemoveWebhook,
fetchWebhooks,
handleAddWebhook,
handleRemoveWebhook,
@@ -219,10 +279,13 @@ export const useAuditWebhookPanelState = (canManageOverride?: boolean) => {
loadError,
hasLoadedConfiguration,
newUrl,
+ openRemoveWebhook,
+ pendingRemoval,
saving,
- setNewUrl,
+ setNewUrl: updateNewUrl,
showUpgradePrompts,
showFeatureGateAction,
+ successNotice,
upgradeDestination,
upgradeActionLabel,
paidRuntimeRequired,