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 viewer results within their reader and page

pulse-triage[bot]71e92bbcf505
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 11d1f192a7..094f635375 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -20,6 +20,29 @@
## Purpose
+### Audit viewer state belongs to its reader and accepted page
+
+The existing Audit Log panel receives live principal, non-secret token/scope
+identity and explicit audit-read capability from the Settings registry. Reader,
+organisation, entitlement or lifetime changes cancel work and withdraw events,
+counts, signature results and batch feedback. An equal-reader status refresh
+keeps its pending operation. A fresh inventory read withdraws the previous page
+and all its signature work before awaiting a replacement; an old result cannot
+verify a new event with the same ID. Only current accepted row objects admit
+verification. Reads and signature checks bind the expected organisation with
+cancellation and no automatic retries. Cancel ends local verification immediately
+and Resume is an explicit action; neither an old batch nor its completion may
+change a new batch's progress or publish feedback.
+
+Failed, refused and malformed reads are unavailable, not empty or verified.
+Verification refusal withdraws the page and requires a new read; other check
+failures remain retryable on the current row. Inventory validation accepts the
+producer's omitted optional strings. `AuditLogReaderLifetime`, existing audit
+request/branch tests and registry tests run in the normal frontend suite.
+Desktop/narrow actual-App proof covers the existing route, including late
+responses and usable Refresh/Verify/Cancel/Resume. This changes no audit source,
+server permissions, signing semantics, retention or installed recovery contract.
+
### Token reveals keep content and copy feedback with the admitted value
The existing token reveal consumer scrolls within the bounded shared dialog,
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index b669061f14..d088926b51 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -15,6 +15,23 @@
## Purpose
+### Audit events and signature checks withdraw with the reader
+
+The existing Settings Audit Log passes its current principal, explicit audit
+read capability and non-secret token/scope identity into the viewer. Accepted
+events, counts, signature results, pending checks and batch feedback belong to
+that reader, organisation and entitlement. Switching, withdrawal and disposal
+clear them and cancel pending work, including work that ignores cancellation.
+Returning to the same identifiers does not readmit an old result. An unchanged
+status response does not invalidate a live request. Every read/check uses the
+expected organisation and disabled automatic retries. Refresh replaces the page
+and its verification generation; stale row objects are not actionable. Read or
+verification refusal stays explicitly unavailable until an admitted refresh,
+never a false empty inventory or an inherited Verified badge. Normal audit
+reader/request and registry tests plus desktop/narrow actual-App browser proof
+cover these boundaries. Backend audit authorization/redaction and original
+administrator/IdP recovery remain separate, unchanged responsibilities.
+
### Audit destinations belong to their current reader
The existing Audit Webhooks panel receives the live principal and explicit
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index c1e107f86a..3550ffcbbe 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,22 @@
## Purpose
+### Audit viewer results cannot outlive their reader or page
+
+Audit event details and verification outcomes in Settings are reader-owned.
+The public viewer withdraws them on principal, token/scope identity, explicit
+read permission, organisation, entitlement or lifetime change. Page replacement
+also cancels and invalidates row and batch signature checks: an obsolete success,
+refusal or completion cannot annotate a same-ID event in a later page or publish
+old batch feedback. Calls remain bound to the original organisation without
+client retry/fallback. Cancel is immediate; recovery reads current inventory and
+only explicit Verify/Resume checks it again. Refusals are unknown access, not
+successful empty results. These consumer changes neither widen backend access
+nor change audit collection, signed records, redaction or retention. Registered
+`AuditLogReaderLifetime`/audit request/registry tests and actual-App desktop/narrow
+proof exercise the consuming route with synthetic events, not installed tenant,
+IdP recovery or measured customer exposure.
+
### Audit webhook configuration withdraws with its reader
The Settings Audit Webhooks consumer treats endpoint addresses and new URL
diff --git a/frontend-modern/src/components/Settings/AuditLogPanel.tsx b/frontend-modern/src/components/Settings/AuditLogPanel.tsx
index 8dceaa592d..c196b7eaab 100644
--- a/frontend-modern/src/components/Settings/AuditLogPanel.tsx
+++ b/frontend-modern/src/components/Settings/AuditLogPanel.tsx
@@ -32,11 +32,16 @@ import {
getAuditLogLoadingState,
getAuditVerificationBadgePresentation,
} from '@/utils/auditLogPresentation';
-import { useAuditLogPanelState } from '@/components/Settings/useAuditLogPanelState';
+import {
+ useAuditLogPanelState,
+ type AuditLogPanelProps,
+} from '@/components/Settings/useAuditLogPanelState';
+import { InlineNotice } from '@/components/shared/InlineNotice';
-export default function AuditLogPanel() {
+export default function AuditLogPanel(props: AuditLogPanelProps) {
const { isMobile } = useBreakpoint();
const {
+ accessAllowed,
activeFilterCount,
auditLoggingEnabled,
autoVerifyEnabled,
@@ -90,7 +95,7 @@ export default function AuditLogPanel() {
verifying,
verifyingAll,
userFilter,
- } = useAuditLogPanelState();
+ } = useAuditLogPanelState(props);
const formatTimestamp = (ts: string) => {
const date = new Date(ts);
@@ -157,7 +162,7 @@ export default function AuditLogPanel() {
<div class="flex w-full flex-wrap items-center gap-2 sm:w-auto">
<button
onClick={refresh}
- disabled={loading() || !auditLoggingEnabled()}
+ disabled={loading() || !accessAllowed()}
class={AUDIT_REFRESH_BUTTON_CLASS}
>
<RefreshCw class={`w-4 h-4 ${loading() ? 'animate-spin' : ''}`} />
@@ -320,6 +325,12 @@ export default function AuditLogPanel() {
</div>
</Show>
+ <Show when={!loading() && auditLoggingEnabled() && !accessAllowed()}>
+ <InlineNotice tone="warning" role="status">
+ Audit log is unavailable for this session.
+ </InlineNotice>
+ </Show>
+
<Show when={error()}>
<div
role="alert"
diff --git a/frontend-modern/src/components/Settings/__tests__/AuditLogReaderLifetime.test.tsx b/frontend-modern/src/components/Settings/__tests__/AuditLogReaderLifetime.test.tsx
new file mode 100644
index 0000000000..38cba6714c
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/AuditLogReaderLifetime.test.tsx
@@ -0,0 +1,451 @@
+import { createSignal } from 'solid-js';
+import { renderHook, waitFor } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { apiFetch, setOrgID } from '@/utils/apiClient';
+import { eventBus } from '@/stores/events';
+import { showSuccess, showWarning } from '@/utils/toast';
+import { useAuditLogPanelState, type AuditEvent } from '../useAuditLogPanelState';
+
+const [licensed, setLicensed] = createSignal(true);
+
+vi.mock('@solidjs/router', () => ({
+ useLocation: () => ({ pathname: '/settings/security-audit', search: '' }),
+ useNavigate: () => vi.fn(),
+}));
+vi.mock('@/stores/license', () => ({
+ getRuntimeCapabilityBlock: () => undefined,
+ hasFeature: () => licensed(),
+ runtimeCapabilitiesLoaded: () => true,
+ loadRuntimeCapabilities: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/stores/licenseCommercial', () => ({ getUpgradeActionDestination: () => '/upgrade' }));
+vi.mock('@/stores/sessionPresentationPolicy', () => ({
+ presentationPolicyHidesUpgradePrompts: () => false,
+}));
+vi.mock('@/utils/toast', () => ({
+ showSuccess: vi.fn(),
+ showWarning: vi.fn(),
+ showToast: vi.fn(),
+}));
+vi.mock('@/utils/apiClient', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/utils/apiClient')>()),
+ apiFetch: vi.fn(),
+}));
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+};
+const event = (id: string): AuditEvent => ({
+ id,
+ timestamp: '2026-11-02T07:00:00Z',
+ event: 'login',
+ user: 'fixture-reader',
+ ip: '192.0.2.1',
+ path: '/api/login',
+ success: true,
+ details: id,
+ signature: 'fixture-signature',
+});
+const json = (value: unknown, status = 200) =>
+ new Response(JSON.stringify(value), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+const list = (ids: string[]) =>
+ json({ events: ids.map(event), total: ids.length, persistentLogging: true });
+const verified = () => json({ available: true, verified: true, message: 'matched' });
+const settle = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+};
+const mount = () => {
+ const [reader, setReader] = createSignal({
+ currentUser: 'reader-a',
+ accessKey: 'token-a',
+ canRead: true,
+ });
+ const hook = renderHook(() =>
+ useAuditLogPanelState({
+ get currentUser() {
+ return reader().currentUser;
+ },
+ get accessKey() {
+ return reader().accessKey;
+ },
+ get canRead() {
+ return reader().canRead;
+ },
+ }),
+ );
+ return { ...hook, reader, setReader };
+};
+
+describe('Audit log reader lifetime', () => {
+ afterEach(() => vi.useRealTimers());
+ beforeEach(() => {
+ setLicensed(true);
+ window.localStorage.clear();
+ window.localStorage.setItem('pulse-audit-auto-verify', 'false');
+ setOrgID('org-a');
+ vi.mocked(apiFetch).mockReset();
+ vi.mocked(showSuccess).mockClear();
+ vi.mocked(showWarning).mockClear();
+ });
+
+ it('withdraws accepted rows and verification immediately on an organisation switch', async () => {
+ const next = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['private-a']))
+ .mockImplementationOnce(() => next.promise);
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ setOrgID('org-b');
+ eventBus.emit('org_switched', 'org-b');
+ expect(result.events()).toEqual([]);
+ expect(result.isPersistent()).toBe(false);
+ expect(result.loading()).toBe(true);
+ next.resolve(list(['private-b']));
+ await waitFor(() => expect(result.events()[0]?.id).toBe('private-b'));
+ expect(apiFetch).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ expectedOrgID: 'org-b', retry: false }),
+ );
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('does not let an old signature completion enter a refreshed page with the same ID', async () => {
+ const oldVerify = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['same-id']))
+ .mockImplementationOnce(() => oldVerify.promise)
+ .mockResolvedValueOnce(list(['same-id']));
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ const verification = result.verifyEvent(result.events()[0]);
+ result.refresh();
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(3));
+ oldVerify.resolve(verified());
+ await verification;
+ expect(result.verification()).toEqual({});
+ expect(result.verifying()).toEqual({});
+ } finally {
+ cleanup();
+ }
+ });
+ it.each(['principal', 'credential', 'read access', 'entitlement'] as const)(
+ 'withdraws reader data on %s loss, then accepts only a fresh read',
+ async (change) => {
+ const old = deferred<Response>();
+ const current = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockImplementationOnce(() => old.promise)
+ .mockImplementationOnce(() => current.promise);
+ const { result, reader, setReader, cleanup } = mount();
+ try {
+ const firstSignal = vi.mocked(apiFetch).mock.calls[0][1]?.signal;
+ if (change === 'principal') setReader({ ...reader(), currentUser: 'reader-b' });
+ if (change === 'credential') setReader({ ...reader(), accessKey: 'token-b' });
+ if (change === 'read access') setReader({ ...reader(), canRead: false });
+ if (change === 'entitlement') setLicensed(false);
+ expect(firstSignal?.aborted).toBe(true);
+ expect(result.events()).toEqual([]);
+ expect(result.verification()).toEqual({});
+ if (change === 'read access' || change === 'entitlement') {
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ result.refresh();
+ result.verifyAll();
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ if (change === 'read access') setReader({ ...reader(), canRead: true });
+ else setLicensed(true);
+ }
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2));
+ old.resolve(list(['withdrawn']));
+ await settle();
+ expect(result.loading()).toBe(true);
+ expect(result.events()).toEqual([]);
+ current.resolve(list(['admitted']));
+ await waitFor(() => expect(result.events()[0]?.id).toBe('admitted'));
+ } finally {
+ cleanup();
+ }
+ },
+ );
+
+ it('ignores equal-reader status refreshes without replacing the pending request', async () => {
+ const read = deferred<Response>();
+ vi.mocked(apiFetch).mockImplementation(() => read.promise);
+ const { result, reader, setReader, cleanup } = mount();
+ try {
+ setReader({ ...reader() });
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(apiFetch).mock.calls[0][1]?.signal?.aborted).toBe(false);
+ read.resolve(list(['kept']));
+ await waitFor(() => expect(result.events()[0]?.id).toBe('kept'));
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('never readmits a response after leaving and returning to the same reader', async () => {
+ const first = deferred<Response>();
+ const second = deferred<Response>();
+ const third = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise)
+ .mockImplementationOnce(() => third.promise);
+ const { result, reader, setReader, cleanup } = mount();
+ try {
+ setReader({ ...reader(), currentUser: 'reader-b' });
+ setReader({ ...reader(), currentUser: 'reader-a' });
+ first.resolve(list(['first-a']));
+ second.resolve(list(['b']));
+ await settle();
+ expect(result.events()).toEqual([]);
+ expect(result.loading()).toBe(true);
+ third.resolve(list(['current-a']));
+ await waitFor(() => expect(result.events()[0]?.id).toBe('current-a'));
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('rejects an obsolete response body even after the HTTP response was admitted', async () => {
+ const body = deferred<unknown>();
+ const oldResponse = new Response();
+ vi.spyOn(oldResponse, 'json').mockImplementation(() => body.promise);
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(oldResponse)
+ .mockResolvedValueOnce(list(['new-reader']));
+ const { result, reader, setReader, cleanup } = mount();
+ try {
+ await waitFor(() => expect(oldResponse.json).toHaveBeenCalled());
+ setReader({ ...reader(), currentUser: 'reader-b' });
+ await waitFor(() => expect(result.events()[0]?.id).toBe('new-reader'));
+ body.resolve({ events: [event('old-private')], total: 1, persistentLogging: true });
+ await settle();
+ expect(result.events()[0]?.id).toBe('new-reader');
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('clears rows while a refresh is pending, not only after its refusal', async () => {
+ const refresh = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['old']))
+ .mockImplementationOnce(() => refresh.promise);
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ result.refresh();
+ expect(result.events()).toEqual([]);
+ expect(result.totalEvents()).toBe(0);
+ expect(result.isPersistent()).toBe(false);
+ refresh.resolve(json({ error: 'private body must not become a toast' }, 403));
+ await waitFor(() => expect(result.error()).toContain('access could not be confirmed'));
+ expect(result.error()).not.toContain('private body');
+ expect(showWarning).not.toHaveBeenCalled();
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('stops a withdrawn batch and cannot finish a new batch with reused IDs', async () => {
+ const old = deferred<Response>();
+ const current = deferred<Response>();
+ let generation = 0;
+ vi.mocked(apiFetch).mockImplementation(async (url) => {
+ if (String(url).includes('/verify')) return generation === 0 ? old.promise : current.promise;
+ return list(['same-id', 'second']);
+ });
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(2));
+ result.verifyAll();
+ expect(result.verifyingAll()).toBe(true);
+ const oldSignal = vi.mocked(apiFetch).mock.calls.at(-1)?.[1]?.signal;
+ generation = 1;
+ setOrgID('org-b');
+ eventBus.emit('org_switched', 'org-b');
+ expect(oldSignal?.aborted).toBe(true);
+ await waitFor(() => expect(result.events()).toHaveLength(2));
+ result.verifyAll();
+ old.resolve(verified());
+ await settle();
+ expect(result.verifyingAll()).toBe(true);
+ expect(result.verifyAllDone()).toBe(0);
+ expect(result.verification()).toEqual({});
+ expect(showSuccess).not.toHaveBeenCalled();
+ current.resolve(verified());
+ await waitFor(() => expect(result.verifyingAll()).toBe(false));
+ expect(result.verifyAllDone()).toBe(2);
+ expect(
+ vi.mocked(apiFetch).mock.calls.filter(([url]) => String(url).includes('/verify')),
+ ).toHaveLength(3);
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('cancels verification immediately even if the transport ignores abort, with explicit Resume', async () => {
+ const old = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['a', 'b']))
+ .mockImplementationOnce(() => old.promise)
+ .mockImplementation(async () => verified());
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(2));
+ result.verifyAll();
+ result.cancelVerification();
+ expect(result.verifyingAll()).toBe(false);
+ expect(result.verifyCanceled()).toBe(true);
+ expect(result.hasResumeEvents()).toBe(true);
+ old.resolve(verified());
+ await settle();
+ expect(result.verification()).toEqual({});
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ result.resumeVerification();
+ await waitFor(() => expect(result.verification().b?.status).toBe('verified'));
+ expect(result.verifyAllDone()).toBe(2);
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('does not verify obsolete row objects, duplicates or a row from another organisation', async () => {
+ const pending = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['a/b']))
+ .mockImplementationOnce(() => pending.promise)
+ .mockResolvedValueOnce(list(['new']));
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ const row = result.events()[0];
+ await result.verifyEvent({ ...row });
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ const work = result.verifyEvent(row);
+ await result.verifyEvent(row);
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ expect(apiFetch).toHaveBeenLastCalledWith(
+ '/api/audit/a%2Fb/verify',
+ expect.objectContaining({ expectedOrgID: 'org-a', retry: false }),
+ );
+ setOrgID('org-b'); // Intentionally no event: action must notice storage drift.
+ await result.verifyEvent(row);
+ expect(
+ vi.mocked(apiFetch).mock.calls.filter(([url]) => String(url).includes('/verify')),
+ ).toHaveLength(1);
+ pending.resolve(verified());
+ await work;
+ await waitFor(() => expect(result.events()[0]?.id).toBe('new'));
+ expect(result.verification()).toEqual({});
+ } finally {
+ cleanup();
+ }
+ });
+
+ it.each([401, 402, 403])(
+ 'withdraws the whole page on a fresh verification refusal (%s)',
+ async (status) => {
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['a', 'b']))
+ .mockResolvedValueOnce(json({ error: 'private-refusal' }, status))
+ .mockResolvedValueOnce(list(['recovered']));
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(2));
+ result.verifyAll();
+ await waitFor(() => expect(result.error()).toContain('access could not be confirmed'));
+ expect(result.events()).toEqual([]);
+ expect(result.verification()).toEqual({});
+ expect(result.verifyingAll()).toBe(false);
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ expect(showWarning).not.toHaveBeenCalled();
+ result.refresh();
+ await waitFor(() => expect(result.events()[0]?.id).toBe('recovered'));
+ } finally {
+ cleanup();
+ }
+ },
+ );
+
+ it.each([
+ { events: null, total: 0, persistentLogging: true },
+ { events: [event('a'), event('a')], total: 2, persistentLogging: true },
+ { events: [event('a')], total: -1, persistentLogging: true },
+ { events: [event('a')], total: 1.5, persistentLogging: true },
+ { events: [null], total: 1, persistentLogging: true },
+ { events: [{ ...event('a'), success: 'true' }], total: 1, persistentLogging: true },
+ ])('keeps malformed inventory unavailable until an explicit read succeeds: %#', async (body) => {
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(json(body))
+ .mockResolvedValueOnce(list(['recovered']));
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.error()).toBe('Audit log returned an invalid response'));
+ expect(result.isPersistent()).toBe(false);
+ expect(result.events()).toEqual([]);
+ result.verifyAll();
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ result.refresh();
+ await waitFor(() => expect(result.events()[0]?.id).toBe('recovered'));
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('accepts omitted optional strings from the actual audit Event JSON contract', async () => {
+ vi.mocked(apiFetch).mockResolvedValue(
+ json({
+ events: [
+ {
+ id: 'startup',
+ timestamp: '2026-11-02T07:00:00Z',
+ event: 'startup',
+ ip: '',
+ success: true,
+ },
+ ],
+ total: 1,
+ persistentLogging: true,
+ }),
+ );
+ const { result, cleanup } = mount();
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ expect(result.error()).toBeNull();
+ } finally {
+ cleanup();
+ }
+ });
+
+ it('aborts pending verification at disposal and suppresses its ignored-abort result', async () => {
+ const pending = deferred<Response>();
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(list(['a']))
+ .mockImplementationOnce(() => pending.promise);
+ const { result, cleanup } = mount();
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ result.verifyAll();
+ const signal = vi.mocked(apiFetch).mock.calls.at(-1)?.[1]?.signal;
+ cleanup();
+ expect(signal?.aborted).toBe(true);
+ pending.resolve(verified());
+ await settle();
+ expect(result.events()).toEqual([]);
+ expect(result.verification()).toEqual({});
+ 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 23e5d901a8..82ce0f8fed 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
@@ -283,4 +283,37 @@ describe('buildSettingsPanelRegistryContext', () => {
canManage: false,
});
});
+ it('binds Audit Log to live principal, explicit capability and normalised credential scopes', () => {
+ const [status, setStatus] = createSignal<SecurityStatus | null>(null);
+ const context = buildSettingsPanelRegistryContext({
+ ...buildParams(null),
+ securityStatus: status,
+ });
+ expect(context.getAuditLogPanelProps()).toEqual({
+ currentUser: undefined,
+ accessKey: '[null,null]',
+ canRead: false,
+ });
+ setStatus({
+ currentUsername: 'audit-reader',
+ apiTokenHint: 'fixture-hint',
+ tokenScopes: ['settings:read', 'monitoring:read'],
+ settingsCapabilities: { auditLog: true },
+ } as SecurityStatus);
+ expect(context.getAuditLogPanelProps()).toMatchObject({
+ currentUser: 'audit-reader',
+ canRead: true,
+ });
+ const key = context.getAuditLogPanelProps()?.accessKey;
+ setStatus({ ...status(), tokenScopes: ['monitoring:read', 'settings:read'] } as SecurityStatus);
+ expect(context.getAuditLogPanelProps()?.accessKey).toBe(key);
+ setStatus({ ...status(), tokenScopes: ['monitoring:read'] } as SecurityStatus);
+ expect(context.getAuditLogPanelProps()?.accessKey).not.toBe(key);
+ setStatus({
+ ...status(),
+ currentUsername: '',
+ settingsCapabilities: { auditLog: false },
+ } as SecurityStatus);
+ expect(context.getAuditLogPanelProps()).toMatchObject({ currentUser: '', canRead: false });
+ });
});
diff --git a/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsx b/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsx
index e1d59cec8c..aa20069656 100644
--- a/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsx
@@ -373,10 +373,10 @@ describe('useAuditLogPanelState branch coverage', () => {
if (isVerifyCall(url)) {
return verifyResponse({ available: true, verified: true, message: 'matched' });
}
- return auditListResponse([]);
+ return auditListResponse([signedEvent('a')]);
});
const { result, cleanup } = await renderIdle();
- const event = signedEvent('a');
+ const event = result.events()[0];
await result.verifyEvent(event);
expect(result.verification()[event.id]).toEqual({ status: 'verified', message: 'matched' });
expect(result.verifying()[event.id]).toBe(false);
@@ -386,10 +386,10 @@ describe('useAuditLogPanelState branch coverage', () => {
it('records an "unavailable" status when verification is not available for the event', async () => {
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (isVerifyCall(url)) return verifyResponse({ available: false, message: 'no key' });
- return auditListResponse([]);
+ return auditListResponse([signedEvent('a')]);
});
const { result, cleanup } = await renderIdle();
- const event = signedEvent('a');
+ const event = result.events()[0];
await result.verifyEvent(event);
expect(result.verification()[event.id]).toEqual({
status: 'unavailable',
@@ -403,10 +403,10 @@ describe('useAuditLogPanelState branch coverage', () => {
if (isVerifyCall(url)) {
return verifyResponse({ available: true, verified: false, message: 'mismatch' });
}
- return auditListResponse([]);
+ return auditListResponse([signedEvent('a')]);
});
const { result, cleanup } = await renderIdle();
- const event = signedEvent('a');
+ const event = result.events()[0];
await result.verifyEvent(event);
expect(result.verification()[event.id]).toEqual({ status: 'failed', message: 'mismatch' });
cleanup();
@@ -417,10 +417,10 @@ describe('useAuditLogPanelState branch coverage', () => {
if (isVerifyCall(url)) {
return verifyResponse({ available: true }, 500, 'Internal Server Error');
}
- return auditListResponse([]);
+ return auditListResponse([signedEvent('a')]);
});
const { result, cleanup } = await renderIdle();
- const event = signedEvent('a');
+ const event = result.events()[0];
await result.verifyEvent(event);
expect(result.verification()[event.id]?.status).toBe('error');
expect(result.verification()[event.id]?.message).toContain('Failed to verify signature');
@@ -515,7 +515,7 @@ describe('useAuditLogPanelState branch coverage', () => {
cleanup();
});
- it('falls back to the ellipsis label when a fetch resets the verify-all total mid-flight', async () => {
+ it('ends the obsolete batch when a refresh replaces its inventory', async () => {
const firstVerify = deferred<Response>();
let verifyCount = 0;
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
@@ -530,7 +530,7 @@ describe('useAuditLogPanelState branch coverage', () => {
result.verifyAll();
expect(result.verifyAllLabel()).toBe('Verifying 0 of 2');
result.refresh();
- expect(result.verifyAllLabel()).toBe('Verifying…');
+ expect(result.verifyAllLabel()).toBe('Verify All');
firstVerify.resolve(verifyResponse({ available: true, verified: true }));
await waitFor(() => expect(result.verifyingAll()).toBe(false));
cleanup();
diff --git a/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.test.tsx
index 3d6e5ee462..e50a837002 100644
--- a/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.test.tsx
@@ -177,4 +177,24 @@ describe('useAuditLogPanelState audit request lifecycle', () => {
expect(result.isPersistent()).toBe(false);
cleanup();
});
+ it('keeps a license refusal unavailable rather than announcing an empty audit log', async () => {
+ vi.mocked(apiFetch)
+ .mockResolvedValueOnce(auditResponse(['existing']))
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: 'feature not included in license' }), { status: 402 }),
+ );
+ const { result, cleanup } = renderHook(() => useAuditLogPanelState());
+ try {
+ await waitFor(() => expect(result.events()).toHaveLength(1));
+ result.refresh();
+ expect(result.events()).toEqual([]);
+ await waitFor(() => expect(result.loading()).toBe(false));
+ expect(result.isPersistent()).toBe(false);
+ expect(result.error()).toBe(
+ 'Audit log access could not be confirmed. Refresh after access is restored.',
+ );
+ } finally {
+ cleanup();
+ }
+ });
});
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
index ce83174af0..a94889d769 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
@@ -12,6 +12,7 @@ import type { SecurityAuthPanel as SecurityAuthPanelType } from './SecurityAuthP
import type { RelaySettingsPanel as RelaySettingsPanelType } from './RelaySettingsPanel';
import type { ReportingPanel as ReportingPanelType } from './ReportingPanel';
import type { AuditWebhookPanel as AuditWebhookPanelType } from './AuditWebhookPanel';
+import type AuditLogPanelType from './AuditLogPanel';
import type { RolesPanel as RolesPanelType } from './RolesPanel';
import type { UserAssignmentsPanel as UserAssignmentsPanelType } from './UserAssignmentsPanel';
import type { InfrastructureWorkspace as InfrastructureWorkspaceType } from './InfrastructureWorkspace';
@@ -48,6 +49,7 @@ export interface SettingsPanelRegistryContext {
getRelayPanelProps: () => Parameters<typeof RelaySettingsPanelType>[0];
getReportingPanelProps: () => Parameters<typeof ReportingPanelType>[0];
getAuditWebhookPanelProps: () => Parameters<typeof AuditWebhookPanelType>[0];
+ getAuditLogPanelProps: () => Parameters<typeof AuditLogPanelType>[0];
getRolesPanelProps: () => Parameters<typeof RolesPanelType>[0];
getUserAssignmentsPanelProps: () => Parameters<typeof UserAssignmentsPanelType>[0];
}
@@ -150,6 +152,7 @@ export const createSettingsPanelRegistry = (
},
'security-audit': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.AuditLogPanel,
+ getProps: context.getAuditLogPanelProps,
},
'security-webhooks': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.AuditWebhookPanel,
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index 67f9e6bd58..443308940c 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -133,6 +133,14 @@ export function buildSettingsPanelRegistryContext(
]),
canRead: settingsCapabilities()?.reportingRead === true,
}),
+ getAuditLogPanelProps: () => ({
+ currentUser: currentUser(),
+ accessKey: JSON.stringify([
+ params.securityStatus()?.apiTokenHint,
+ params.securityStatus()?.tokenScopes?.slice().sort(),
+ ]),
+ canRead: settingsCapabilities()?.auditLog === true,
+ }),
getAuditWebhookPanelProps: () => ({
currentUser: currentUser(),
canRead: settingsCapabilities()?.auditWebhooksRead === true,
diff --git a/frontend-modern/src/components/Settings/useAuditLogPanelState.ts b/frontend-modern/src/components/Settings/useAuditLogPanelState.ts
index 79319379c0..a4708498e7 100644
--- a/frontend-modern/src/components/Settings/useAuditLogPanelState.ts
+++ b/frontend-modern/src/components/Settings/useAuditLogPanelState.ts
@@ -1,4 +1,13 @@
-import { createEffect, createMemo, createSignal, onCleanup, onMount, untrack } from 'solid-js';
+import {
+ batch,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ onMount,
+ untrack,
+} from 'solid-js';
import type { Accessor } from 'solid-js';
import { useLocation, useNavigate } from '@solidjs/router';
import {
@@ -6,7 +15,8 @@ import {
createLocalStorageNumberSignal,
STORAGE_KEYS,
} from '@/utils/localStorage';
-import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';
+import { apiErrorFromResponse, apiFetch, getOrgID } from '@/utils/apiClient';
+import { eventBus } from '@/stores/events';
import { showSuccess, showToast, showWarning } from '@/utils/toast';
import { hasFeature, runtimeCapabilitiesLoaded } from '@/stores/license';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
@@ -19,11 +29,11 @@ export interface AuditEvent {
id: string;
timestamp: string;
event: string;
- user: string;
+ user?: string;
ip: string;
- path: string;
+ path?: string;
success: boolean;
- details: string;
+ details?: string;
signature?: string;
}
@@ -75,7 +85,13 @@ const parseVerificationFilter = (raw: string | null | undefined): string =>
const normalizeAuditPageSize = (value: number): number =>
ALLOWED_AUDIT_PAGE_SIZES.has(value) ? value : DEFAULT_AUDIT_PAGE_SIZE;
-export const useAuditLogPanelState = () => {
+export interface AuditLogPanelProps {
+ currentUser?: string;
+ accessKey?: string;
+ canRead?: boolean;
+}
+
+export const useAuditLogPanelState = (props: AuditLogPanelProps = {}) => {
const location = useLocation();
const navigate = useNavigate();
const [events, setEvents] = createSignal<AuditEvent[]>([]);
@@ -153,13 +169,17 @@ export const useAuditLogPanelState = () => {
);
const [pageInput, setPageInput] = createSignal('');
const [isMounted, setIsMounted] = createSignal(false);
- const [cancelVerifyAll, setCancelVerifyAll] = createSignal(false);
const [verifyCanceled, setVerifyCanceled] = createSignal(false);
const [verifyControllers, setVerifyControllers] = createSignal<Record<string, AbortController>>(
{},
);
let auditRequestController: AbortController | null = null;
let auditRequestGeneration = 0;
+ let verificationGeneration = 0;
+ let verificationBatch: object | null = null;
+ let autoVerifyHandle: ReturnType<typeof setTimeout> | undefined;
+ let userFilterDebounceHandle: number | null = null;
+ let disposed = false;
const auditLoggingEnabled = createMemo(
() => runtimeCapabilitiesLoaded() && hasFeature('audit_logging'),
@@ -181,17 +201,73 @@ export const useAuditLogPanelState = () => {
);
const upgradeActionLabel = () => (paidRuntimeRequired() ? 'Download Pulse Pro' : 'View plans');
+ const accessAllowed = () => auditLoggingEnabled() && props.canRead !== false;
+ const currentReader = () => ({
+ org: getOrgID() || 'default',
+ user: props.currentUser,
+ accessKey: props.accessKey,
+ allowed: accessAllowed(),
+ });
+ const [reader, setReader] = createSignal(currentReader());
+ let readerInitialized = false;
+ const readerIsCurrent = () => {
+ const current = currentReader();
+ const accepted = reader();
+ return (
+ !disposed &&
+ Object.keys(current).every(
+ (key) => current[key as keyof typeof current] === accepted[key as keyof typeof accepted],
+ )
+ );
+ };
+ // Storage can change before its event arrives. A stale action/completion is
+ // not permission to dispatch under the newly selected organisation.
+ const ensureCurrentReader = () => {
+ if (disposed) return false;
+ if (readerIsCurrent()) return true;
+ resetReader();
+ return false;
+ };
+ const requestOptions = (controller: AbortController) => ({
+ signal: controller.signal,
+ expectedOrgID: reader().org,
+ retry: false,
+ });
+ const stopVerification = (clearResults = false) => {
+ verificationGeneration += 1;
+ verificationBatch = null;
+ if (autoVerifyHandle !== undefined) clearTimeout(autoVerifyHandle);
+ autoVerifyHandle = undefined;
+ for (const controller of Object.values(verifyControllers())) controller.abort();
+ batch(() => {
+ setVerifyControllers({});
+ setVerifying({});
+ setVerifyingAll(false);
+ if (clearResults) {
+ setVerification({});
+ setVerifyAllTotal(0);
+ setVerifyAllDone(0);
+ setVerifyCanceled(false);
+ }
+ });
+ };
+ const clearInventory = () => {
+ stopVerification(true);
+ setEvents([]);
+ setTotalEvents(0);
+ setIsPersistent(false);
+ setError(null);
+ };
+
const fetchAuditEvents = async (options?: { limit?: number; offset?: number }) => {
+ if (!ensureCurrentReader()) return;
auditRequestController?.abort();
auditRequestController = null;
const requestGeneration = ++auditRequestGeneration;
-
- if (!auditLoggingEnabled()) {
- setEvents([]);
- setTotalEvents(0);
- setIsPersistent(false);
- setError(null);
- setLoading(false);
+ const acceptedReader = reader();
+ batch(clearInventory);
+ if (!accessAllowed()) {
+ setLoading(!runtimeCapabilitiesLoaded());
return;
}
@@ -200,12 +276,12 @@ export const useAuditLogPanelState = () => {
const controller = new AbortController();
auditRequestController = controller;
+ const isCurrentRead = () =>
+ ensureCurrentReader() &&
+ acceptedReader === reader() &&
+ requestGeneration === auditRequestGeneration &&
+ auditRequestController === controller;
setLoading(true);
- setError(null);
- setVerification({});
- setVerifying({});
- setVerifyAllTotal(0);
- setVerifyAllDone(0);
try {
const params = new URLSearchParams();
@@ -217,14 +293,11 @@ export const useAuditLogPanelState = () => {
if (successFilter() === 'failed') params.set('success', 'false');
const response = await apiFetch(`/api/audit?${params.toString()}`, {
- signal: controller.signal,
+ ...requestOptions(controller),
});
- if (requestGeneration !== auditRequestGeneration) return;
- if (response.status === 402) {
- setEvents([]);
- setTotalEvents(0);
- setIsPersistent(false);
- setError(null);
+ if (!isCurrentRead()) return;
+ if ([401, 402, 403].includes(response.status)) {
+ setError('Audit log access could not be confirmed. Refresh after access is restored.');
return;
}
if (!response.ok) {
@@ -235,11 +308,34 @@ export const useAuditLogPanelState = () => {
}
const data: AuditResponse = await response.json();
- if (requestGeneration !== auditRequestGeneration) return;
+ if (!isCurrentRead()) return;
+ const ids = new Set<string>();
if (
+ !data ||
!Array.isArray(data.events) ||
- typeof data.total !== 'number' ||
- typeof data.persistentLogging !== 'boolean'
+ !Number.isSafeInteger(data.total) ||
+ data.total < 0 ||
+ data.total < data.events.length ||
+ typeof data.persistentLogging !== 'boolean' ||
+ data.events.some((event) => {
+ if (
+ !event ||
+ typeof event.id !== 'string' ||
+ !event.id.trim() ||
+ ids.has(event.id) ||
+ typeof event.timestamp !== 'string' ||
+ typeof event.event !== 'string' ||
+ (event.user !== undefined && typeof event.user !== 'string') ||
+ typeof event.ip !== 'string' ||
+ (event.path !== undefined && typeof event.path !== 'string') ||
+ (event.details !== undefined && typeof event.details !== 'string') ||
+ typeof event.success !== 'boolean' ||
+ (event.signature !== undefined && typeof event.signature !== 'string')
+ )
+ return true;
+ ids.add(event.id);
+ return false;
+ })
) {
throw new Error('Audit log returned an invalid response');
}
@@ -260,33 +356,29 @@ export const useAuditLogPanelState = () => {
if (data.persistentLogging && autoVerifyEnabled()) {
const verificationLimit = autoVerifyLimit();
if (verificationLimit <= 0) return;
- setTimeout(() => {
- if (!isMounted() || requestGeneration !== auditRequestGeneration) return;
+ autoVerifyHandle = setTimeout(() => {
+ autoVerifyHandle = undefined;
+ if (
+ !isMounted() ||
+ !ensureCurrentReader() ||
+ acceptedReader !== reader() ||
+ requestGeneration !== auditRequestGeneration
+ )
+ return;
void verifyAllEvents({ limit: verificationLimit, showToast: false });
}, 0);
}
} catch (err) {
- if (
- requestGeneration !== auditRequestGeneration ||
- (err as { name?: string })?.name === 'AbortError'
- ) {
+ if (!isCurrentRead() || (err as { name?: string })?.name === 'AbortError') {
return;
}
const message = getAuditLogFetchErrorMessage(err);
- if (typeof message === 'string' && /feature not included in license/i.test(message)) {
- setEvents([]);
- setTotalEvents(0);
- setIsPersistent(false);
- setError(null);
- return;
- }
setEvents([]);
setTotalEvents(0);
setIsPersistent(false);
setError(message);
- showWarning('Audit Log Error', message);
} finally {
- if (requestGeneration === auditRequestGeneration) {
+ if (isCurrentRead()) {
auditRequestController = null;
setLoading(false);
}
@@ -294,65 +386,94 @@ export const useAuditLogPanelState = () => {
};
const verifyEvent = async (event: AuditEvent) => {
- if (!auditLoggingEnabled() || !event.signature) return;
-
- setVerifying((prev) => ({ ...prev, [event.id]: true }));
-
- try {
- const controller = new AbortController();
+ if (
+ !ensureCurrentReader() ||
+ !accessAllowed() ||
+ loading() ||
+ error() ||
+ !events().includes(event) ||
+ !event.signature ||
+ verifyControllers()[event.id]
+ )
+ return;
+ const acceptedReader = reader();
+ const generation = verificationGeneration;
+ const controller = new AbortController();
+ const isCurrentVerification = () =>
+ ensureCurrentReader() &&
+ acceptedReader === reader() &&
+ generation === verificationGeneration &&
+ verifyControllers()[event.id] === controller &&
+ events().includes(event);
+ batch(() => {
+ setVerifying((prev) => ({ ...prev, [event.id]: true }));
setVerifyControllers((prev) => ({ ...prev, [event.id]: controller }));
- if (!isMounted()) {
- controller.abort();
- }
-
- const response = await apiFetch(`/api/audit/${event.id}/verify`, {
- signal: controller.signal,
- });
- if (!response.ok) {
- throw new Error(`Failed to verify signature: ${response.statusText}`);
+ });
+ try {
+ const response = await apiFetch(
+ `/api/audit/${encodeURIComponent(event.id)}/verify`,
+ requestOptions(controller),
+ );
+ if (!isCurrentVerification()) return;
+ if ([401, 402, 403].includes(response.status)) {
+ batch(() => {
+ clearInventory();
+ setError('Audit log access could not be confirmed. Refresh after access is restored.');
+ });
+ return;
}
-
+ if (!response.ok) throw new Error('Failed to verify signature. Refresh or retry.');
const data: VerifyResponse = await response.json();
- let status: VerificationStatus = 'unavailable';
- if (!data.available) {
- status = 'unavailable';
- } else if (data.verified) {
- status = 'verified';
- } else {
- status = 'failed';
- }
-
- setVerification((prev) => ({
- ...prev,
- [event.id]: { status, message: data.message || '' },
- }));
+ if (!isCurrentVerification()) return;
+ if (
+ !data ||
+ typeof data.available !== 'boolean' ||
+ (data.available && typeof data.verified !== 'boolean') ||
+ (data.message !== undefined && typeof data.message !== 'string')
+ )
+ throw new Error('Failed to verify signature. Refresh or retry.');
+ const status: VerificationStatus = !data.available
+ ? 'unavailable'
+ : data.verified
+ ? 'verified'
+ : 'failed';
+ setVerification((prev) => ({ ...prev, [event.id]: { status, message: data.message || '' } }));
} catch (err) {
- if ((err as { name?: string })?.name === 'AbortError') {
- return;
- }
-
+ if (!isCurrentVerification() || (err as { name?: string })?.name === 'AbortError') return;
setVerification((prev) => ({
...prev,
[event.id]: {
status: 'error',
- message: err instanceof Error ? err.message : 'Unknown error',
+ message: 'Failed to verify signature. Refresh or retry.',
},
}));
} finally {
- setVerifying((prev) => ({ ...prev, [event.id]: false }));
- setVerifyControllers((prev) => {
- const next = { ...prev };
- delete next[event.id];
- return next;
- });
+ if (isCurrentVerification()) {
+ batch(() => {
+ setVerifying((prev) => ({ ...prev, [event.id]: false }));
+ setVerifyControllers((prev) => {
+ const next = { ...prev };
+ delete next[event.id];
+ return next;
+ });
+ });
+ }
}
};
const verifyAllEvents = async (options?: VerifyAllOptions) => {
- if (!auditLoggingEnabled()) return;
-
+ if (!ensureCurrentReader() || !accessAllowed() || loading() || error() || verificationBatch)
+ return;
+ const acceptedReader = reader();
+ const generation = verificationGeneration;
+ const batchIdentity = {};
+ const isCurrentBatch = () =>
+ ensureCurrentReader() &&
+ acceptedReader === reader() &&
+ generation === verificationGeneration &&
+ verificationBatch === batchIdentity;
const limit = options?.limit;
- let signedEvents = events().filter((event) => event.signature);
+ let signedEvents = events().filter((event) => event.signature && !verifying()[event.id]);
if (options?.resume) {
signedEvents = signedEvents.filter((event) => {
const state = verification()[event.id];
@@ -364,29 +485,20 @@ export const useAuditLogPanelState = () => {
}
if (signedEvents.length === 0) return;
+ verificationBatch = batchIdentity;
setVerifyingAll(true);
setVerifyCanceled(false);
- setCancelVerifyAll(false);
setVerifyAllTotal(signedEvents.length);
setVerifyAllDone(0);
for (const event of signedEvents) {
- if (cancelVerifyAll()) {
- setVerifyingAll(false);
- setVerifyCanceled(true);
- if (options?.showToast) {
- showToast('info', 'Signature verification canceled');
- }
- for (const controller of Object.values(verifyControllers())) {
- controller.abort();
- }
- return;
- }
-
+ if (!isCurrentBatch()) return;
await verifyEvent(event);
+ if (!isCurrentBatch()) return;
setVerifyAllDone((prev) => prev + 1);
}
+ verificationBatch = null;
setVerifyingAll(false);
setVerifyCanceled(false);
@@ -598,7 +710,12 @@ export const useAuditLogPanelState = () => {
};
const cancelVerification = () => {
- setCancelVerifyAll(true);
+ if (!verifyingAll()) return;
+ batch(() => {
+ stopVerification();
+ setVerifyCanceled(true);
+ });
+ showToast('info', 'Signature verification canceled');
};
const goToFirstPage = () => goToOffset(0);
@@ -642,26 +759,35 @@ export const useAuditLogPanelState = () => {
}
});
- createEffect(() => {
- if (!runtimeCapabilitiesLoaded()) {
- setLoading(true);
- return;
- }
- if (!hasFeature('audit_logging')) {
- auditRequestController?.abort();
- auditRequestController = null;
- auditRequestGeneration += 1;
- setEvents([]);
- setTotalEvents(0);
- setIsPersistent(false);
- setError(null);
- setLoading(false);
- return;
- }
- untrack(() => {
- void fetchAuditEvents();
+ const resetReader = () => {
+ auditRequestController?.abort();
+ auditRequestController = null;
+ auditRequestGeneration += 1;
+ if (userFilterDebounceHandle !== null) window.clearTimeout(userFilterDebounceHandle);
+ userFilterDebounceHandle = null;
+ batch(() => {
+ setReader(currentReader());
+ clearInventory();
+ if (readerInitialized) {
+ resetPaging();
+ updateSearchParam((params) => {
+ params.delete('user');
+ });
+ }
+ readerInitialized = true;
+ setLoading(!runtimeCapabilitiesLoaded() || accessAllowed());
});
- });
+ if (!disposed) void fetchAuditEvents();
+ };
+ createEffect(
+ on(
+ [runtimeCapabilitiesLoaded, accessAllowed, () => props.currentUser, () => props.accessKey],
+ (current, previous) => {
+ if (!previous || current.some((value, index) => value !== previous[index])) resetReader();
+ },
+ ),
+ );
+ const unsubscribeOrg = eventBus.on('org_switched', resetReader);
// Live-apply: server-side filters (event, success) trigger a fresh fetch from
// the first page immediately on change. userFilter debounces to avoid one
@@ -675,8 +801,8 @@ export const useAuditLogPanelState = () => {
void value;
return;
}
- if (!auditLoggingEnabled()) return;
- refetchFromFirstPage();
+ if (!accessAllowed()) return;
+ untrack(refetchFromFirstPage);
});
let initialSuccessFilterApplied = false;
@@ -687,11 +813,10 @@ export const useAuditLogPanelState = () => {
void value;
return;
}
- if (!auditLoggingEnabled()) return;
- refetchFromFirstPage();
+ if (!accessAllowed()) return;
+ untrack(refetchFromFirstPage);
});
- let userFilterDebounceHandle: number | null = null;
let initialUserFilterApplied = false;
createEffect(() => {
const value = userFilter();
@@ -700,7 +825,7 @@ export const useAuditLogPanelState = () => {
void value;
return;
}
- if (!auditLoggingEnabled()) return;
+ if (!accessAllowed()) return;
if (userFilterDebounceHandle !== null) {
window.clearTimeout(userFilterDebounceHandle);
}
@@ -711,21 +836,19 @@ export const useAuditLogPanelState = () => {
});
onCleanup(() => {
+ disposed = true;
+ unsubscribeOrg();
setIsMounted(false);
- setCancelVerifyAll(true);
auditRequestController?.abort();
auditRequestController = null;
auditRequestGeneration += 1;
- if (userFilterDebounceHandle !== null) {
- window.clearTimeout(userFilterDebounceHandle);
- userFilterDebounceHandle = null;
- }
- for (const controller of Object.values(verifyControllers())) {
- controller.abort();
- }
+ if (userFilterDebounceHandle !== null) window.clearTimeout(userFilterDebounceHandle);
+ userFilterDebounceHandle = null;
+ batch(clearInventory);
});
return {
+ accessAllowed,
activeFilterChips,
activeFilterCount,
auditLoggingEnabled,