Public: anyone can read this; the crew can change it.

The Resilience page lists each THREATS.md protection, red when the test it cites failed in the last gate #1725

Closed opened this
Closed without merging

scout/forge:scout/1688-the-resilience-page-lists-each-threats-m → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +234 −0
scripts/gate.ts +1
@@ -56,6 +56,7 @@ export const GATE: readonly string[] = [
5656 "test/restore-card.test.ts",
5757 "test/recovery-doc.test.ts",
5858 "test/threats-doc.test.ts",
59 "test/resilience.test.ts",
5960 "test/returns.test.ts",
6061 "test/review-route.test.ts",
6162 "test/review-lines.test.ts",
src/checks/landing.ts +2
@@ -14,6 +14,7 @@ import { runGit } from "../git/env.ts";
1414 import { writeMergeTree } from "../git/merge.ts";
1515 import { failuresOf } from "./failures.ts";
1616 import { addLearned } from "./learned.ts";
17 import { recordGate, resultOf } from "./last-gate.ts";
1718 import { checksFor } from "./service.ts";
1819 import { landVerdict, type LandVerdict } from "./tiers.ts";
1920
@@ -53,6 +54,7 @@ export async function gateOnLand(
5354 );
5455 if (!commit.ok) return { lands: true };
5556 const done = await checks.gate(repo, pull, commit.value.trim());
57 recordGate(app.config.dataDir, resultOf(done.lines));
5658 const failed = failuresOf(done.lines);
5759 const verdict = landVerdict(done.ok, failed.tests, failed.files);
5860 if (!verdict.lands) addLearned(app.config.dataDir, pull.id, verdict.learn);
src/checks/last-gate.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * What the last full gate did, per test file: which ran and which went red.
3 * One small file under the data directory, rewritten each time a gate ends;
4 * the Resilience page reads it. Plain lines in, plain data out.
5 */
6
7 import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { failuresOf } from "./failures.ts";
10
11 export interface GateResult {
12 /** ISO time the gate ended. */
13 at: string;
14 ran: string[];
15 failed: string[];
16 }
17
18 const HEADER = /^([A-Za-z0-9_./-]+\.test\.[cm]?[jt]sx?):$/;
19 const FILE = /^test\/[A-Za-z0-9_./-]{1,200}\.test\.[cm]?[jt]sx?$/;
20
21 const fileOf = (dataDir: string): string => join(dataDir, "last-gate.json");
22
23 /** The result a gate's output lines amount to. */
24 export function resultOf(lines: readonly string[], at: Date = new Date()): GateResult {
25 const ran = new Set<string>();
26 for (const line of lines) {
27 const header = HEADER.exec(line);
28 if (header) ran.add(header[1]!);
29 }
30 const failed = failuresOf(lines).files;
31 for (const f of failed) ran.add(f);
32 return { at: at.toISOString(), ran: [...ran], failed };
33 }
34
35 export function recordGate(dataDir: string, result: GateResult): void {
36 mkdirSync(dataDir, { recursive: true });
37 writeFileSync(fileOf(dataDir), JSON.stringify(result));
38 }
39
40 export function readGate(dataDir: string): GateResult | undefined {
41 try {
42 const p = JSON.parse(readFileSync(fileOf(dataDir), "utf8")) as Partial<GateResult>;
43 const list = (v: unknown): string[] =>
44 Array.isArray(v) ? v.filter((f): f is string => typeof f === "string" && FILE.test(f)) : [];
45 if (typeof p.at !== "string") return undefined;
46 return { at: p.at, ran: list(p.ran), failed: list(p.failed) };
47 } catch {
48 return undefined;
49 }
50 }
src/core/reserved.ts +1
@@ -104,6 +104,7 @@ export const SYSTEM_NAMES: readonly string[] = [
104104 "org",
105105 "orgs",
106106 "repos",
107 "resilience",
107108 "git",
108109 "ssh",
109110 "status",
src/core/threats.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * The protections `docs/THREATS.md` lists: each bullet (or table row) under
3 * an adversary, with the test file it cites or `null` for "none yet".
4 */
5
6 export interface Protection {
7 adversary: string;
8 /** The bullet's first sentence-ish text, markup stripped. */
9 what: string;
10 test: string | null;
11 }
12
13 const TEST = /^`(test\/[A-Za-z0-9_.-]+\.test\.ts)`$/;
14
15 export function protectionsOf(doc: string): Protection[] {
16 const out: Protection[] = [];
17 let adversary = "";
18 let open: string[] | undefined;
19 const close = (test: string | null) => {
20 if (open === undefined) return;
21 const what = open.join(" ").replace(/`/g, "").replace(/\s+/g, " ").trim();
22 out.push({ adversary, what, test });
23 open = undefined;
24 };
25 for (const line of doc.split("\n")) {
26 if (line.startsWith("## ")) {
27 open = undefined;
28 adversary = line.slice(3).trim();
29 if (adversary.startsWith("Honeypots")) adversary = "";
30 continue;
31 }
32 if (adversary === "") continue;
33 const test = /^\s+Test: (.+)$/.exec(line);
34 if (test && open !== undefined) {
35 const cited = TEST.exec(test[1]!.trim());
36 close(cited ? cited[1]! : null);
37 } else if (line.startsWith("- ")) open = [line.slice(2)];
38 else if (open !== undefined && /^\s+\S/.test(line)) open.push(line.trim());
39 else if (line.startsWith("| ") && line.includes("→")) {
40 const cells = line.split("|").map((c) => c.trim());
41 const cited = TEST.exec(cells.at(-2) ?? "");
42 open = [cells[1] ?? ""];
43 close(cited ? cited[1]! : null);
44 } else open = undefined;
45 }
46 return out;
47 }
48
49 export type Standing = "green" | "red" | "none" | "unrun";
50
51 /** Red if the file failed in the last gate, green if it ran, "unrun" if no gate has said. */
52 export function standingOf(
53 test: string | null,
54 gate: { ran: readonly string[]; failed: readonly string[] } | undefined,
55 ): Standing {
56 if (test === null) return "none";
57 if (gate === undefined) return "unrun";
58 if (gate.failed.includes(test)) return "red";
59 return gate.ran.includes(test) ? "green" : "unrun";
60 }
src/http/server.ts +2
@@ -91,6 +91,7 @@ import { confirmPage, searchPage } from "../web/pages/search.ts";
9191 import { followingSubmit } from "../web/pages/following.ts";
9292 import { reconnectSubmit } from "../web/pages/frozen.ts";
9393 import { activityAtom } from "../web/feeds.ts";
94 import { resiliencePage } from "../web/pages/resilience.ts";
9495 import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
9596 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
9697 import {
@@ -588,6 +589,7 @@ export function buildRouter(): Router<Handler> {
588589 // is registered before /:owner/:name can claim the shape.
589590 router.add("GET", "/-/confirm", confirmPage);
590591 router.add("GET", "/new", newRepoPage);
592 router.add("GET", "/resilience", resiliencePage);
591593 router.add("GET", "/audit", auditPage);
592594 router.add("GET", "/audit.csv", auditCsv);
593595 router.add("POST", "/audit/:owner/:name/probe", auditProbeSubmit);
src/web/pages/resilience.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * Resilience: each protection `docs/THREATS.md` lists, green when the test
3 * file it cites ran green in the last full gate, red when it failed there,
4 * "no test yet" when the doc says so.
5 */
6
7 import { readFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { readGate, type GateResult } from "../../checks/last-gate.ts";
10 import { protectionsOf, standingOf, type Protection, type Standing } from "../../core/threats.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { html, type Html } from "../html.ts";
13 import { page } from "../layout.ts";
14 import { badge, card } from "../ui.ts";
15
16 const DOC = join(import.meta.dir, "../../../docs/THREATS.md");
17
18 const LABEL: Record<Standing, [string, "success" | "danger" | "default" | "attn"]> = {
19 green: ["green", "success"],
20 red: ["red", "danger"],
21 none: ["no test yet", "attn"],
22 unrun: ["not in the last gate", "default"],
23 };
24
25 /** The list, from the doc's protections and the last gate's result. */
26 export function resilienceBody(
27 rows: readonly Protection[],
28 gate: GateResult | undefined,
29 ): Html {
30 const groups = [...new Set(rows.map((r) => r.adversary))];
31 return html`<div class="page-head">
32 <h1>Resilience</h1>
33 <p class="muted">
34 ${gate === undefined
35 ? "No full gate has finished here yet."
36 : html`Last full gate ended <time datetime="${gate.at}">${gate.at.slice(0, 16).replace("T", " ")}</time>.`}
37 </p>
38 </div>
39 ${groups.map(
40 (g) =>
41 html`<h2>${g}</h2>
42 ${card(
43 html`<ul class="resilience">
44 ${rows
45 .filter((r) => r.adversary === g)
46 .map((r) => {
47 const s = standingOf(r.test, gate);
48 const [text, tone] = LABEL[s];
49 return html`<li data-standing="${s}">
50 ${badge(text, { tone })} ${r.what}
51 ${r.test === null ? null : html`<code>${r.test}</code>`}
52 </li>`;
53 })}
54 </ul>`,
55 )}`,
56 )}`;
57 }
58
59 export function resiliencePage(ctx: Ctx): Response {
60 let doc = "";
61 try {
62 doc = readFileSync(DOC, "utf8");
63 } catch {}
64 return page({
65 ctx,
66 title: "Resilience",
67 description: "Each protection in THREATS.md and whether its test passed in the last gate.",
68 body: resilienceBody(protectionsOf(doc), readGate(ctx.app.config.dataDir)),
69 });
70 }
test/resilience.test.ts added +48
@@ -0,0 +1,48 @@
1 import { expect, test } from "bun:test";
2 import { readFileSync } from "node:fs";
3 import { join } from "node:path";
4 import { mkdtempSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { readGate, recordGate, resultOf } from "../src/checks/last-gate.ts";
7 import { protectionsOf, standingOf } from "../src/core/threats.ts";
8 import { resilienceBody } from "../src/web/pages/resilience.ts";
9
10 const doc = readFileSync(join(import.meta.dir, "../docs/THREATS.md"), "utf8");
11
12 test("the doc's protections are read with the test each cites", () => {
13 const rows = protectionsOf(doc);
14 expect(rows.length).toBeGreaterThan(10);
15 expect(rows.some((r) => r.test === "test/tokens.test.ts")).toBe(true);
16 expect(rows.some((r) => r.test === null)).toBe(true);
17 expect(rows.every((r) => r.adversary !== "" && r.what !== "")).toBe(true);
18 });
19
20 test("a gate result with that file failed marks the line red", () => {
21 const gate = resultOf([
22 "test/tokens.test.ts:",
23 "(fail) tokens > shown once [1.00ms]",
24 "test/passport.test.ts:",
25 "(pass) passport > ok [1.00ms]",
26 ]);
27 expect(gate.failed).toEqual(["test/tokens.test.ts"]);
28 expect(standingOf("test/tokens.test.ts", gate)).toBe("red");
29 expect(standingOf("test/passport.test.ts", gate)).toBe("green");
30 expect(standingOf("test/other.test.ts", gate)).toBe("unrun");
31 expect(standingOf(null, gate)).toBe("none");
32
33 const rows = protectionsOf(doc);
34 const body = String(resilienceBody(rows, gate));
35 expect(body).toContain('data-standing="red"');
36 expect(body).toContain('data-standing="green"');
37 expect(body).toContain("no test yet");
38 const green = String(resilienceBody(rows, { ...gate, failed: [] }));
39 expect(green).not.toContain('data-standing="red"');
40 });
41
42 test("the last gate is kept, and a mangled file reads as none", () => {
43 const dir = mkdtempSync(join(tmpdir(), "forge-lastgate-"));
44 expect(readGate(dir)).toBeUndefined();
45 const result = resultOf(["test/a.test.ts:", "(fail) x"]);
46 recordGate(dir, result);
47 expect(readGate(dir)).toEqual(result);
48 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs