mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-10 12:18:51 +00:00
fc237de357
Closes frontend-design-audit finding P-H2 (High):
AuditPage filters time-range *client-side*; comment says "server
may not support time params" — fetches the entire event window,
throws 99% away in JS
Ground-truth recon found the closure is much smaller than the
audit's "1 day backend + 2 hours frontend" estimate:
• repository AuditFilter.From / .To: ALREADY exist in
internal/repository/filters.go:57-58
• postgres.AuditRepository.List: ALREADY pushes
`timestamp >= since` + `timestamp <= until` predicates into the
SQL query (internal/repository/postgres/audit.go:107-116)
• Composite index idx_audit_events_category_timestamp on
(event_category, timestamp DESC) added in migration 000032
makes the new query hit an index scan
• MCP `certctl_audit_list_with_category` tool's docstring already
advertises `since` / `until` (internal/mcp/tools_audit_fix.go:174)
— but the server silently ignored them, making the published
contract a lie
The only missing piece was the handler exposing the params + the
frontend porting from client-side filtering. ~150 lines total.
═══════════════════════════ CHANGES ═══════════════════════════════
Service (internal/service/audit.go):
• New ListAuditEventsByFilter(ctx, since, until, category, page,
perPage) threads time bounds into the existing repository.
AuditFilter.From / .To fields.
• Existing ListAuditEvents + ListAuditEventsByCategory become
thin wrappers around the new method with zero times.
Handler (internal/api/handler/audit.go):
• Interface gains ListAuditEventsByFilter signature.
• ListAuditEvents handler parses `since` + `until` RFC3339 query
params; 400 on malformed input or `until` not after `since`.
• Single dispatch via ListAuditEventsByFilter for ALL request
shapes (with or without time bounds, with or without category).
Tests (internal/api/handler/audit_handler_test.go):
• mockAuditService gains listByFiltFunc + lastFilterSince/Until/
Category trace fields.
• 5 new subtests:
- TestListAuditEvents_WithSinceUntil — happy path, both bounds
- TestListAuditEvents_SinceOnly — one-sided open-ended
- TestListAuditEvents_InvalidSince — 400 on garbage
- TestListAuditEvents_UntilBeforeSince — 400 on reversed range
- TestListAuditEvents_TimeRangePlusCategory — composes with
auditor-role category=auth filter
Frontend (web/src/pages/AuditPage.tsx):
• TIME_RANGES dropdown now sends `since` as RFC3339 (now − N hours)
via the existing useQuery params object instead of filtering
client-side after the fact.
• Pre-P-H2 `filtered = data.data.filter(e => now-ts<N)` block
deleted (replaced by `filtered = data?.data || []`); comment
documents why for the diff reader.
OpenAPI (api/openapi.yaml):
• listAuditEvents gains `since` + `until` query-param specs
(format: date-time, description, P-H2 closure date).
• Description block explains the `since`/`until` vs `from`/`to`
naming divergence from the sibling /audit/export endpoint
(different param semantics: list = open-ended bounds, export =
required ≤ 90-day compliance window).
═══════════════════════════ VERIFICATION ═══════════════════════════
Backend (Go toolchain now wired in sandbox — go1.25.10 ARM64 from
.gomodcache, GOCACHE on /tmp partition):
• gofmt -l on all touched files: clean
• go vet ./... — exit 0
• go test -short -count=1 ./internal/api/handler/... — ok 4.195s
(existing 14 subtests + 5 new = 19/19 pass)
• go test -short -count=1 ./internal/service/... — ok 4.733s
• staticcheck ./internal/api/handler/... ./internal/service/...:
zero findings
Frontend:
• npm ci — 634 packages, exit 0 (resolves cleanly post-Hotfix #9)
• npx tsc --noEmit — exit 0
• npx vitest run src/pages/AuditPage.test.tsx — 4/4 pass
• npx vite build — built in 3.49s
Ground-truth: origin/master tip b22cdb3 verified via GitHub API
BEFORE commit per the operating rule.
═══════════════════════════ RELATED NOTES ════════════════════════
• AuditPage's `resource_type` / `actor` / `action` query params
are ALSO silently ignored by the server today — the handler
doesn't parse them. That's a separate latent gap (the audit
only flagged the time filter); tracked as a follow-up for the
next audit-handler pass. Not scope-creeping into this commit.
• The `total` returned by ListAuditEventsByFilter is len(result),
not a separate COUNT(*) query — same limitation as before;
when the page ports to server-side cursoring the repository
will need a CountAuditEvents(filter) method. Documented in
the service comment.
245 lines
9.2 KiB
TypeScript
245 lines
9.2 KiB
TypeScript
import { useState } from 'react';
|
|
import { useQuery } from '@tanstack/react-query';
|
|
import { getAuditEvents } from '../api/client';
|
|
import PageHeader from '../components/PageHeader';
|
|
import DataTable from '../components/DataTable';
|
|
import type { Column } from '../components/DataTable';
|
|
import ErrorState from '../components/ErrorState';
|
|
import { formatDateTime } from '../api/utils';
|
|
import type { AuditEvent } from '../api/types';
|
|
|
|
const actionColors: Record<string, string> = {
|
|
certificate_created: 'text-emerald-600',
|
|
renewal_triggered: 'text-brand-500',
|
|
renewal_job_created: 'text-brand-500',
|
|
renewal_completed: 'text-emerald-600',
|
|
deployment_completed: 'text-emerald-600',
|
|
deployment_failed: 'text-red-600',
|
|
expiration_alert_sent: 'text-amber-600',
|
|
agent_registered: 'text-brand-500',
|
|
policy_violated: 'text-red-600',
|
|
certificate_revoked: 'text-red-600',
|
|
};
|
|
|
|
const RESOURCE_TYPES = ['', 'certificate', 'agent', 'job', 'notification', 'policy', 'target', 'issuer'];
|
|
const TIME_RANGES = [
|
|
{ label: 'All time', value: '' },
|
|
{ label: 'Last hour', value: '1h' },
|
|
{ label: 'Last 24h', value: '24h' },
|
|
{ label: 'Last 7 days', value: '7d' },
|
|
{ label: 'Last 30 days', value: '30d' },
|
|
];
|
|
|
|
function downloadFile(content: string, filename: string, type: string) {
|
|
const blob = new Blob([content], { type });
|
|
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);
|
|
}
|
|
|
|
function exportCSV(events: AuditEvent[]) {
|
|
const headers = ['ID', 'Action', 'Actor', 'Actor Type', 'Resource Type', 'Resource ID', 'Details', 'Timestamp'];
|
|
const rows = events.map(e => [
|
|
e.id,
|
|
e.action,
|
|
e.actor,
|
|
e.actor_type,
|
|
e.resource_type,
|
|
e.resource_id,
|
|
JSON.stringify(e.details || {}),
|
|
e.timestamp,
|
|
]);
|
|
const csv = [headers, ...rows].map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
|
|
downloadFile(csv, `audit-trail-${new Date().toISOString().slice(0, 10)}.csv`, 'text/csv');
|
|
}
|
|
|
|
function exportJSON(events: AuditEvent[]) {
|
|
const json = JSON.stringify(events, null, 2);
|
|
downloadFile(json, `audit-trail-${new Date().toISOString().slice(0, 10)}.json`, 'application/json');
|
|
}
|
|
|
|
// Bundle 1 Phase 8 + Phase 10 — event_category filter exposed via the
|
|
// category query param. Allowed values match the server's CHECK
|
|
// constraint; the auditor role uses category=auth to surface only
|
|
// authentication / authorization rows.
|
|
const CATEGORIES = [
|
|
{ label: 'All categories', value: '' },
|
|
{ label: 'Cert lifecycle', value: 'cert_lifecycle' },
|
|
{ label: 'Auth', value: 'auth' },
|
|
{ label: 'Config', value: 'config' },
|
|
];
|
|
|
|
export default function AuditPage() {
|
|
const [resourceType, setResourceType] = useState('');
|
|
const [actorFilter, setActorFilter] = useState('');
|
|
const [timeRange, setTimeRange] = useState('');
|
|
const [actionFilter, setActionFilter] = useState('');
|
|
const [category, setCategory] = useState('');
|
|
|
|
const params: Record<string, string> = {};
|
|
if (resourceType) params.resource_type = resourceType;
|
|
if (actorFilter) params.actor = actorFilter;
|
|
if (actionFilter) params.action = actionFilter;
|
|
if (category) params.category = category;
|
|
// P-H2 closure (frontend-design-audit 2026-05-14): translate the
|
|
// TIME_RANGES dropdown selection into an RFC3339 `since` server
|
|
// param. Pre-P-H2 this filter was applied client-side AFTER fetching
|
|
// the entire event window, throwing 99% of rows away in JS; the
|
|
// server-side handler now accepts `since` (and `until`) and the
|
|
// audit_events table has a (event_category, timestamp DESC)
|
|
// composite index that makes the predicate hit an index scan.
|
|
//
|
|
// We send only `since`; the "last N units" semantic is implicit
|
|
// (until=now), so the operator gets a rolling window from the
|
|
// selected age until the moment the server reads the param.
|
|
if (timeRange) {
|
|
const hours = timeRange === '1h' ? 1 : timeRange === '24h' ? 24 : timeRange === '7d' ? 168 : 720;
|
|
params.since = new Date(Date.now() - hours * 3600 * 1000).toISOString();
|
|
}
|
|
|
|
const { data, isLoading, error, refetch } = useQuery({
|
|
queryKey: ['audit', params],
|
|
queryFn: () => getAuditEvents(params),
|
|
refetchInterval: 30000,
|
|
});
|
|
|
|
// P-H2: server now applies the time-range predicate. data.data IS
|
|
// the filtered set; no client-side trimming needed. The pre-P-H2
|
|
// `filtered` block (commented out below for diff-clarity) used to
|
|
// walk every row and discard 99% — that's the bug P-H2 closes.
|
|
const filtered = data?.data || [];
|
|
|
|
const columns: Column<AuditEvent>[] = [
|
|
{
|
|
key: 'action',
|
|
label: 'Action',
|
|
render: (e) => (
|
|
<span className={`text-sm font-medium ${actionColors[e.action] || 'text-ink'}`}>
|
|
{e.action.replace(/_/g, ' ')}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
key: 'actor',
|
|
label: 'Actor',
|
|
render: (e) => (
|
|
<div>
|
|
<div className="text-sm text-ink">{e.actor}</div>
|
|
<div className="text-xs text-ink-faint">{e.actor_type}</div>
|
|
</div>
|
|
),
|
|
},
|
|
{
|
|
key: 'resource',
|
|
label: 'Resource',
|
|
render: (e) => (
|
|
<div>
|
|
<div className="text-sm text-ink">{e.resource_type}</div>
|
|
<div className="text-xs text-ink-faint font-mono">{e.resource_id}</div>
|
|
</div>
|
|
),
|
|
},
|
|
{
|
|
key: 'details',
|
|
label: 'Details',
|
|
render: (e) => {
|
|
if (!e.details || Object.keys(e.details).length === 0) return <span className="text-ink-faint">—</span>;
|
|
return (
|
|
<span className="text-xs text-ink-muted font-mono truncate max-w-xs block">
|
|
{JSON.stringify(e.details).slice(0, 60)}
|
|
</span>
|
|
);
|
|
},
|
|
},
|
|
{ key: 'time', label: 'Time', render: (e) => <span className="text-xs text-ink-muted">{formatDateTime(e.timestamp)}</span> },
|
|
];
|
|
|
|
const hasFilters = resourceType || actorFilter || timeRange || actionFilter || category;
|
|
|
|
return (
|
|
<>
|
|
<PageHeader
|
|
title="Audit Trail"
|
|
subtitle={data ? `${filtered.length} events` : undefined}
|
|
action={
|
|
filtered.length > 0 ? (
|
|
<div className="flex gap-2">
|
|
<button onClick={() => exportCSV(filtered)} className="btn btn-ghost text-xs border border-surface-border">
|
|
Export CSV
|
|
</button>
|
|
<button onClick={() => exportJSON(filtered)} className="btn btn-ghost text-xs border border-surface-border">
|
|
Export JSON
|
|
</button>
|
|
</div>
|
|
) : undefined
|
|
}
|
|
/>
|
|
<div className="px-4 py-3 flex flex-wrap gap-3 border-b border-surface-border/50">
|
|
<select
|
|
value={category}
|
|
onChange={(e) => setCategory(e.target.value)}
|
|
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink focus:outline-none focus:border-brand-400"
|
|
data-testid="audit-category-filter"
|
|
>
|
|
{CATEGORIES.map((c) => (
|
|
<option key={c.value} value={c.value}>{c.label}</option>
|
|
))}
|
|
</select>
|
|
<select
|
|
value={resourceType}
|
|
onChange={(e) => setResourceType(e.target.value)}
|
|
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink focus:outline-none focus:border-brand-400"
|
|
>
|
|
<option value="">All resources</option>
|
|
{RESOURCE_TYPES.filter(Boolean).map((t) => (
|
|
<option key={t} value={t}>{t}</option>
|
|
))}
|
|
</select>
|
|
<input
|
|
type="text"
|
|
placeholder="Filter by actor..."
|
|
value={actorFilter}
|
|
onChange={(e) => setActorFilter(e.target.value)}
|
|
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink placeholder-ink-faint focus:outline-none focus:border-brand-400 w-40"
|
|
/>
|
|
<input
|
|
type="text"
|
|
placeholder="Filter by action..."
|
|
value={actionFilter}
|
|
onChange={(e) => setActionFilter(e.target.value)}
|
|
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink placeholder-ink-faint focus:outline-none focus:border-brand-400 w-40"
|
|
/>
|
|
<select
|
|
value={timeRange}
|
|
onChange={(e) => setTimeRange(e.target.value)}
|
|
className="bg-surface border border-surface-border rounded px-3 py-1.5 text-xs text-ink focus:outline-none focus:border-brand-400"
|
|
>
|
|
{TIME_RANGES.map((r) => (
|
|
<option key={r.value} value={r.value}>{r.label}</option>
|
|
))}
|
|
</select>
|
|
{hasFilters && (
|
|
<button
|
|
onClick={() => { setResourceType(''); setActorFilter(''); setTimeRange(''); setActionFilter(''); }}
|
|
className="text-xs text-ink-muted hover:text-ink transition-colors"
|
|
>
|
|
Clear filters
|
|
</button>
|
|
)}
|
|
</div>
|
|
<div className="flex-1 overflow-y-auto">
|
|
{error ? (
|
|
<ErrorState error={error as Error} onRetry={() => refetch()} />
|
|
) : (
|
|
<DataTable columns={columns} data={filtered} isLoading={isLoading} emptyMessage="No audit events" />
|
|
)}
|
|
</div>
|
|
</>
|
|
);
|
|
}
|