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

A threat model worth retiring on: the forge's security written down against intelligent adversaries, zero trust between its own parts, and the owner's operational security as a first-class concern #1214

Closed opened this in answer to
Closed without merging

scout/forge:scout/1149-a-threat-model-worth-retiring-on-the-for → main 8 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +889 −0
README.md +12
@@ -595,6 +595,18 @@ carries today, each entry under the issue that owns it; an entry that is no
595595 longer hollow turns the check red, so the list only shrinks.
596596 `bun scripts/hollow.ts` prints the same lines on their own.
597597
598 ## Resilience
599
600 `docs/THREATS.md` is the forge's threat model: its adversaries, the protection
601 against each, the test that proves it (or an honest "none yet"), and the
602 internal calls between its own parts with the credential each one carries. The
603 same data (`src/kernel/threats.ts`) is shown to an admin at Settings →
604 Resilience on the web and by `R` on the terminal launcher. A line is green only
605 when a test proves it and states no gap; red follows the latest finished check
606 of the forge's own repository (`FORGE_REPO`) on its default branch. The
607 read-only, admin-only `resilience` MCP tool returns the same lines and calls
608 (anyone else gets "no such tool").
609
598610 ## Shape
599611
600612 ```
docs/THREATS.md added +103
@@ -0,0 +1,103 @@
1 # Threats — who attacks the forge, and what stands in the way
2
3 The same list lives as data in `src/kernel/threats.ts` and is drawn on
4 **Settings → Resilience** (a forge admin's page). `test/threats.test.ts` fails
5 when this file and the data disagree, when a proof names a file or title that
6 does not exist, or when a line says "none yet" without a gap. Each line below
7 names a mechanical protection and the test that proves it, or says honestly
8 that no test exists yet. Red on the Resilience page follows the latest
9 finished check: a line is red when a failing test's name contains its title
10 (the check keeps at most three names).
11
12 The stance: assume an attacker who is patient, automated and clever; trust no
13 network position; make the safe path the easy one.
14
15 ## Adversaries and their lines
16
17 Format: `id` — what stands in the way — proof (`file` · title) or **none yet**.
18
19 ### A snooper on the network
20
21 Wants: sessions, tokens, the contents of private repositories and apps (and,
22 one day, camera feeds an app serves).
23
24 | id | protection | proof |
25 | --- | --- | --- |
26 | `edge-identity` | Behind the platform edge an identity is trusted only when its signature verifies. | `test/edge-auth.test.ts` · edgeIdentity |
27 | `output-escaped` | Diffs and highlighted code are escaped on output. | `test/security-xss.test.ts` · XSS through diff/highlight rendering |
28 | `security-floor` | Every response carries the security headers. | `test/api-errors.test.ts` · the security floor still covers a miss under /api/ — **gap:** only a miss under `/api/` is checked, not every response |
outdated

Same correction as in threats.ts: CSP and Referrer-Policy are both read by the cited test.

29 | `transport` | Traffic is encrypted. | **none yet** — TLS is the edge's; nothing proves the forge refuses a plain-HTTP session cookie |
30
31 ### A stolen token
32
33 Wants: to act as its owner for as long as it lives.
34
35 | id | protection | proof |
36 | --- | --- | --- |
37 | `token-scope` | A read-only token cannot mutate through the web routes. | `test/security-merge.test.ts` · security: read-only token scope bypass |
38 | `run-token-dies` | A crew run's token expires and is deleted when the run ends. | `test/apps-adversarial.test.ts` · rule 6: a run token dies with the run |
39 | `token-anomaly` | A token used from somewhere new is noticed. | **none yet** — no detection exists |
40
41 ### A compromised vendor
42
43 Wants: a foothold through code the forge did not write.
44
45 | id | protection | proof |
46 | --- | --- | --- |
47 | `child-env` | App and agent processes start from an explicit short environment, never the forge's. | `test/apps-adversarial.test.ts` · rule 8: a child inherits nothing it was not handed |
48 | `zero-dependencies` | No runtime dependency exists to compromise. | `test/threats.test.ts` · threats: no runtime dependencies |
49 | `vendor-pinning` | The base image, Bun and git are pinned by digest. | **none yet** — trusted by tag |
50
51 ### A hostile agent inside a run
52
53 Wants: out of its sandbox, onto the default branch, or to the forge's secrets.
54
55 | id | protection | proof |
56 | --- | --- | --- |
57 | `shell-sandbox` | An agent's shell is sandboxed and denied the data directory. | `test/crew-sandbox.test.ts` · the shell sandbox |
58 | `cell-egress` | A cell reaches only declared hosts, through the proxy; never private addresses. | `test/contain.test.ts` · egress: what a cell may reach |
59 | `sealed-work` | Sealed work is invisible to strangers and readers. | `test/sealed-git.test.ts` · a stranger and a reader cannot reach the fix |
60 | `agent-cannot-land` | An agent never moves the default branch; a person lands. | `test/apps-adversarial.test.ts` · rule 1: the repository takes no push from the crew |
61
62 ### An intelligent automated attacker at scale
63
64 Wants: accounts, spam, guessable credentials, exhausted memory.
65
66 | id | protection | proof |
67 | --- | --- | --- |
68 | `body-limits` | Request bodies are capped at the boundary. | `test/body-limits.test.ts` · request body limits |
69 | `new-accounts` | Accounts younger than seven days cannot create repositories or forks (guard on). | `test/guard-new-accounts.test.ts` · guard_new_accounts |
70 | `adaptive-defence` | Probing is slowed, then refused, per source and forge-wide. | **none yet** — login and token guessing have no shared adaptive limit |
71
72 ## Zero trust between the forge's own parts
73
74 Bar: every internal call carries a short-lived, scoped credential, is logged,
75 and can be refused; nothing trusts a network position. Today:
76
77 | call | credential | short-lived | logged | proof |
78 | --- | --- | --- | --- | --- |
79 | agent run → forge | a token minted for the run, deleted at its end | yes | yes | `run-token-dies` |
80 | app cell → egress proxy | the cell's own network namespace; allowed by host | no | yes | `cell-egress` |
81 | forge proxy → app | `x-forge-identity` signed, with an expiry | yes | no | `test/apps.test.ts` |
82 | platform edge → forge | a signed identity | no | no | `edge-identity` |
83 | parent forge → child forge | a shared secret in `x-forge-parent` | no | no | **none yet** |
84
85 Four of five fall short of the bar; the Resilience page marks them. **Not

"Both are the next pulls": link them. Open the issues for the credential module and the sentinel check, and for the one-line less-than-default notice, so that merging with Closes #1149 does not lose them. Or change the pull to Part of #1149.

86 built:** a kernel module issuing the credentials, and a sentinel check that
87 flags an unauthenticated internal call. The two are #1396 and #1397, and the one-line
88 less-than-default notice is #1398; until
89 they land this table is a map, not a guarantee.
90
91 ## Security that does not get in the way
92
93 The default is the safe path: sealed values, contained runs, scoped and
94 expiring tokens. Passkeys are not built. A person should be told once, in one
95 line, when something is less than the default — today only egress "report"
96 mode says so (Settings → Capacity); the rest is not yet done.
97
98 ## Honeypots, later
99
100 A `kind: "honeypot"` app: looks like a target, records what touches it into
101 the dataset, holds nothing real. Not built; named so isolation (`contain`),
102 egress and the dataset grow toward it. A honeypot must be contained harder
103 than any app, never share a network with one, and never hold a real secret.
scripts/gate.ts +1
@@ -158,6 +158,7 @@ export const GATE: readonly string[] = [
158158 "test/forge-cloudflare-celld.test.ts",
159159 "test/branch_tell.test.ts",
160160 "test/usage.test.ts",
161 "test/threats.test.ts",
161162 "test/tokens.test.ts",
162163 "test/credentials.test.ts",
163164 "test/standing.test.ts",
src/core/resilience.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * What the forge's own latest check says, for the threat model's red.
3 *
4 * Only the forge's repository (`FORGE_REPO`, `owner/name`) on its default
5 * branch counts — production, the thing that runs. A check of any other
6 * repository, or of a pull, never repaints the forge's protections.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 /** The failing names of the forge's latest finished default-branch check. */
12 export function latestFailingNames(
13 db: Database,
14 forgeRepo: string | undefined,
15 ): string[] {
16 const [owner, name, ...rest] = (forgeRepo ?? "").split("/");
17 if (!owner || !name || rest.length > 0) return [];
18 const r = db
19 .query<{ state: string; check_detail: string }, [string, string]>(
20 `SELECT run.state, run.check_detail FROM run
21 JOIN repo ON repo.id = run.repo_id
22 JOIN user ON user.id = repo.owner_id
23 WHERE run.kind = 'check' AND run.state IN ('ok', 'failed')
24 AND run.env = repo.default_branch
25 AND user.username = ?1 COLLATE NOCASE
26 AND repo.name = ?2 COLLATE NOCASE
27 ORDER BY run.id DESC LIMIT 1`,
28 )
29 .get(owner, name);
30 if (!r || r.state !== "failed" || r.check_detail === "") return [];
31 try {
32 const names = (JSON.parse(r.check_detail) as { names?: unknown }).names;
33 return Array.isArray(names)
34 ? names.filter((n): n is string => typeof n === "string")
35 : [];
36 } catch {
37 return [];
38 }
39 }
src/http/mcp.ts +35
@@ -21,6 +21,14 @@ import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2121 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2222 import { changeLimit, listLimits } from "../actions/limits.ts";
2323 import { LIMIT_KEYS } from "../settings/limits.ts";
24 import { latestFailingNames } from "../core/resilience.ts";
25 import {
26 ADVERSARIES,
27 INTERNAL_CALLS,
28 standing,
29 THREATS,
30 weakCalls,
31 } from "../kernel/threats.ts";
2432 import { relationOf, takeUpdates } from "../actions/forks.ts";
2533 import { watchMilestone } from "../actions/watches.ts";
2634 import {
@@ -1828,6 +1836,33 @@ const TOOLS: readonly Tool[] = [
18281836 });
18291837 },
18301838 },
1839 {
1840 name: "resilience",
1841 description:
1842 "The forge's threat model, read-only, for a forge admin: each protection with its adversary, the test that proves it, the gap it states and its standing (proven, failing, partly proven or no test yet), then the internal calls between the forge's parts and which are below the bar. Red follows the latest finished check of the forge's own repository on its default branch. The same as Settings → Resilience.",
1843 inputSchema: { type: "object", properties: {} },
1844 writes: false,
1845 run(ctx, user) {
1846 if (!user.isAdmin) return bad("not_found", "no such tool here");
1847 const failing = latestFailingNames(ctx.app.db, ctx.app.config.forgeRepo);
1848 const weak = new Set(weakCalls().map((c) => c.id));
1849 return good({
1850 protections: THREATS.map((t) => ({
1851 adversary: ADVERSARIES[t.adversary],
1852 protection: t.protection,
1853 proof: t.proof?.file ?? null,
1854 gap: t.gap ?? null,
1855 standing: standing(t, failing),
1856 })),
1857 internalCalls: INTERNAL_CALLS.map((c) => ({
1858 from: c.from,
1859 to: c.to,
1860 credential: c.credential,
1861 belowTheBar: weak.has(c.id),
1862 })),
1863 });
1864 },
1865 },
18311866 ];
18321867
18331868 /**
src/http/server.ts +2
@@ -8,6 +8,7 @@
88 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
99 import { unsealReleased } from "../actions/sealed.ts";
1010 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
11 import { resiliencePage } from "../web/pages/resilience.ts";
1112 import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts";
1213 import {
1314 closeStreamsOf,
@@ -667,6 +668,7 @@ export function buildRouter(): Router<Handler> {
667668 router.add("POST", "/settings/cloud/remove", cloudRemove);
668669 router.add("GET", "/settings/capacity", capacityPage);
669670 router.add("POST", "/settings/capacity", capacitySet);
671 router.add("GET", "/settings/resilience", resiliencePage);
670672 router.add("GET", "/admin/limits", limitsPage);
671673 router.add("POST", "/admin/limits", limitsSet);
672674 router.add("GET", "/settings/backups", backupsPage);
src/kernel/threats.ts added +295
@@ -0,0 +1,295 @@
1 /**
2 * The forge's threat model as data: who attacks, what stands in the way,
3 * and the test that proves it. `docs/THREATS.md` is the same list in
4 * words; `test/threats.test.ts` fails when the two disagree, when a proof
5 * names a file or a `describe` that does not exist, or when a line claims
6 * a protection with no proof and does not say so.
7 *
8 * A line is `proven` (it names the test file and the `describe` title that
9 * holds it) or `open` (an honest "none yet", with what is missing). Pure:
10 * plain data in, plain data out.
11 */
12
13 export type Adversary =
14 | "snooper"
15 | "stolen-token"
16 | "vendor"
17 | "hostile-agent"
18 | "automated-attacker";
19
20 export const ADVERSARIES: Readonly<Record<Adversary, string>> = {
21 snooper: "A snooper on the network",
22 "stolen-token": "A stolen token",
23 vendor: "A compromised vendor",
24 "hostile-agent": "A hostile agent inside a run",
25 "automated-attacker": "An intelligent automated attacker at scale",
26 };
27
28 export interface Proof {
29 /** Repository-relative path of the test file. */
30 readonly file: string;
31 /** A `describe` or test title in that file; a failing test's name contains it. */
32 readonly needle: string;
33 }
34
35 export interface Threat {
36 readonly id: string;
37 readonly adversary: Adversary;
38 /** What stands in the way, one sentence. */
39 readonly protection: string;
40 /** The proof, or null when none exists yet. */
41 readonly proof: Proof | null;
42 /** For an open line: what is missing. */
43 readonly gap?: string;
44 }
45
46 export const THREATS: readonly Threat[] = [
47 {
48 id: "edge-identity",
49 adversary: "snooper",
50 protection:
51 "Behind the platform edge, an identity is trusted only when its signature verifies; a forged header is anonymous.",
52 proof: { file: "test/edge-auth.test.ts", needle: "edgeIdentity" },
53 },
54 {
55 id: "output-escaped",
56 adversary: "snooper",
57 protection:
58 "Diffs and highlighted code are escaped on output, so a hostile file cannot script a reader's session.",
59 proof: {
60 file: "test/security-xss.test.ts",
61 needle: "XSS through diff/highlight rendering",
62 },
63 },
64 {
65 id: "security-floor",
66 adversary: "snooper",
67 protection:
68 "Every response leaves with the security headers (CSP, nosniff, referrer policy).",
69 proof: {
70 file: "test/api-errors.test.ts",
71 needle: "the security floor still covers a miss under /api/",
72 },
73 gap: "Only a miss under /api/ is checked for the three headers, not every response.",
outdated

This gap says CSP and Referrer-Policy are unproven, but the page will badge the line "proven". Either add a test that reads all three headers on a page response (cheap, and it closes the gap) or make standing honour gap.

outdated

This gap is false: test/api-errors.test.ts:121-122 asserts referrer-policy is same-origin and that content-security-policy is set. Set the needle to "the security floor still covers a miss under /api/" and either remove the gap or state the real one: only a miss under /api/ is checked, not every response.

74 },
75 {
76 id: "transport",
77 adversary: "snooper",
78 protection: "Traffic between a person and the forge is encrypted.",
79 proof: null,
80 gap: "TLS is the edge's, not the forge's; nothing here proves the forge refuses a plain-HTTP session cookie.",
81 },
82 {
83 id: "token-scope",
84 adversary: "stolen-token",
85 protection:
86 "A read-only token cannot mutate through the web routes; scope is a floor, not a convention.",
87 proof: {
88 file: "test/security-merge.test.ts",
89 needle: "security: read-only token scope bypass",
90 },
91 },
92 {
93 id: "run-token-dies",
94 adversary: "stolen-token",
95 protection:
96 "A crew run's token expires and is deleted when the run ends; a copy taken from a run is dead afterwards.",
97 proof: {
98 file: "test/apps-adversarial.test.ts",
99 needle: "rule 6: a run token dies with the run",
100 },
101 },
102 {
103 id: "token-anomaly",
104 adversary: "stolen-token",
105 protection:
106 "A token used from somewhere new, or at a new rate, is noticed and the owner told.",
107 proof: null,
108 gap: "No detection exists; a stolen long-lived token works until its owner revokes it.",
109 },
110 {
111 id: "child-env",
112 adversary: "vendor",
113 protection:
114 "An app or agent process starts from an explicit short environment, never the forge's own, so a vendor's code in an app holds no forge secret.",
115 proof: {
116 file: "test/apps-adversarial.test.ts",
117 needle: "rule 8: a child inherits nothing it was not handed",
118 },
119 },
120 {
121 id: "zero-dependencies",
122 adversary: "vendor",
123 protection:
124 "The forge has no runtime dependency, so there is no package to compromise.",
125 proof: {
126 file: "test/threats.test.ts",
127 needle: "threats: no runtime dependencies",
128 },
129 },
130 {
131 id: "vendor-pinning",
132 adversary: "vendor",
133 protection:
134 "The base image, Bun and git are pinned and verified by digest.",
135 proof: null,
136 gap: "Dev dependencies, the base image and the toolchain are trusted by tag.",
137 },
138 {
139 id: "shell-sandbox",
140 adversary: "hostile-agent",
141 protection:
142 "An agent's shell is held to a sandbox that denies the forge's data directory.",
143 proof: { file: "test/crew-sandbox.test.ts", needle: "the shell sandbox" },
144 },
145 {
146 id: "cell-egress",
147 adversary: "hostile-agent",
148 protection:
149 "An app's cell reaches only the hosts its manifest declares, through the forge's proxy; private addresses are never reachable.",
150 proof: {
151 file: "test/contain.test.ts",
152 needle: "egress: what a cell may reach",
153 },
154 },
155 {
156 id: "sealed-work",
157 adversary: "hostile-agent",
158 protection:
159 "Sealed work is invisible to a stranger and a reader; only a writer and the crew reach it.",
160 proof: {
161 file: "test/sealed-git.test.ts",
162 needle: "a stranger and a reader cannot reach the fix",
163 },
164 },
165 {
166 id: "agent-cannot-land",
167 adversary: "hostile-agent",
168 protection:
169 "An agent never moves the default branch and never merges; a person lands.",
170 proof: {
171 file: "test/apps-adversarial.test.ts",
172 needle: "rule 1: the repository takes no push from the crew",
173 },
174 },
175 {
176 id: "body-limits",
177 adversary: "automated-attacker",
178 protection:
179 "Request bodies are capped at the boundary, so one request cannot exhaust memory.",
180 proof: {
181 file: "test/body-limits.test.ts",
182 needle: "request body limits",
183 },
184 },
185 {
186 id: "new-accounts",
187 adversary: "automated-attacker",
188 protection:
189 "The new-account guard refuses repository creation and forks by accounts younger than seven days.",
190 proof: {
191 file: "test/guard-new-accounts.test.ts",
192 needle: "guard_new_accounts",
193 },
194 },
195 {
196 id: "adaptive-defence",
197 adversary: "automated-attacker",
198 protection:
199 "Probing at machine speed is slowed, then refused, per source and for the whole forge.",
200 proof: null,
201 gap: "Reports are limited per source; login and token guessing have no shared, adaptive limit.",
202 },
203 ];
204
205 /**
206 * The internal calls and how each is authenticated today. `credential` is
207 * what a caller presents; `shortLived` and `logged` are the zero-trust
208 * bar from the issue, stated as they are, not as they should be.
209 */
210 export interface InternalCall {
211 readonly id: string;
212 readonly from: string;
213 readonly to: string;
214 readonly credential: string;
215 readonly shortLived: boolean;
216 readonly logged: boolean;
217 readonly proof: Proof | null;
218 }
219
220 export const INTERNAL_CALLS: readonly InternalCall[] = [
221 {
222 id: "runner-forge",
223 from: "agent run",
224 to: "forge",
225 credential: "a token minted for the run, expiring, deleted at the end",
226 shortLived: true,
227 logged: true,
228 proof: THREATS.find((t) => t.id === "run-token-dies")!.proof,
229 },
230 {
231 id: "cell-proxy",
232 from: "app cell",
233 to: "egress proxy",
234 credential: "the cell's own network namespace; the proxy allows by host",
235 shortLived: false,
236 logged: true,
237 proof: THREATS.find((t) => t.id === "cell-egress")!.proof,
238 },
239 {
240 id: "proxy-app",
241 from: "forge proxy",
242 to: "app",
243 credential: "x-forge-identity signed with an expiry (x-forge-signature)",
244 shortLived: true,
245 logged: false,
246 proof: {
247 file: "test/apps.test.ts",
248 needle: "apps: production, previews, data, gates, crew",
249 },
250 },
251 {
252 id: "edge-forge",
253 from: "platform edge",
254 to: "forge",
255 credential: "a signed identity the forge verifies",
256 shortLived: false,
257 logged: false,
258 proof: THREATS.find((t) => t.id === "edge-identity")!.proof,
259 },
260 {
261 id: "child-parent",
262 from: "parent forge",
263 to: "child forge",
264 credential: "a shared secret in x-forge-parent, shown by the parent",
265 shortLived: false,
266 logged: false,
267 proof: null,
268 },
269 ];
270
271 /** The calls that fall short of the bar: not short-lived, not logged, or unproven. */
272 export function weakCalls(): readonly InternalCall[] {
273 return INTERNAL_CALLS.filter(
274 (c) => !c.shortLived || !c.logged || c.proof === null,
275 );
276 }
277
278 export type Standing = "green" | "red" | "partial" | "open";
279
280 /**
281 * Where one line stands given the failing test names of the latest failed
282 * check (`CheckDetail.names`, at most three): red when a failing name
283 * belongs to the line's `describe`, open when it has no proof at all,
284 * partial when it has a proof but names a `gap` the proof does not close,
285 * green only when it has a proof, no gap and no failure.
286 */
287 export function standing(
288 threat: Pick<Threat, "proof" | "gap">,
289 failing: readonly string[],
290 ): Standing {
outdated

A proven line that also has a gap (security-floor) comes out "green" and shows as "proven". Return a distinct partial/open standing when gap is set, so the page never claims more than the test proves.

291 if (threat.proof === null) return "open";
292 const needle = threat.proof.needle;
293 if (failing.some((name) => name.includes(needle))) return "red";
294 return threat.gap ? "partial" : "green";
295 }
src/tui/screens/dashboard.ts +7
@@ -70,6 +70,7 @@ import { newRepoScreen } from "./newrepo.ts";
7070 import { pullScreen } from "./pull.ts";
7171 import { repoScreen } from "./repo.ts";
7272 import { local } from "./where.ts";
73 import { resilienceScreen } from "./resilience.ts";
7374 import { signInScreen } from "./signin.ts";
7475
7576 /**
@@ -398,6 +399,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
398399 }),
399400 binding(["n"], "new repo", { disabled: !f.signedIn }),
400401 binding(["A"], "account", { disabled: !f.signedIn }),
402 binding(["R"], "resilience", { disabled: !f.user?.isAdmin }),
401403 binding(["s"], "sign in", { disabled: f.signedIn }),
402404 binding(["r"], "refresh"),
403405 ];
@@ -530,6 +532,11 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
530532 openOnWeb(f, ctx, "/settings", "Account settings");
531533 return true;
532534 }
535 if (e.key === "R" && f.user?.isAdmin) {
536 const next = resilienceScreen(f, ctx);
537 if (next !== undefined) ctx.push(next);
538 return true;
539 }
533540 if (e.key === "s" && !f.signedIn) {
534541 ctx.push(signInScreen(f, ctx, reload));
535542 return true;
src/tui/screens/resilience.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * `R` — the forge's threat model, read-only, for an admin: one row per
3 * protection with its standing, then the internal calls and which of them
4 * are below the bar. The same data and the same gate as Settings →
5 * Resilience on the web; a member never reaches it.
6 */
7
8 import { latestFailingNames } from "../../core/resilience.ts";
9 import {
10 ADVERSARIES,
11 INTERNAL_CALLS,
12 standing,
13 THREATS,
14 weakCalls,
15 type Standing,
16 } from "../../kernel/threats.ts";
17 import type { Ctx, Screen } from "../app/app.ts";
18 import { binding } from "../app/keys.ts";
19 import type { Session } from "../session.ts";
20 import { card, type Tone } from "../ui/widgets.ts";
21 import { ListState, drawList, type ListRow } from "./common.ts";
22
23 const LOOK: Record<Standing, { tone: Tone; text: string }> = {
24 green: { tone: "success", text: "proven" },
25 red: { tone: "danger", text: "failing" },
26 partial: { tone: "attn", text: "partly proven" },
27 open: { tone: "attn", text: "no test yet" },
28 };
29
30 /** The rows the screen lists, in the page's order. Pure, so a test reads them. */
31 export function resilienceRows(failing: readonly string[]): ListRow[] {
32 const rows: ListRow[] = [];
33 for (const [key, label] of Object.entries(ADVERSARIES))
34 for (const t of THREATS.filter((x) => x.adversary === key)) {
35 const look = LOOK[standing(t, failing)];
36 rows.push({
37 title: t.protection,
38 tone: look.tone,
39 secondary: t.gap ?? t.proof?.file ?? "",
40 meta: `${label} · ${look.text}`,
41 });
42 }
43 const weak = new Set(weakCalls().map((c) => c.id));
44 for (const c of INTERNAL_CALLS)
45 rows.push({
46 title: `${c.from} → ${c.to}`,
47 tone: weak.has(c.id) ? "attn" : "success",
48 secondary: c.credential,
49 meta: weak.has(c.id) ? "internal call · below the bar" : "internal call",
50 });
51 return rows;
52 }
53
54 /** The screen, or nothing when the viewer is not an admin. */
55 export function resilienceScreen(f: Session, ctx: Ctx): Screen | undefined {
56 if (!f.user?.isAdmin) return undefined;
57 const state = new ListState();
58 const rows = resilienceRows(latestFailingNames(f.db, f.app.config.forgeRepo));
59 return {
60 title: "Resilience",
61 keys: [binding(["j", "k"], "move"), binding(["esc"], "close")],
62 render(area, s) {
63 const inner = card(s, area, ctx.theme.c, {
64 title: "Resilience",
65 footer: f.app.config.forgeRepo ?? "FORGE_REPO unset",
66 focused: true,
67 });
68 drawList(s, inner, ctx.theme.c, state, rows);
69 },
70 key(e) {
71 if (e.key === "esc") {
72 ctx.pop();
73 return true;
74 }
75 return state.key(e, rows.length);
76 },
77 };
78 }
src/web/pages/origins.ts +7
@@ -80,6 +80,7 @@ export type AccountSection =
8080 | "backups"
8181 | "secrets"
8282 | "capacity"
83 | "resilience"
8384 | "limits"
8485 | "cloud";
8586
@@ -132,6 +133,12 @@ export function accountSections(
132133 icon: "activity" as const,
133134 current: current === "capacity",
134135 },
136 {
137 label: "Resilience",
138 href: "/settings/resilience",
139 icon: "shield" as const,
140 current: current === "resilience",
141 },
135142 {
136143 label: "Limits",
137144 href: "/admin/limits",
src/web/pages/resilience.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * Resilience, for a forge admin: the threat model (`docs/THREATS.md`, as
3 * `kernel/threats.ts`) with each protection's standing. A line is green
4 * when it names a test, states no gap, and the forge's latest finished
5 * check on its default branch did not fail it; red when that check's failing
6 * names (at most three) include it; partly proven when a gap is stated; open
7 * when no test proves it yet — said plainly, never dressed as green.
8 */
9
10 import { latestFailingNames } from "../../core/resilience.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import {
13 ADVERSARIES,
14 INTERNAL_CALLS,
15 standing,
16 THREATS,
17 weakCalls,
18 type Standing,
19 } from "../../kernel/threats.ts";
20 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
21 import { html } from "../html.ts";
22 import { page } from "../layout.ts";
23 import { badge, card, icon, row } from "../ui.ts";
24 import { accountSections } from "./origins.ts";
25
26 const LOOK: Record<
27 Standing,
28 { tone: "success" | "danger" | "attn"; text: string }
29 > = {
30 green: { tone: "success", text: "proven" },
outdated

High: this is any repository's latest check, not the forge's. Another repo's failing (or passing) check repaints the forge's threat model. Filter on the forge's own repo id and default branch, and test that a foreign failure leaves lines green.

31 red: { tone: "danger", text: "failing" },
32 partial: { tone: "attn", text: "partly proven" },
33 open: { tone: "attn", text: "no test yet" },
34 };
35
36 // GET /settings/resilience
37 export function resiliencePage(ctx: Ctx): Response {
38 if (!ctx.auth.user) return signInFirst(ctx);
39 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
40 const failing = latestFailingNames(ctx.app.db, ctx.app.config.forgeRepo);
41 const groups = Object.entries(ADVERSARIES).map(([key, label]) => {
42 const rows = THREATS.filter((t) => t.adversary === key).map((t) => {
43 const s = standing(t, failing);
44 return row({
45 lead: icon("shield"),
46 title: html`${t.protection}`,
47 meta: html`${
48 t.proof
49 ? html`<span class="mono">${t.proof.file}</span>`
50 : html`None yet.`
51 }
52 ${t.gap ? html`<br />${t.gap}` : null}`,
53 trail: badge(LOOK[s].text, { tone: LOOK[s].tone }),
54 });
55 });
56 return card(
57 html`<ul class="list">
58 ${rows}
59 </ul>`,
60 {
61 head: html`<h2>${label}</h2>`,
62 pad: false,
63 },
64 );
65 });
66 const weak = new Set(weakCalls().map((c) => c.id));
67 const calls = INTERNAL_CALLS.map((c) =>
68 row({
69 lead: icon("activity"),
70 title: html`${c.from} → ${c.to}`,
71 meta: html`${c.credential}`,
72 trail: weak.has(c.id)
73 ? badge("below the bar", { tone: "attn" })
74 : badge("meets the bar", { tone: "success" }),
75 }),
76 );
77 const body = html`<p class="muted small mb">
78 The forge's threat model, one line per protection. Red follows the latest
79 finished check of
80 ${ctx.app.config.forgeRepo ?? "the forge's repository (FORGE_REPO is unset, so none)"}
81 on its default branch; it names at most three failing tests.
82 </p>
83 ${groups}
84 ${card(
85 html`<ul class="list">
86 ${calls}
87 </ul>`,
88 {
89 head: html`<h2>Internal calls</h2>`,
90 pad: false,
91 },
92 )}`;
93 return page({
94 ctx,
95 title: "Resilience",
96 body: html`<div class="page-head"><h1>Resilience</h1></div>
97 ${settingsLayout(
98 accountSections("resilience", { admin: true }),
99 body,
100 "Account settings",
101 )}`,
102 });
103 }
test/mcp.test.ts +13
@@ -199,6 +199,7 @@ describe("the forge over MCP", () => {
199199 "plan",
200200 "capacity",
201201 "limits",
202 "resilience",
202203 "report",
203204 ]);
204205 const byName = new Map<string, any>(
@@ -551,6 +552,18 @@ describe("the forge over MCP", () => {
551552 });
552553 expect(res.status).toBe(401);
553554 });
555 test("resilience: admins only, read-only, the threat model with standings", async () => {
556 expect((await tool(bobRw, "resilience")).error).toContain("no such tool");
557 const read = await tool(ro, "resilience");
558 expect(read.value.protections.length).toBeGreaterThan(0);
559 expect(
560 read.value.protections.every((p: any) =>
561 ["green", "red", "partial", "open"].includes(p.standing),
562 ),
563 ).toBe(true);
564 expect(read.value.internalCalls.some((c: any) => c.belowTheBar)).toBe(true);
565 });
566
554567 test("limits: admins only, dry by default, an admin-scope token to change", async () => {
555568 const key = "front.pinned_max";
556569 const admin = createToken(app.db, alice.id, "admin", "admin").token;
test/threats.test.ts added +194
@@ -0,0 +1,194 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import {
3 INTERNAL_CALLS,
4 standing,
5 THREATS,
6 weakCalls,
7 } from "../src/kernel/threats.ts";
8 import { latestFailingNames } from "../src/core/resilience.ts";
9 import { resilienceRows } from "../src/tui/screens/resilience.ts";
10 import { Database } from "bun:sqlite";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
17
18 const root = new URL("..", import.meta.url).pathname;
19 const doc = await Bun.file(`${root}docs/THREATS.md`).text();
20
21 describe("threats: the model and its proofs", () => {
22 test("every proof names a file and a title that exist", async () => {
23 for (const t of THREATS) {
24 if (t.proof === null) continue;
25 const text = await Bun.file(`${root}${t.proof.file}`).text();
26 expect(text.includes(t.proof.needle), `${t.id}: ${t.proof.needle}`).toBe(
27 true,
28 );
29 }
30 });
31
32 test("a line with no proof says what is missing", () => {
33 for (const t of THREATS)
34 if (t.proof === null) expect(t.gap, t.id).toBeTruthy();
35 });
36
37 test("the document and the data agree", () => {
38 for (const t of THREATS) {
39 const line = doc.split("\n").find((l) => l.startsWith(`| \`${t.id}\` |`));
40 expect(line, t.id).toBeDefined();
41 if (t.proof === null) expect(line).toContain("**none yet**");
42 else {
43 expect(line).toContain(t.proof.file);
44 expect(line).toContain(t.proof.needle);
45 }
46 }
47 expect(
48 doc.split("\n").filter((l) => /^\| `[a-z-]+` \|/.test(l)).length,
49 ).toBe(THREATS.length);
50 });
51
52 test("the internal-call map lists every call and the weak ones", () => {
53 expect(INTERNAL_CALLS.length).toBe(5);
54 expect(weakCalls().map((c) => c.id)).toContain("child-parent");
55 expect(weakCalls().map((c) => c.id)).not.toContain("runner-forge");
56 });
57 });
58
59 describe("threats: standing", () => {
60 const proven = { proof: { file: "a", needle: "the shell sandbox" } };
61 test("a failing name that contains the title marks the line red", () => {
62 expect(standing(proven, ["the shell sandbox > denies x"])).toBe("red");
63 expect(standing(proven, ["something else"])).toBe("green");
64 expect(standing({ proof: null }, [])).toBe("open");
65 });
66
67 test("a proof with a stated gap is partly proven, never green", () => {
68 const gapped = { proof: { file: "a", needle: "n" }, gap: "not all of it" };
69 expect(standing(gapped, [])).toBe("partial");
70 expect(standing(gapped, ["n > x"])).toBe("red");
71 const floor = THREATS.find((t) => t.id === "security-floor");
72 expect(floor && standing(floor, [])).toBe("partial");
73 expect(THREATS.some((t) => standing(t, []) === "green")).toBe(true);
74 });
75
76 test("only the forge's own default-branch check decides red", () => {
77 const db = new Database(":memory:");
78 db.run("CREATE TABLE user (id TEXT, username TEXT)");
79 db.run(
80 "CREATE TABLE repo (id TEXT, owner_id TEXT, name TEXT, default_branch TEXT)",
81 );
82 db.run(
83 "CREATE TABLE run (id INTEGER PRIMARY KEY, repo_id TEXT, kind TEXT, env TEXT, state TEXT, check_detail TEXT)",
84 );
85 db.run("INSERT INTO user VALUES ('u', 'trevato'), ('v', 'eve')");
86 db.run(
87 "INSERT INTO repo VALUES ('forge', 'u', 'forge', 'main'), ('other', 'v', 'x', 'main')",
88 );
89 const add = (repo: string, env: string, state: string, names: string[]) =>
90 db.run(
91 "INSERT INTO run (repo_id, kind, env, state, check_detail) VALUES (?, 'check', ?, ?, ?)",
92 [repo, env, state, JSON.stringify({ names })],
93 );
94 expect(latestFailingNames(db, "trevato/forge")).toEqual([]);
95 add("forge", "main", "failed", ["x > y"]);
96 expect(latestFailingNames(db, "trevato/forge")).toEqual(["x > y"]);
97 // A foreign failure, a foreign pass and a pull's pass change nothing.
98 add("other", "main", "failed", ["z > w"]);
99 add("other", "main", "ok", []);
100 add("forge", "pull-3", "ok", []);
101 expect(latestFailingNames(db, "trevato/forge")).toEqual(["x > y"]);
102 // Foreign failure alone leaves every line off red.
103 const failing = latestFailingNames(db, "eve/nothing");
104 expect(failing).toEqual([]);
105 expect(THREATS.every((t) => standing(t, failing) !== "red")).toBe(true);
106 // The forge's own next default-branch pass clears it.
107 add("forge", "main", "ok", []);
108 expect(latestFailingNames(db, "trevato/forge")).toEqual([]);
109 // No forge repository named: nothing is known, nothing is red.
110 expect(latestFailingNames(db, undefined)).toEqual([]);
111 });
112
113 test("the terminal lists every protection and every internal call", () => {
114 const rows = resilienceRows([]);
115 expect(rows.length).toBe(THREATS.length + INTERNAL_CALLS.length);
116 expect(rows.some((r) => r.meta?.includes("partly proven"))).toBe(true);
117 expect(rows.some((r) => r.meta?.includes("below the bar"))).toBe(true);
118 });
119 });
120
121 describe("threats: no runtime dependencies", () => {
122 test("package.json dependencies is empty", async () => {
123 const pkg = JSON.parse(await Bun.file(`${root}package.json`).text());
124 expect(Object.keys(pkg.dependencies ?? {})).toEqual([]);
125 });
126 });
127
128 describe("threats: the Resilience page", () => {
129 let dir: string;
130 let app: App;
131 let http: ForgeHttp;
132 const cookie = async (username: string) => {
133 const res = await http.handle(
134 new Request("http://forge.test/signin", {
135 method: "POST",
136 redirect: "manual",
137 headers: {
138 "content-type": "application/x-www-form-urlencoded",
139 origin: "http://forge.test",
140 },
141 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
142 }),
143 );
144 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
145 };
146 beforeAll(async () => {
147 dir = await mkdtemp(join(tmpdir(), "forge-threats-"));
148 app = createApp({ dataDir: dir, port: 0 });
149 http = forgeHttp(app);
150 for (const [username, adminIfFirst] of [
151 ["alice", true],
152 ["bob", false],
153 ] as const) {
154 const u = await createUser(app.db, {
155 trusted: true,
156 username,
157 email: `${username}@forge.local`,
158 password: "a-good-passphrase",
159 adminIfFirst,
160 });
161 if (!u.ok) throw new Error(u.error);
162 }
163 });
164 afterAll(async () => {
165 http.close();
166 app.close();
167 await rm(dir, { recursive: true, force: true });
168 });
169
170 test("an admin reads every line; a member and nobody are told it is not there", async () => {
171 const mine = await http.handle(
172 new Request("http://forge.test/settings/resilience", {
173 headers: { cookie: await cookie("alice") },
174 }),
175 );
176 expect(mine.status).toBe(200);
177 const text = await mine.text();
178 for (const t of THREATS)
179 expect(text).toContain(t.protection.slice(0, 30).replace(/'/g, "&#39;"));
180 expect(text).toContain("no test yet");
181 expect(text).toContain("partly proven");
182 expect(text).toContain("below the bar");
183 const bob = await http.handle(
184 new Request("http://forge.test/settings/resilience", {
185 headers: { cookie: await cookie("bob") },
186 }),
187 );
188 expect(bob.status).toBe(404);
189 const anon = await http.handle(
190 new Request("http://forge.test/settings/resilience"),
191 );
192 expect(anon.status).not.toBe(200);
193 });
194 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs