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).
This commit is contained in:
shankar0123
2026-05-09 21:03:59 +00:00
parent af4fa12724
commit 69a508dfcf
24 changed files with 2413 additions and 29 deletions
+341
View File
@@ -0,0 +1,341 @@
import { useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
authGetRole,
authListPermissions,
authUpdateRole,
authDeleteRole,
authAddRolePermission,
authRemoveRolePermission,
type AuthPermission,
} from '../../api/client';
import { useAuthMe } from '../../hooks/useAuthMe';
import PageHeader from '../../components/PageHeader';
import ErrorState from '../../components/ErrorState';
// =============================================================================
// Bundle 1 Phase 10 — RoleDetailPage.
//
// Shows a single role plus its current permission grants. Surfaces:
//
// - Edit role modal (auth.role.edit)
// - Delete role action (auth.role.delete) — disabled when actors hold
// the role (server returns 409; UX surfaces via ErrorState).
// - Add permission picker (auth.role.edit) populated from the
// canonical catalogue.
// - Remove permission action per row (auth.role.edit).
//
// Each action is HIDDEN when the caller lacks the permission. The
// server still 403s an end-run; client-side hide is UX, not security.
// =============================================================================
export default function RoleDetailPage() {
const { id = '' } = useParams<{ id: string }>();
const me = useAuthMe();
const qc = useQueryClient();
const navigate = useNavigate();
const detailQuery = useQuery({
queryKey: ['auth', 'role', id],
queryFn: () => authGetRole(id),
enabled: Boolean(id),
staleTime: 30_000,
});
const permsCatalogue = useQuery<AuthPermission[], Error>({
queryKey: ['auth', 'permissions'],
queryFn: authListPermissions,
staleTime: 5 * 60_000,
});
const [editOpen, setEditOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
const canEdit = me.hasPerm('auth.role.edit') || me.isAdmin();
const canDelete = me.hasPerm('auth.role.delete') || me.isAdmin();
if (detailQuery.isLoading) return <PageHeader title="Role" subtitle="Loading…" />;
if (detailQuery.error || !detailQuery.data)
return (
<div className="space-y-4">
<PageHeader title="Role" />
<ErrorState
error={detailQuery.error ?? new Error('not found')}
onRetry={() => qc.invalidateQueries({ queryKey: ['auth', 'role', id] })}
/>
</div>
);
const { role, permissions } = detailQuery.data;
const handleDelete = async () => {
if (!window.confirm(`Delete role ${role.name}? This cannot be undone.`)) return;
setSubmitting(true);
setActionError(null);
try {
await authDeleteRole(role.id);
navigate('/auth/roles');
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setSubmitting(false);
}
};
const handleAddPermission = async (perm: string) => {
setSubmitting(true);
setActionError(null);
try {
await authAddRolePermission(role.id, { permission: perm });
qc.invalidateQueries({ queryKey: ['auth', 'role', role.id] });
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setSubmitting(false);
}
};
const handleRemovePermission = async (perm: string) => {
setSubmitting(true);
setActionError(null);
try {
await authRemoveRolePermission(role.id, perm);
qc.invalidateQueries({ queryKey: ['auth', 'role', role.id] });
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setSubmitting(false);
}
};
const grantedPermNames = new Set(permissions.map(p => p.permission_id));
const availablePerms = (permsCatalogue.data ?? []).filter(p => !grantedPermNames.has(p.name));
return (
<div className="space-y-4" data-testid={`role-detail-${role.id}`}>
<PageHeader
title={role.name}
subtitle={`Role ID: ${role.id} · ${permissions.length} permission(s)`}
action={
<div className="flex gap-2">
<Link to="/auth/roles" className="btn btn-ghost" data-testid="role-back">
Back
</Link>
{canEdit && (
<button
className="btn btn-primary"
onClick={() => setEditOpen(true)}
data-testid="role-edit-button"
>
Edit
</button>
)}
{canDelete && (
<button
className="btn btn-danger"
onClick={handleDelete}
disabled={submitting}
data-testid="role-delete-button"
>
Delete
</button>
)}
</div>
}
/>
{actionError && (
<div
className="bg-red-50 border border-red-200 text-red-700 text-sm p-3 rounded"
data-testid="role-action-error"
>
{actionError}
</div>
)}
<div className="bg-surface border border-surface-border rounded p-4 space-y-2">
<div className="text-xs uppercase tracking-wide text-ink-muted">Description</div>
<div className="text-sm">{role.description || <span className="text-ink-muted">(none)</span>}</div>
</div>
<div className="bg-surface border border-surface-border rounded">
<div className="px-4 py-3 border-b border-surface-border flex items-center justify-between">
<div>
<div className="text-sm font-semibold">Permissions ({permissions.length})</div>
<div className="text-xs text-ink-muted">
Permissions granted at the listed scope. Global wins over more-specific scopes.
</div>
</div>
{canEdit && availablePerms.length > 0 && (
<select
className="bg-white border border-surface-border rounded px-3 py-1.5 text-sm"
defaultValue=""
onChange={e => {
if (e.target.value) {
void handleAddPermission(e.target.value);
e.target.value = '';
}
}}
data-testid="role-add-permission-select"
>
<option value="">Add permission</option>
{availablePerms.map(p => (
<option key={p.id} value={p.name}>
{p.name}
</option>
))}
</select>
)}
</div>
{permissions.length === 0 ? (
<div className="p-6 text-sm text-ink-muted text-center" data-testid="role-permissions-empty">
No permissions granted. {canEdit ? 'Use the picker above to add some.' : ''}
</div>
) : (
<table className="w-full text-sm" data-testid="role-permissions-table">
<thead className="bg-surface-muted text-xs uppercase tracking-wide text-ink-muted">
<tr>
<th className="text-left px-3 py-2">Permission</th>
<th className="text-left px-3 py-2">Scope</th>
{canEdit && <th className="px-3 py-2 w-24"></th>}
</tr>
</thead>
<tbody>
{permissions.map(p => {
const permName = lookupPermNameByID(permsCatalogue.data ?? [], p.permission_id);
return (
<tr key={p.permission_id} className="border-t border-surface-border">
<td className="px-3 py-2 font-mono text-xs">{permName}</td>
<td className="px-3 py-2 text-xs">
{p.scope_type}
{p.scope_id ? ` (${p.scope_id})` : ''}
</td>
{canEdit && (
<td className="px-3 py-2 text-right">
<button
className="btn btn-ghost text-xs"
onClick={() => handleRemovePermission(permName)}
disabled={submitting}
data-testid={`role-remove-${permName}`}
>
Remove
</button>
</td>
)}
</tr>
);
})}
</tbody>
</table>
)}
</div>
{editOpen && (
<EditRoleModal
roleId={role.id}
initialName={role.name}
initialDescription={role.description ?? ''}
onClose={() => setEditOpen(false)}
onSuccess={() => {
setEditOpen(false);
qc.invalidateQueries({ queryKey: ['auth', 'role', role.id] });
qc.invalidateQueries({ queryKey: ['auth', 'roles'] });
}}
/>
)}
</div>
);
}
function lookupPermNameByID(catalogue: AuthPermission[], id: string): string {
// The role-permissions response uses permission_id which the server
// populates as the canonical permission NAME (the schema treats
// permission name as the row id surrogate). Belt-and-braces
// fallback: if the catalogue knows the id, return its display name.
const m = catalogue.find(p => p.id === id || p.name === id);
return m?.name ?? id;
}
interface EditModalProps {
roleId: string;
initialName: string;
initialDescription: string;
onClose: () => void;
onSuccess: () => void;
}
function EditRoleModal({ roleId, initialName, initialDescription, onClose, onSuccess }: EditModalProps) {
const [name, setName] = useState(initialName);
const [description, setDescription] = useState(initialDescription);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const dirty = name !== initialName || description !== initialDescription;
const handleClose = () => {
if (dirty && !window.confirm('Discard unsaved changes?')) return;
onClose();
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setSubmitting(true);
setError(null);
try {
await authUpdateRole(roleId, { name: name.trim(), description: description.trim() });
onSuccess();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setSubmitting(false);
}
};
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={handleClose}>
<div
className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl"
onClick={e => e.stopPropagation()}
data-testid="edit-role-modal"
>
<h2 className="text-lg font-semibold text-ink mb-4">Edit role</h2>
{error && (
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700">{error}</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-ink mb-1">Name *</label>
<input
value={name}
onChange={e => setName(e.target.value)}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm"
required
data-testid="edit-role-name"
/>
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Description</label>
<textarea
value={description}
onChange={e => setDescription(e.target.value)}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm"
rows={3}
data-testid="edit-role-description"
/>
</div>
<div className="flex gap-2 pt-2">
<button
type="submit"
disabled={submitting || !dirty || !name.trim()}
className="flex-1 btn btn-primary disabled:opacity-50"
data-testid="edit-role-submit"
>
{submitting ? 'Saving…' : 'Save'}
</button>
<button type="button" onClick={handleClose} className="flex-1 btn btn-ghost" data-testid="edit-role-cancel">
Cancel
</button>
</div>
</form>
</div>
</div>
);
}