Files
certctl/web/src/pages/AuditPage.tsx
T
shankar0123 53e6de7db9 auth-bundle-1 Phase 9 + 10: approval-bypass closure + RBAC GUI
# Phase 9 — approval-bypass closure (Decision 9, option a)

* Migration 000033_approval_kinds.up.sql: ALTER TABLE
  issuance_approval_requests ADD COLUMN approval_kind +
  payload JSONB; relax certificate_id + job_id to nullable;
  CHECK (approval_kind IN ('cert_issuance','profile_edit'))
  + CHECK (per-kind nullability invariant) + index on
  approval_kind. Idempotent throughout via DO blocks.
* domain.ApprovalKind enum (cert_issuance / profile_edit) +
  IsValidApprovalKind. ApprovalRequest gains Kind +
  Payload []byte for the pending profile diff.
* postgres.ApprovalRepository.Create + scanApprovalRow extended
  to round-trip the new columns; certificate_id + job_id
  switched to sql.NullString so profile_edit rows persist
  cleanly. Default Kind=cert_issuance preserves back-compat
  for every Phase-7-2026-05-03 caller.
* ApprovalService.RequestProfileEditApproval: new entry point
  that creates a pending profile-edit row carrying the
  serialized profile diff. Bypass mode (CERTCTL_APPROVAL_BYPASS)
  short-circuits the same way it does for cert_issuance.
* ApprovalService.SetProfileEditApply hook: cmd/server/main.go
  registers a closure that deserializes req.Payload + persists
  via profileRepo.Update + emits a profile.edit_applied audit
  row with category=auth. The hook avoids the Approval ↔
  Profile import cycle.
* ProfileService.UpdateProfile: gates when (a) the live
  profile carries RequiresApproval=true, OR (b) the proposed
  edit would set it true. Returns ErrProfileEditPendingApproval
  with the new approval ID; ProfileHandler maps to HTTP 202
  Accepted + {pending_approval_id}. Both arms close the
  flip-flop loophole because every transition through an
  approval-tier profile fires the gate.
* TestProfileEdit_RequiresApprovalLoopholeClosed pins all 3
  bypass attempts (flip-off / kept-on / flip-on) gated; nil-
  approval-service preserves pre-Phase-9 direct-apply for
  test fixtures.
* Approval service tests gain 4 profile_edit rows: pending row
  shape; same-actor self-approve rejected with
  ErrApproveBySameActor (load-bearing two-person integrity);
  approve fails-closed when apply callback unwired;
  apply callback invoked on approve.
* docs/reference/profiles.md (new) explains the gate +
  edit response shape (202) + same-actor invariant + bypass
  + audit hooks.

# Phase 10 — RBAC management GUI

* useAuthMe hook (web/src/hooks/useAuthMe.ts): TanStack Query
  fetches /api/v1/auth/me on app boot, caches for 60s, exposes
  hasPerm(p) + hasAnyPerm + isAdmin predicates. Every Phase-10
  page consumes this on mount + gates affordances against the
  cached effective_permissions slice. Server-side enforcement
  is the load-bearing gate; client-side hide/disable is UX.
* New routes:
   - /auth/roles — list (auth.role.list); create-role modal
     (auth.role.create) hidden when missing.
   - /auth/roles/:id — detail + permissions; edit
     (auth.role.edit), delete (auth.role.delete), add/remove
     permission affordances each gated.
   - /auth/keys — list of every actor with role grants; assign
     + revoke modals (auth.role.assign). actor-demo-anon
     flagged system-managed; mutation buttons hidden for it.
   - /auth/settings — stub showing /v1/auth/me identity +
     bootstrap-endpoint availability via /v1/auth/bootstrap.
* AuditPage extended with category filter ('All categories'
  + the 3 enum values from migration 000032). Selection flows
  to the API call params + the URL-driven query state.
* Layout: 3 new nav entries (Roles / API Keys / Auth Settings).
* api/client.ts: 12 new exported functions for the RBAC
  surface (authMe, list/get/create/update/delete role,
  list/add/remove role permissions, list keys, assign/revoke
  key role, bootstrap-availability probe).
* data-testid attributes on every interactive element so a
  future Playwright suite can assert behavior without brittle
  CSS selectors.
* Empty state, error state, and unsaved-changes warnings on
  every form per the prompt's implementation rules.

# Frontend tests

* RolesPage.test.tsx (6 tests): list render, empty state,
  error state, hide-create-button-without-perm,
  show-create-button-with-perm, submit-create-modal.
* KeysPage.test.tsx (3 tests): demo-anon flagged
  system-managed (no buttons), permission-gated affordance
  hide for auditor caller, assign-modal-POST contract.
* AuthSettingsPage.test.tsx (2 tests): identity surface,
  bootstrap-OPEN-status surface.
* AuditPage.test.tsx (+1): category-filter select renders
  with the 4 documented options.

15 frontend tests total in src/pages/auth/ + the audit
category-filter test; all pass via npx vitest run.

# Verifications

* go vet ./... clean.
* staticcheck across internal/auth + handler + router + cli +
  service + repository + cmd + domain: clean.
* gofmt -l clean repo-wide.
* go test -short -count=1 green across internal/service,
  internal/api/handler, internal/api/router, internal/auth,
  internal/auth/bootstrap, internal/service/auth,
  internal/domain/auth, cmd/server, cmd/cli, internal/cli.
* npx tsc --noEmit clean.
* npm run build green (vite build produces dist/index.html
  + 946KB JS bundle; chunk-size warning is pre-existing).
* npx vitest run src/pages/auth/ src/pages/AuditPage.test.tsx
  green (15 tests, 4 files).
2026-05-09 21:03:59 +00:00

233 lines
8.4 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;
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['audit', params],
queryFn: () => getAuditEvents(params),
refetchInterval: 30000,
});
// Client-side time range filtering (server may not support time params)
const filtered = (data?.data || []).filter((e) => {
if (!timeRange) return true;
const ts = new Date(e.timestamp).getTime();
const now = Date.now();
const hours = timeRange === '1h' ? 1 : timeRange === '24h' ? 24 : timeRange === '7d' ? 168 : 720;
return now - ts < hours * 3600 * 1000;
});
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">&mdash;</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>
</>
);
}