Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(audit): WS-H3 audit export bundles (CSV + HTML/print-to-PDF)

Beenu Arora2338628563a5
diff --git a/apps/web/src/components/audit/AuditLogView.test.tsx b/apps/web/src/components/audit/AuditLogView.test.tsx
new file mode 100644
index 000000000..5a8135271
--- /dev/null
+++ b/apps/web/src/components/audit/AuditLogView.test.tsx
@@ -0,0 +1,233 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// WS-H3 — pin the export-button wiring on AuditLogView. The component exposes
+// two affordances ("Export CSV" / "Export PDF (HTML)") that must:
+// 1. forward the *currently filtered* view to auditApi.{exportCsv,exportHtml}
+// 2. trigger a real browser download / new-tab open
+// 3. disable themselves while a request is inflight or when 0 rows match
+//
+// We mock SWR (so we control the data the table sees), the auditApi exports,
+// react-hot-toast (so we don't need a portal root), and the URL/window
+// sinks (so the download anchor + window.open don't blow up jsdom).
+
+const swrCalls = vi.hoisted(() => new Map<string, unknown>());
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: (key: string) => {
+ const data = swrCalls.get(key);
+ return {
+ data,
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(async () => undefined),
+ };
+ },
+}));
+
+const exportCsvMock = vi.hoisted(() => vi.fn());
+const exportHtmlMock = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ // Real ApiError surface so the component's `instanceof ApiError` branches
+ // continue to match.
+ ApiError: class ApiError extends Error {
+ status: number;
+ body: string;
+ constructor(message: string, status = 0, body = '') {
+ super(message);
+ this.name = 'ApiError';
+ this.status = status;
+ this.body = body;
+ }
+ },
+ auditApi: {
+ exportCsv: exportCsvMock,
+ exportHtml: exportHtmlMock,
+ },
+}));
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock('react-hot-toast', () => ({
+ __esModule: true,
+ default: { success: toastSuccess, error: toastError },
+}));
+
+import { AuditLogView } from './AuditLogView';
+
+// A tiny helper to register the SWR fixture for the default page-1 query.
+function seedAuditPage(items: unknown[], total = items.length) {
+ // Component builds `/api/v1/audit?page=1&page_size=50` when no filters set.
+ swrCalls.set('/api/v1/audit?page=1&page_size=50', {
+ items,
+ total,
+ page: 1,
+ page_size: 50,
+ total_pages: total === 0 ? 1 : Math.ceil(total / 50),
+ });
+}
+
+const sampleEvent = {
+ id: 'evt-1',
+ tenant_id: 't1',
+ actor_id: 'u1',
+ actor_email: '[email protected]',
+ actor_ip: '10.0.1.12',
+ action: 'cases:create',
+ resource: 'case',
+ resource_id: 'c-0001',
+ changes: { title: 'Suspicious lateral movement' },
+ created_at: new Date('2026-05-01T12:00:00Z').toISOString(),
+};
+
+beforeEach(() => {
+ swrCalls.clear();
+ exportCsvMock.mockReset();
+ exportHtmlMock.mockReset();
+ toastSuccess.mockReset();
+ toastError.mockReset();
+
+ // jsdom doesn't implement these — the component depends on them for the
+ // CSV anchor click and the HTML new-tab open. Stub them as no-ops so we
+ // can assert the call sequence rather than fight the environment.
+ if (typeof URL.createObjectURL === 'undefined') {
+ Object.defineProperty(URL, 'createObjectURL', {
+ value: vi.fn(() => 'blob:mock-url'),
+ writable: true,
+ });
+ } else {
+ URL.createObjectURL = vi.fn(() => 'blob:mock-url') as unknown as typeof URL.createObjectURL;
+ }
+ if (typeof URL.revokeObjectURL === 'undefined') {
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ value: vi.fn(),
+ writable: true,
+ });
+ } else {
+ URL.revokeObjectURL = vi.fn() as unknown as typeof URL.revokeObjectURL;
+ }
+ // window.open returns a fake window so the success branch fires.
+ vi.spyOn(window, 'open').mockImplementation(() => ({}) as unknown as Window);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('AuditLogView export buttons', () => {
+ it('renders the CSV and HTML export buttons next to the title', () => {
+ seedAuditPage([sampleEvent]);
+
+ render(<AuditLogView />);
+
+ expect(screen.getByRole('heading', { level: 1, name: /audit log/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /export csv/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /export pdf \(html\)/i })).toBeInTheDocument();
+ });
+
+ it('calls auditApi.exportCsv with the empty filter set when nothing is filtered', async () => {
+ seedAuditPage([sampleEvent]);
+ exportCsvMock.mockResolvedValueOnce({
+ body: 'id,action\nevt-1,cases:create\n',
+ filename: 'aisoc-audit-20260501T120000Z.csv',
+ });
+
+ render(<AuditLogView />);
+
+ await userEvent.click(screen.getByRole('button', { name: /export csv/i }));
+
+ await waitFor(() => expect(exportCsvMock).toHaveBeenCalledTimes(1));
+ // No filters set: builder must hand the API an empty object — not e.g.
+ // an object with `search: ""` that the server might mis-interpret.
+ expect(exportCsvMock).toHaveBeenCalledWith({});
+ await waitFor(() =>
+ expect(toastSuccess).toHaveBeenCalledWith(
+ expect.stringContaining('aisoc-audit-20260501T120000Z.csv'),
+ ),
+ );
+ });
+
+ it('forwards search + action + resource filters into the export payload', async () => {
+ seedAuditPage([sampleEvent]);
+ // Pre-seed the SWR key the component will use *after* the filters land,
+ // so the filtered render still has data and the buttons stay enabled.
+ // (When SWR misses, the component falls back to MOCK_AUDIT anyway, so
+ // the buttons remain enabled — but we still seed the final key so any
+ // SWR-driven re-render is deterministic.)
+ swrCalls.set(
+ '/api/v1/audit?page=1&page_size=50&search=admin&action=cases%3A&resource=case',
+ { items: [sampleEvent], total: 1, page: 1, page_size: 50, total_pages: 1 },
+ );
+ exportCsvMock.mockResolvedValueOnce({
+ body: 'id,action\nevt-1,cases:create\n',
+ filename: 'aisoc-audit-filtered.csv',
+ });
+
+ render(<AuditLogView />);
+
+ // Drive the three filter knobs the way an analyst would. The action and
+ // resource filters are <select>s; the search is a free-text <input>.
+ // Form order is: search input, action select, resource select.
+ await userEvent.type(screen.getByPlaceholderText(/search email or action/i), 'admin');
+ const selects = screen.getAllByRole('combobox');
+ await userEvent.selectOptions(selects[0], 'cases:');
+ await userEvent.selectOptions(selects[1], 'case');
+
+ await userEvent.click(screen.getByRole('button', { name: /export csv/i }));
+
+ await waitFor(() => expect(exportCsvMock).toHaveBeenCalledTimes(1));
+ expect(exportCsvMock).toHaveBeenCalledWith({
+ search: 'admin',
+ action: 'cases:',
+ resource: 'case',
+ });
+ });
+
+ it('opens the print-ready HTML in a new tab on Export PDF (HTML)', async () => {
+ seedAuditPage([sampleEvent]);
+ exportHtmlMock.mockResolvedValueOnce({
+ html: '<!doctype html><html><body><h1>Audit Log Export</h1></body></html>',
+ filename: 'aisoc-audit-20260501T120000Z.html',
+ });
+
+ render(<AuditLogView />);
+
+ await userEvent.click(screen.getByRole('button', { name: /export pdf \(html\)/i }));
+
+ await waitFor(() => expect(exportHtmlMock).toHaveBeenCalledTimes(1));
+ expect(window.open).toHaveBeenCalledWith('blob:mock-url', '_blank', 'noopener,noreferrer');
+ await waitFor(() =>
+ expect(toastSuccess).toHaveBeenCalledWith(
+ expect.stringMatching(/save as pdf/i),
+ ),
+ );
+ });
+
+ it('surfaces a toast when the export endpoint returns 403', async () => {
+ seedAuditPage([sampleEvent]);
+ const { ApiError } = await import('@/lib/api');
+ exportCsvMock.mockRejectedValueOnce(
+ new ApiError('forbidden', 403, '{"detail": "missing audit_log:read"}'),
+ );
+
+ render(<AuditLogView />);
+
+ await userEvent.click(screen.getByRole('button', { name: /export csv/i }));
+
+ await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
+ expect(toastError).toHaveBeenCalledWith(expect.stringMatching(/audit_log:read/i));
+ });
+
+ it('disables the export buttons when there are zero rows in the current view', () => {
+ seedAuditPage([], 0);
+
+ render(<AuditLogView />);
+
+ const csv = screen.getByRole('button', { name: /export csv/i });
+ const html = screen.getByRole('button', { name: /export pdf \(html\)/i });
+ expect(csv).toBeDisabled();
+ expect(html).toBeDisabled();
+ });
+});
diff --git a/apps/web/src/components/audit/AuditLogView.tsx b/apps/web/src/components/audit/AuditLogView.tsx
index 4e661f252..3d56d6da3 100644
--- a/apps/web/src/components/audit/AuditLogView.tsx
+++ b/apps/web/src/components/audit/AuditLogView.tsx
@@ -2,8 +2,10 @@
import { useState, useCallback } from 'react';
import useSWR from 'swr';
+import toast from 'react-hot-toast';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
import { ErrorState } from '@/components/ui/ErrorState';
+import { auditApi, ApiError, type AuditExportFilters } from '@/lib/api';
interface AuditEvent {
id: string;
@@ -72,6 +74,10 @@ export function AuditLogView() {
const [actionFilter, setActionFilter] = useState('');
const [resourceFilter, setResourceFilter] = useState('');
const [expandedId, setExpandedId] = useState<string | null>(null);
+ // WS-H3 — export-bundle UX state. We model the two formats as a single
+ // exclusive lock so the analyst can't double-fire CSV + HTML and end up
+ // with two browser save dialogs racing each other.
+ const [exporting, setExporting] = useState<'csv' | 'html' | null>(null);
const params = new URLSearchParams({ page: String(page), page_size: '50' });
if (search) params.set('search', search);
@@ -91,20 +97,162 @@ export function AuditLogView() {
setPage(1);
}, []);
+ // Build the filter payload once so CSV and HTML stay in lock-step with the
+ // table. We deliberately send only the filter knobs the export endpoint
+ // understands — page/page_size are list-view concerns, not export ones.
+ const buildExportFilters = useCallback((): AuditExportFilters => {
+ const filters: AuditExportFilters = {};
+ if (search) filters.search = search;
+ if (actionFilter) filters.action = actionFilter;
+ if (resourceFilter) filters.resource = resourceFilter;
+ return filters;
+ }, [search, actionFilter, resourceFilter]);
+
+ /**
+ * Trigger a CSV download of the (filtered) audit trail. We go through fetch
+ * (rather than a plain anchor href) so we can attach the bearer token,
+ * surface a toast on auth failure, and disable the button while the
+ * server is streaming.
+ */
+ const handleExportCsv = useCallback(async () => {
+ if (exporting) return;
+ setExporting('csv');
+ try {
+ const { body, filename } = await auditApi.exportCsv(buildExportFilters());
+ const blob = new Blob([body], { type: 'text/csv;charset=utf-8' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ toast.success(`Exported ${filename}`);
+ } catch (e) {
+ const msg = e instanceof ApiError
+ ? `Couldn't export audit log (HTTP ${e.status}). ${e.status === 403 ? 'Your role lacks audit_log:read.' : 'Try again.'}`
+ : "Couldn't export audit log. Try again.";
+ toast.error(msg);
+ } finally {
+ setExporting(null);
+ }
+ }, [buildExportFilters, exporting]);
+
+ /**
+ * Open the print-ready HTML bundle in a new tab. The browser's native
+ * "Save as PDF" produces the compliance binder — same pattern as the
+ * weekly digest report (WS-G2). No server-side weasyprint required.
+ */
+ const handleExportHtml = useCallback(async () => {
+ if (exporting) return;
+ setExporting('html');
+ try {
+ const { html } = await auditApi.exportHtml(buildExportFilters());
+ // Pop into a new tab via Blob URL — survives strict-CSP environments
+ // better than document.write, and gives the user a real file:// style
+ // experience for the print dialog.
+ const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
+ const url = URL.createObjectURL(blob);
+ const win = window.open(url, '_blank', 'noopener,noreferrer');
+ if (!win) {
+ toast.error('Pop-up blocked — allow pop-ups to view the export.');
+ } else {
+ // Give the new tab time to load before we revoke; revoking
+ // immediately can null out the contents on slower browsers.
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
+ toast.success('Opened audit-log export. Use your browser to save as PDF.');
+ }
+ } catch (e) {
+ const msg = e instanceof ApiError
+ ? `Couldn't open audit export (HTTP ${e.status}). ${e.status === 403 ? 'Your role lacks audit_log:read.' : 'Try again.'}`
+ : "Couldn't open audit export. Try again.";
+ toast.error(msg);
+ } finally {
+ setExporting(null);
+ }
+ }, [buildExportFilters, exporting]);
+
+ const exportDisabled = exporting !== null || (data?.items.length ?? 0) === 0;
+
return (
<div className="space-y-4">
- <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between gap-4 flex-wrap">
<div>
<h1 className="text-2xl font-bold">Audit Log</h1>
<p className="text-sm text-gray-400 mt-1">
Immutable record of all platform actions
</p>
</div>
- {data && (
- <span className="text-sm text-gray-500">
- {data.total.toLocaleString()} total events
- </span>
- )}
+ <div className="flex items-center gap-3">
+ {data && (
+ <span className="text-sm text-gray-500">
+ {data.total.toLocaleString()} total events
+ </span>
+ )}
+ {/* WS-H3 — compliance bundle exports. Both buttons honour the
+ current filter set so an analyst can scope a binder to e.g.
+ "all role grants in the last week" without server-side gymnastics. */}
+ <div
+ className="flex items-center gap-2"
+ role="group"
+ aria-label="Export audit log"
+ >
+ <button
+ type="button"
+ onClick={handleExportCsv}
+ disabled={exportDisabled}
+ title={
+ exportDisabled && (data?.items.length ?? 0) === 0
+ ? 'Nothing to export with the current filters'
+ : 'Download the filtered audit trail as RFC 4180 CSV'
+ }
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md border border-gray-600 bg-gray-800 text-gray-200 hover:bg-gray-700 hover:border-gray-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ className="w-4 h-4"
+ aria-hidden="true"
+ >
+ <path
+ fillRule="evenodd"
+ d="M10 3a.75.75 0 01.75.75v8.69l2.72-2.72a.75.75 0 111.06 1.06l-4 4a.75.75 0 01-1.06 0l-4-4a.75.75 0 011.06-1.06l2.72 2.72V3.75A.75.75 0 0110 3zM3.75 14a.75.75 0 01.75.75V16h11v-1.25a.75.75 0 011.5 0V16a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 013 16v-1.25a.75.75 0 01.75-.75z"
+ clipRule="evenodd"
+ />
+ </svg>
+ {exporting === 'csv' ? 'Exporting…' : 'Export CSV'}
+ </button>
+ <button
+ type="button"
+ onClick={handleExportHtml}
+ disabled={exportDisabled}
+ title={
+ exportDisabled && (data?.items.length ?? 0) === 0
+ ? 'Nothing to export with the current filters'
+ : 'Open a print-ready HTML bundle (use browser to Save as PDF)'
+ }
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md border border-indigo-500/40 bg-indigo-500/10 text-indigo-200 hover:bg-indigo-500/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ className="w-4 h-4"
+ aria-hidden="true"
+ >
+ <path d="M5 4a2 2 0 00-2 2v1h14V6a2 2 0 00-2-2H5z" />
+ <path
+ fillRule="evenodd"
+ d="M3 9h14v5a2 2 0 01-2 2H5a2 2 0 01-2-2V9zm4 2a1 1 0 100 2h6a1 1 0 100-2H7z"
+ clipRule="evenodd"
+ />
+ </svg>
+ {exporting === 'html' ? 'Opening…' : 'Export PDF (HTML)'}
+ </button>
+ </div>
+ </div>
</div>
{/* Filters */}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 341cec645..276c6f95d 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -3424,6 +3424,135 @@ export const reportsApi = {
},
};
+// ─── Audit log / compliance bundle helpers ──────────────────────────────────
+
+/**
+ * Filters accepted by the audit-log export endpoint. Mirrors the query
+ * parameters supported by ``GET /api/v1/audit/export`` so the UI layer can
+ * forward whatever the analyst is currently filtering on without translation.
+ */
+export type AuditExportFilters = {
+ action?: string;
+ resource?: string;
+ actor_id?: string;
+ search?: string;
+ /** Hard cap to keep a single export bounded — defaults to API max (10 000). */
+ limit?: number;
+};
+
+function buildAuditExportSearch(
+ filters: AuditExportFilters,
+ format: 'csv' | 'html',
+): URLSearchParams {
+ const search = new URLSearchParams({ format });
+ if (filters.action) search.set('action', filters.action);
+ if (filters.resource) search.set('resource', filters.resource);
+ if (filters.actor_id) search.set('actor_id', filters.actor_id);
+ if (filters.search) search.set('search', filters.search);
+ if (typeof filters.limit === 'number' && filters.limit > 0) {
+ search.set('limit', String(filters.limit));
+ }
+ return search;
+}
+
+function buildAuditExportHeaders(accept: string): Record<string, string> {
+ const headers: Record<string, string> = {
+ Accept: accept,
+ 'X-Tenant-Id': TENANT_ID,
+ };
+ if (typeof window !== 'undefined') {
+ try {
+ const token = window.localStorage.getItem(AUTH_TOKEN_KEY);
+ if (token) headers.Authorization = `Bearer ${token}`;
+ } catch {
+ /* localStorage unavailable; ignore */
+ }
+ }
+ return headers;
+}
+
+export const auditApi = {
+ /**
+ * WS-H3 — download the (filtered) audit trail as RFC 4180 CSV. Returns the
+ * raw CSV body so the UI can wrap it in a Blob and trigger a download via
+ * an anchor click. Going through ``fetch`` (instead of a plain anchor) lets
+ * us forward the bearer token from localStorage and surface an
+ * ``ApiError`` if the export is rejected (e.g. missing audit_log:read).
+ */
+ exportCsv: async (filters: AuditExportFilters = {}): Promise<{ body: string; filename: string }> => {
+ const url = `${API_BASE}/api/v1/audit/export?${buildAuditExportSearch(filters, 'csv').toString()}`;
+ const response = await fetch(url, {
+ headers: buildAuditExportHeaders('text/csv'),
+ cache: 'no-store',
+ });
+ if (!response.ok) {
+ const detail = await response.text().catch(() => '');
+ throw new ApiError(
+ `API ${response.status} ${response.statusText} — /audit/export?format=csv`,
+ response.status,
+ detail,
+ );
+ }
+ const filename = parseFilenameFromContentDisposition(
+ response.headers.get('Content-Disposition'),
+ `aisoc-audit-${timestampSlug()}.csv`,
+ );
+ const body = await response.text();
+ return { body, filename };
+ },
+
+ /**
+ * WS-H3 — fetch the print-ready HTML bundle of the (filtered) audit trail.
+ * Mirrors ``reportsApi.weeklyDigestHtml``: pop the result into a new tab and
+ * let the browser's native "Save as PDF" produce the compliance binder, no
+ * server-side weasyprint dependency required.
+ */
+ exportHtml: async (filters: AuditExportFilters = {}): Promise<{ html: string; filename: string }> => {
+ const url = `${API_BASE}/api/v1/audit/export?${buildAuditExportSearch(filters, 'html').toString()}`;
+ const response = await fetch(url, {
+ headers: buildAuditExportHeaders('text/html'),
+ cache: 'no-store',
+ });
+ if (!response.ok) {
+ const detail = await response.text().catch(() => '');
+ throw new ApiError(
+ `API ${response.status} ${response.statusText} — /audit/export?format=html`,
+ response.status,
+ detail,
+ );
+ }
+ const filename = parseFilenameFromContentDisposition(
+ response.headers.get('Content-Disposition'),
+ `aisoc-audit-${timestampSlug()}.html`,
+ );
+ const html = await response.text();
+ return { html, filename };
+ },
+};
+
+/** Parse ``filename="…"`` out of a Content-Disposition header. */
+function parseFilenameFromContentDisposition(
+ header: string | null,
+ fallback: string,
+): string {
+ if (!header) return fallback;
+ // Match RFC 6266 filename="…" — quoted form is what FastAPI emits for us.
+ const match = header.match(/filename="([^"]+)"/i);
+ return match ? match[1] : fallback;
+}
+
+/** ``20260509T234501Z`` style slug for client-side filenames. */
+function timestampSlug(): string {
+ const now = new Date();
+ const pad = (n: number) => n.toString().padStart(2, '0');
+ return (
+ `${now.getUTCFullYear()}` +
+ `${pad(now.getUTCMonth() + 1)}` +
+ `${pad(now.getUTCDate())}` +
+ `T${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}Z`
+ );
+}
+
// ─── Realtime / WebSocket helpers ────────────────────────────────────────────
export const realtimeApi = {
diff --git a/services/api/app/api/v1/endpoints/audit.py b/services/api/app/api/v1/endpoints/audit.py
index 1954638fb..3fdd0a664 100644
--- a/services/api/app/api/v1/endpoints/audit.py
+++ b/services/api/app/api/v1/endpoints/audit.py
@@ -1,21 +1,35 @@
"""Audit log API endpoints.
-GET /api/v1/audit — paginated, filterable audit trail
+GET /api/v1/audit — paginated, filterable audit trail
+GET /api/v1/audit/export — full export of the (filtered) trail as CSV or HTML
"""
import uuid
+from datetime import UTC, datetime
from typing import Annotated
from fastapi import APIRouter, Depends, Query
+from fastapi.responses import HTMLResponse, PlainTextResponse
from pydantic import BaseModel
from sqlalchemy import func, select
from app.api.v1.deps import AuthUser, require_permission
from app.db.rls import TenantDBSession
from app.models.audit import AuditLog
+from app.services.audit_export import (
+ AuditRow,
+ ExportContext,
+ render_audit_csv,
+ render_audit_html,
+)
router = APIRouter(prefix="/audit", tags=["audit"])
+# Hard cap on a single export request — keeps memory + browser-side
+# rendering predictable and forces operators to narrow filters for very
+# long-running tenants. The real audit trail is never truncated server-side.
+_EXPORT_MAX_ROWS = 10_000
+
class AuditEventOut(BaseModel):
id: uuid.UUID
@@ -40,6 +54,33 @@ class AuditListResponse(BaseModel):
total_pages: int
+def _filtered_audit_query(
+ *,
+ tenant_id: uuid.UUID,
+ action: str | None,
+ resource: str | None,
+ actor_id: uuid.UUID | None,
+ search: str | None,
+):
+ """Build the base SQLAlchemy query for audit reads.
+
+ Pulled out so the list and export endpoints share identical filtering
+ semantics — the exported CSV/HTML is always exactly what the analyst
+ sees in the UI.
+ """
+ q = select(AuditLog).where(AuditLog.tenant_id == tenant_id)
+ if action:
+ q = q.where(AuditLog.action.like(f"{action}%"))
+ if resource:
+ q = q.where(AuditLog.resource == resource)
+ if actor_id:
+ q = q.where(AuditLog.actor_id == actor_id)
+ if search:
+ term = f"%{search}%"
+ q = q.where(AuditLog.action.ilike(term) | AuditLog.actor_email.ilike(term))
+ return q
+
+
@router.get("", response_model=AuditListResponse)
async def list_audit_events(
current_user: Annotated[AuthUser, Depends(require_permission("audit_log:read"))],
@@ -52,17 +93,13 @@ async def list_audit_events(
search: str | None = Query(default=None, description="Search actor_email or action"),
) -> AuditListResponse:
"""Return a paginated, tenant-scoped audit trail."""
- q = select(AuditLog).where(AuditLog.tenant_id == current_user.tenant_id)
-
- if action:
- q = q.where(AuditLog.action.like(f"{action}%"))
- if resource:
- q = q.where(AuditLog.resource == resource)
- if actor_id:
- q = q.where(AuditLog.actor_id == actor_id)
- if search:
- term = f"%{search}%"
- q = q.where(AuditLog.action.ilike(term) | AuditLog.actor_email.ilike(term))
+ q = _filtered_audit_query(
+ tenant_id=current_user.tenant_id,
+ action=action,
+ resource=resource,
+ actor_id=actor_id,
+ search=search,
+ )
count_q = select(func.count()).select_from(q.subquery())
total_result = await db.execute(count_q)
@@ -93,3 +130,97 @@ async def list_audit_events(
page_size=page_size,
total_pages=max(1, -(-total // page_size)),
)
+
+
+ "/export",
+ summary="Export the (filtered) audit trail as CSV or print-ready HTML",
+ response_model=None,
+)
+async def export_audit_events(
+ current_user: Annotated[AuthUser, Depends(require_permission("audit_log:read"))],
+ db: TenantDBSession,
+ fmt: str = Query(default="csv", alias="format", pattern="^(csv|html)$"),
+ action: str | None = Query(default=None, description="Filter by action prefix, e.g. 'cases:'"),
+ resource: str | None = Query(default=None),
+ actor_id: uuid.UUID | None = Query(default=None),
+ search: str | None = Query(default=None, description="Search actor_email or action"),
+ limit: int = Query(default=_EXPORT_MAX_ROWS, ge=1, le=_EXPORT_MAX_ROWS),
+) -> PlainTextResponse | HTMLResponse:
+ """Return the filtered audit trail as a downloadable artefact.
+
+ * ``format=csv`` (default) — RFC 4180 CSV, suitable for SIEM ingest
+ and compliance binders.
+ * ``format=html`` — self-contained HTML the browser can save to PDF.
+
+ The same filters as ``GET /audit`` apply, so the exported bundle
+ matches what the analyst is looking at in the UI. A hard ``limit``
+ of 10 000 rows keeps a single export bounded — narrow the filters
+ for very long-running tenants.
+ """
+ q = _filtered_audit_query(
+ tenant_id=current_user.tenant_id,
+ action=action,
+ resource=resource,
+ actor_id=actor_id,
+ search=search,
+ )
+ q = q.order_by(AuditLog.created_at.desc()).limit(limit)
+
+ result = await db.execute(q)
+ events = result.scalars().all()
+
+ rows = [
+ AuditRow(
+ id=str(e.id),
+ tenant_id=str(e.tenant_id),
+ actor_id=str(e.actor_id) if e.actor_id else None,
+ actor_email=e.actor_email,
+ actor_ip=str(e.actor_ip) if e.actor_ip else None,
+ action=e.action,
+ resource=e.resource,
+ resource_id=e.resource_id,
+ changes=e.changes,
+ created_at=e.created_at,
+ )
+ for e in events
+ ]
+
+ generated_at = datetime.now(UTC)
+ timestamp_slug = generated_at.strftime("%Y%m%dT%H%M%SZ")
+
+ if fmt == "csv":
+ body = render_audit_csv(rows)
+ return PlainTextResponse(
+ content=body,
+ media_type="text/csv; charset=utf-8",
+ headers={
+ "Content-Disposition": (
+ f'attachment; filename="aisoc-audit-{timestamp_slug}.csv"'
+ ),
+ "X-Total-Rows": str(len(rows)),
+ },
+ )
+
+ context = ExportContext(
+ tenant_id=str(current_user.tenant_id),
+ generated_at=generated_at,
+ generated_by_email=current_user.email,
+ filters={
+ "action": action,
+ "resource": resource,
+ "actor_id": str(actor_id) if actor_id else None,
+ "search": search,
+ },
+ total_rows=len(rows),
+ )
+ html_body = render_audit_html(rows, context)
+ return HTMLResponse(
+ content=html_body,
+ headers={
+ "Content-Disposition": (
+ f'inline; filename="aisoc-audit-{timestamp_slug}.html"'
+ ),
+ "X-Total-Rows": str(len(rows)),
+ },
+ )
diff --git a/services/api/app/services/audit_export.py b/services/api/app/services/audit_export.py
new file mode 100644
index 000000000..a93226282
--- /dev/null
+++ b/services/api/app/services/audit_export.py
@@ -0,0 +1,305 @@
+"""Audit export — deterministic CSV + print-ready HTML bundles.
+
+WS-H3 — buyer-value plan
+========================
+Produces compliance-ready exports of the audit trail in two formats:
+
+* ``csv`` — tabular for SIEM ingest, evidence binders, and spreadsheet review.
+* ``html`` — self-contained, print-friendly document the browser can save
+ to PDF without any server-side PDF dependency.
+
+Design goals
+------------
+* Pure functions: the renderers below take an in-memory list of
+ ``AuditRow`` and a ``ExportContext`` and return a ``str``. No DB, no I/O.
+ This is what makes the exports reproducible and easy to unit-test.
+* CSV is RFC 4180 compliant (CRLF line endings, ``QUOTE_ALL`` so JSON
+ payloads in ``changes`` survive embedded commas/quotes/newlines).
+* HTML mirrors the design tokens of the executive digest renderer
+ (WS-G2) and case summary renderer (WS-D2) so operators get a
+ consistent visual identity across all artefacts.
+* Defensive HTML escaping — every field touches tenant data.
+"""
+
+from __future__ import annotations
+
+import csv
+import html
+import io
+import json
+from dataclasses import dataclass
+from datetime import UTC, datetime
+
+
+@dataclass(frozen=True)
+class AuditRow:
+ """One row of the export. Mirrors the public ``AuditEventOut`` shape.
+
+ ``changes`` is an arbitrary JSON-serialisable dict (or None); the
+ renderers below stringify it defensively rather than trusting input.
+ """
+
+ id: str
+ tenant_id: str
+ actor_id: str | None
+ actor_email: str | None
+ actor_ip: str | None
+ action: str
+ resource: str | None
+ resource_id: str | None
+ changes: dict | None
+ created_at: datetime
+
+
+@dataclass(frozen=True)
+class ExportContext:
+ """Metadata for the export header — what filters were applied, by whom."""
+
+ tenant_id: str
+ generated_at: datetime
+ generated_by_email: str | None
+ filters: dict[str, str | None]
+ total_rows: int
+
+
+# ---------------------------------------------------------------------------
+# CSV
+# ---------------------------------------------------------------------------
+
+
+_CSV_HEADERS = (
+ "id",
+ "tenant_id",
+ "created_at",
+ "actor_id",
+ "actor_email",
+ "actor_ip",
+ "action",
+ "resource",
+ "resource_id",
+ "changes",
+)
+
+
+def render_audit_csv(rows: list[AuditRow]) -> str:
+ """Serialise ``rows`` to a deterministic CSV document.
+
+ * Header row first — column order is part of the contract; downstream
+ SIEM connectors and compliance scripts pin to it.
+ * ``QUOTE_ALL`` so embedded commas, quotes, and newlines in JSON
+ payloads (``changes``) cannot break field boundaries.
+ * CRLF line endings (RFC 4180) so the file imports cleanly on Windows.
+ * ``changes`` is JSON-encoded with ``sort_keys=True`` so identical
+ payloads render identically across runs.
+ """
+ buf = io.StringIO(newline="")
+ # csv writer must not insert its own newlines on top of ours — we use
+ # the platform-agnostic default ("\r\n") which is RFC 4180 compliant.
+ writer = csv.writer(buf, quoting=csv.QUOTE_ALL, lineterminator="\r\n")
+ writer.writerow(_CSV_HEADERS)
+ for row in rows:
+ changes_blob = (
+ ""
+ if row.changes is None
+ else json.dumps(row.changes, sort_keys=True, separators=(",", ":"))
+ )
+ writer.writerow(
+ (
+ row.id,
+ row.tenant_id,
+ row.created_at.astimezone(UTC).isoformat().replace("+00:00", "Z"),
+ row.actor_id or "",
+ row.actor_email or "",
+ row.actor_ip or "",
+ row.action,
+ row.resource or "",
+ row.resource_id or "",
+ changes_blob,
+ )
+ )
+ return buf.getvalue()
+
+
+# ---------------------------------------------------------------------------
+# HTML
+# ---------------------------------------------------------------------------
+
+
+def _esc(value: object) -> str:
+ """HTML-safe rendering for arbitrary values."""
+ return html.escape("" if value is None else str(value))
+
+
+def _fmt_dt(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
+
+
+def _filter_chip(label: str, value: str | None) -> str:
+ if value is None or value == "":
+ return ""
+ return (
+ '<span style="display:inline-block;margin:0 6px 6px 0;padding:3px 8px;'
+ 'border:1px solid #cbd5e1;border-radius:9999px;background:#f1f5f9;'
+ 'font-size:11px;color:#1e293b;">'
+ f"{_esc(label)}: <strong>{_esc(value)}</strong></span>"
+ )
+
+
+def _action_chip(action: str) -> str:
+ # Colour-code by action prefix so a printed page is scannable even
+ # when the table runs to dozens of rows.
+ family = action.split(":", 1)[0] if ":" in action else action
+ palette = {
+ "auth": "#1d4ed8",
+ "cases": "#7c3aed",
+ "alerts": "#c2410c",
+ "detection": "#0f766e",
+ "playbooks": "#9333ea",
+ "connectors": "#0891b2",
+ "settings": "#475569",
+ "users": "#475569",
+ "audit": "#334155",
+ }
+ colour = palette.get(family, "#475569")
+ return (
+ f'<span style="display:inline-block;padding:2px 6px;border-radius:4px;'
+ f"background:{colour};color:#fff;font-size:10px;font-family:ui-monospace,"
+ f'SFMono-Regular,Menlo,Consolas,monospace;">{_esc(action)}</span>'
+ )
+
+
+def _changes_cell(changes: dict | None) -> str:
+ if changes is None:
+ return '<span style="color:#94a3b8;">—</span>'
+ try:
+ pretty = json.dumps(changes, sort_keys=True, indent=2)
+ except (TypeError, ValueError):
+ # If the changes payload is not JSON-serialisable for any reason,
+ # fall back to repr so the report still renders without crashing.
+ pretty = repr(changes)
+ return (
+ '<pre style="margin:0;padding:6px 8px;background:#f8fafc;'
+ "border:1px solid #e2e8f0;border-radius:4px;font-size:11px;"
+ 'font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;'
+ 'white-space:pre-wrap;word-break:break-word;max-width:480px;">'
+ f"{_esc(pretty)}</pre>"
+ )
+
+
+def _row_html(row: AuditRow) -> str:
+ actor = row.actor_email or row.actor_id or "—"
+ ip = row.actor_ip or "—"
+ resource = (
+ f"{_esc(row.resource)}<br/><span style=\"color:#64748b;font-size:11px;\">"
+ f"{_esc(row.resource_id)}</span>"
+ if row.resource and row.resource_id
+ else _esc(row.resource or row.resource_id or "—")
+ )
+ return (
+ '<tr style="border-bottom:1px solid #e2e8f0;vertical-align:top;">'
+ f'<td style="padding:8px 12px;font-size:11px;color:#475569;white-space:nowrap;">'
+ f"{_esc(_fmt_dt(row.created_at))}</td>"
+ f'<td style="padding:8px 12px;">{_action_chip(row.action)}</td>'
+ f'<td style="padding:8px 12px;font-size:12px;color:#1e293b;">{_esc(actor)}<br/>'
+ f'<span style="color:#64748b;font-size:11px;">{_esc(ip)}</span></td>'
+ f'<td style="padding:8px 12px;font-size:12px;color:#1e293b;">{resource}</td>'
+ f'<td style="padding:8px 12px;">{_changes_cell(row.changes)}</td>'
+ "</tr>"
+ )
+
+
+def render_audit_html(rows: list[AuditRow], context: ExportContext) -> str:
+ """Render an audit export as a self-contained HTML document.
+
+ The output is intentionally a single string with inline CSS so that
+ the file remains portable when downloaded — no external stylesheets,
+ no JavaScript, browser print-to-PDF works out of the box.
+ """
+ filters_html = "".join(
+ _filter_chip(label, value) for label, value in context.filters.items()
+ ) or '<span style="color:#94a3b8;font-size:12px;">No filters applied — full audit trail.</span>'
+
+ rows_html = (
+ "".join(_row_html(row) for row in rows)
+ if rows
+ else (
+ '<tr><td colspan="5" style="padding:24px;text-align:center;'
+ 'color:#64748b;font-size:13px;">No audit events match the selected filters.</td></tr>'
+ )
+ )
+
+ generated_by = context.generated_by_email or "system"
+ return f"""<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<title>AiSOC — Audit Export</title>
+<meta name="viewport" content="width=device-width,initial-scale=1" />
+<style>
+ /* Print-friendly page setup; no external resources. */
+ @page {{ size: A4 landscape; margin: 12mm; }}
+ body {{
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ color: #0f172a;
+ background: #ffffff;
+ margin: 0;
+ padding: 24px;
+ }}
+ h1 {{ font-size: 22px; margin: 0 0 4px 0; }}
+ h2 {{ font-size: 14px; margin: 16px 0 8px 0; color: #334155; }}
+ table {{ width: 100%; border-collapse: collapse; }}
+ th {{
+ text-align: left;
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: #475569;
+ padding: 8px 12px;
+ border-bottom: 2px solid #cbd5e1;
+ background: #f8fafc;
+ }}
+ .meta {{ color: #64748b; font-size: 12px; }}
+ .kpis {{ display: flex; gap: 16px; margin: 12px 0 8px 0; }}
+ .kpi {{
+ border: 1px solid #e2e8f0;
+ border-radius: 8px;
+ padding: 8px 12px;
+ background: #f8fafc;
+ min-width: 120px;
+ }}
+ .kpi .label {{ font-size: 11px; color: #64748b; text-transform: uppercase; letter-spacing: 0.04em; }}
+ .kpi .value {{ font-size: 16px; font-weight: 600; color: #0f172a; }}
+</style>
+</head>
+<body>
+ <header>
+ <h1>Audit Trail Export</h1>
+ <div class="meta">
+ Tenant <code>{_esc(context.tenant_id)}</code> &middot;
+ generated {_esc(_fmt_dt(context.generated_at))} by {_esc(generated_by)}
+ </div>
+ <div class="kpis">
+ <div class="kpi"><div class="label">Rows</div><div class="value">{context.total_rows}</div></div>
+ <div class="kpi"><div class="label">Format</div><div class="value">HTML / print</div></div>
+ </div>
+ <h2>Filters applied</h2>
+ <div>{filters_html}</div>
+ </header>
+ <table>
+ <thead>
+ <tr>
+ <th style="width:160px;">Timestamp</th>
+ <th style="width:160px;">Action</th>
+ <th style="width:200px;">Actor</th>
+ <th style="width:200px;">Resource</th>
+ <th>Changes</th>
+ </tr>
+ </thead>
+ <tbody>{rows_html}</tbody>
+ </table>
+ <footer style="margin-top:24px;color:#94a3b8;font-size:11px;">
+ AiSOC audit export &middot; immutable, append-only event store &middot;
+ column order is stable for SIEM ingestion compatibility.
+ </footer>
+</body>
+</html>"""
diff --git a/services/api/tests/test_audit_export.py b/services/api/tests/test_audit_export.py
new file mode 100644
index 000000000..81ddef303
--- /dev/null
+++ b/services/api/tests/test_audit_export.py
@@ -0,0 +1,303 @@
+"""Tests for WS-H3 — audit export builders (CSV + HTML).
+
+The builders in ``app.services.audit_export`` are pure functions: they take
+an in-memory list of ``AuditRow`` plus an ``ExportContext`` and return a
+``str``. That makes them easy to lock down against the wire-format expected
+by SIEM ingest connectors and compliance binders.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+from datetime import UTC, datetime
+
+import pytest
+from app.services.audit_export import (
+ AuditRow,
+ ExportContext,
+ render_audit_csv,
+ render_audit_html,
+)
+
+GENERATED_AT = datetime(2026, 5, 9, 16, 30, 0, tzinfo=UTC)
+
+
+def _row(**overrides) -> AuditRow:
+ """Builder with sensible defaults for an audit row."""
+ base = {
+ "id": "11111111-1111-1111-1111-111111111111",
+ "tenant_id": "22222222-2222-2222-2222-222222222222",
+ "actor_id": "33333333-3333-3333-3333-333333333333",
+ "actor_email": "[email protected]",
+ "actor_ip": "10.0.0.1",
+ "action": "cases:update",
+ "resource": "case",
+ "resource_id": "case-42",
+ "changes": {"status": ["open", "investigating"]},
+ "created_at": datetime(2026, 5, 9, 12, 0, 0, tzinfo=UTC),
+ }
+ base.update(overrides)
+ return AuditRow(**base)
+
+
+def _context(rows: list[AuditRow], **overrides) -> ExportContext:
+ base = {
+ "tenant_id": "22222222-2222-2222-2222-222222222222",
+ "generated_at": GENERATED_AT,
+ "generated_by_email": "[email protected]",
+ "filters": {
+ "action": "cases:",
+ "resource": None,
+ "actor_id": None,
+ "search": None,
+ },
+ "total_rows": len(rows),
+ }
+ base.update(overrides)
+ return ExportContext(**base)
+
+
+# ---------------------------------------------------------------------------
+# CSV
+# ---------------------------------------------------------------------------
+
+
+class TestCsvRenderer:
+ def test_header_row_order_is_stable(self):
+ """The column contract is part of the SIEM ingest interface — pin it."""
+ out = render_audit_csv([])
+ reader = csv.reader(io.StringIO(out))
+ header = next(reader)
+ assert header == [
+ "id",
+ "tenant_id",
+ "created_at",
+ "actor_id",
+ "actor_email",
+ "actor_ip",
+ "action",
+ "resource",
+ "resource_id",
+ "changes",
+ ]
+
+ def test_empty_rows_renders_only_header(self):
+ out = render_audit_csv([])
+ assert out.endswith("\r\n")
+ assert out.count("\r\n") == 1
+
+ def test_single_row_round_trips(self):
+ row = _row()
+ out = render_audit_csv([row])
+ reader = csv.reader(io.StringIO(out))
+ next(reader) # skip header
+ parsed = next(reader)
+ assert parsed[0] == row.id
+ assert parsed[1] == row.tenant_id
+ assert parsed[2] == "2026-05-09T12:00:00Z"
+ assert parsed[3] == row.actor_id
+ assert parsed[4] == row.actor_email
+ assert parsed[5] == row.actor_ip
+ assert parsed[6] == row.action
+ assert parsed[7] == row.resource
+ assert parsed[8] == row.resource_id
+ # changes should be JSON, not Python repr
+ assert json.loads(parsed[9]) == {"status": ["open", "investigating"]}
+
+ def test_changes_is_sorted_for_determinism(self):
+ """Same payload should serialise identically across runs."""
+ row_a = _row(changes={"b": 1, "a": 2})
+ row_b = _row(changes={"a": 2, "b": 1})
+ assert render_audit_csv([row_a]) == render_audit_csv([row_b])
+
+ def test_null_changes_serialises_as_empty_string(self):
+ out = render_audit_csv([_row(changes=None)])
+ reader = csv.reader(io.StringIO(out))
+ next(reader)
+ assert next(reader)[9] == ""
+
+ def test_null_optional_fields_become_empty_strings(self):
+ row = _row(actor_id=None, actor_email=None, actor_ip=None, resource=None, resource_id=None)
+ out = render_audit_csv([row])
+ reader = csv.reader(io.StringIO(out))
+ next(reader)
+ parsed = next(reader)
+ assert parsed[3] == "" # actor_id
+ assert parsed[4] == "" # actor_email
+ assert parsed[5] == "" # actor_ip
+ assert parsed[7] == "" # resource
+ assert parsed[8] == "" # resource_id
+
+ def test_quote_all_protects_embedded_separators(self):
+ """Commas, quotes, and newlines in JSON must not break field boundaries."""
+ nasty = {
+ "note": 'has "quotes", commas, and \nnewlines',
+ "list": [1, 2, 3],
+ }
+ row = _row(changes=nasty)
+ out = render_audit_csv([row])
+ # Re-parse with a strict reader; if QUOTE_ALL is missing this raises.
+ reader = csv.reader(io.StringIO(out))
+ next(reader) # header
+ parsed = next(reader)
+ # round-trip the JSON cell back to a dict — proves the embedded
+ # quotes/commas/newlines survived the CSV escaping pass.
+ assert json.loads(parsed[9]) == nasty
+
+ def test_uses_crlf_line_endings(self):
+ """RFC 4180 mandates CRLF — Windows analysts open these files daily."""
+ out = render_audit_csv([_row()])
+ # exactly two CRLFs: header + single data row
+ assert out.count("\r\n") == 2
+ # and no bare LFs that aren't part of the CRLF pair
+ assert out.replace("\r\n", "").count("\n") == 0
+
+ def test_preserves_row_order(self):
+ rows = [
+ _row(id="11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa", action="alerts:create"),
+ _row(id="22222222-bbbb-bbbb-bbbb-bbbbbbbbbbbb", action="cases:update"),
+ _row(id="33333333-cccc-cccc-cccc-cccccccccccc", action="auth:login"),
+ ]
+ out = render_audit_csv(rows)
+ reader = csv.reader(io.StringIO(out))
+ next(reader)
+ ids = [next(reader)[0] for _ in rows]
+ assert ids == [r.id for r in rows]
+
+
+# ---------------------------------------------------------------------------
+# HTML
+# ---------------------------------------------------------------------------
+
+
+class TestHtmlRenderer:
+ def test_renders_a_full_html_document(self):
+ out = render_audit_html([], _context([]))
+ assert out.startswith("<!DOCTYPE html>")
+ assert out.rstrip().endswith("</html>")
+ assert "<title>AiSOC — Audit Export</title>" in out
+
+ def test_header_includes_tenant_and_generator_metadata(self):
+ ctx = _context([])
+ out = render_audit_html([], ctx)
+ assert ctx.tenant_id in out
+ assert "[email protected]" in out
+ assert "2026-05-09 16:30:00 UTC" in out
+
+ def test_falls_back_to_system_when_no_actor_email(self):
+ out = render_audit_html([], _context([], generated_by_email=None))
+ assert "by system" in out
+
+ def test_empty_rows_shows_friendly_empty_message(self):
+ out = render_audit_html([], _context([]))
+ assert "No audit events match the selected filters." in out
+
+ def test_filters_render_as_chips_when_present(self):
+ out = render_audit_html([], _context([]))
+ # default _context has action="cases:" set
+ assert "action" in out
+ assert "cases:" in out
+
+ def test_no_filters_shows_full_audit_trail_message(self):
+ ctx = _context(
+ [],
+ filters={"action": None, "resource": None, "actor_id": None, "search": None},
+ )
+ out = render_audit_html([], ctx)
+ assert "No filters applied" in out
+
+ def test_kpi_total_rows_matches_context(self):
+ rows = [_row(), _row(id="aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")]
+ ctx = _context(rows)
+ out = render_audit_html(rows, ctx)
+ # KPI block prints the total — make sure the integer surfaces.
+ assert ">2<" in out
+
+ def test_row_renders_action_chip_and_actor_block(self):
+ row = _row()
+ out = render_audit_html([row], _context([row]))
+ assert "cases:update" in out
+ assert "[email protected]" in out
+ assert "10.0.0.1" in out
+ assert "case" in out
+ assert "case-42" in out
+
+ def test_changes_payload_is_pretty_printed_json(self):
+ row = _row(changes={"foo": "bar", "n": 1})
+ out = render_audit_html([row], _context([row]))
+ # The renderer HTML-escapes the JSON before injecting it, so quotes
+ # show up as &quot; — that's correct, the table cell still renders
+ # readable JSON to the eye but is XSS-safe.
+ assert "&quot;foo&quot;: &quot;bar&quot;" in out
+ assert "&quot;n&quot;: 1" in out
+ # Pretty-printed with newlines preserved inside the <pre> block.
+ assert "{\n &quot;foo&quot;" in out
+
+ def test_html_escapes_dangerous_field_values(self):
+ """Audit rows hold tenant data — defensive escaping or it's an XSS hole."""
+ evil = "<script>alert(1)</script>"
+ row = _row(actor_email=evil, action=evil, resource=evil, resource_id=evil)
+ out = render_audit_html([row], _context([row]))
+ assert "<script>alert(1)</script>" not in out
+ assert "&lt;script&gt;alert(1)&lt;/script&gt;" in out
+
+ def test_html_escapes_changes_payload(self):
+ row = _row(changes={"payload": "<img src=x onerror=alert(1)>"})
+ out = render_audit_html([row], _context([row]))
+ assert "<img src=x onerror=alert(1)>" not in out
+ assert "&lt;img src=x onerror=alert(1)&gt;" in out
+
+ def test_action_chip_colour_is_deterministic_per_family(self):
+ """Same action prefix must always render the same colour."""
+ row_a = _row(action="auth:login")
+ row_b = _row(action="auth:logout")
+ out_a = render_audit_html([row_a], _context([row_a]))
+ out_b = render_audit_html([row_b], _context([row_b]))
+ # extract the auth chip colour from both renders and compare
+ marker = "background:#1d4ed8" # auth family
+ assert marker in out_a
+ assert marker in out_b
+
+ def test_handles_non_serialisable_changes_without_crashing(self):
+ """Defensive: if a payload sneaks through with a non-JSON value,
+ we still want a renderable page rather than a 500."""
+
+ class NotJsonable:
+ pass
+
+ # the dataclass is typed as ``dict | None`` but at runtime we may
+ # have to cope with anything Postgres put in JSONB.
+ row = _row(changes={"obj": NotJsonable()})
+ out = render_audit_html([row], _context([row]))
+ assert out.startswith("<!DOCTYPE html>")
+ assert "NotJsonable" in out # repr fallback fired
+
+
+# ---------------------------------------------------------------------------
+# Stability
+# ---------------------------------------------------------------------------
+
+
+def test_csv_output_is_deterministic():
+ """Same input -> same bytes. Important for diffing exports during audits."""
+ rows = [_row(), _row(id="44444444-4444-4444-4444-444444444444", action="alerts:ack")]
+ assert render_audit_csv(rows) == render_audit_csv(rows)
+
+
+def test_html_output_is_deterministic():
+ rows = [_row()]
+ ctx = _context(rows)
+ assert render_audit_html(rows, ctx) == render_audit_html(rows, ctx)
+
+
+ "fmt_func",
+ [render_audit_csv, lambda rows: render_audit_html(rows, _context(rows))],
+)
+def test_handles_empty_input(fmt_func):
+ """Both renderers must produce a valid artefact even with zero rows."""
+ out = fmt_func([])
+ assert isinstance(out, str)
+ assert len(out) > 0