Files
certctl/web/src/pages/NotificationsPage.test.tsx
certctl-bot 3f5c2344ab fix(web,ci): close TS↔Go type drift across 5 entities (D-2 master)
Closes five 2026-04-24 audit findings (all P2, all category cat-f /
diff-05x06-*) by reconciling the TypeScript interfaces in
web/src/api/types.ts with the on-wire JSON shape Go's
internal/domain/*.go structs actually emit. D-1 closed the same pattern
for one entity (Certificate / ManagedCertificate); D-2 covers the
remaining five.

Per-entity verdicts (audit's "stricter side is the contract"):

  Agent       — TRIM 5 phantoms (last_heartbeat, capabilities, tags,
                created_at, updated_at). Go emits last_heartbeat_at only.
  Target      — ADD 2 (retired_at?, retired_reason?) — I-004 fields.
  DiscCert    — ADD pem_data? — real field, real Go emit, omitempty.
  Issuer      — TRIM phantom status. Go has Enabled bool only.
  Notif       — TRIM phantom subject. Go has Message string only.
  Certificate — verify-only; D-1 closure confirmed clean at recon.

Consumer fixes (same commit as the trim):
- AgentDetailPage.tsx — remove dead Capabilities + Tags sections (always
  rendered empty); replace agent.created_at/updated_at row with the
  Go-emitted registered_at; widen heartbeatStatus() to accept undefined.
- AgentsPage.tsx — same heartbeatStatus widening.
- IssuersPage.tsx + IssuerDetailPage.tsx — issuerStatus() now derives
  from `enabled` exclusively; the dead `issuer.status || 'Unknown'`
  fallback is gone.
- NotificationsPage.tsx — drop dead `|| n.subject` fallback.
- NotificationsPage.test.tsx — drop dead `subject:` from mocks.
- api/utils.ts::timeAgo widened to accept string | undefined | null.
- api/types.test.ts — Agent (I-004) fixture trimmed of the 5 phantoms.

Tests (Vitest):
- 5 new describe blocks in web/src/api/types.test.ts:
  - Agent interface (D-2 phantom-fields trim) — 2 it blocks
  - Target interface (D-2 retirement fields) — 2 it blocks
  - DiscoveredCertificate interface (D-2 pem_data ADD) — 2 it blocks
  - Issuer interface (D-2 status phantom trim) — 1 it block
  - Notification interface (D-2 subject phantom trim) — 1 it block
- Each block uses the literal-construction pattern from D-1; trimmed
  fields are pinned via excess-property comments that compile-fail when
  uncommented if a phantom is reintroduced.

CI regression guardrail:
- .github/workflows/ci.yml — existing D-1 step renamed to "Forbidden
  StatusBadge dead-key + TS phantom-field regression guard (D-1 + D-2)".
  Three new awk-windowed greps over Agent / Issuer / Notification
  interfaces in types.ts. The Agent grep includes a `grep -v
  'last_heartbeat_at'` filter to avoid false positives on the
  legitimate Go-emitted heartbeat field.

Documentation:
- CHANGELOG.md — new D-2 section above B-1 under [unreleased] with full
  Added/Removed/Audit findings closed/Known follow-ups breakdown.
- docs/architecture.md — Web Dashboard section gains a new "TS ↔ Go
  type contract rule (D-1 + D-2 closure)" paragraph capturing the
  stricter-side-wins rule and the CI guardrail it's anchored by.
- coverage-gap-audit-2026-04-24-v5/unified-audit.md — Live Tracker score
  20/47 → 25/47 (P2: 6/27 → 11/27). Per-finding  RESOLVED Status
  blocks added to all 5 diff-05x06-* entries plus the verify-only
  Certificate entry. Closed-bundle index gets D-2 row.

Verification (all gates green):
- cd web && tsc --noEmit                 → clean
- cd web && vitest run --reporter=dot    → 9 files, 302 tests passing
                                            (was 294 → +8 D-2 cases)
- cd web && vite build                   → clean
- go vet ./internal/... ./cmd/...        → clean (no Go touched)
- golangci-lint v2.11.4 run ./...        → 0 issues
- D-2 Agent guardrail dry-run            → empty (good)
- D-2 Issuer guardrail dry-run           → empty (good)
- D-2 Notification guardrail dry-run     → empty (good)
- D-2 Target ADD-shape sanity            → 2 retirement fields present
- D-2 DiscCert ADD-shape sanity          → pem_data present
- D-1 Certificate guardrail still clean  → empty (good)
- OpenAPI YAML parses                    → 89 paths

Audit findings closed:
- diff-05x06-7cdf4e78ae24 (P2, Agent TS↔Go drift)
- diff-05x06-2044a46f4dd0 (P2, Target TS↔DeploymentTarget Go drift)
- diff-05x06-85ab6b98a2f7 (P2, DiscoveredCertificate TS↔Go drift)
- diff-05x06-97fab8783a5c (P2, Issuer TS↔Go drift)
- diff-05x06-caba9eb3620e (P2, Notification TS↔NotificationEvent drift)
- diff-05x06-af18a8d7ef41 (P2) — verified clean since D-1; no edit

Deferred follow-ups:
- Issuer richer status view (enabled × test_status) — UX scope, not drift.
- Real Agent metadata (capabilities, tags) — backend feature, not drift.
- DiscoveredCertificate pem_data list-response perf — separate backend change.
2026-04-25 16:07:31 +00:00

210 lines
7.2 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter } from 'react-router-dom';
import type { ReactNode } from 'react';
// -----------------------------------------------------------------------------
// I-005: NotificationsPage Phase 1 Red — Dead Letter tab + Requeue action
//
// This file pins the frontend contract Phase 2 Green must implement:
//
// 1. A "Dead letter" tab renders alongside the existing status filter, and
// selecting it causes the underlying query to fetch with { status: 'dead' }.
// The tab does not exist at HEAD — the tab-locator assertions are the Red.
//
// 2. Notifications in status='dead' render a "Requeue" action button. HEAD
// only renders "Mark read" for Pending rows and no action for anything
// else — the button-locator assertion is the Red.
//
// 3. Clicking "Requeue" invokes requeueNotification(id) from the API client
// and invalidates the notifications query. `requeueNotification` does not
// yet exist as an export from ../api/client — tsc --noEmit will fail with
// "Property 'requeueNotification' does not exist" when Phase 2 Green runs
// its verification gates, which is the compile-time Red halt. This file is
// structured so Phase 2 Green's single fix (add the client export + page
// wiring) flips the entire suite Green at once.
// -----------------------------------------------------------------------------
vi.mock('../api/client', () => ({
getNotifications: vi.fn(),
getNotification: vi.fn(),
markNotificationRead: vi.fn(),
requeueNotification: vi.fn(),
}));
// Imported after vi.mock so the mock replaces the real module.
import NotificationsPage from './NotificationsPage';
import * as client from '../api/client';
function renderWithQuery(ui: ReactNode) {
const qc = new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0, staleTime: 0 },
},
});
return render(
<QueryClientProvider client={qc}>
<MemoryRouter>{ui}</MemoryRouter>
</QueryClientProvider>,
);
}
// D-2 (master): pre-D-2 these mocks set `subject:` — the field was a TS
// phantom the Go-side struct never emitted. Post-D-2 the phantom is
// removed from the Notification interface; the mocks no longer set it.
const pendingNotif = {
id: 'notif-001',
type: 'ExpirationWarning',
channel: 'Email',
recipient: 'admin@example.com',
message: 'Certificate expiring in 7 days',
status: 'Pending',
certificate_id: 'mc-prod-001',
created_at: new Date().toISOString(),
};
const deadNotif = {
id: 'notif-dead-001',
type: 'ExpirationWarning',
channel: 'Email',
recipient: 'admin@example.com',
message: 'Certificate expiring in 7 days',
status: 'dead',
certificate_id: 'mc-prod-001',
created_at: new Date().toISOString(),
retry_count: 5,
last_error: 'SMTP connection refused',
};
describe('NotificationsPage — I-005 Dead Letter + Requeue (Phase 1 Red)', () => {
beforeEach(() => {
vi.clearAllMocks();
cleanup();
});
it('renders a Dead letter tab in the filter toolbar', async () => {
vi.mocked(client.getNotifications).mockResolvedValue({
data: [pendingNotif],
total: 1,
page: 1,
per_page: 100,
});
renderWithQuery(<NotificationsPage />);
await waitFor(() => {
expect(screen.queryByText(/Loading/i)).not.toBeInTheDocument();
});
// Red: no Dead letter tab exists at HEAD. Phase 2 Green adds a button/tab
// labeled "Dead letter" (matches docs/testing-guide UI label).
expect(screen.getByRole('button', { name: /Dead letter/i })).toBeInTheDocument();
});
it('clicking Dead letter tab fetches notifications with status=dead', async () => {
vi.mocked(client.getNotifications).mockResolvedValue({
data: [],
total: 0,
page: 1,
per_page: 100,
});
renderWithQuery(<NotificationsPage />);
await waitFor(() => {
expect(screen.queryByText(/Loading/i)).not.toBeInTheDocument();
});
const tab = screen.getByRole('button', { name: /Dead letter/i });
fireEvent.click(tab);
// Red: Phase 2 Green must route the Dead letter tab's query through
// getNotifications({ status: 'dead', per_page: '100' }). HEAD only ever
// calls getNotifications({ per_page: '100' }) — no status param is ever
// passed through.
await waitFor(() => {
const calls = vi.mocked(client.getNotifications).mock.calls;
const deadCall = calls.find(([params]) => (params as Record<string, string>)?.status === 'dead');
expect(deadCall, 'expected getNotifications to be called with status=dead').toBeTruthy();
});
});
it('renders a Requeue button on dead notifications', async () => {
vi.mocked(client.getNotifications).mockResolvedValue({
data: [deadNotif],
total: 1,
page: 1,
per_page: 100,
});
renderWithQuery(<NotificationsPage />);
await waitFor(() => {
expect(screen.queryByText(/Loading/i)).not.toBeInTheDocument();
});
// Switch to Dead letter tab so the mocked dead notification becomes visible.
const tab = screen.getByRole('button', { name: /Dead letter/i });
fireEvent.click(tab);
await waitFor(() => {
// Red: HEAD renders no action for status='dead'. Phase 2 Green adds a
// "Requeue" button next to each dead row.
expect(screen.getByRole('button', { name: /Requeue/i })).toBeInTheDocument();
});
});
it('clicking Requeue invokes requeueNotification(id) from the API client', async () => {
vi.mocked(client.getNotifications).mockResolvedValue({
data: [deadNotif],
total: 1,
page: 1,
per_page: 100,
});
vi.mocked(client.requeueNotification).mockResolvedValue({ status: 'requeued' });
renderWithQuery(<NotificationsPage />);
await waitFor(() => {
expect(screen.queryByText(/Loading/i)).not.toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: /Dead letter/i }));
const requeueBtn = await screen.findByRole('button', { name: /Requeue/i });
fireEvent.click(requeueBtn);
// Red: client.requeueNotification is not an exported function at HEAD, and
// the page does not call it. Both the mock and the page wiring are added
// in Phase 2 Green.
await waitFor(() => {
expect(client.requeueNotification).toHaveBeenCalledWith('notif-dead-001');
});
});
it('dead notifications surface retry_count and last_error metadata', async () => {
vi.mocked(client.getNotifications).mockResolvedValue({
data: [deadNotif],
total: 1,
page: 1,
per_page: 100,
});
renderWithQuery(<NotificationsPage />);
await waitFor(() => {
expect(screen.queryByText(/Loading/i)).not.toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: /Dead letter/i }));
await waitFor(() => {
// Red: HEAD does not display retry_count or last_error. Phase 2 Green
// must surface these so operators can see *why* a notification died.
expect(screen.getByText(/SMTP connection refused/i)).toBeInTheDocument();
expect(screen.getByText(/5/)).toBeInTheDocument();
});
});
});