From ea124ee8389a390783b0638cd34e46c3fbf44d27 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 13:00:38 -0600 Subject: [PATCH] console: a change to enforced outside the review shows the evidence and asks for the acknowledgment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fleet's "Change mode for selected…" and the workload page's "change…" enforced in one step with no verdict, even for a workload with no flows and no time in simulation, while the review's promotion asks for an explicit acknowledgment past any verdict that is not safe. Both call the same endpoint and the same domain function, which accept any mode change: the gate is the console's (ADR-0001 as amended). ModeChangeDialog now reads, for each workload a change to enforced would move, the verdict the review composes for that workload alone, over the review's default range: the same four rollups and evidence gaps loadReview reads, by workload, through the same buildRows and composeVerdict (loadWorkloadEvidence in review/data.ts). enforceEvidence divides the selection into safe, never simulated, not safe, and already enforced. When all are safe the change is one step, as a promotion is; otherwise the promote dialog's verdict block counts them ("No simulation evidence for N of M selected", "Not safe to enforce for N of M selected"), lists the workloads behind each count, and the confirm waits on one acknowledgment for the selection, with the promote dialog's nudge. Nothing is written while the evidence is read or if it cannot be. Changes to visibility or simulation stay one step and read nothing. ADR-0001 takes a dated amendment; ARCHITECTURE.md, the promotion guide, the command-line reference, and the design package's extension record say where the gate now stands. The command line and the operator API are unchanged. Fixes #94. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- ARCHITECTURE.md | 2 +- CHANGELOG.md | 4 + .../adr/0001-visibility-before-enforcement.md | 3 +- docs/design/PACKAGE.md | 11 + docs/guides/promotion-and-enforcement.md | 2 +- docs/reference/innerwall-cli.md | 2 +- ui/src/routes/fleet/ModeChangeDialog.tsx | 254 +++++++++++- ui/src/routes/fleet/fleet.test.tsx | 391 +++++++++++++++++- ui/src/routes/review/data.ts | 69 +++- ui/src/routes/review/model.ts | 54 +++ ui/src/routes/workload/workload.test.tsx | 105 +++++ 11 files changed, 885 insertions(+), 12 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d624f4d..e1dbc05 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -153,7 +153,7 @@ Surfaces, in product order: 1. **Flow map** — the live dependency graph (ReactFlow), aggregated by label group rather than per-host, because a thousand-node hairball is not visibility. Drill-down expands groups to workloads to flows. 2. **Policy editor** — live edits with conditional writes and every admission finding shown in place, and a dry run that shows each workload's rendered change before anything is written. 3. **Simulation review** — a ruleset's would-block traffic from the workloads simulating it: "these seventeen real connections from the last week would have been denied," with the verdict, the evidence gaps, and the promotion to enforcement, which asks for an explicit acknowledgment when the verdict is not safe. -4. **Workload inventory** — registry, labels, agent health, desired-vs-actual ruleset version. +4. **Workload inventory** — registry, labels, agent health, desired-vs-actual ruleset version, and mode changes; a change to enforced from here carries the review's verdict for each workload it would move and asks for the same explicit acknowledgment when any is not safe or never simulated. 5. **Enrollment** — generate scoped, expiring, pre-labeled provisioning tokens with the copy-paste enroll command. Deliberately polished: it is the first thirty seconds of every evaluation. ## 10. Scale-out roadmap (designed, not built) diff --git a/CHANGELOG.md b/CHANGELOG.md index 117bc16..98be3a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ Notable changes to Innerwall, newest first. Versions follow semantic versioning; before 1.0, a minor version may change anything. +## Unreleased + +- **A change to enforced outside the simulation review shows the evidence and asks for the acknowledgment** (#94). The fleet's **Change mode for selected…** and the **change…** beside the mode on the workload page set any mode in one step, enforced included: a workload enrolled minutes earlier, with no flows and no time in simulation, could be enforced with one click, with no verdict and no acknowledgment, while the review's promotion asks for one past any verdict that is not safe. A change to enforced from either dialog now reads, for each workload it would move, the verdict the review composes for that workload alone over the review's default range (the last 24 hours), with the same reads and the same composition, and draws the review's verdict block. When every such workload's verdict is safe, the change is one step, as a promotion is. Otherwise the block counts them ("No simulation evidence for N of M selected", "Not safe to enforce for N of M selected"), lists the workloads behind each count with the review's reason, and the confirm, "Enforce anyway on N workloads", writes nothing until one acknowledgment for the selection is checked. While the evidence is read, or if it cannot be, nothing is written. The dialog stays the deliberate way to enforce what the review would not offer, such as a re-enrolled host whose previous identity earned enforcement. Changes to visibility or simulation stay one step. Console only: `innerwall workload set-mode` and `POST /api/v1/mode-changes` still accept a change to enforced with no evidence and no acknowledgment. ADR-0001 takes a dated amendment. + ## v0.5.2 — an entry admits what it says, and renewal survives a suspend One change refuses what was admitted before: an entry typed as a protocol and a separator with nothing after it (`tcp:`, `tcp/`, `udp:`, `udp/`, `icmp:`, `icmp/`) was read as every port of the protocol, or as `icmp`, and is now refused on the command line's `--entry` and in the console's entry inputs (#239). Every port is written as the bare protocol, `tcp`, as it always could be. A script that passes `--entry tcp:` or `--entry tcp/` must pass `--entry tcp` instead. Stored services and rules are unaffected, as are documents and REST bodies, which carry the protocol and its ports as separate fields. Beside it, an agent whose host was suspended across its renewal point renews at once on resume, the console reads entries and refused text as the command line and the control plane do, and the control plane's log names a credential refused past the renewal grace and says where a retired workload's stream ended. diff --git a/docs/adr/0001-visibility-before-enforcement.md b/docs/adr/0001-visibility-before-enforcement.md index cead3f3..ac7cc7d 100644 --- a/docs/adr/0001-visibility-before-enforcement.md +++ b/docs/adr/0001-visibility-before-enforcement.md @@ -19,7 +19,7 @@ All v1 milestones deliver visibility value standalone; enforcement is the second ## Consequences - The trust barrier at install time drops to that of an observability agent. -- Every enforcement decision is offered with its evidence; "what would break" is a query, not a guess. The console's promotion refuses to proceed past an unsafe verdict or missing evidence without the operator's explicit acknowledgment. The surface and the command line accept a mode change directly, for automation, so the guarantee is the default and the evidence, not a server-side refusal; a server-side evidence guard on mode changes is recorded backlog. *(Amended 2026-10-06; see Amendments.)* +- Every enforcement decision is offered with its evidence; "what would break" is a query, not a guess. The console refuses to enforce past an unsafe verdict or missing evidence without the operator's explicit acknowledgment, whether the change starts at the simulation review's promotion or at one of the console's mode changes. The surface and the command line accept a mode change directly, for automation, so the guarantee is the default and the evidence, not a server-side refusal; a server-side evidence guard on mode changes is recorded backlog. *(Amended 2026-10-06 and 2026-11-25; see Amendments.)* - The flow pipeline and map must be production-quality from day one — they are the product, not instrumentation. - Revenue-of-attention risk: the project must resist becoming only a mapping tool; enforcement is the destination and stays on the roadmap's critical path. @@ -27,3 +27,4 @@ All v1 milestones deliver visibility value standalone; enforcement is the second - **2026-10-06 (PR #25, conformance-audit absorption; maintainer ruling).** The core discipline stands: visibility by default, simulation on the exact enforced ruleset, enforcement opt-in per workload or label scope and never a global switch. Four passages overstated the mechanism and are corrected in place. The decision said the sequence is "enforced by the platform"; what ships is visibility as every workload's starting mode, evidence surfaced at every step, and promotion operator-gated in the console behind an explicit acknowledgment when the verdict is not safe or the evidence has gaps, while the surface and the command line accept a mode change directly. Decision 1 said agents "touch nothing"; in visibility the agent installs its owned table empty, with no verdict chain. Decision 2 described policy drafts replayed against observed flows; policy is edited live with no draft, simulation is the enforced ruleset with a terminal rule that accepts and records (ADR-0020), and a dry-run render previews a hypothetical policy. The consequence that every enforcement decision is preceded by evidence is corrected to say it is offered with its evidence. A server-side evidence guard on mode changes, refusing an unacknowledged promotion at the domain layer, is recorded backlog; until it lands the console is where the gate lives, and the record says so. Maintainer ruling on PR #25: amendment, not supersession, because the platform-enforced-sequence wording overstated the mechanism while the core discipline stands. The ruling was made with the tradeoff in view: no version of the code ever refused a mode change at the domain layer, so this records what has always shipped rather than withdrawing a guarantee that existed, and the guard that would make the stronger wording true is the backlog item above. - **2026-10-08 (PR #32, issue #30).** The core discipline stands: visibility by default, simulation on the exact enforced ruleset, enforcement opt-in per workload or label scope. Decision 1 said the visibility table holds no verdict chain and nothing is evaluated, and the 2026-10-06 note above says the table is installed empty. An empty table references no connection tracking, so on a host where nothing else did, the kernel tracked nothing and visibility collected nothing. Decision 1 is corrected in place: the table holds one observation chain whose one rule engages connection tracking and accepts. No policy is evaluated and nothing is dropped, so visibility still asks of an operator only what an observability agent does. ADR-0020 carries the chain's shape and the decision that visibility logs nothing. +- **2026-11-25 (issue #94).** Additive detail; the decision and the backlog item stand. The console's acknowledgment gate covered only the simulation review's promotion, while the console's other two paths to enforced, the fleet's mode change for a selection and the workload page's mode change, enforced in one step with no evidence shown. The consequence is corrected in place: the gate covers every console path to enforced. Each workload such a change would move is given the verdict the review composes for a scope of that workload alone, over the review's default range, and when any is not safe or never simulated the change counts them, names them, and waits on the same explicit acknowledgment. These paths stay the operator's deliberate way to enforce what the review would not offer. Changes to visibility or simulation only loosen and stay one step. The surface and the command line are unchanged and still accept a mode change directly; the server-side evidence guard remains the recorded backlog. diff --git a/docs/design/PACKAGE.md b/docs/design/PACKAGE.md index cb0e391..e85c847 100644 --- a/docs/design/PACKAGE.md +++ b/docs/design/PACKAGE.md @@ -240,3 +240,14 @@ Recorded 2026-10-21 (INN-63, INN-70, ADR-0023), **proposed for the maintainer's - **The credential issued and the credential presented** are two more field rows of the Status card, "issued" and "in use" (or "presented" while the stream is down), each a mono serial with a caption. A presented serial that is not the one issued, on a live stream, takes the alert severity glyph and tone with "not the one issued", and a caption says what the divergence can mean. Copy added: "Retired", "retired *ago*", "refused · retired", "refused · workload retired", "retired" (chip), "Lifecycle" (column and group), "No active workloads; *N* workloads are retired.", "Show retired", "Showing *N* · most recently retired first", "frozen", "Retire…", "Retire selected…", the retired card's sentence, the Status card's retired caption, the retire dialog's titles ("Retire *host*?", "Retire *N* workloads?"), sentences, acknowledgment, confirms ("Retire workload", "Retire *N* workloads"), nudge, and outcomes; the credential's phrases ("valid · renews by *instant*", "expired *ago* · in grace", "expired *ago* · re-enroll", "expired *ago* · will recover by renewal", "expired *ago* · needs re-enrollment") and their captions, "Mint a provisioning token", the field labels "issued", "in use", "presented", "not the one issued", and their captions. + +## Design-package extensions: a change to enforced outside the review + +Recorded 2026-11-25 (#94), **proposed for the maintainer's acceptance**. The package draws the promote dialog and its acknowledgment variant, and has no board for the mode-change dialog (the fleet's **Change mode for selected…** and the workload strip's **change…**). A change to enforced from that dialog is composed from the promote dialog's own patterns; it adds no tokens, no components, and no icons. + +- **The verdict block** is the promote dialog's, under the target-mode chips, drawn only when the target is Enforced and the selection holds a workload not yet enforced: the flow `allowed` glyph with "Safe to enforce" and "No observed traffic would be dropped." when the review would call every such workload safe; otherwise the severity `error` glyph with "Not safe to enforce yet" and the counts as its line. Each verdict is the one the simulation review composes for a scope of that workload alone, over the review's default range. +- **The workloads behind the counts** sit under the block on the canvas well, rows on hairlines as in the promote dialog's partition: "Never simulated" with the hostnames as links, each workload not safe to enforce with its hostname as a link and the review's first failing condition on the alert tone, then "Safe to enforce" and "Already enforced" with their counts. +- **The acknowledgment** is the promote dialog's sunk checkbox and nudge, one for the whole selection. The confirm is the plate, held in its disabled state and kept focusable while the evidence is read and until acknowledged; it reads "Enforce anyway on *N* workloads" when the acknowledgment is asked, and keeps "Change to enforced" otherwise. +- **Visibility and Simulation** draw none of it: they only loosen, and stay one step. + +Copy added: "No simulation evidence for *N* of *M* selected", "Not safe to enforce for *N* of *M* selected", "Never simulated", "no verdict", "+*N* more not safe to enforce", the caption ("Each verdict is the one the simulation review composes for the workload over the last *range*." and, when the acknowledgment is asked, "This enforces the selection as chosen; the review promotes only the workloads that earned it."), the acknowledgments ("I understand this workload is not safe to enforce yet", "I understand *N* of these *M* workloads are not safe to enforce yet"), and "Loading each workload's evidence…". The headlines, the safe line, the nudge, and "Enforce anyway on *N* workloads" are the promote dialog's. diff --git a/docs/guides/promotion-and-enforcement.md b/docs/guides/promotion-and-enforcement.md index f5ab9f1..1ea475e 100644 --- a/docs/guides/promotion-and-enforcement.md +++ b/docs/guides/promotion-and-enforcement.md @@ -24,7 +24,7 @@ Promotion starts from a ruleset's simulation review ([reading a simulation revie **Rolling back is the same action in reverse:** change the workloads' mode back to simulation (the fleet's **Change mode for selected…**, the **change…** beside the mode on the workload page, or `innerwall workload set-mode simulation`). Nothing is dropped from the moment the agent applies it. > [!WARNING] -> The review's verdict and its acknowledgment live in the promote flow only. The fleet's **Change mode for selected…**, the **change…** beside the mode on the workload page, `innerwall workload set-mode`, and `POST /api/v1/mode-changes` set any mode, enforced included, in one step, with no verdict and no acknowledgment, even for a workload with no simulation evidence at all. Promote through the review; use mode changes to roll back or to move workloads into simulation. A server-side evidence guard is on the [roadmap](../../ROADMAP.md). +> The console gates every change to enforced, wherever it starts. The fleet's **Change mode for selected…** and the **change…** beside the mode on the workload page give each workload the change would move the verdict the review composes for that workload alone, over the review's default range (the last 24 hours), and when any of them is not safe or never simulated, the dialog counts them ("No simulation evidence for N of M selected", "Not safe to enforce for N of M selected"), names the workloads behind each count, and enforces only after the same explicit acknowledgment a promotion past an unsafe verdict takes. It is the deliberate way to enforce what the review would not offer, such as a re-enrolled host whose previous identity earned enforcement; promote through the review otherwise. Changes to visibility or simulation stay one step. The gate is the console's: `innerwall workload set-mode` and `POST /api/v1/mode-changes` set any mode, enforced included, in one step, with no verdict and no acknowledgment, even for a workload with no simulation evidence at all. A server-side evidence guard is on the [roadmap](../../ROADMAP.md). ## What enforcement looks like on the host diff --git a/docs/reference/innerwall-cli.md b/docs/reference/innerwall-cli.md index ffadf98..091745e 100644 --- a/docs/reference/innerwall-cli.md +++ b/docs/reference/innerwall-cli.md @@ -234,7 +234,7 @@ innerwall workload retire - **`counts`** prints the active fleet's size: `removed`, then each sync state, then the total, then `retired`. A removed workload is counted in `removed` alone, so the lines above the total sum to it; a retired workload is outside the total and counted in `retired` alone. It is the read `GET /api/v1/workloads/counts` serves. - **`status`** prints one workload in full: mode, lifecycle (active, or retired and when), sync state, the owned table's state, applied and latest versions, last seen on the control channel, last flow report, last snapshot sent, last acknowledgment, last failed apply, credential expiry and any late renewal, agent version, dropped flow records, source overruns, clock skew, addresses, host facts, and listening services. - **`set-labels`** replaces the workload's whole label set and renders. The labels are admitted against the grammar (ADR-0022). -- **`set-mode`** changes one workload's mode, as a recorded mode change of exactly that workload, and renders. It does not consult the simulation review: the review's verdict and its acknowledgment gate are in the console's promote flow only ([promotion and enforcement](../guides/promotion-and-enforcement.md)). +- **`set-mode`** changes one workload's mode, as a recorded mode change of exactly that workload, and renders. It does not consult the simulation review: the review's verdict and its acknowledgment gate are the console's, on its promote flow and on its mode changes to enforced, and `set-mode` enforces with neither ([promotion and enforcement](../guides/promotion-and-enforcement.md)). - **`resend-snapshot`** directs the workload's agent to reconnect, so its new stream begins with a snapshot. Delivery is not confirmed: the `last snapshot` instant in `workload status` advances when the agent has reconnected ([states](states.md#resend-snapshot)). - **`retire`** retires the workload, one way, through the function `POST /api/v1/workloads/{id}/retire` calls: its credential is refused from then on, its live stream is ended, its addresses leave every peer set, and an open silence of its agent is stored as an evidence gap. It prints the instant, how many workloads' policy versions advanced, and the silence it closed, if any. A retired workload's labels and mode can no longer be changed. Its history stays readable by its id; the host returns only by enrolling again, as a new workload ([states](states.md#retired)). Until the old credential expires, enrollment on the host refuses to overwrite it: stop the daemon and remove the agent's state directory first ([credential lifecycle](../guides/credential-lifecycle.md#beyond-the-grace-re-enrollment)). diff --git a/ui/src/routes/fleet/ModeChangeDialog.tsx b/ui/src/routes/fleet/ModeChangeDialog.tsx index 9e38fe9..264a4cd 100644 --- a/ui/src/routes/fleet/ModeChangeDialog.tsx +++ b/ui/src/routes/fleet/ModeChangeDialog.tsx @@ -1,8 +1,11 @@ -import { useEffect, useState } from "react"; +import { useEffect, useId, useRef, useState } from "react"; +import { Link } from "react-router"; import type { ProblemError } from "@/api/client"; import { createModeChange } from "@/api/fleet"; import { type Mode, ProblemType, type Workload } from "@/api/schema"; import { ChoiceChips, modes } from "@/components/fleet/status"; +import { LoadingRow, ProblemNotice } from "@/components/Problem"; +import { defaultRange } from "@/components/RangeControl"; import { SeverityNote, StatusGlyph } from "@/components/StatusGlyph"; import { Button } from "@/components/ui/button"; import { @@ -13,7 +16,11 @@ import { DialogFooter, DialogHeader, } from "@/components/ui/dialog"; -import { useWrite } from "@/lib/resource"; +import { count } from "@/lib/format"; +import { useResource, useWrite } from "@/lib/resource"; +import { cn } from "@/lib/utils"; +import { loadWorkloadEvidence } from "../review/data"; +import { type EnforceEvidence, enforceEvidence } from "../review/model"; const order: Mode[] = ["visibility", "simulation", "enforced"]; const shown = 8; @@ -25,6 +32,15 @@ const shown = 8; // both numbers rather than applied to a set nobody reviewed. Success is // an acknowledgement of the recorded intent, not of progress: the list // shows convergence as each workload's applied version meets latest. +// +// A change to enforced from here does not pass through the simulation +// review, so it brings the review's evidence with it: each workload it +// would move is given the verdict the review composes for it, and when +// any of them is not safe, or never simulated, the confirm waits on the +// same explicit acknowledgment a promotion past an unsafe verdict takes +// (ADR-0001). It stays the deliberate way to enforce what the review +// would not offer, and says so. A change to visibility or simulation +// only loosens, and stays one step. export function ModeChangeDialog({ title = "Change mode for selected", open, @@ -44,6 +60,12 @@ export function ModeChangeDialog({ const [target, setTarget] = useState(null); const [submitting, setSubmitting] = useState(false); const [problem, setProblem] = useState(null); + const [acknowledged, setAcknowledged] = useState(false); + // The operator tried to confirm before acknowledging: the + // acknowledgment says what it is waiting for and takes the focus. + const [nudged, setNudged] = useState(false); + const ackRef = useRef(null); + const ackHintId = useId(); useEffect(() => { if (open) { @@ -51,6 +73,30 @@ export function ModeChangeDialog({ setProblem(null); } }, [open]); + // biome-ignore lint/correctness/useExhaustiveDependencies: a new target or a reopened dialog asks again + useEffect(() => { + setAcknowledged(false); + setNudged(false); + }, [open, target]); + + const enforcing = open && target === "enforced"; + const moving = workloads.filter((w) => w.mode !== "enforced"); + const { resource: evidence, reload: reloadEvidence } = useResource( + async () => + enforcing + ? enforceEvidence(workloads, await loadWorkloadEvidence(moving)) + : null, + [enforcing, workloads.map((w) => `${w.id}:${w.mode}`).join(",")], + ); + const judged = + enforcing && evidence.status === "ready" ? evidence.data : null; + const unsupported = judged + ? judged.unsimulated.length + judged.notSafe.length + : 0; + // The evidence for a change to enforced is still being read or could + // not be: nothing is submitted without it. + const gateHeld = enforcing && moving.length > 0 && judged === null; + const awaitingAck = unsupported > 0 && !acknowledged; const already = target ? workloads.filter((w) => w.mode === target).length @@ -58,6 +104,15 @@ export function ModeChangeDialog({ async function submit() { if (!target) return; + // The confirm is never a disabled control while it waits on the + // evidence or the acknowledgment: a click it cannot act on changes + // nothing and keeps the dialog open. + if (gateHeld) return; + if (awaitingAck) { + setNudged(true); + ackRef.current?.focus(); + return; + } setSubmitting(true); setProblem(null); try { @@ -136,6 +191,60 @@ export function ModeChangeDialog({ ) : null} + {enforcing && moving.length > 0 ? ( + evidence.status === "error" ? ( + + ) : judged ? ( + + ) : ( + + ) + ) : null} + {judged && unsupported > 0 ? ( +
+ + {nudged && !acknowledged ? ( +
+ + Nothing was enforced. Check the acknowledgment above to + enforce anyway. + +
+ ) : null} +
+ ) : null} {mismatch ? (
+ {/* A confirm held back by the evidence or the acknowledgment + is the plate's disabled state, kept focusable so its + reason can be reached. */} ); } + +// Evidence is the verdict block of a change to enforced: the review's +// own headline for the set, how many of the selection no verdict stands +// behind, and the workloads behind each count. +function Evidence({ + judged, + selected, + unsupported, +}: { + judged: EnforceEvidence; + selected: number; + unsupported: number; +}) { + const safe = unsupported === 0; + const u = judged.unsimulated.length; + const k = judged.notSafe.length; + const counts = [ + u > 0 + ? `No simulation evidence for ${count(u)} of ${count(selected)} selected` + : null, + k > 0 + ? `Not safe to enforce for ${count(k)} of ${count(selected)} selected` + : null, + ].filter((x): x is string => x !== null); + const n = (x: number) => `${count(x)} ${x === 1 ? "workload" : "workloads"}`; + const row = + "grid min-h-row-pitch grid-cols-[1fr_auto] items-center gap-x-4 border-t border-hairline px-3 py-2 first:border-t-0"; + const num = "type-mono-sm text-secondary"; + const host = (w: Workload) => ( + + {w.hostname} + + ); + return ( +
+
+ +
+
+ {safe ? "Safe to enforce" : "Not safe to enforce yet"} +
+
+ {safe + ? "No observed traffic would be dropped." + : `${counts.join("; ")}.`} +
+
+
+ {!safe ? ( +
+ {u > 0 ? ( +
+ + + Never simulated{" "} + no verdict + + {judged.unsimulated.slice(0, shown).map(host)} + {u > shown ? ( + + +{u - shown} more + + ) : null} + + {n(u)} +
+ ) : null} + {judged.notSafe.slice(0, shown).map(({ workload: w, verdict }) => ( +
+ + {host(w)} + + {verdict.failing[0]?.text ?? verdict.headline} + + + {n(1)} +
+ ))} + {k > shown ? ( +
+ + +{k - shown} more not safe to enforce + + {n(k - shown)} +
+ ) : null} + {judged.safe.length > 0 ? ( +
+ Safe to enforce + {n(judged.safe.length)} +
+ ) : null} + {judged.enforced.length > 0 ? ( +
+ Already enforced + {n(judged.enforced.length)} +
+ ) : null} +
+ ) : null} +

