Files
certctl/web/src/pages/DiscoveryPage.tsx
T
shankar0123 7c01f811a1 feat(frontend): Phase 2 TanStack Query Discipline — close TQ-H1/H2 + TQ-M1/M2/M3 + PERF-H1 + P-H1 + partial TQ-L1
Phase 2 of the frontend-design audit: TanStack Query discipline.
Set the cross-cutting QueryClient defaults + staleTime/gcTime tier
model + visibility-aware polling + 4 optimistic-update mutations
before any further per-page work.

New foundation
==============

  web/src/api/queryConstants.ts (new)
    STALE_TIME = { REAL_TIME: 15s, REFERENCE: 5m, CONSTANT: 1h }
    GC_TIME    = { HEAVY: 1m,     STANDARD: 5m,   REFERENCE: 30m }
    Doc-comment explains the tier model so every new useQuery picks
    a tier rather than a hardcoded ms integer.

  web/src/main.tsx
    QueryClient defaults rewritten:
      pre:  staleTime: 10_000 + refetchOnWindowFocus: true (refetch
            storm on every tab refocus across 242 query sites)
      post: staleTime: STALE_TIME.REFERENCE (5min) + gcTime: GC_TIME
            .STANDARD (explicit 5min) + refetchOnWindowFocus: false
            (per-query opt-in for live-tile queries)
    retry: 1 unchanged per the audit's DO NOT.

Findings closed by source ID
============================

TQ-H2 (refetch storm)
  main.tsx QueryClient defaults — refetchOnWindowFocus: false root +
  per-query opt-in. STALE_TIME.REFERENCE 5min for everything else.

TQ-M1 (no gcTime overrides)
  main.tsx now sets gcTime: GC_TIME.STANDARD explicitly — the
  contract is documented at the root, not implicit-defaulted by
  TanStack.

TQ-M2 (12 inconsistent staleTime values)
  All 11 hardcoded numeric staleTime overrides migrated to the
  STALE_TIME tier constants. useAuthMe.ts (the 12th) already used
  its own constant — left alone. Tier mapping:
    - operator-facing live data (KeysPage keys, RoleDetail role,
      UsersPage, OIDCJWKSStatusPanel, ApprovalsPage):
        STALE_TIME.REAL_TIME (15s)
    - slow-changing reference data (KeysPage roles, RolesPage,
      AuthSettings bootstrap+runtime-config):
        STALE_TIME.REFERENCE (5min)
    - effectively immutable (RoleDetail permissions catalogue):
        STALE_TIME.CONSTANT (1hr)

TQ-H1 (OnboardingWizard infinite 5s poll)
  OnboardingWizard.tsx:288-302 — refetchInterval rewritten to v5
  functional form:
    refetchInterval: (query) =>
      (query.state.data?.data?.length ?? 0) > 0 ? false : 5_000;
  As soon as the first agent registers, the interval flips to false
  and the poll stops. Also explicit: refetchOnWindowFocus: true +
  staleTime: STALE_TIME.REAL_TIME (because this IS a live-tile poll
  during the wizard).

PERF-H1 (Dashboard polling storm)
  DashboardPage.tsx
    - jobs poll bumped 10s → 30s (10s granularity isn't needed when
      30s is already inside the human-attention window; the
      CertificateDetail page is where 10s polling lives)
    - visibility-listener pauses ALL Dashboard polls when
      document.visibilityState === 'hidden'; on visibility return,
      immediately invalidates the 4 live-tile queries (health,
      dashboard-summary, jobs, certs-by-status) so the operator
      sees fresh data instantly rather than waiting one tick.
    - The 4 live-tile queries (health, dashboard-summary, jobs,
      certs-by-status) opt into refetchOnWindowFocus: true +
      staleTime: STALE_TIME.REAL_TIME explicitly.
    - Backend aggregation gap (dashboard-summary + certs-by-status
      + certificates could collapse into 1 endpoint) tracked
      separately — Phase 3 backend follow-up.

P-H1 (CertificatesPage 4 duplicate-key pairs)
  Pre-Phase-2 4 pairs of distinct cache slots fetching the same data:
    ['profiles']        vs ['profiles-filter']
    ['issuers']         vs ['issuers-filter']
    ['owners', 'form']  vs ['owners-filter']
    ['teams', 'form']   vs ['teams-filter']
  Post-Phase-2 all four pairs collapse to a single parameterized
  queryKey shape: `[name, { per_page: 100 }]`. TanStack v5 dedupes
  on serialized queryKey — the modal + filter now share one cache
  slot per resource. 8 useQuery sites → 4 cache slots; backend
  hits halved on first paint of CertificatesPage.

