diff --git a/dashboard/e2e/infra-security.spec.ts b/dashboard/e2e/infra-security.spec.ts index f560829e..2f68f7d4 100644 --- a/dashboard/e2e/infra-security.spec.ts +++ b/dashboard/e2e/infra-security.spec.ts @@ -52,6 +52,7 @@ async function mockApi(page: Page, init: Partial = {}): Promise { if (p === "/api/security/infrastructure/insights") return json(route, INFRA_INSIGHTS); if (p === "/api/security/infrastructure/check") return json(route, { status: "queued" }, 202); if (/^\/api\/security\/infrastructure\/findings\/[^/]+\/fix$/.test(p)) return json(route, { status: "started", reason: null }); + if (/^\/api\/security\/infrastructure\/findings\/[^/]+\/apply$/.test(p)) return json(route, { status: "queued", when: (body as { when?: string } | null)?.when ?? "next-maintenance" }); if (p === "/api/infra/analysis" || p.startsWith("/api/infra")) return json(route, { analysis: null }); return json(route, { error: `Not mocked: ${method} ${p}` }, 404); }); @@ -61,6 +62,61 @@ async function mockApi(page: Page, init: Partial = {}): Promise { const call = (db: Db, c: string) => db.calls.filter((x) => x.call === c); test.describe("Infrastructure vulnerabilities", () => { + test("fixed and removed rows leave the open list, an update in AWS is approved, and a stale read refreshes", async ({ page }) => { + const osUpdate = infraFinding({ + id: "f_os", + kind: "rds_cluster", + name: "staging-orders-db", + title: "Aurora cluster staging-orders-db: operating system update (the cluster and its 1 instance) pending", + tier: "P2", + fix: { + kind: "apply", + summary: "CoderHelm applies the operating system update in AWS after your approval (`os-upgrade`)", + location: null, + from: "16.13", + to: "", + cli: [], + console: "", + apply_by: "", + reason: "New Operating System patch is available", + decision: "CoderHelm applies this in AWS after one approval.", + apply: { action: "os-upgrade", arns: ["arn:aws:rds:us-east-1:111122223333:cluster:staging-orders-db"], permission: "rds:ApplyPendingMaintenanceAction", default_opt_in: "next-maintenance", effect: "Each instance restarts." }, + }, + }); + const fixed = infraFinding({ id: "f_fixed", title: "Aurora cluster prod-orders-db: engine version upgrade to 16.13 pending", status: "fixed", fixed_at: iso(-2), actionable: false }); + const removed = infraFinding({ + id: "f_removed", + kind: "rds_instance", + title: "RDS instance legacy-db-0002: operating system update pending", + status: "removed", + fixed_at: iso(-2), + removed_at: iso(-2), + actionable: false, + fix: { kind: "runbook", summary: "Apply it in AWS", location: null, from: "", to: "", cli: ["aws rds apply-pending-maintenance-action"], console: "", apply_by: "", reason: "" }, + }); + const merged = infraFinding({ id: "f_merged", title: "Merged duplicate", status: "merged" }); + const stale = infraOverview({ findings: [osUpdate, fixed, removed, merged], read_at: iso(-30), oldest_read_at: iso(-30), refreshing: true }); + const db = await mockApi(page, { overview: stale }); + await page.goto("/security/infrastructure"); + await expect(page.getByTestId("infra-refreshing")).toBeVisible(); + const open = page.getByRole("list", { name: "Infrastructure findings" }).getByTestId("infra-row"); + await expect(open).toHaveCount(1); + await expect(open.first()).toContainText("operating system update"); + await expect(page.getByText("Merged duplicate")).toHaveCount(0); + // Approve: the default is the next maintenance window. + await open.first().getByTestId("infra-apply").click(); + await expect.poll(() => call(db, "POST /api/security/infrastructure/findings/f_os/apply").length).toBe(1); + expect(call(db, "POST /api/security/infrastructure/findings/f_os/apply")[0].body).toEqual({ when: "next-maintenance" }); + // The closed rows sit under their own filter, with nothing to click. + await page.getByRole("group", { name: "Show" }).getByRole("button", { name: /Fixed \/ Removed/ }).click(); + const closed = page.getByRole("list", { name: "Fixed or removed findings" }).getByTestId("infra-row"); + await expect(closed).toHaveCount(2); + await expect(closed.getByTestId("infra-fix")).toHaveCount(0); + await expect(closed.getByTestId("infra-apply")).toHaveCount(0); + await expect(closed.getByTestId("fix-chip")).toHaveCount(0); + await expect(closed.filter({ hasText: "legacy-db-0002" }).getByTestId("infra-closed")).toHaveAttribute("data-status", "removed"); + }); + test("the Infrastructure tab groups by fix: PRs, a runbook card and AWS-managed rows that never count", async ({ page }) => { const db = await mockApi(page); await page.goto("/security/infrastructure"); diff --git a/dashboard/src/app/security/infrastructure/page.tsx b/dashboard/src/app/security/infrastructure/page.tsx index e21916e9..9ae06718 100644 --- a/dashboard/src/app/security/infrastructure/page.tsx +++ b/dashboard/src/app/security/infrastructure/page.tsx @@ -3,9 +3,11 @@ // Security › Infrastructure: what runs in the team's AWS accounts, matched // against AWS's bulletins and the Amazon Linux and Bottlerocket advisories, // one row per fix. A fix is a pull request in the code that defines the -// resource, a runbook step in AWS, or nothing at all (AWS-managed). A row -// closes only when Coderhelm reads the account again and sees the fix -// running. +// resource, an action Coderhelm applies in AWS after one approval, a runbook +// step, or nothing at all (AWS-managed). A row closes only when Coderhelm +// reads the account again: fixed when the fix runs, removed when the +// resource is gone. Opening the page refreshes a read older than a few +// minutes; the list updates when that read is done. import { Suspense, useEffect, useMemo, useState } from "react"; import Link from "next/link"; @@ -26,7 +28,10 @@ import { SECURITY_ADMIN, TIERS, closedWords, type Tier } from "@/lib/security"; import { INFRA_STATUS_LOOK, countWords, + inAws, infraApi, + isClosed, + type ApplyWhen, type InfraFeed, type InfraFinding, type InfraOverview, @@ -52,7 +57,11 @@ export default function SecurityInfrastructurePage() { } const TIER_TONE: Record = { P0: "danger", P1: "attention", P2: "waiting", P3: "muted" }; -type FixFilter = "" | "pr" | "runbook"; +type FixFilter = "" | "pr" | "aws_step"; +type View = "open" | "closed"; +/** While a refresh runs: how often the page asks again, and for how long. */ +const REFRESH_POLL_MS = 15_000; +const REFRESH_POLL_FOR_MS = 4 * 60_000; function InfrastructureFindings() { const { toast } = useToast(); @@ -66,6 +75,7 @@ function InfrastructureFindings() { const [checking, setChecking] = useState(false); const [tier, setTier] = useState(""); const [fixKind, setFixKind] = useState(""); + const [view, setView] = useState("open"); useEffect(() => { let live = true; @@ -85,6 +95,37 @@ function InfrastructureFindings() { }; }, [attempt]); + // A refresh the page started: ask again until the read is newer, then + // show the new list in place. + const refreshing = !!data?.refreshing; + const readAt = data?.read_at ?? null; + useEffect(() => { + if (!refreshing) return; + let live = true; + const started = Date.now(); + const t = window.setInterval(() => { + if (Date.now() - started > REFRESH_POLL_FOR_MS) { + window.clearInterval(t); + setData((d) => (d ? { ...d, refreshing: false } : d)); + return; + } + infraApi.overview().then( + (o) => { + if (!live) return; + if (o.read_at !== readAt) { + window.clearInterval(t); + setData({ ...o, refreshing: false }); + } + }, + () => {}, + ); + }, REFRESH_POLL_MS); + return () => { + live = false; + window.clearInterval(t); + }; + }, [refreshing, readAt]); + const check = async () => { setChecking(true); try { @@ -168,8 +209,19 @@ function InfrastructureFindings() { )} + - + )} @@ -177,14 +229,38 @@ function InfrastructureFindings() { ); } +/** When the list was last read from AWS, and whether a read is running now. */ +function Freshness({ data }: { data: InfraOverview }) { + const at = data.oldest_read_at ?? data.read_at; + return ( +

+ {at ? ( + <> + Checked against AWS

+ ); +} + function Tiles({ data }: { data: InfraOverview }) { const c = data.counts; const now = c.p0 + c.p1; + const steps = c.runbooks + (c.applies ?? 0); return ( 0 ? "danger" : "neutral"} note={now > 0 ? `P0 ${c.p0}, P1 ${c.p1}` : "Nothing urgent"} testId="infra-tile-now" /> - 0 ? "warning" : "neutral"} note="Runbook cards, never run for you" testId="infra-tile-runbooks" /> + 0 ? "warning" : "neutral"} + note={(c.applies ?? 0) > 0 ? "Coderhelm applies them after your approval" : "Runbook cards"} + testId="infra-tile-runbooks" + /> ); @@ -198,6 +274,8 @@ function FindingsSection({ setTier, fixKind, setFixKind, + view, + setView, }: { data: InfraOverview; admin: boolean; @@ -206,14 +284,39 @@ function FindingsSection({ setTier: (t: Tier | "") => void; fixKind: FixFilter; setFixKind: (f: FixFilter) => void; + view: View; + setView: (v: View) => void; }) { - const open = data.findings.filter((f) => f.fix.kind !== "aws"); - const aws = data.findings.filter((f) => f.fix.kind === "aws"); - const shown = useMemo(() => open.filter((f) => (!tier || f.tier === tier) && (!fixKind || f.fix.kind === fixKind)), [open, tier, fixKind]); + // Fixed and removed rows are history: never in the open list, never with + // a Runbook or Fix PR button. + const open = useMemo(() => data.findings.filter((f) => f.fix.kind !== "aws" && !isClosed(f)), [data.findings]); + const closed = useMemo(() => data.findings.filter((f) => f.fix.kind !== "aws" && isClosed(f)), [data.findings]); + const aws = data.findings.filter((f) => f.fix.kind === "aws" && !isClosed(f)); + const pool = view === "open" ? open : closed; + const shown = useMemo( + () => + pool.filter( + (f) => (!tier || f.tier === tier) && (!fixKind || (fixKind === "pr" ? f.fix.kind === "pr" : inAws(f))), + ), + [pool, tier, fixKind], + ); const c = data.counts; + const focused = focus && closed.some((f) => f.id === focus) && !open.some((f) => f.id === focus); + useEffect(() => { + if (focused) setView("closed"); + }, [focused, setView]); return (
+ setView(v as View)} + options={[ + { value: "open", label: "Open", count: open.length }, + { value: "closed", label: "Fixed / Removed", tone: "success", count: closed.length }, + ]} + />
@@ -235,14 +338,14 @@ function FindingsSection({ {shown.length === 0 ? ( 0 ? () => (setTier(""), setFixKind("")) : undefined} + title={pool.length === 0 ? (view === "open" ? "Nothing to fix" : "Nothing fixed or removed in 30 days") : "No findings match"} + onClear={pool.length > 0 ? () => (setTier(""), setFixKind("")) : undefined} testId="infra-empty" > - {open.length === 0 ? "Nothing your accounts run is behind a fix you have to make. AWS-managed rows are below." : undefined} + {pool.length === 0 && view === "open" ? "Nothing your accounts run is behind a fix you have to make. AWS-managed rows are below." : undefined} ) : ( - + {shown.map((f) => ( ))} @@ -271,6 +374,25 @@ function FindingRow({ f, admin, dryRun, defaultOpen }: { f: InfraFinding; admin: const [asked, setAsked] = useState(null); const status = INFRA_STATUS_LOOK[f.status] ?? INFRA_STATUS_LOOK.open; const aws = f.fix.kind === "aws"; + const done = isClosed(f); + const [approving, setApproving] = useState(null); + const approve = async (when: ApplyWhen) => { + setApproving(when); + try { + const r = await infraApi.apply(f.id, when); + const words = + r.status === "queued" + ? when === "immediate" + ? "Approved: Coderhelm applies it in AWS now (non-production first) and reads it back." + : "Approved: Coderhelm applies it in the next maintenance window (non-production first) and reads it back." + : (r.reason ?? "Nothing to apply."); + setAsked(words); + toast(words); + } catch (e) { + toast(e instanceof Error && /\b403\b/.test(e.message) ? "Only admins can approve updates in AWS." : "Could not approve it. Try again.", "error"); + } + setApproving(null); + }; const askFix = async () => { setAsking(true); try { @@ -288,7 +410,9 @@ function FindingRow({ f, admin, dryRun, defaultOpen }: { f: InfraFinding; admin: const prWords = f.pr ? (f.pr.state === "merged" ? "merged, waiting for the new version to run" : closed ? closedWords(f.pr) : f.pr.state) : null; // A pull request closed without merging is history, not a fix on its way: the fix is offered again. // (A finding the replacement check moved to its runbook is no longer a "pr" fix, so it gets no button.) - const canAsk = admin && f.fix.kind === "pr" && f.status === "open" && (!f.pr || closed) && !asked; + const canAsk = !done && admin && f.fix.kind === "pr" && f.status === "open" && (!f.pr || closed) && !asked; + const applied = !!f.apply?.applied_at; + const canApprove = !done && admin && f.fix.kind === "apply" && f.status === "open" && !applied && !f.apply?.approved_at && !asked; return ( + + {status.label} + + ) : ( <> {f.pr && ( @@ -321,13 +452,42 @@ function FindingRow({ f, admin, dryRun, defaultOpen }: { f: InfraFinding; admin: )} {!aws && !f.pr && f.status !== "open" && {status.label}} + {f.fix.kind === "apply" && f.apply?.approved_at && ( + + {applied ? "Sent to AWS" : "Approved"} + + )} + ) } actions={ canAsk ? ( + ) : canApprove ? ( + + + + ) : null } details={} @@ -340,6 +500,11 @@ function FindingRow({ f, admin, dryRun, defaultOpen }: { f: InfraFinding; admin:

)} {asked &&

{asked}

} + {!done && f.apply?.note && ( +

+ {f.apply.note} +

+ )}
); } @@ -368,7 +533,7 @@ function Sources({ feeds, readAt }: { feeds: InfraFeed[] | null; readAt: string testId="infra-source" status={{ tone: readAt ? "success" : "muted" }} title="Your AWS accounts" - meta={[readAt ? "Read once a day, read-only" : "Not read yet"]} + meta={[readAt ? "Read once a day, and again when this page opens after a few minutes; read-only" : "Not read yet"]} time={readAt} />
diff --git a/dashboard/src/app/security/infrastructure/parts.tsx b/dashboard/src/app/security/infrastructure/parts.tsx index 10093ae7..ef93d60b 100644 --- a/dashboard/src/app/security/infrastructure/parts.tsx +++ b/dashboard/src/app/security/infrastructure/parts.tsx @@ -15,6 +15,7 @@ import { linkButton } from "@/components/ui"; import { CONFIDENCE_LOOK, FIX_LOOK, + isClosed, howWords, locationHref, locationWords, @@ -109,7 +110,7 @@ export function dayWords(day: string): string { export function showFromTo(f: InfraFinding): boolean { const to = f.fix.to?.trim() ?? ""; if (!to) return false; - if (f.fix.kind === "runbook" && f.sources.some((s) => s.kind === "maintenance" && s.id.split(":").includes(to))) return false; + if ((f.fix.kind === "runbook" || f.fix.kind === "apply") && f.sources.some((s) => s.kind === "maintenance" && s.id.split(":").includes(to))) return false; return to !== f.fix.summary && !/^(system-update|db-upgrade|os-patch|service-update|service-software)$/.test(to); } @@ -374,13 +375,63 @@ export function PrNotesBlocks({ n }: { n: InfraPrNotes }) { ); } +/** What Coderhelm applies after an approval, and what AWS answered. */ +function ApplyBlock({ f }: { f: InfraFinding }) { + const plan = f.fix.apply; + if (!plan) return null; + const a = f.apply; + return ( + +

+ {plan.action} through AWS's apply-pending-maintenance-action, on {plan.arns.length} resource{plan.arns.length === 1 ? "" : "s"}, in the next + maintenance window unless you pick now. {plan.effect} +

+ {a?.approved_at && ( +

+ Approved by {a.approved_by || "an admin"}

+ )} + {a?.missing_permission && ( +

+ The role in this account lacks {a.missing_permission}. Turn ApplyMaintenance on in the role's update stack, or follow the runbook below. +

+ )} +
+ ); +} + /** What opens under a finding's row. */ export function FindingDetails({ f }: { f: InfraFinding }) { const fix = f.fix; - const rb = fix.kind === "runbook" ? (fix.runbook ?? null) : null; - const order = fix.order ?? []; + const done = isClosed(f); + // A runbook is shown for a runbook fix, and behind an apply only when the + // role may not apply it. A closed finding shows no steps at all. + const rb = !done && (fix.kind === "runbook" || (fix.kind === "apply" && !!f.apply?.missing_permission)) ? (fix.runbook ?? null) : null; + const order = done ? [] : (fix.order ?? []); return ( <> + {done && ( + +

+ {f.status === "removed" ? ( + <> + A full read of the account

+
+ )} {fix.kind === "aws" ? (

{fix.reason || "AWS patches this service itself."}

@@ -397,8 +448,9 @@ export function FindingDetails({ f }: { f: InfraFinding }) { )}
)} - {fix.kind !== "aws" && fix.decision && ( - + {!done && fix.kind === "apply" && } + {!done && fix.kind !== "aws" && fix.decision && ( +

@@ -436,9 +488,9 @@ export function FindingDetails({ f }: { f: InfraFinding }) {
)} {fix.kind !== "aws" && } - {fix.kind === "pr" && fix.notes && } + {!done && fix.kind === "pr" && fix.notes && } {rb && } - {!rb && fix.kind !== "aws" && fix.cli.length > 0 && ( + {!done && !rb && fix.kind !== "aws" && fix.kind !== "apply" && fix.cli.length > 0 && (
@@ -446,14 +498,14 @@ export function FindingDetails({ f }: { f: InfraFinding }) { {fix.kind === "runbook" &&

Coderhelm never runs this. A person with access to the account does.

} )} - {!rb && fix.kind === "runbook" && fix.console && ( + {!done && !rb && fix.kind === "runbook" && fix.console && (

)} - {!rb && fix.apply_by && ( + {!done && !rb && fix.apply_by && (

Apply by {dayWords(fix.apply_by)}. AWS applies it itself after that, in the maintenance window. @@ -494,7 +546,8 @@ export function FindingDetails({ f }: { f: InfraFinding }) {

- First seen

diff --git a/dashboard/src/lib/infra-security.ts b/dashboard/src/lib/infra-security.ts index 677f6e33..fbf93e5c 100644 --- a/dashboard/src/lib/infra-security.ts +++ b/dashboard/src/lib/infra-security.ts @@ -22,8 +22,35 @@ export type InfraKind = | "opensearch_domain" | "container_image"; -export type FixKind = "pr" | "runbook" | "aws"; -export type InfraStatus = "open" | "fixing" | "pr_open" | "fixed" | "aws_managed" | "dismissed"; +export type FixKind = "pr" | "apply" | "runbook" | "aws"; +export type InfraStatus = "open" | "fixing" | "pr_open" | "fixed" | "aws_managed" | "dismissed" | "removed" | "merged"; + +/** When to apply a pending action in AWS. */ +export type ApplyWhen = "next-maintenance" | "immediate"; + +/** How Coderhelm applies a pending action once a person approves it. */ +export interface InfraApplyPlan { + /** AWS's name for the action: os-upgrade, system-update, db-upgrade, ... */ + action: string; + arns: string[]; + /** The IAM action the role needs. */ + permission: string; + default_opt_in: ApplyWhen; + /** What applying it does to the database, in a line. */ + effect: string; +} + +/** A person's approval, and what AWS answered. */ +export interface InfraApplyState { + opt_in: ApplyWhen; + approved_by: string; + approved_at: string; + applied_at?: string; + applied?: string[]; + note?: string; + /** The IAM action the role lacks, when AWS refused for that. */ + missing_permission?: string; +} export type InfraConfidence = "high" | "medium" | "low"; @@ -142,6 +169,8 @@ export interface InfraFix { after?: string[]; /** Why no CVE is named, or that an advisory is only related. */ advisory_note?: string; + /** What Coderhelm applies after one approval (kind "apply"). */ + apply?: InfraApplyPlan | null; } export interface InfraFinding { @@ -176,6 +205,12 @@ export interface InfraFinding { first_seen_at: string; updated_at: string; fixed_at?: string | null; + /** When a full read of the account stopped listing the resource. */ + removed_at?: string | null; + /** A person's approval of the action Coderhelm applies, and AWS's answer. */ + apply?: InfraApplyState | null; + /** False once the finding is closed: nothing to open, follow or approve. */ + actionable?: boolean; environment?: string; /** The lines of a fix run's change that would have replaced or destroyed a data resource. */ refused?: string[]; @@ -199,15 +234,43 @@ export interface InfraAccount { missing: string[]; update_url: string | null; read: { read_at: string; resources: number; errors: InfraReadError[] } | null; + /** Whether the role may apply approved maintenance (null until checked). */ + apply_maintenance?: boolean | null; } export interface InfraOverview { enabled: boolean; dry_run: boolean; - counts: { open: number; p0: number; p1: number; p2: number; p3: number; prs: number; runbooks: number; aws_managed: number; fixed_30d: number }; + counts: { + open: number; + p0: number; + p1: number; + p2: number; + p3: number; + prs: number; + runbooks: number; + aws_managed: number; + fixed_30d: number; + removed_30d?: number; + applies?: number; + }; accounts: InfraAccount[]; findings: InfraFinding[]; read_at: string | null; + /** The oldest of the accounts' latest reads: how old the list can be. */ + oldest_read_at: string | null; + /** Opening the page started a fresh read of the accounts. */ + refreshing: boolean; +} + +/** Fixed or removed: closed by a read of the account. */ +export function isClosed(f: Pick): boolean { + return f.status === "fixed" || f.status === "removed"; +} + +/** A step in AWS: a runbook, or an action Coderhelm applies after approval. */ +export function inAws(f: Pick): boolean { + return f.fix.kind === "runbook" || f.fix.kind === "apply"; } export interface InfraPending { @@ -304,8 +367,10 @@ export function checkInfraOverview(r: unknown): InfraOverview { enabled: o.enabled !== false, dry_run: o.dry_run === true, accounts: Array.isArray(o.accounts) ? (o.accounts as InfraAccount[]) : [], - findings, + findings: findings.filter((f) => f.status !== "merged"), read_at: typeof o.read_at === "string" ? o.read_at : null, + oldest_read_at: typeof o.oldest_read_at === "string" ? o.oldest_read_at : typeof o.read_at === "string" ? o.read_at : null, + refreshing: o.refreshing === true, }; } @@ -355,6 +420,12 @@ export const infraApi = { check: () => request<{ status: string }>("/api/security/infrastructure/check", json("POST")), fix: (id: string) => request<{ status: "started" | "queued" | "skipped"; reason: string | null }>(`/api/security/infrastructure/findings/${encodeURIComponent(id)}/fix`, json("POST")), + /** Approve a pending action Coderhelm applies in AWS. */ + apply: (id: string, when: ApplyWhen) => + request<{ status: "queued" | "skipped"; reason?: string | null; when?: ApplyWhen }>( + `/api/security/infrastructure/findings/${encodeURIComponent(id)}/apply`, + json("POST", { when }), + ), }; // ── Words ─────────────────────────────────────────────────────────────── @@ -392,6 +463,7 @@ export function countWords(kind: InfraKind, n: number): string { export const FIX_LOOK: Record = { pr: { label: "Fix PR", tone: "info", hover: "A pull request in the code that defines it." }, + apply: { label: "Applied by Coderhelm", tone: "info", hover: "A step in AWS with no code change. Coderhelm applies it after one approval, non-production first, and checks the result." }, runbook: { label: "Runbook", tone: "attention", hover: "A step to apply in AWS. Coderhelm shows it; it never runs it." }, aws: { label: "AWS-managed", tone: "muted", hover: "AWS patches it. Nothing to do." }, }; @@ -403,6 +475,8 @@ export const INFRA_STATUS_LOOK: Record