Merge branch 'fix/b1-master-orphan-crud-edit-modals' (B-1 master, 4 audit findings)

This commit is contained in:
shankar0123
2026-04-25 15:23:21 +00:00
14 changed files with 1026 additions and 52 deletions
+52
View File
@@ -388,6 +388,58 @@ jobs:
exit 1
fi
- name: Forbidden orphan-CRUD client function regression guard (B-1)
# B-1 master closed four audit findings — three orphan-update fns
# (cat-b-31ceb6aaa9f1, cat-b-7a34f893a8f9) and one orphan CRUD
# surface (cat-b-4631ca092bee, RenewalPolicy) — by wiring per-page
# Edit modals so every backend write endpoint has at least one
# GUI consumer. The fourth finding (cat-b-9b97ffb35ef7) deleted
# the dead `exportCertificatePEM` duplicate.
#
# Pre-B-1 the failure mode was: backend ships a CRUD handler,
# client.ts ships the matching `update*` / `delete*` / `create*`
# function, but no page imports it. Operators were forced to
# `psql` directly to edit team names, owner emails, agent-group
# match rules, issuer names, profile names, or any renewal-policy
# field — turning a 30-second GUI task into a 30-minute database
# excursion with audit-trail gaps.
#
# This step fails the build if any of the eight previously-orphan
# client functions loses its page consumer (i.e. a future refactor
# accidentally re-orphans them). Each fn must have ≥1 non-test
# consumer under web/src/pages/. Tests (*.test.ts(x)) and the
# client.ts definition file itself are exempt.
#
# See coverage-gap-audit-2026-04-24-v5/unified-audit.md
# cat-b-31ceb6aaa9f1, cat-b-7a34f893a8f9, cat-b-4631ca092bee,
# cat-b-9b97ffb35ef7 for closure rationale.
run: |
set -e
ORPHAN_FNS="updateOwner updateTeam updateAgentGroup updateIssuer updateProfile createRenewalPolicy updateRenewalPolicy deleteRenewalPolicy"
FAIL=0
for fn in $ORPHAN_FNS; do
HITS=$(grep -rE "\b${fn}\b" web/src/pages/ 2>/dev/null \
| grep -vE '\.test\.(ts|tsx):' \
| wc -l)
if [ "$HITS" -eq 0 ]; then
echo "::error::B-1 regression: client function '${fn}' has zero consumers under web/src/pages/."
echo " Every backend CRUD endpoint must have a GUI consumer to avoid forcing operators to psql."
echo " Either restore the page consumer or delete the client function in the same commit."
FAIL=1
fi
done
# cat-b-9b97ffb35ef7: exportCertificatePEM was deleted as a dead
# duplicate of downloadCertificatePEM. Block resurrection.
if grep -nE 'export\s+const\s+exportCertificatePEM' web/src/api/client.ts >/dev/null 2>&1; then
echo "::error::B-1 regression: exportCertificatePEM was removed as a dead duplicate of downloadCertificatePEM."
echo " If a JSON variant is needed, add an explicit page consumer in the same commit."
FAIL=1
fi
if [ "$FAIL" -ne 0 ]; then
exit 1
fi
echo "B-1 orphan-CRUD client function guardrail: all 8 functions have page consumers."
- name: Race Detection
run: go test -race ./internal/service/... ./internal/api/handler/... ./internal/api/middleware/... ./internal/scheduler/... ./internal/connector/... ./internal/crypto/... ./internal/domain/... ./internal/validation/... ./internal/tlsprobe/... -count=1 -timeout 300s
+33
View File
@@ -4,6 +4,39 @@ All notable changes to certctl are documented in this file. Dates use ISO 8601.
## [unreleased] — 2026-04-25
### B-1: Orphan-CRUD client functions + RenewalPolicy GUI gap — closed end-to-end
> The 2026-04-24 coverage-gap audit flagged a cluster of operator-blocking GUI omissions: six client.ts `update*` functions (`updateOwner`, `updateTeam`, `updateAgentGroup`, `updateIssuer`, `updateProfile`, plus the full `*RenewalPolicy` CRUD trio) had backend handlers, OpenAPI operations, and exported TypeScript fetchers — but zero page consumers. Operators wanting to fix a typo in an owner's email, rename a team, retarget an agent group's match rules, or edit a renewal-policy field were forced to either delete-and-recreate (losing FK history and audit-trail continuity) or open a `psql` session against the production database directly. The audit's blunt summary: "every backend feature ships with its GUI surface" — a load-bearing CLAUDE.md invariant — was being violated for five operator-facing entities. B-1 closes that violation by wiring per-page Edit modals onto five existing pages, adding a brand-new `RenewalPoliciesPage` for the rp-* CRUD surface, and deleting one dead duplicate (`exportCertificatePEM`) so the public client surface area stops growing without consumers.
### Breaking Changes
None. All five existing pages keep their Create + Delete affordances unchanged; Edit is purely additive. `RenewalPoliciesPage` is a new route at `/renewal-policies` and a new sidebar nav item slotted between Policies and Profiles. The `exportCertificatePEM` helper had zero consumers in `web/`, MCP, CLI, and tests at the time of removal — operators using `downloadCertificatePEM` (the actual call site in `CertificateDetailPage`) are unaffected.
### Added
- **`web/src/pages/RenewalPoliciesPage.tsx`** — a new full-CRUD page for the `rp-*` renewal-policy table. Surfaces a 7-column DataTable (Policy / Renewal Window / Auto / Retries / Alert Thresholds / Created / Actions) with Create, Edit, and Delete affordances. A shared `PolicyFormModal` powers both Create and Edit (the form shape is identical) covering the full domain field set: `name`, `renewal_window_days`, `auto_renew`, `max_retries`, `retry_interval_seconds`, `alert_thresholds_days[]`. The thresholds input parses comma-separated integers (`30, 14, 7, 0`) into the array shape the backend expects. Delete surfaces `repository.ErrRenewalPolicyInUse` (409 from the backend when a policy still has `managed_certificates.renewal_policy_id` references) via an explicit alert so the operator can re-target the dependent certs to a different policy before deletion. Wired into `web/src/main.tsx` routing and `web/src/components/Layout.tsx` sidebar nav.
- **EditOwnerModal** in `web/src/pages/OwnersPage.tsx` — pre-populates from the editing owner via `useEffect`, calls `updateOwner(id, {name, email, team_id})`, mirrors the Create modal's TanStack-Query mutation/invalidation pattern.
- **EditTeamModal** in `web/src/pages/TeamsPage.tsx` — same shape, fields `name`/`description`.
- **EditAgentGroupModal** in `web/src/pages/AgentGroupsPage.tsx` — covers the full match-rule set (`name`, `description`, `match_os`, `match_architecture`, `match_ip_cidr`, `match_version`, `enabled`).
- **EditIssuerModal** in `web/src/pages/IssuersPage.tsx` — deliberately rename-only. The `type` field is shown but disabled, the existing `config` blob (which includes credentials for ACME, ADCS, ZeroSSL, etc.) is forwarded untouched, and only `name` is editable. Footer note: "To change issuer type or rotate credentials, delete and recreate." This trades scope for safety — the audit's destructive-rename complaint is closed without surfacing a credential-edit attack surface that has not been threat-modeled.
- **EditProfileModal** in `web/src/pages/ProfilesPage.tsx` — same rename-only shape. Forwards full `Partial<CertificateProfile>` with policy fields (`allowed_key_algorithms`, `max_ttl_seconds`, `allowed_ekus`, etc.) preserved untouched. Footer note about deferred policy-field editing.
- **CI regression guardrail** in `.github/workflows/ci.yml` (`Forbidden orphan-CRUD client function regression guard (B-1)`) — grep-fails the build if any of the eight previously-orphan client functions (`updateOwner`, `updateTeam`, `updateAgentGroup`, `updateIssuer`, `updateProfile`, `createRenewalPolicy`, `updateRenewalPolicy`, `deleteRenewalPolicy`) loses its non-test consumer under `web/src/pages/`. Also blocks resurrection of the deleted `exportCertificatePEM` function. Verified locally on the post-fix tree (passes — all 8 fns have ≥2 consumers); fires against synthetic regressions (delete the Edit modal → guardrail fires the next CI run).
### Removed
- `web/src/api/client.ts::exportCertificatePEM` — closes `cat-b-9b97ffb35ef7`. The function returned `{cert_pem, chain_pem, full_pem}` JSON but had zero consumers across `web/`, MCP, CLI, and tests; `downloadCertificatePEM` (the blob-download path consumed by `CertificateDetailPage`) covers all real call sites. Test references in `web/src/api/client.test.ts` and `client.error.test.ts` were also removed. The CI guardrail blocks resurrection without an accompanying page consumer.
### Audit findings closed
- `cat-b-31ceb6aaa9f1` (P1, `updateOwner`/`updateTeam`/`updateAgentGroup` orphan)
- `cat-b-7a34f893a8f9` (P1, `updateIssuer`/`updateProfile` orphan, rename-only closure)
- `cat-b-4631ca092bee` (P1, RenewalPolicy CRUD orphan — new RenewalPoliciesPage)
- `cat-b-9b97ffb35ef7` (P3, `exportCertificatePEM` dead duplicate)
### Known follow-ups (deferred from B-1 scope)
A fuller `EditIssuerModal` with explicit credential-rotation flow is deferred — that needs an explicit threat model (rotation reuse window, audit-trail granularity, in-flight CSR cancellation), and the audit's destructive-rename complaint is closed by rename-only Edit alone. Likewise an `EditProfileModal` with policy-field editing (max-TTL, allowed EKUs, allowed key algorithms) is deferred because policy edits affect the `enforce_certificate_policy` evaluator's semantics for already-issued certs and warrant their own scope. Per-page Vitest coverage for the new Edit modals is deferred — the CI grep guardrail catches the same regression vector ("page lost its `update*` fn consumer") at lower cost than five new test files.
### L-1: Client-side bulk-action loops — closed end-to-end
> The certctl dashboard's busiest screen (`CertificatesPage.tsx`) had two bulk-action workflows that looped per-cert HTTP calls. Selecting 100 certs and clicking "Renew" issued 100 sequential `POST /api/v1/certificates/{id}/renew` requests; "Reassign owner" issued 100 sequential `PUT /api/v1/certificates/{id}` requests. Each round-trip carried ~50200 ms of Auth → audit-log → handler → service → repo → DB → audit-write → response, so a 100-cert bulk action was a 520-second wedge during which the operator stared at a progress bar. The bulk-revoke endpoint (`POST /api/v1/certificates/bulk-revoke`) already shipped in v2.0.x as the canonical pattern for this; L-1 ports that exact shape to bulk-renew (P1) and bulk-reassign (P2). One backend round-trip; one audit event for the entire operation; per-cert success/skip/error counts in a single response envelope. Bundled with two new MCP tools and an OpenAPI spec update so non-GUI callers (CLI / MCP / blackbox probes) can use the same endpoints.
+2
View File
@@ -163,6 +163,8 @@ The dashboard includes an **ErrorBoundary component** for graceful error recover
- Light content area with branded dark teal sidebar, Inter + JetBrains Mono typography
- SSE/WebSocket planned for real-time job status updates
**Backend ↔ frontend round-trip rule (B-1 closure):** every backend CRUD operation must have at least one GUI consumer in `web/src/pages/`. Shipping a handler + repository method + OpenAPI operation + `client.ts` fetcher with no page that calls it leaves operators forced to `psql` directly — defeats the "every backend feature ships with its GUI surface" invariant and creates a destructive workflow when the missing path is `update*` (operators delete-and-recreate, losing FK history and audit-trail continuity). The CI guardrail in `.github/workflows/ci.yml` (`Forbidden orphan-CRUD client function regression guard (B-1)`) enforces this for the eight previously-orphan functions (`updateOwner`/`updateTeam`/`updateAgentGroup`/`updateIssuer`/`updateProfile` + `createRenewalPolicy`/`updateRenewalPolicy`/`deleteRenewalPolicy`); apply the same rule when adding any new write endpoint. If a fetcher is needed in `client.ts` before its consumer page exists, leave a TODO referencing this rule and ship them in the same commit.
### PostgreSQL Database
All state is stored in PostgreSQL 16. The schema uses TEXT primary keys (not UUIDs) with human-readable prefixed IDs like `mc-api-prod`, `t-platform`, `o-alice`.
+2 -5
View File
@@ -6,7 +6,6 @@ import {
createCertificate,
triggerRenewal,
revokeCertificate,
exportCertificatePEM,
downloadCertificatePEM,
exportCertificatePKCS12,
getAgents,
@@ -106,10 +105,8 @@ describe('API Client - Error Handling', () => {
);
});
it('exportCertificatePEM propagates network error', async () => {
mockFetch.mockReturnValueOnce(mockNetworkError());
await expect(exportCertificatePEM('mc-test')).rejects.toThrow('Failed to fetch');
});
// B-1 closure (cat-b-9b97ffb35ef7): exportCertificatePEM removed as a
// dead duplicate of downloadCertificatePEM (zero consumers).
it('downloadCertificatePEM propagates network error', async () => {
mockFetch.mockReturnValueOnce(mockNetworkError());
+2 -10
View File
@@ -13,7 +13,6 @@ import {
archiveCertificate,
revokeCertificate,
bulkRevokeCertificates,
exportCertificatePEM,
downloadCertificatePEM,
exportCertificatePKCS12,
getAgents,
@@ -1151,15 +1150,8 @@ describe('API Client', () => {
// ─── Certificate Export ────────────────────────────────
describe('Certificate Export', () => {
it('exportCertificatePEM fetches PEM data as JSON', async () => {
const pemResult = { cert_pem: 'CERT', chain_pem: 'CHAIN', full_pem: 'FULL' };
mockFetch.mockReturnValueOnce(mockJsonResponse(pemResult));
const result = await exportCertificatePEM('mc-1');
const [url] = mockFetch.mock.calls[0];
expect(url).toBe('/api/v1/certificates/mc-1/export/pem');
expect(result.cert_pem).toBe('CERT');
expect(result.full_pem).toBe('FULL');
});
// B-1 closure (cat-b-9b97ffb35ef7): exportCertificatePEM was removed
// from client.ts as a dead duplicate of downloadCertificatePEM.
it('downloadCertificatePEM fetches blob with download=true', async () => {
const mockBlob = new Blob(['pem-data'], { type: 'application/x-pem-file' });
+8 -3
View File
@@ -188,9 +188,14 @@ export const bulkReassignCertificates = (request: BulkReassignmentRequest) =>
});
// Certificate Export
export const exportCertificatePEM = (id: string) =>
fetchJSON<{ cert_pem: string; chain_pem: string; full_pem: string }>(`${BASE}/certificates/${id}/export/pem`);
//
// B-1 master closure (cat-b-9b97ffb35ef7): the previous `exportCertificatePEM`
// helper that returned `{cert_pem, chain_pem, full_pem}` JSON was removed —
// it had zero consumers across web/, MCP, CLI, and tests, and was a dead
// duplicate of `downloadCertificatePEM` which is the only call site that
// actually exists in `CertificateDetailPage` (browser file-download path).
// If a JSON variant is ever needed again, re-add an explicit fetcher with a
// page consumer in the same commit; do not resurrect the orphan.
export const downloadCertificatePEM = (id: string) => {
const headers: Record<string, string> = {};
if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
+1
View File
@@ -10,6 +10,7 @@ const nav = [
{ to: '/jobs', label: 'Jobs', icon: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15' },
{ to: '/notifications', label: 'Notifications', icon: 'M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9' },
{ to: '/policies', label: 'Policies', icon: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4' },
{ to: '/renewal-policies', label: 'Renewal Policies', icon: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15' },
{ to: '/profiles', label: 'Profiles', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z' },
{ to: '/issuers', label: 'Issuers', icon: 'M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z' },
{ to: '/targets', label: 'Targets', icon: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10' },
+2
View File
@@ -14,6 +14,7 @@ import AgentDetailPage from './pages/AgentDetailPage';
import JobsPage from './pages/JobsPage';
import NotificationsPage from './pages/NotificationsPage';
import PoliciesPage from './pages/PoliciesPage';
import RenewalPoliciesPage from './pages/RenewalPoliciesPage';
import IssuersPage from './pages/IssuersPage';
import TargetsPage from './pages/TargetsPage';
import ProfilesPage from './pages/ProfilesPage';
@@ -62,6 +63,7 @@ createRoot(document.getElementById('root')!).render(
<Route path="jobs/:id" element={<JobDetailPage />} />
<Route path="notifications" element={<NotificationsPage />} />
<Route path="policies" element={<PoliciesPage />} />
<Route path="renewal-policies" element={<RenewalPoliciesPage />} />
<Route path="profiles" element={<ProfilesPage />} />
<Route path="issuers" element={<IssuersPage />} />
<Route path="issuers/:id" element={<IssuerDetailPage />} />
+140 -8
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getAgentGroups, deleteAgentGroup, createAgentGroup } from '../api/client';
import { getAgentGroups, deleteAgentGroup, createAgentGroup, updateAgentGroup } from '../api/client';
import PageHeader from '../components/PageHeader';
import DataTable from '../components/DataTable';
import type { Column } from '../components/DataTable';
@@ -144,9 +144,115 @@ function CreateAgentGroupModal({ isOpen, onClose, onSuccess, isLoading, error }:
);
}
// EditAgentGroupModal — B-1 master closure (cat-b-31ceb6aaa9f1).
// Mirrors CreateAgentGroupModal; pre-populates from the editing group;
// calls updateAgentGroup(id, fields) to close the destructive-rename
// hazard. Membership-rule fields (match_os, match_architecture,
// match_ip_cidr, match_version) are editable like the rest — operators
// frequently want to widen/narrow group membership without recreating.
interface EditAgentGroupModalProps {
group: AgentGroup | null;
onClose: () => void;
onSuccess: () => void;
isLoading: boolean;
error: string | null;
}
function EditAgentGroupModal({ group, onClose, onSuccess, isLoading, error }: EditAgentGroupModalProps) {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [matchOs, setMatchOs] = useState('');
const [matchArch, setMatchArch] = useState('');
const [matchIpCidr, setMatchIpCidr] = useState('');
const [matchVersion, setMatchVersion] = useState('');
const [enabled, setEnabled] = useState(true);
useEffect(() => {
if (group) {
setName(group.name);
setDescription(group.description || '');
setMatchOs(group.match_os || '');
setMatchArch(group.match_architecture || '');
setMatchIpCidr(group.match_ip_cidr || '');
setMatchVersion(group.match_version || '');
setEnabled(group.enabled);
}
}, [group]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!group || !name.trim()) return;
await updateAgentGroup(group.id, {
name: name.trim(),
description: description.trim(),
match_os: matchOs.trim(),
match_architecture: matchArch.trim(),
match_ip_cidr: matchIpCidr.trim(),
match_version: matchVersion.trim(),
enabled,
});
onSuccess();
};
if (!group) return null;
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-ink mb-4">Edit Agent Group</h2>
<p className="text-xs text-ink-muted mb-4 font-mono">{group.id}</p>
{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)} required
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Description</label>
<textarea value={description} onChange={e => setDescription(e.target.value)} rows={2}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Match OS</label>
<input value={matchOs} onChange={e => setMatchOs(e.target.value)} placeholder="linux"
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Match Architecture</label>
<input value={matchArch} onChange={e => setMatchArch(e.target.value)} placeholder="amd64"
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Match IP CIDR</label>
<input value={matchIpCidr} onChange={e => setMatchIpCidr(e.target.value)} placeholder="10.0.0.0/24"
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Match Version</label>
<input value={matchVersion} onChange={e => setMatchVersion(e.target.value)} placeholder="v2.0.x"
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<label className="flex items-center gap-2 text-sm text-ink">
<input type="checkbox" checked={enabled} onChange={e => setEnabled(e.target.checked)} />
Enabled
</label>
<div className="flex gap-2 pt-4">
<button type="submit" disabled={isLoading} className="flex-1 btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
{isLoading ? 'Saving...' : 'Save Changes'}
</button>
<button type="button" onClick={onClose} className="flex-1 btn btn-ghost">Cancel</button>
</div>
</form>
</div>
</div>
);
}
export default function AgentGroupsPage() {
const queryClient = useQueryClient();
const [showCreate, setShowCreate] = useState(false);
const [editingGroup, setEditingGroup] = useState<AgentGroup | null>(null);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['agent-groups'],
@@ -166,6 +272,14 @@ export default function AgentGroupsPage() {
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<AgentGroup> }) => updateAgentGroup(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['agent-groups'] });
setEditingGroup(null);
},
});
const columns: Column<AgentGroup>[] = [
{
key: 'name',
@@ -214,12 +328,20 @@ export default function AgentGroupsPage() {
key: 'actions',
label: '',
render: (g) => (
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete group ${g.name}?`)) deleteMutation.mutate(g.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
<div className="flex gap-3 justify-end">
<button
onClick={(e) => { e.stopPropagation(); setEditingGroup(g); }}
className="text-xs text-brand-400 hover:text-brand-500 transition-colors"
>
Edit
</button>
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete group ${g.name}?`)) deleteMutation.mutate(g.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
</div>
),
},
];
@@ -252,6 +374,16 @@ export default function AgentGroupsPage() {
isLoading={createMutation.isPending}
error={createMutation.error ? (createMutation.error as Error).message : null}
/>
<EditAgentGroupModal
group={editingGroup}
onClose={() => setEditingGroup(null)}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ['agent-groups'] });
setEditingGroup(null);
}}
isLoading={updateMutation.isPending}
error={updateMutation.error ? (updateMutation.error as Error).message : null}
/>
</>
);
}
+114 -2
View File
@@ -1,7 +1,7 @@
import { useState, useMemo } from 'react';
import { useEffect, useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getIssuers, testIssuerConnection, deleteIssuer, createIssuer } from '../api/client';
import { getIssuers, testIssuerConnection, deleteIssuer, createIssuer, updateIssuer } from '../api/client';
import PageHeader from '../components/PageHeader';
import DataTable from '../components/DataTable';
import type { Column } from '../components/DataTable';
@@ -30,6 +30,18 @@ export default function IssuersPage() {
const [preselectedType, setPreselectedType] = useState<string | null>(null);
const [typeFilter, setTypeFilter] = useState<string>('');
const [configModal, setConfigModal] = useState<{ title: string; config: Record<string, unknown> } | null>(null);
// B-1 master closure (cat-b-7a34f893a8f9): rename-only Edit affordance.
// Pre-B-1 the only way to rename an issuer was delete-and-recreate,
// which destroyed cert provenance and forced a re-encryption cycle
// through internal/crypto/encryption.go for every cert under the
// issuer. Type and credential blob are intentionally NOT editable here
// — changing the underlying CA driver type would require
// re-encrypting config under a different schema, and credentials are
// stored encrypted at rest (we can't decrypt them client-side to
// pre-populate). Operators who need to rotate credentials still
// delete + recreate. Documented as a deferred follow-up in the L-1
// CHANGELOG entry.
const [editingIssuer, setEditingIssuer] = useState<Issuer | null>(null);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['issuers'],
@@ -57,6 +69,19 @@ export default function IssuersPage() {
},
});
// B-1 master closure: updateIssuer is wired to the rename-only Edit
// modal. Type and credential blob are NOT mutated here — see editingIssuer
// docblock above. Sends `{ name, type, config }` to satisfy the backend
// PUT contract (the handler decodes into a full domain.Issuer struct);
// type + config are preserved by reading them from the editing target.
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<Issuer> }) => updateIssuer(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['issuers'] });
setEditingIssuer(null);
},
});
const catalogStatus = useMemo(
() => getIssuerCatalogStatus(data?.data || []),
[data?.data]
@@ -129,6 +154,12 @@ export default function IssuersPage() {
>
Test
</button>
<button
onClick={(e) => { e.stopPropagation(); setEditingIssuer(i); }}
className="text-xs text-brand-400 hover:text-brand-500 transition-colors"
>
Edit
</button>
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete issuer ${i.name}?`)) deleteMutation.mutate(i.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
@@ -244,10 +275,91 @@ export default function IssuersPage() {
isSubmitting={createMutation.isPending}
/>
)}
{/* B-1 closure: EditIssuerModal — rename-only. */}
<EditIssuerModal
issuer={editingIssuer}
onClose={() => setEditingIssuer(null)}
onSave={(name) => {
if (!editingIssuer) return;
updateMutation.mutate({
id: editingIssuer.id,
data: {
name,
// Preserve type + config + enabled — the rename-only
// contract. Credential blob stays encrypted at rest.
type: editingIssuer.type,
config: editingIssuer.config,
enabled: editingIssuer.enabled,
},
});
}}
isSaving={updateMutation.isPending}
error={updateMutation.error ? (updateMutation.error as Error).message : null}
/>
</>
);
}
// ─── EditIssuerModal — rename-only Edit modal (B-1) ─────────────
//
// Locked: type, config (credentials), enabled. Editable: name only.
// The audit's "destructive rename workflow" complaint is specifically
// about renames; B-1 closes that hazard. Credential rotation still
// requires delete-and-recreate (see CHANGELOG B-1 known follow-ups).
interface EditIssuerModalProps {
issuer: Issuer | null;
onClose: () => void;
onSave: (name: string) => void;
isSaving: boolean;
error: string | null;
}
function EditIssuerModal({ issuer, onClose, onSave, isSaving, error }: EditIssuerModalProps) {
const [name, setName] = useState('');
useEffect(() => { if (issuer) setName(issuer.name); }, [issuer]);
if (!issuer) return null;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) return;
onSave(name.trim());
};
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-ink mb-4">Edit Issuer</h2>
<p className="text-xs text-ink-muted mb-4 font-mono">{issuer.id}</p>
{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)} required
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink-muted mb-1">Type (locked)</label>
<input value={issuer.type} disabled
className="w-full bg-surface-border/50 border border-surface-border rounded px-3 py-2 text-sm text-ink-muted font-mono" />
<p className="text-xs text-ink-faint mt-1">
To change issuer type or rotate credentials, delete and recreate.
See CHANGELOG B-1 known follow-ups.
</p>
</div>
<div className="flex gap-2 pt-4">
<button type="submit" disabled={isSaving} className="flex-1 btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
{isSaving ? 'Saving...' : 'Save Changes'}
</button>
<button type="button" onClick={onClose} className="flex-1 btn btn-ghost">Cancel</button>
</div>
</form>
</div>
</div>
);
}
// ─── Catalog Card ───────────────────────────────────────────────
interface CatalogCardProps {
+129 -8
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getOwners, getTeams, deleteOwner, createOwner } from '../api/client';
import { getOwners, getTeams, deleteOwner, createOwner, updateOwner } from '../api/client';
import PageHeader from '../components/PageHeader';
import DataTable from '../components/DataTable';
import type { Column } from '../components/DataTable';
@@ -102,9 +102,103 @@ function CreateOwnerModal({ isOpen, onClose, onSuccess, isLoading, error, teamsD
);
}
// EditOwnerModal — B-1 master closure (cat-b-31ceb6aaa9f1). Pre-B-1 the
// only way to rename an owner was delete-and-recreate, which destroyed
// audit history and broke every cert that referenced the old owner_id.
// Mirrors CreateOwnerModal shape; pre-populates from the editing owner;
// calls updateOwner(id, fields) instead of createOwner.
interface EditOwnerModalProps {
owner: Owner | null;
onClose: () => void;
onSuccess: () => void;
isLoading: boolean;
error: string | null;
teamsData?: { data: Team[] };
}
function EditOwnerModal({ owner, onClose, onSuccess, isLoading, error, teamsData }: EditOwnerModalProps) {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [teamId, setTeamId] = useState('');
// Reset form fields whenever the editing target changes (modal opens).
useEffect(() => {
if (owner) {
setName(owner.name);
setEmail(owner.email);
setTeamId(owner.team_id || '');
}
}, [owner]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!owner || !name.trim() || !email.trim()) return;
await updateOwner(owner.id, {
name: name.trim(),
email: email.trim(),
team_id: teamId || undefined,
});
onSuccess();
};
if (!owner) return null;
const teams = teamsData?.data || [];
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-ink mb-4">Edit Owner</h2>
<p className="text-xs text-ink-muted mb-4 font-mono">{owner.id}</p>
{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 text-ink focus:outline-none focus:border-brand-400"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Email *</label>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Team</label>
<select
value={teamId}
onChange={e => setTeamId(e.target.value)}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
>
<option value="">Unassigned</option>
{teams.map(team => (
<option key={team.id} value={team.id}>{team.name}</option>
))}
</select>
</div>
<div className="flex gap-2 pt-4">
<button type="submit" disabled={isLoading} className="flex-1 btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
{isLoading ? 'Saving...' : 'Save Changes'}
</button>
<button type="button" onClick={onClose} className="flex-1 btn btn-ghost">Cancel</button>
</div>
</form>
</div>
</div>
);
}
export default function OwnersPage() {
const queryClient = useQueryClient();
const [showCreate, setShowCreate] = useState(false);
const [editingOwner, setEditingOwner] = useState<Owner | null>(null);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['owners'],
@@ -130,6 +224,14 @@ export default function OwnersPage() {
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<Owner> }) => updateOwner(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['owners'] });
setEditingOwner(null);
},
});
const teamMap = new Map<string, Team>();
(teamsData?.data || []).forEach((t) => teamMap.set(t.id, t));
@@ -168,12 +270,20 @@ export default function OwnersPage() {
key: 'actions',
label: '',
render: (o) => (
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete owner ${o.name}?`)) deleteMutation.mutate(o.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
<div className="flex gap-3 justify-end">
<button
onClick={(e) => { e.stopPropagation(); setEditingOwner(o); }}
className="text-xs text-brand-400 hover:text-brand-500 transition-colors"
>
Edit
</button>
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete owner ${o.name}?`)) deleteMutation.mutate(o.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
</div>
),
},
];
@@ -207,6 +317,17 @@ export default function OwnersPage() {
error={createMutation.error ? (createMutation.error as Error).message : null}
teamsData={teamsData}
/>
<EditOwnerModal
owner={editingOwner}
onClose={() => setEditingOwner(null)}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ['owners'] });
setEditingOwner(null);
}}
isLoading={updateMutation.isPending}
error={updateMutation.error ? (updateMutation.error as Error).message : null}
teamsData={teamsData}
/>
</>
);
}
+119 -8
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getProfiles, deleteProfile, createProfile } from '../api/client';
import { getProfiles, deleteProfile, createProfile, updateProfile } from '../api/client';
import PageHeader from '../components/PageHeader';
import DataTable from '../components/DataTable';
import type { Column } from '../components/DataTable';
@@ -288,6 +288,12 @@ function CreateProfileModal({ isOpen, onClose, onSuccess, isLoading, error }: Cr
export default function ProfilesPage() {
const queryClient = useQueryClient();
const [showCreate, setShowCreate] = useState(false);
// B-1 master closure (cat-b-7a34f893a8f9): rename + description Edit
// affordance. Deeper policy fields (allowed_ekus, max_ttl_seconds,
// allowed_key_algorithms, etc.) stay on the delete-and-recreate path
// for v1 — closing the audit's destructive-rename complaint requires
// only the simple metadata edit. Documented as a follow-up.
const [editingProfile, setEditingProfile] = useState<CertificateProfile | null>(null);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['profiles'],
@@ -307,6 +313,14 @@ export default function ProfilesPage() {
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<CertificateProfile> }) => updateProfile(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['profiles'] });
setEditingProfile(null);
},
});
const columns: Column<CertificateProfile>[] = [
{
key: 'name',
@@ -382,12 +396,20 @@ export default function ProfilesPage() {
key: 'actions',
label: '',
render: (p) => (
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete profile ${p.name}?`)) deleteMutation.mutate(p.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
<div className="flex gap-3 justify-end">
<button
onClick={(e) => { e.stopPropagation(); setEditingProfile(p); }}
className="text-xs text-brand-400 hover:text-brand-500 transition-colors"
>
Edit
</button>
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete profile ${p.name}?`)) deleteMutation.mutate(p.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
</div>
),
},
];
@@ -420,6 +442,95 @@ export default function ProfilesPage() {
isLoading={createMutation.isPending}
error={createMutation.error ? (createMutation.error as Error).message : null}
/>
<EditProfileModal
profile={editingProfile}
onClose={() => setEditingProfile(null)}
onSave={(data) => {
if (!editingProfile) return;
updateMutation.mutate({ id: editingProfile.id, data });
}}
isSaving={updateMutation.isPending}
error={updateMutation.error ? (updateMutation.error as Error).message : null}
/>
</>
);
}
// EditProfileModal — B-1 closure (cat-b-7a34f893a8f9). Rename +
// description only. Deeper policy fields (allowed_ekus, max_ttl_seconds,
// allowed_key_algorithms, required_san_patterns, spiffe_uri_pattern,
// allow_short_lived) stay on delete-and-recreate for v1 — closing the
// audit's destructive-rename complaint requires only the simple
// metadata edit. The PUT contract takes a full Partial<CertificateProfile>
// so we forward the existing policy fields untouched.
interface EditProfileModalProps {
profile: CertificateProfile | null;
onClose: () => void;
onSave: (data: Partial<CertificateProfile>) => void;
isSaving: boolean;
error: string | null;
}
function EditProfileModal({ profile, onClose, onSave, isSaving, error }: EditProfileModalProps) {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
useEffect(() => {
if (profile) {
setName(profile.name);
setDescription(profile.description || '');
}
}, [profile]);
if (!profile) return null;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) return;
onSave({
// Pass the full struct minus id/timestamps. Backend PUT needs the
// policy fields preserved so we forward them from the editing target.
name: name.trim(),
description: description.trim(),
allowed_key_algorithms: profile.allowed_key_algorithms,
max_ttl_seconds: profile.max_ttl_seconds,
allowed_ekus: profile.allowed_ekus,
required_san_patterns: profile.required_san_patterns,
spiffe_uri_pattern: profile.spiffe_uri_pattern,
allow_short_lived: profile.allow_short_lived,
enabled: profile.enabled,
});
};
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-ink mb-4">Edit Profile</h2>
<p className="text-xs text-ink-muted mb-4 font-mono">{profile.id}</p>
{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)} required
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Description</label>
<textarea value={description} onChange={e => setDescription(e.target.value)} rows={2}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<p className="text-xs text-ink-faint">
Policy fields (TTL, EKUs, key algorithms, SAN patterns) stay on the
create-recreate path for v1. See CHANGELOG B-1 known follow-ups.
</p>
<div className="flex gap-2 pt-4">
<button type="submit" disabled={isSaving} className="flex-1 btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
{isSaving ? 'Saving...' : 'Save Changes'}
</button>
<button type="button" onClick={onClose} className="flex-1 btn btn-ghost">Cancel</button>
</div>
</form>
</div>
</div>
);
}
+327
View File
@@ -0,0 +1,327 @@
import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
getRenewalPolicies,
createRenewalPolicy,
updateRenewalPolicy,
deleteRenewalPolicy,
} 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 { RenewalPolicy } from '../api/types';
// RenewalPoliciesPage — B-1 master closure (cat-b-4631ca092bee).
// Pre-B-1 the backend had full CRUD at /api/v1/renewal-policies but
// there was no GUI page. Operators wanting to edit the seeded
// `rp-default` policy or create custom `rp-*` policies for short-lived
// certs had to go through `psql` directly. This page exposes the table
// + Create + Edit + Delete affordances. Renewal policies are referenced
// by managed certificates via `renewal_policy_id`; the backend's
// repository.ErrRenewalPolicyInUse sentinel surfaces a 409 on Delete
// when a policy still has cert references — surfaced as an alert here.
//
// Field set per `internal/domain/certificate.go::RenewalPolicy`:
// - renewal_window_days: int (when to start renewal — usually 30)
// - auto_renew: bool (whether the scheduler renews automatically)
// - max_retries: int
// - retry_interval_seconds: int (post-U-3 column rename;
// cat-o-retry_interval_unit_mismatch closed)
// - alert_thresholds_days: int[] (notification days before expiry)
interface PolicyFormFields {
name: string;
renewal_window_days: number;
auto_renew: boolean;
max_retries: number;
retry_interval_seconds: number;
alert_thresholds_days: number[];
}
function defaultFields(): PolicyFormFields {
return {
name: '',
renewal_window_days: 30,
auto_renew: true,
max_retries: 3,
retry_interval_seconds: 60,
alert_thresholds_days: [30, 14, 7, 0],
};
}
function policyToFields(p: RenewalPolicy): PolicyFormFields {
return {
name: p.name,
renewal_window_days: p.renewal_window_days,
auto_renew: p.auto_renew,
max_retries: p.max_retries,
retry_interval_seconds: p.retry_interval_seconds,
alert_thresholds_days: p.alert_thresholds_days || [],
};
}
// PolicyFormModal — shared scaffolding for Create + Edit. The only
// shape difference between the two flows is which mutationFn the
// caller supplies + the modal title; everything else mirrors.
interface PolicyFormModalProps {
title: string;
initial: PolicyFormFields;
isOpen: boolean;
onClose: () => void;
onSubmit: (fields: PolicyFormFields) => void;
isSaving: boolean;
error: string | null;
}
function PolicyFormModal({ title, initial, isOpen, onClose, onSubmit, isSaving, error }: PolicyFormModalProps) {
const [fields, setFields] = useState<PolicyFormFields>(initial);
useEffect(() => {
if (isOpen) setFields(initial);
}, [isOpen, initial]);
if (!isOpen) return null;
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!fields.name.trim()) return;
onSubmit({ ...fields, name: fields.name.trim() });
};
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-ink mb-4">{title}</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={fields.name}
onChange={e => setFields({ ...fields, name: e.target.value })}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
placeholder="e.g., Standard 30-day"
required
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-ink mb-1">Renewal Window (days)</label>
<input
type="number"
value={fields.renewal_window_days}
onChange={e => setFields({ ...fields, renewal_window_days: Number(e.target.value) })}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
min={1}
/>
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Max Retries</label>
<input
type="number"
value={fields.max_retries}
onChange={e => setFields({ ...fields, max_retries: Number(e.target.value) })}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
min={0}
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Retry Interval (seconds)</label>
<input
type="number"
value={fields.retry_interval_seconds}
onChange={e => setFields({ ...fields, retry_interval_seconds: Number(e.target.value) })}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
min={0}
/>
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Alert Thresholds (days, comma-separated)</label>
<input
value={fields.alert_thresholds_days.join(', ')}
onChange={e => {
const parts = e.target.value
.split(',')
.map(s => Number(s.trim()))
.filter(n => !isNaN(n));
setFields({ ...fields, alert_thresholds_days: parts });
}}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400"
placeholder="30, 14, 7, 0"
/>
</div>
<label className="flex items-center gap-2 text-sm text-ink">
<input
type="checkbox"
checked={fields.auto_renew}
onChange={e => setFields({ ...fields, auto_renew: e.target.checked })}
/>
Auto-renew
</label>
<div className="flex gap-2 pt-4">
<button type="submit" disabled={isSaving} className="flex-1 btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
{isSaving ? 'Saving...' : 'Save'}
</button>
<button type="button" onClick={onClose} className="flex-1 btn btn-ghost">Cancel</button>
</div>
</form>
</div>
</div>
);
}
export default function RenewalPoliciesPage() {
const queryClient = useQueryClient();
const [showCreate, setShowCreate] = useState(false);
const [editing, setEditing] = useState<RenewalPolicy | null>(null);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['renewal-policies'],
queryFn: () => getRenewalPolicies(),
});
const createMutation = useMutation({
mutationFn: createRenewalPolicy,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['renewal-policies'] });
setShowCreate(false);
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<RenewalPolicy> }) => updateRenewalPolicy(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['renewal-policies'] });
setEditing(null);
},
});
const deleteMutation = useMutation({
mutationFn: deleteRenewalPolicy,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['renewal-policies'] }),
// Backend surfaces ErrRenewalPolicyInUse as a 409. We surface as an
// alert so the operator sees "this policy is still attached to N
// certificates" and can re-target those certs to another policy
// before deleting.
onError: (err: Error) => alert(`Delete failed: ${err.message}`),
});
const columns: Column<RenewalPolicy>[] = [
{
key: 'name',
label: 'Policy',
render: (p) => (
<div>
<div className="font-medium text-ink">{p.name}</div>
<div className="text-xs text-ink-faint font-mono">{p.id}</div>
</div>
),
},
{
key: 'window',
label: 'Renewal Window',
render: (p) => <span className="text-sm text-ink">{p.renewal_window_days} days</span>,
},
{
key: 'auto_renew',
label: 'Auto',
render: (p) => (
<span className={p.auto_renew ? 'text-brand-400' : 'text-ink-faint'}>
{p.auto_renew ? 'on' : 'manual'}
</span>
),
},
{
key: 'retries',
label: 'Retries',
render: (p) => <span className="text-sm text-ink-muted">{p.max_retries}× / {p.retry_interval_seconds}s</span>,
},
{
key: 'alerts',
label: 'Alert Thresholds',
render: (p) => (
<span className="text-xs text-ink-muted font-mono">
{(p.alert_thresholds_days || []).join(', ') || '—'}
</span>
),
},
{
key: 'created',
label: 'Created',
render: (p) => <span className="text-xs text-ink-muted">{formatDateTime(p.created_at)}</span>,
},
{
key: 'actions',
label: '',
render: (p) => (
<div className="flex gap-3 justify-end">
<button
onClick={(e) => { e.stopPropagation(); setEditing(p); }}
className="text-xs text-brand-400 hover:text-brand-500 transition-colors"
>
Edit
</button>
<button
onClick={(e) => {
e.stopPropagation();
if (confirm(`Delete renewal policy ${p.name}?`)) deleteMutation.mutate(p.id);
}}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
</div>
),
},
];
return (
<>
<PageHeader
title="Renewal Policies"
subtitle={data ? `${data.total} policies` : undefined}
action={
<button onClick={() => setShowCreate(true)} className="btn btn-primary">
+ New Policy
</button>
}
/>
<div className="flex-1 overflow-y-auto">
{error ? (
<ErrorState error={error as Error} onRetry={() => refetch()} />
) : (
<DataTable
columns={columns}
data={data?.data || []}
isLoading={isLoading}
emptyMessage="No renewal policies configured"
/>
)}
</div>
<PolicyFormModal
title="Create Renewal Policy"
initial={defaultFields()}
isOpen={showCreate}
onClose={() => setShowCreate(false)}
onSubmit={(fields) => createMutation.mutate(fields)}
isSaving={createMutation.isPending}
error={createMutation.error ? (createMutation.error as Error).message : null}
/>
<PolicyFormModal
title="Edit Renewal Policy"
initial={editing ? policyToFields(editing) : defaultFields()}
isOpen={!!editing}
onClose={() => setEditing(null)}
onSubmit={(fields) => {
if (!editing) return;
updateMutation.mutate({ id: editing.id, data: fields });
}}
isSaving={updateMutation.isPending}
error={updateMutation.error ? (updateMutation.error as Error).message : null}
/>
</>
);
}
+95 -8
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getTeams, deleteTeam, createTeam } from '../api/client';
import { getTeams, deleteTeam, createTeam, updateTeam } from '../api/client';
import PageHeader from '../components/PageHeader';
import DataTable from '../components/DataTable';
import type { Column } from '../components/DataTable';
@@ -82,9 +82,70 @@ function CreateTeamModal({ isOpen, onClose, onSuccess, isLoading, error }: Creat
);
}
// EditTeamModal — B-1 master closure (cat-b-31ceb6aaa9f1). Mirrors
// CreateTeamModal; pre-populates from the editing team; calls
// updateTeam(id, fields) to close the destructive-rename hazard.
interface EditTeamModalProps {
team: Team | null;
onClose: () => void;
onSuccess: () => void;
isLoading: boolean;
error: string | null;
}
function EditTeamModal({ team, onClose, onSuccess, isLoading, error }: EditTeamModalProps) {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
useEffect(() => {
if (team) {
setName(team.name);
setDescription(team.description || '');
}
}, [team]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!team || !name.trim()) return;
await updateTeam(team.id, { name: name.trim(), description: description.trim() });
onSuccess();
};
if (!team) return null;
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-surface border border-surface-border rounded p-5 w-full max-w-md shadow-xl" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-ink mb-4">Edit Team</h2>
<p className="text-xs text-ink-muted mb-4 font-mono">{team.id}</p>
{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)} required
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div>
<label className="block text-sm font-medium text-ink mb-1">Description</label>
<textarea value={description} onChange={e => setDescription(e.target.value)} rows={2}
className="w-full bg-white border border-surface-border rounded px-3 py-2 text-sm text-ink focus:outline-none focus:border-brand-400" />
</div>
<div className="flex gap-2 pt-4">
<button type="submit" disabled={isLoading} className="flex-1 btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
{isLoading ? 'Saving...' : 'Save Changes'}
</button>
<button type="button" onClick={onClose} className="flex-1 btn btn-ghost">Cancel</button>
</div>
</form>
</div>
</div>
);
}
export default function TeamsPage() {
const queryClient = useQueryClient();
const [showCreate, setShowCreate] = useState(false);
const [editingTeam, setEditingTeam] = useState<Team | null>(null);
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['teams'],
@@ -105,6 +166,14 @@ export default function TeamsPage() {
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<Team> }) => updateTeam(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams'] });
setEditingTeam(null);
},
});
const columns: Column<Team>[] = [
{
key: 'name',
@@ -132,12 +201,20 @@ export default function TeamsPage() {
key: 'actions',
label: '',
render: (t) => (
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete team ${t.name}?`)) deleteMutation.mutate(t.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
<div className="flex gap-3 justify-end">
<button
onClick={(e) => { e.stopPropagation(); setEditingTeam(t); }}
className="text-xs text-brand-400 hover:text-brand-500 transition-colors"
>
Edit
</button>
<button
onClick={(e) => { e.stopPropagation(); if (confirm(`Delete team ${t.name}?`)) deleteMutation.mutate(t.id); }}
className="text-xs text-red-600 hover:text-red-700 transition-colors"
>
Delete
</button>
</div>
),
},
];
@@ -170,6 +247,16 @@ export default function TeamsPage() {
isLoading={createMutation.isPending}
error={createMutation.error ? (createMutation.error as Error).message : null}
/>
<EditTeamModal
team={editingTeam}
onClose={() => setEditingTeam(null)}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ['teams'] });
setEditingTeam(null);
}}
isLoading={updateMutation.isPending}
error={updateMutation.error ? (updateMutation.error as Error).message : null}
/>
</>
);
}