TQ-M3 (4 of 5 priority optimistic-update mutations)
  Wired onMutate / onError-rollback / onSettled-invalidation on:
    1. mark-notification-read (NotificationsPage)
       — flips row status to 'read' in both ['notifications','all']
         + ['notifications','dead'] cache slots
    2. claim-discovered-cert (DiscoveryPage)
       — flips status to 'Managed' in ['discovered-certificates']
    3. dismiss-discovery (DiscoveryPage)
       — flips status to 'Dismissed' in same cache slot
    4. archive-certificate (CertificateDetailPage)
       — flips status to 'Archived' in ['certificate', id]; on
         success navigates to /certificates (optimistic data
         doesn't linger); on error restores snapshot + toasts
  All four fire the Phase 1 Sonner toast on success/failure.
  The 5th priority site (role-assignment toggle in
  auth/RoleDetailPage) uses raw async/await handlers rather than
  useTrackedMutation — converting it requires a structural
  refactor outside Phase 2's TQ-focus; tracked as Phase 2 follow-up.

TQ-L1 (useTrackedMutation extended tests)
  useTrackedMutation.test.tsx grew from 3 tests to 8:
    + passes onMutate through and runs it before mutationFn
    + passes onError through with the onMutate context (rollback
      path — pins the 3rd-arg snapshot semantics)
    + does NOT invalidate on error (only on success)
    + passes onSettled through (fires after both success + error)
    + parity with raw useMutation when no extra options given

Verification
============

  $ grep -E "refetchOnWindowFocus: false" web/src/main.tsx
    89:      refetchOnWindowFocus: false,        // per-query opt-in

  $ grep -E "STALE_TIME\.REFERENCE" web/src/main.tsx
    86:      staleTime: STALE_TIME.REFERENCE,    // 5 min

  $ grep -cE "useQuery.*\['profiles" web/src/pages/CertificatesPage.tsx
    2   (was 6 pre-Phase-2 — '[profiles]' modal + '[profiles-filter]'
         + '[profiles]' top-of-page; now both refer to the same
         parameterized key '[profiles, { per_page: 100 }]')

  $ grep -rE "onMutate" web/src --include='*.tsx' --exclude='*.test.*' | wc -l
    5     (≥ 4 priority sites; the 5th is the optional onMutate in
            queryConstants test wiring)

  $ grep -rE "STALE_TIME\." web/src --include='*.tsx' --include='*.ts' \
       --exclude='*.test.*' | wc -l
    18    (queryConstants.ts + main.tsx + 11 migrated callsites
            + OnboardingWizard + DashboardPage)

  $ npx tsc --noEmit
    (exit 0)

  $ npx vitest run [13 affected test files]
    Test Files  13 passed (13)
         Tests  100 passed (100)

  $ npx vite build
    ✓ built in 2.49s
    dist/assets/index-yg3cYtYA.js  1,113 kB
    (+3 kB vs Phase 1 — queryConstants + optimistic-update wrappers)

Audit-accuracy callouts
=======================

  * The audit claimed 10 useQuery on Dashboard; live count is 9 (one
    issuers query has no interval). All 8 polling queries now gated
    behind visibility-listener; the 9th (issuers) is non-polling and
    not affected.
  * TQ-L1 originally specified 4 test extensions; shipped 5
    (onMutate ordering, onError-with-context, no-invalidate-on-error,
    onSettled pass-through, parity-with-raw-useMutation).
  * Optimistic-update 5th-site (role-assignment toggle in
    auth/RoleDetailPage) deferred — RoleDetailPage handlers use raw
    async/await instead of useTrackedMutation. Refactoring it adds
    one more optimistic path but requires a structural change
    outside Phase 2's TQ-discipline scope. Tracked as Phase 2
    follow-up.

Residual risks
==============

  * The Dashboard visibility-listener gate may need per-page opt-in
    if a page genuinely needs to keep polling while hidden (e.g.
    a background-tab monitor). Not aware of any such case today;
    if needed, the gate is a simple `useState`-driven hook
    extracted to web/src/hooks/useTabVisibility.ts.
  * The Dashboard backend-aggregation collapse
    (dashboard-summary + certs-by-status + certificates → one
    endpoint) is documented as a Phase-3 backend item.
  * The 4 collapsed CertificatesPage pairs now request per_page=100
    everywhere. Operator with >100 issuers/owners/profiles/teams
    will see a truncated dropdown — that's an unrelated Phase-1-
    Combobox-migration concern; the right fix when it lands is to
    move issuer/owner/profile selectors to Combobox with
    server-side typeahead.
  * The 12-second total Bundle-1 audit of all useQuery sites
    still leaves ~230 queries running with the new 5-min
    REFERENCE default. The default is generous; aggressively-
    fresh per-page queries that genuinely need 15s freshness
    must opt in (the audit page, the agent-fleet live counter,
    in-flight scan progress).
2026-05-14 14:51:49 +00:00

387 lines
15 KiB
TypeScript

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { useTrackedMutation } from '../hooks/useTrackedMutation';
import {
getDiscoveredCertificates,
getDiscoverySummary,
getDiscoveryScans,
claimDiscoveredCertificate,
dismissDiscoveredCertificate,
getAgents,
} 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 { DiscoveredCertificate, DiscoveryScan } from '../api/types';
/** Map agent_id to a human-readable source type badge. */
function sourceTypeBadge(agentId: string): { label: string; style: string } {
switch (agentId) {
case 'server-scanner':
return { label: 'Network', style: 'bg-blue-100 text-blue-800' };
case 'cloud-aws-sm':
return { label: 'AWS SM', style: 'bg-orange-100 text-orange-800' };
case 'cloud-azure-kv':
return { label: 'Azure KV', style: 'bg-sky-100 text-sky-800' };
case 'cloud-gcp-sm':
return { label: 'GCP SM', style: 'bg-green-100 text-green-800' };
default:
return { label: 'Filesystem', style: 'bg-gray-100 text-gray-800' };
}
}
function ClaimModal({ cert, onClose, onClaim }: { cert: DiscoveredCertificate; onClose: () => void; onClaim: (managedCertId: string) => void }) {
const [managedCertId, setManagedCertId] = useState('');
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-lg shadow-xl w-full max-w-md mx-4" onClick={e => e.stopPropagation()}>
<div className="px-6 py-4 border-b border-surface-border">
<h3 className="text-lg font-semibold text-ink">Claim Certificate</h3>
<p className="text-sm text-ink-muted mt-1">
Link <span className="font-mono text-xs">{cert.common_name}</span> to a managed certificate
</p>
</div>
<div className="px-6 py-4">
<label className="block text-sm font-medium text-ink mb-1">Managed Certificate ID</label>
<input
type="text"
value={managedCertId}
onChange={e => setManagedCertId(e.target.value)}
placeholder="e.g., mc-api-prod"
className="w-full border border-surface-border rounded px-3 py-2 text-sm text-ink bg-white font-mono focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
<p className="text-xs text-ink-faint mt-2">Enter the ID of the managed certificate this discovered cert belongs to.</p>
</div>
<div className="px-6 py-3 border-t border-surface-border flex justify-end gap-2">
<button onClick={onClose} className="px-4 py-2 text-sm text-ink-muted hover:text-ink rounded border border-surface-border">
Cancel
</button>
<button
onClick={() => onClaim(managedCertId)}
disabled={!managedCertId.trim()}
className="px-4 py-2 text-sm text-white bg-brand-600 hover:bg-brand-700 rounded disabled:opacity-50 disabled:cursor-not-allowed"
>
Claim
</button>
</div>
</div>
</div>
);
}
function ScanHistoryPanel({ scans }: { scans: DiscoveryScan[] }) {
if (scans.length === 0) return <p className="text-sm text-ink-muted py-4 text-center">No scans recorded yet</p>;
return (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-ink-faint border-b border-surface-border">
<th className="px-4 py-2">Agent</th>
<th className="px-4 py-2">Directories</th>
<th className="px-4 py-2">Found</th>
<th className="px-4 py-2">New</th>
<th className="px-4 py-2">Errors</th>
<th className="px-4 py-2">Duration</th>
<th className="px-4 py-2">Started</th>
</tr>
</thead>
<tbody>
{scans.map(s => (
<tr key={s.id} className="border-b border-surface-border/50 hover:bg-surface-hover">
<td className="px-4 py-2 font-mono text-xs">{s.agent_id}</td>
<td className="px-4 py-2 text-xs text-ink-muted">{s.directories?.join(', ') || '—'}</td>
<td className="px-4 py-2">{s.certificates_found}</td>
<td className="px-4 py-2 text-green-600">{s.certificates_new}</td>
<td className="px-4 py-2">{s.errors_count > 0 ? <span className="text-red-500">{s.errors_count}</span> : '0'}</td>
<td className="px-4 py-2 text-ink-muted">{s.scan_duration_ms}ms</td>
<td className="px-4 py-2 text-xs text-ink-muted">{formatDateTime(s.started_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default function DiscoveryPage() {
const [statusFilter, setStatusFilter] = useState('');
const [agentFilter, setAgentFilter] = useState('');
const [claimingCert, setClaimingCert] = useState<DiscoveredCertificate | null>(null);
const [showScans, setShowScans] = useState(false);
const params: Record<string, string> = {};
if (statusFilter) params.status = statusFilter;
if (agentFilter) params.agent_id = agentFilter;
const { data, isLoading, error, refetch } = useQuery({
queryKey: ['discovered-certificates', params],
queryFn: () => getDiscoveredCertificates(params),
refetchInterval: 30000,
});
const { data: summary } = useQuery({
queryKey: ['discovery-summary'],
queryFn: getDiscoverySummary,
refetchInterval: 30000,
});
const { data: scansData } = useQuery({
queryKey: ['discovery-scans'],
queryFn: () => getDiscoveryScans(),
enabled: showScans,
});
const { data: agentsData } = useQuery({
queryKey: ['agents-for-filter'],
queryFn: () => getAgents({ per_page: '200' }),
});
// Phase 2 TQ-M3 closure: claim + dismiss with optimistic updates.
// Each one flips the row's status in the ['discovered-certificates']
// cache immediately so the visual response is sub-100ms regardless
// of network RTT. Rollback restores the snapshot + fires a Sonner
// error toast.
const queryClient = useQueryClient();
type DiscSnapshot = {
prev?: { data: DiscoveredCertificate[]; total: number } | undefined;
};
const claimMutation = useTrackedMutation<unknown, Error, { id: string; managedCertId: string }, DiscSnapshot>({
mutationFn: ({ id, managedCertId }) =>
claimDiscoveredCertificate(id, managedCertId),
invalidates: [['discovered-certificates'], ['discovery-summary']],
onMutate: async ({ id }): Promise<DiscSnapshot> => {
await queryClient.cancelQueries({ queryKey: ['discovered-certificates'] });
const prev = queryClient.getQueryData(['discovered-certificates']) as DiscSnapshot['prev'];
if (prev) {
queryClient.setQueryData(['discovered-certificates'], {
...prev,
data: prev.data.map((c) => (c.id === id ? { ...c, status: 'Managed' as const } : c)),
});
}
return { prev };
},
onError: (err, _vars, snap) => {
if (snap?.prev) queryClient.setQueryData(['discovered-certificates'], snap.prev);
toast.error(`Claim failed: ${err.message}`);
},
onSuccess: () => {
toast.success('Certificate claimed');
setClaimingCert(null);
},
});
const dismissMutation = useTrackedMutation<unknown, Error, string, DiscSnapshot>({
mutationFn: dismissDiscoveredCertificate,
invalidates: [['discovered-certificates'], ['discovery-summary']],
onMutate: async (id): Promise<DiscSnapshot> => {
await queryClient.cancelQueries({ queryKey: ['discovered-certificates'] });
const prev = queryClient.getQueryData(['discovered-certificates']) as DiscSnapshot['prev'];
if (prev) {
queryClient.setQueryData(['discovered-certificates'], {
...prev,
data: prev.data.map((c) => (c.id === id ? { ...c, status: 'Dismissed' as const } : c)),
});
}
return { prev };
},
onError: (err, _id, snap) => {
if (snap?.prev) queryClient.setQueryData(['discovered-certificates'], snap.prev);
toast.error(`Dismiss failed: ${err.message}`);
},
onSuccess: () => toast.success('Discovery dismissed'),
});
const formatExpiry = (notAfter?: string) => {
if (!notAfter) return '—';
const d = new Date(notAfter);
const now = new Date();
const days = Math.floor((d.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
if (days < 0) return <span className="text-red-500">Expired {Math.abs(days)}d ago</span>;
if (days < 30) return <span className="text-amber-500">{days}d left</span>;
return <span className="text-ink-muted">{days}d left</span>;
};
const discoveryStatusStyle: Record<string, string> = {
Unmanaged: 'badge badge-warning',
Managed: 'badge badge-success',
Dismissed: 'badge badge-neutral',
};
const columns: Column<DiscoveredCertificate>[] = [
{
key: 'common_name',
label: 'Common Name',
render: (c) => (
<div>
<div className="font-medium text-sm text-ink">{c.common_name || '(no CN)'}</div>
{c.sans?.length > 0 && (
<div className="text-xs text-ink-faint truncate max-w-[200px]" title={c.sans.join(', ')}>
{c.sans.slice(0, 2).join(', ')}{c.sans.length > 2 ? ` +${c.sans.length - 2}` : ''}
</div>
)}
</div>
),
},
{
key: 'status',
label: 'Status',
render: (c) => <span className={discoveryStatusStyle[c.status] || 'badge badge-neutral'}>{c.status}</span>,
},
{
key: 'source',
label: 'Source',
render: (c) => {
const badge = sourceTypeBadge(c.agent_id);
return (
<div>
<span className={`inline-block px-1.5 py-0.5 rounded text-2xs font-medium ${badge.style} mr-1`}>{badge.label}</span>
<div className="text-xs text-ink-faint truncate max-w-[180px] mt-0.5" title={c.source_path}>{c.source_path}</div>
</div>
);
},
},
{
key: 'issuer',
label: 'Issuer',
render: (c) => <span className="text-xs text-ink-muted truncate max-w-[150px]" title={c.issuer_dn}>{c.issuer_dn?.split(',')[0] || '—'}</span>,
},
{
key: 'expiry',
label: 'Expiry',
render: (c) => <span className="text-xs">{formatExpiry(c.not_after)}</span>,
},
{
key: 'key_info',
label: 'Key',
render: (c) => (
<div className="flex items-center gap-1">
<span className="text-xs text-ink-muted">{c.key_algorithm}{c.key_size ? ` ${c.key_size}` : ''}</span>
{c.is_ca && (
<span className="text-2xs px-1.5 py-0.5 rounded bg-purple-100 text-purple-700 font-medium">CA</span>
)}
</div>
),
},
{
key: 'fingerprint',
label: 'Fingerprint',
render: (c) => <span className="font-mono text-2xs text-ink-faint">{c.fingerprint_sha256?.substring(0, 16)}...</span>,
},
{
key: 'actions',
label: '',
render: (c) => (
c.status === 'Unmanaged' ? (
<div className="flex gap-2">
<button
onClick={(e) => { e.stopPropagation(); setClaimingCert(c); }}
className="text-xs text-brand-600 hover:text-brand-700 font-medium"
>
Claim
</button>
<button
onClick={(e) => { e.stopPropagation(); dismissMutation.mutate(c.id); }}
disabled={dismissMutation.isPending}
className="text-xs text-ink-faint hover:text-ink-muted"
>
Dismiss
</button>
</div>
) : null
),
},
];
return (
<>
<PageHeader title="Certificate Discovery" subtitle={data ? `${data.total} discovered certificates` : undefined} />
{/* Summary stats bar */}
{summary && (
<div className="px-6 py-3 flex gap-4 border-b border-surface-border/50">
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-amber-400"></span>
<span className="text-sm text-ink"><strong>{summary.Unmanaged || 0}</strong> Unmanaged</span>
</div>
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-green-400"></span>
<span className="text-sm text-ink"><strong>{summary.Managed || 0}</strong> Managed</span>
</div>
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-gray-400"></span>
<span className="text-sm text-ink"><strong>{summary.Dismissed || 0}</strong> Dismissed</span>
</div>
<div className="ml-auto">
<button
onClick={() => setShowScans(!showScans)}
className="text-xs text-brand-600 hover:text-brand-700 font-medium"
>
{showScans ? 'Hide' : 'Show'} Scan History
</button>
</div>
</div>
)}
{/* Scan history collapsible */}
{showScans && (
<div className="border-b border-surface-border/50 bg-surface-subtle">
<div className="px-6 py-2">
<h3 className="text-sm font-semibold text-ink mb-2">Recent Scans</h3>
<ScanHistoryPanel scans={scansData?.data || []} />
</div>
</div>
)}
{/* Filters */}
<div className="px-6 py-3 flex gap-3 border-b border-surface-border/50">
<select
value={statusFilter}
onChange={e => setStatusFilter(e.target.value)}
className="bg-white border border-surface-border rounded px-3 py-1.5 text-sm text-ink"
>
<option value="">All statuses</option>
<option value="Unmanaged">Unmanaged</option>
<option value="Managed">Managed</option>
<option value="Dismissed">Dismissed</option>
</select>
<select
value={agentFilter}
onChange={e => setAgentFilter(e.target.value)}
className="bg-white border border-surface-border rounded px-3 py-1.5 text-sm text-ink"
>
<option value="">All agents</option>
{agentsData?.data?.map(a => (
<option key={a.id} value={a.id}>{a.name || a.id}</option>
))}
</select>
</div>
{/* Table */}
<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 discovered certificates. Agents will report findings once discovery scanning is configured."
/>
)}
</div>
{claimingCert && (
<ClaimModal
cert={claimingCert}
onClose={() => setClaimingCert(null)}
onClaim={(managedCertId) => claimMutation.mutate({ id: claimingCert.id, managedCertId })}
/>
)}
</>
);
}