+ Each verdict is the one the{" "} + + simulation review + {" "} + composes for the workload over the last {defaultRange}. + {safe + ? "" + : " This enforces the selection as chosen; the review promotes only the workloads that earned it."} +

+
+ ); +} diff --git a/ui/src/routes/fleet/fleet.test.tsx b/ui/src/routes/fleet/fleet.test.tsx index d4ef83e..a2853d5 100644 --- a/ui/src/routes/fleet/fleet.test.tsx +++ b/ui/src/routes/fleet/fleet.test.tsx @@ -1,16 +1,20 @@ import { screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterAll, describe, expect, it, vi } from "vitest"; -import type { Workload } from "@/api/schema"; +import type { EvidenceGap, RollupGroup, Workload } from "@/api/schema"; import { hoursFromNow, minutesAgo, workload } from "@/test/fixtures"; import { chip, + emptyRollup, + gapsOf, mockSurface, problem, type Route, renderApp, signedIn, } from "@/test/harness"; +import { peer } from "@/test/map"; +import { gap, peerService, ps } from "@/test/review"; // The clock is fixed for this file: the fixtures below are instants // relative to now, built when the module loads, and the assertions read @@ -474,6 +478,7 @@ describe("mode change for selected", () => { let changed = false; const { calls } = mockSurface([ ...frame, + ...evidence({}), fleet(() => ({ workloads: changed ? [ @@ -524,8 +529,22 @@ describe("mode change for selected", () => { expect( within(dialog).getByText("1 already in enforced; the other 1 change."), ).toBeInTheDocument(); + // checkout-prod-07 is degraded: the review would not call it safe, + // so the change waits on the acknowledgment. + expect( + await within(dialog).findByText( + "Not safe to enforce for 1 of 2 selected.", + ), + ).toBeInTheDocument(); await user.click( - within(dialog).getByRole("button", { name: "Change to enforced" }), + within(dialog).getByLabelText( + "I understand 1 of these 2 workloads is not safe to enforce yet", + ), + ); + await user.click( + within(dialog).getByRole("button", { + name: "Enforce anyway on 1 workload", + }), ); await waitFor(() => @@ -601,6 +620,374 @@ describe("mode change for selected", () => { }); }); +// evidence answers the reads a change to enforced makes for each workload +// it would move: the peer-and-service groups under each decision and the +// evidence gaps, by the workload the read names. +function evidence( + groups: Record< + string, + Partial> + >, + gaps: Record = {}, +): Route[] { + return [ + { + method: "GET", + path: "/api/v1/address-groups", + reply: { status: 200, json: { address_groups: [] } }, + }, + { + method: "GET", + path: "/api/v1/flows/rollup", + reply: (_b, q) => { + const v = q.get("verdict") as "would_block" | "allowed"; + const g = groups[q.get("workload") ?? ""]?.[v] ?? []; + return { + status: 200, + json: + g.length > 0 && q.get("group_by") === "peer,service" + ? peerService(g) + : emptyRollup(q), + }; + }, + }, + { + method: "GET", + path: "/api/v1/flows/gaps", + reply: (_b, q) => ({ + status: 200, + json: gapsOf(gaps[q.get("workload") ?? ""] ?? [], q), + }), + }, + ]; +} + +function evidenceReads( + calls: { method: string; path: string }[], + what: "rollup" | "gaps", +) { + return calls + .filter((c) => c.path.startsWith(`/api/v1/flows/${what}`)) + .map((c) => new URL(c.path, "http://console.test").searchParams); +} + +const okPost: Route = { + method: "POST", + path: "/api/v1/mode-changes", + reply: { + status: 200, + json: { + mode_change_id: "5e0c1c7e-0000-4000-8000-000000000003", + matched: 1, + desired_updated: 1, + }, + }, +}; + +// A workload enrolled minutes ago: visibility, no flows, never simulated. +const fresh = workload({ + hostname: "web-new-01", + labels: { app: "web", env: "prod" }, + mode: "visibility", + enrolled_at: minutesAgo(4), +}); +// Simulating on its latest policy, every observed connection admitted. +const earned = workload({ + hostname: "web-prod-02", + labels: { app: "web", env: "prod" }, + mode: "simulation", +}); +// Simulating on its latest policy, with traffic enforcing would drop. +const dropping = workload({ + hostname: "web-prod-03", + labels: { app: "web", env: "prod" }, + mode: "simulation", +}); +const office = peer.address("192.0.2.40"); + +async function openEnforce(user: ReturnType) { + await user.click( + screen.getByRole("button", { name: "Change mode for selected…" }), + ); + const dialog = await screen.findByRole("dialog", { + name: "Change mode for selected", + }); + await user.click(within(dialog).getByRole("radio", { name: /Enforced/ })); + return dialog; +} + +describe("a change to enforced from the fleet", () => { + it("holds a workload with no simulation evidence for the acknowledgment and writes nothing without it", async () => { + const { calls } = mockSurface([ + ...frame, + fleet(() => ({ workloads: [fresh], next_cursor: null })), + ...evidence({}), + okPost, + ]); + const user = userEvent.setup(); + renderApp("/workloads"); + await screen.findByRole("link", { name: "web-new-01" }); + await user.click(screen.getByLabelText("Select web-new-01")); + const dialog = await openEnforce(user); + + const block = await within(dialog).findByTestId("evidence"); + expect(block).toHaveTextContent("Not safe to enforce yet"); + expect(block).toHaveTextContent( + "No simulation evidence for 1 of 1 selected.", + ); + expect(block).toHaveTextContent("Never simulated"); + expect( + within(block).getByRole("link", { name: "web-new-01" }), + ).toHaveAttribute("href", `/workloads/${fresh.id}`); + expect(block).toHaveTextContent( + "This enforces the selection as chosen; the review promotes only the workloads that earned it.", + ); + + const confirm = within(dialog).getByRole("button", { + name: "Enforce anyway on 1 workload", + }); + expect(confirm).toHaveAttribute("aria-disabled", "true"); + await user.click(confirm); + expect( + within(dialog).getByText( + "Nothing was enforced. Check the acknowledgment above to enforce anyway.", + ), + ).toBeInTheDocument(); + const ack = within(dialog).getByLabelText( + "I understand this workload is not safe to enforce yet", + ); + expect(ack).toHaveFocus(); + expect(calls.some((c) => c.method === "POST")).toBe(false); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + + await user.click(ack); + expect(confirm).not.toHaveAttribute("aria-disabled"); + await user.click(confirm); + await waitFor(() => + expect(calls.find((c) => c.method === "POST")?.body).toEqual({ + workload_ids: [fresh.id], + target_mode: "enforced", + expected_match_count: 1, + }), + ); + }); + + it("reads each workload's evidence over the review's default range and enforces safe evidence in one step, as a promotion does", async () => { + const { calls } = mockSurface([ + ...frame, + fleet(() => ({ workloads: [earned], next_cursor: null })), + ...evidence({ + [earned.id]: { allowed: [ps(office, "tcp/443", 120, 1)] }, + }), + okPost, + ]); + const user = userEvent.setup(); + renderApp("/workloads"); + await screen.findByRole("link", { name: "web-prod-02" }); + await user.click(screen.getByLabelText("Select web-prod-02")); + const dialog = await openEnforce(user); + + const block = await within(dialog).findByTestId("evidence"); + expect(block).toHaveTextContent("Safe to enforce"); + expect(block).toHaveTextContent("No observed traffic would be dropped."); + expect(within(dialog).queryByRole("checkbox")).not.toBeInTheDocument(); + + // The same four rollups and the gaps the review reads, for this + // one workload, over the last 24 hours. + const rollups = evidenceReads(calls, "rollup"); + expect( + rollups.map((q) => `${q.get("group_by")} ${q.get("verdict")}`).sort(), + ).toEqual([ + "peer,service allowed", + "peer,service would_block", + "src,dst allowed", + "src,dst would_block", + ]); + const gaps = evidenceReads(calls, "gaps"); + expect(gaps).toHaveLength(1); + for (const q of [...rollups, ...gaps]) { + expect(q.get("workload")).toBe(earned.id); + expect( + Date.parse(q.get("to") ?? "") - Date.parse(q.get("from") ?? ""), + ).toBe(24 * 3_600_000); + } + + await user.click( + within(dialog).getByRole("button", { name: "Change to enforced" }), + ); + await waitFor(() => + expect(calls.find((c) => c.method === "POST")?.body).toEqual({ + workload_ids: [earned.id], + target_mode: "enforced", + expected_match_count: 1, + }), + ); + }); + + it("counts a mixed selection by what stands behind each workload and asks once for the batch", async () => { + const enforcedAlready = workload({ + hostname: "web-prod-04", + labels: { app: "web", env: "prod" }, + mode: "enforced", + }); + const gapped = workload({ + hostname: "web-prod-05", + labels: { app: "web", env: "prod" }, + mode: "simulation", + }); + const { calls } = mockSurface([ + ...frame, + fleet(() => ({ + workloads: [fresh, earned, dropping, gapped, enforcedAlready], + next_cursor: null, + })), + ...evidence( + { + [earned.id]: { allowed: [ps(office, "tcp/443", 120, 1)] }, + [dropping.id]: { + would_block: [ps(office, "tcp/22", 4, 1)], + allowed: [ps(office, "tcp/443", 80, 1)], + }, + [gapped.id]: { allowed: [ps(office, "tcp/443", 60, 1)] }, + }, + { [gapped.id]: [gap(gapped, 90, 80)] }, + ), + okPost, + ]); + const user = userEvent.setup(); + renderApp("/workloads"); + await screen.findByRole("link", { name: "web-new-01" }); + await user.click(screen.getByLabelText("Select all shown")); + const dialog = await openEnforce(user); + + const block = await within(dialog).findByTestId("evidence"); + expect(block).toHaveTextContent( + "No simulation evidence for 1 of 5 selected; Not safe to enforce for 2 of 5 selected.", + ); + expect( + within(block).getByRole("link", { name: "web-new-01" }), + ).toBeInTheDocument(); + const droppingRow = within(block) + .getByRole("link", { name: "web-prod-03" }) + .closest("div"); + expect(droppingRow).toHaveTextContent( + "1 peer/service pair would be dropped", + ); + const gappedRow = within(block) + .getByRole("link", { name: "web-prod-05" }) + .closest("div"); + expect(gappedRow).toHaveTextContent("Evidence incomplete for web-prod-05"); + expect(block).toHaveTextContent("Safe to enforce1 workload"); + expect(block).toHaveTextContent("Already enforced1 workload"); + expect( + within(block).queryByRole("link", { name: "web-prod-02" }), + ).not.toBeInTheDocument(); + // The enforced workload is not moved, so its evidence is not read. + expect( + evidenceReads(calls, "rollup").some( + (q) => q.get("workload") === enforcedAlready.id, + ), + ).toBe(false); + + const confirm = within(dialog).getByRole("button", { + name: "Enforce anyway on 4 workloads", + }); + await user.click(confirm); + expect(calls.some((c) => c.method === "POST")).toBe(false); + await user.click( + within(dialog).getByLabelText( + "I understand 3 of these 5 workloads are not safe to enforce yet", + ), + ); + expect(within(dialog).getAllByRole("checkbox")).toHaveLength(1); + await user.click(confirm); + await waitFor(() => + expect(calls.find((c) => c.method === "POST")?.body).toEqual({ + workload_ids: [ + fresh.id, + earned.id, + dropping.id, + gapped.id, + enforcedAlready.id, + ], + target_mode: "enforced", + expected_match_count: 5, + }), + ); + }); + + it("writes nothing while the evidence cannot be read", async () => { + const { calls } = mockSurface([ + ...frame, + fleet(() => ({ workloads: [earned], next_cursor: null })), + { + method: "GET", + path: "/api/v1/flows/rollup", + reply: { status: 500, problem: problem("internal", 500) }, + }, + ...evidence({}), + okPost, + ]); + const user = userEvent.setup(); + renderApp("/workloads"); + await screen.findByRole("link", { name: "web-prod-02" }); + await user.click(screen.getByLabelText("Select web-prod-02")); + const dialog = await openEnforce(user); + expect( + await within(dialog).findByText(/each workload's evidence/), + ).toBeInTheDocument(); + const confirm = within(dialog).getByRole("button", { + name: "Change to enforced", + }); + expect(confirm).toHaveAttribute("aria-disabled", "true"); + await user.click(confirm); + expect(calls.some((c) => c.method === "POST")).toBe(false); + }); + + it.each([ + ["simulation", "Simulation"], + ["visibility", "Visibility"], + ] as const)( + "keeps a change to %s one step, with no evidence read", + async (mode, label) => { + const { calls } = mockSurface([ + ...frame, + fleet(() => ({ + workloads: [{ ...dropping, mode: "enforced" }, fresh], + next_cursor: null, + })), + ...evidence({}), + okPost, + ]); + const user = userEvent.setup(); + renderApp("/workloads"); + await screen.findByRole("link", { name: "web-new-01" }); + await user.click(screen.getByLabelText("Select all shown")); + await user.click( + screen.getByRole("button", { name: "Change mode for selected…" }), + ); + const dialog = await screen.findByRole("dialog"); + await user.click( + within(dialog).getByRole("radio", { name: new RegExp(label) }), + ); + expect(within(dialog).queryByTestId("evidence")).not.toBeInTheDocument(); + expect(within(dialog).queryByRole("checkbox")).not.toBeInTheDocument(); + await user.click( + within(dialog).getByRole("button", { name: `Change to ${mode}` }), + ); + await waitFor(() => + expect(calls.find((c) => c.method === "POST")?.body).toEqual({ + workload_ids: [dropping.id, fresh.id], + target_mode: mode, + expected_match_count: 2, + }), + ); + expect(evidenceReads(calls, "rollup")).toHaveLength(0); + expect(evidenceReads(calls, "gaps")).toHaveLength(0); + }, + ); +}); + const decommissioned = workload({ hostname: "batch-prod-01", labels: { app: "batch", env: "prod" }, diff --git a/ui/src/routes/review/data.ts b/ui/src/routes/review/data.ts index 4830607..7f87a80 100644 --- a/ui/src/routes/review/data.ts +++ b/ui/src/routes/review/data.ts @@ -13,15 +13,19 @@ import type { Ruleset, Workload, } from "@/api/schema"; -import { type RangeKey, ranges } from "@/components/RangeControl"; +import { defaultRange, type RangeKey, ranges } from "@/components/RangeControl"; import { type ByVerdict, + buildRows, + composeVerdict, peerGroupOf, type ReviewRollups, type ReviewVerdict, + type ReviewVerdictResult, reviewVerdicts, scopeRequirements, serviceName, + type WorkloadEvidence, } from "./model"; // The most groups one rollup returns, and the page size of the walk of @@ -76,6 +80,69 @@ function rollup( }); } +// How many workloads' evidence is read at once when a selection's is. +const evidenceConcurrency = 4; + +// loadWorkloadEvidence composes, for each workload a change to enforced +// would move, the verdict the simulation review would give a scope of +// that workload alone, over the review's default range: the same four +// rollups and the same evidence gaps the review reads for a ruleset's +// scope, read for the one workload, and the same composition. There is +// no second evidence rule here; what the review calls safe is safe, and +// a workload that never simulated fails as the review fails it. +export async function loadWorkloadEvidence( + workloads: Workload[], + range: RangeKey = defaultRange, + now = Date.now(), +): Promise { + const to = new Date(now).toISOString(); + const from = new Date(now - ranges[range]).toISOString(); + if (workloads.length === 0) return []; + const { address_groups: addressGroups } = await listAddressGroups(); + const one = async (w: Workload): Promise => { + const read = (group_by: RollupGrouping, verdict: ReviewVerdict) => + getRollup({ + group_by, + verdict, + workload: w.id, + from, + to, + limit: rowLimit, + }); + const [wouldBlock, allowed, sdWouldBlock, sdAllowed, gaps] = + await Promise.all([ + read("peer,service", "would_block"), + read("peer,service", "allowed"), + read("src,dst", "would_block"), + read("src,dst", "allowed"), + getGaps({ workload: w.id, from, to, limit: gapLimit }), + ]); + const rollups: ReviewRollups = { + peerService: { would_block: wouldBlock, allowed }, + srcDst: { would_block: sdWouldBlock, allowed: sdAllowed }, + }; + return composeVerdict({ + rows: buildRows(rollups, addressGroups, 1), + workloads: [w], + rollups, + gaps: gaps.gaps, + gapsTruncated: gaps.truncated, + range: { from, to }, + now, + rowLimit, + }); + }; + const out: WorkloadEvidence[] = []; + for (let i = 0; i < workloads.length; i += evidenceConcurrency) { + const batch = workloads.slice(i, i + evidenceConcurrency); + const verdicts = await Promise.all(batch.map(one)); + batch.forEach((workload, j) => { + out.push({ workload, verdict: verdicts[j] }); + }); + } + return out; +} + // pairCount is how many rows a would-block rollup folds into, the count // a ruleset's tab shows. function pairCount(r: Rollup, groups: ReadonlyMap) { diff --git a/ui/src/routes/review/model.ts b/ui/src/routes/review/model.ts index a836343..5651d91 100644 --- a/ui/src/routes/review/model.ts +++ b/ui/src/routes/review/model.ts @@ -786,3 +786,57 @@ export function promotionIds( .map((u) => u.workload.id), ]; } + +// --- enforcing outside the review --------------------------------------------- + +// WorkloadEvidence is one workload's verdict as the review composes it +// for a scope of that workload alone. +export interface WorkloadEvidence { + workload: Workload; + verdict: ReviewVerdictResult; +} + +// EnforceEvidence divides the workloads a change to enforced would move +// by what their verdicts say. Unsimulated is the workloads that never +// simulated, so no verdict stands behind them (the review fails them on +// the visibility condition); notSafe is the rest the review would not +// call safe, each with its verdict; safe is what the review would +// enforce without an acknowledgment. Already enforced workloads are not +// moved and are not judged. +export interface EnforceEvidence { + safe: Workload[]; + unsimulated: Workload[]; + notSafe: WorkloadEvidence[]; + enforced: Workload[]; +} + +export function enforceEvidence( + selected: Workload[], + evidence: WorkloadEvidence[], +): EnforceEvidence { + const byId = new Map(evidence.map((e) => [e.workload.id, e])); + const out: EnforceEvidence = { + safe: [], + unsimulated: [], + notSafe: [], + enforced: [], + }; + for (const w of selected) { + if (w.mode === "enforced") { + out.enforced.push(w); + continue; + } + const e = byId.get(w.id); + if (!e) { + // No verdict was composed for it: nothing stands behind it. + out.unsimulated.push(w); + } else if (e.verdict.safe) { + out.safe.push(w); + } else if (e.verdict.failing.some((c) => c.id === "visibility")) { + out.unsimulated.push(w); + } else { + out.notSafe.push(e); + } + } + return out; +} diff --git a/ui/src/routes/workload/workload.test.tsx b/ui/src/routes/workload/workload.test.tsx index 12f2564..9b6b626 100644 --- a/ui/src/routes/workload/workload.test.tsx +++ b/ui/src/routes/workload/workload.test.tsx @@ -1006,10 +1006,27 @@ describe("resend snapshot", () => { }); }); +const noAddressGroups: Route = { + method: "GET", + path: "/api/v1/address-groups", + reply: { status: 200, json: { address_groups: [] } }, +}; + describe("mode change from the detail", () => { it("changes this one workload by id", async () => { const { calls } = surface({ + workload: () => ({ + ...db, + sync: { + ...db.sync, + state: "synced", + applied_version: 42, + latest_version: 42, + error: "", + }, + }), extra: [ + noAddressGroups, { method: "POST", path: "/api/v1/mode-changes", @@ -1030,6 +1047,11 @@ describe("mode change from the detail", () => { const dialog = await screen.findByRole("dialog", { name: "Change mode" }); expect(dialog).toHaveTextContent("this workload"); await user.click(within(dialog).getByRole("radio", { name: /Enforced/ })); + // Simulating on its latest policy with nothing the review would + // drop: the review's verdict is safe and the change is one step. + expect(await within(dialog).findByTestId("evidence")).toHaveTextContent( + "Safe to enforce", + ); await user.click( within(dialog).getByRole("button", { name: "Change to enforced" }), ); @@ -1041,6 +1063,89 @@ describe("mode change from the detail", () => { }), ); }); + + it("holds a change to enforced of a workload that never simulated for the acknowledgment", async () => { + const { calls } = surface({ + workload: () => ({ ...db, mode: "visibility" }), + extra: [ + noAddressGroups, + { + method: "POST", + path: "/api/v1/mode-changes", + reply: { + status: 200, + json: { + mode_change_id: "5e0c1c7e-0000-4000-8000-000000000004", + matched: 1, + desired_updated: 1, + }, + }, + }, + ], + }); + const user = userEvent.setup(); + renderApp(`/workloads/${db.id}`); + await user.click(await screen.findByRole("button", { name: "change…" })); + const dialog = await screen.findByRole("dialog", { name: "Change mode" }); + await user.click(within(dialog).getByRole("radio", { name: /Enforced/ })); + expect(await within(dialog).findByTestId("evidence")).toHaveTextContent( + "No simulation evidence for 1 of 1 selected.", + ); + const confirm = within(dialog).getByRole("button", { + name: "Enforce anyway on 1 workload", + }); + await user.click(confirm); + expect(calls.some((c) => c.method === "POST")).toBe(false); + await user.click( + within(dialog).getByLabelText( + "I understand this workload is not safe to enforce yet", + ), + ); + await user.click(confirm); + await waitFor(() => + expect(calls.find((c) => c.method === "POST")?.body).toEqual({ + workload_ids: [db.id], + target_mode: "enforced", + expected_match_count: 1, + }), + ); + }); + + it("keeps a change to simulation one step", async () => { + const { calls } = surface({ + workload: () => ({ ...db, mode: "visibility" }), + extra: [ + { + method: "POST", + path: "/api/v1/mode-changes", + reply: { + status: 200, + json: { + mode_change_id: "5e0c1c7e-0000-4000-8000-000000000005", + matched: 1, + desired_updated: 1, + }, + }, + }, + ], + }); + const user = userEvent.setup(); + renderApp(`/workloads/${db.id}`); + await user.click(await screen.findByRole("button", { name: "change…" })); + const dialog = await screen.findByRole("dialog", { name: "Change mode" }); + await user.click(within(dialog).getByRole("radio", { name: /Simulation/ })); + expect(within(dialog).queryByTestId("evidence")).not.toBeInTheDocument(); + await user.click( + within(dialog).getByRole("button", { name: "Change to simulation" }), + ); + await waitFor(() => + expect(calls.find((c) => c.method === "POST")?.body).toEqual({ + workload_ids: [db.id], + target_mode: "simulation", + expected_match_count: 1, + }), + ); + }); }); describe("label editor", () => {