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

The edge keeps the last Resilience page and serves it, marked as a copy, while the forge is down #16793

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16260-the-edge-keeps-the-last-resilience-page → main 0 commits fork

  • Merged. scout/16260-the-edge-keeps-the-last-resilience-page was merged into main as c02779f.

Review

Sign in to review this change.
9 files changed +334 −2
docs/features/edge-resilience-copy.md added +25
@@ -0,0 +1,25 @@
1 ---
2 topic: Backups and moving
3 row: The edge keeps the last Resilience page
4 ---
5 # The edge keeps the last Resilience page (#16260)
6
7 A forge behind the Cloudflare front door (`infra/forge-cloudflare/`) keeps
8 a copy of its Resilience map at the edge. While the body is unreachable, the
9 Worker answers a browser's `GET /settings/resilience` with that copy: the
10 protections as THREATS.md words them, under a box that says **This is a copy** and
11 how old it is ("3 minutes ago"). The edge cannot tell an admin from anyone else, so the copy
12 carries only what the docs already publish: no standings, test files, backups line or nightly output.
13 Those stay on `/resilience`, for a signed-in admin. Any other page gets the restarting page.
14
15 - **Turn it on:** give the forge `FORGE_EDGE_COPY_URL` (the Worker's origin)
16 and `FORGE_EDGE_COPY_TOKEN`, and the Worker the same value as its
17 `COPY_TOKEN` secret. With either unset the forge pushes nothing. The Worker's
18 host is the operator's, so it is not in the repository's `forge.json` `egress`: add it in the
19 deployment that sets `FORGE_EDGE_COPY_URL` (or on the app's settings page), or the gate refuses the push.
20 - **When it pushes:** the `edge-resilience` duty (every minute, listed on
21 `/maintenance`) renders the map and PUTs it to `/_edge/resilience` on the Worker
22 on boot and whenever it differs from what the Worker last took. The Worker
23 refuses a push without the token (403) or over 256 KB of bytes (400, read as a stream and stopped at the cap).
24 - **Not in the copy:** nightly output and anything that needs the body. The
25 copy is text, escaped, and served with a CSP that allows no script.
infra/forge-cloudflare/README.md +7
@@ -54,3 +54,10 @@ loopback, esbuild 0.28.2:
5454 | Next request | ≈ 150 ms |
5555 | p50 over 100 requests, through the Worker and Durable Object to the body | ≈ 29 ms |
5656 | p99 | ≈ 126 ms |
57
58 ## The edge's copy of Resilience
59
60 The forge PUTs its Resilience map to `/_edge/resilience` (bearer `COPY_TOKEN`, a
61 Worker secret: `wrangler secret put COPY_TOKEN`); the Durable Object keeps the
62 last one. While the body is unreachable, `GET /settings/resilience` answers that
63 copy, marked as a copy with its age. See `docs/features/edge-resilience-copy.md`.
infra/forge-cloudflare/worker.js +88 −1
@@ -44,20 +44,107 @@ export function restartingPage(heard) {
4444 });
4545 }
4646
47 const COPY_PATH = "/_edge/resilience";
48 const COPY_MAX = 256 * 1024;
49
50 /** "3 minutes", "2 hours": the age of the copy in words, from whole seconds. */
51 export function ageWords(seconds) {
52 const s = Math.max(0, Math.floor(seconds));
53 const unit = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
54 if (s < 60) return unit(s, "second");
55 if (s < 3600) return unit(Math.floor(s / 60), "minute");
56 if (s < 86400) return unit(Math.floor(s / 3600), "hour");
57 return unit(Math.floor(s / 86400), "day");
58 }
59
60 /**
61 * The request body as text, read as a stream with a running byte count; null once it passes `max`
62 * bytes (UTF-8, not characters), without reading the rest.
63 */
64 export async function readCapped(request, max) {
65 if (!request.body) return "";
66 const reader = request.body.getReader();
67 const chunks = [];
68 let total = 0;
69 for (;;) {
70 const { done, value } = await reader.read();
71 if (done) break;
72 total += value.byteLength;
73 if (total > max) {
74 await reader.cancel();
75 return null;
76 }
77 chunks.push(value);
78 }
79 const all = new Uint8Array(total);
80 let at = 0;
81 for (const c of chunks) (all.set(c, at), (at += c.byteLength));
82 return new TextDecoder().decode(all);
83 }
84
85 /** Equal strings, compared without stopping at the first difference. */
86 function sameSecret(a, b) {
87 if (typeof a !== "string" || typeof b !== "string" || a.length === 0 || a.length !== b.length) return false;
88 let diff = 0;
89 for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
90 return diff === 0;
91 }
92
93 /**
94 * The last Resilience map the forge pushed, served while the body is down: the
95 * forge's own (already escaped) markup inside a page that says it is a copy and
96 * how old it is. No script runs: the CSP allows none.
97 */
98 export function copyPage(copy, now) {
99 const seconds = (now - Date.parse(copy.at)) / 1000;
100 const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Resilience (a copy)</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:48rem;margin:2rem auto;padding:0 1rem;color:#222}.copy{border:1px solid #b60;padding:.5rem 1rem;border-radius:.5rem}ul{padding-left:1rem}li{margin:.5rem 0;overflow-wrap:anywhere}@media(prefers-color-scheme:dark){body{background:#111;color:#ddd}}</style></head><body><p class="copy" role="status"><strong>This is a copy.</strong> The forge is not answering; this is the Resilience page as it last pushed it, <time datetime="${copy.at}">${ageWords(seconds)} ago</time>.</p>${copy.body}</body></html>`;
101 return new Response(html, {
102 status: 200,
103 headers: {
104 "content-type": "text/html; charset=utf-8",
105 "cache-control": "no-store",
106 age: String(Math.max(0, Math.floor(seconds))),
107 "x-forge-edge-copy": copy.at,
108 "content-security-policy": CSP,
109 "x-content-type-options": "nosniff",
110 "referrer-policy": "same-origin",
111 },
112 });
113 }
114
47115 export class Forge {
48116 heard = null;
49117 constructor(state, env) {
118 this.state = state;
50119 this.env = env;
51120 }
121 /** PUT /_edge/resilience: the forge hands over its map. Needs COPY_TOKEN as a bearer. */
122 async keep(request) {
123 const auth = (request.headers.get("authorization") || "").replace(/^Bearer /, "");
124 if (!sameSecret(auth, this.env.COPY_TOKEN)) return new Response("no\n", { status: 403 });
125 const body = await readCapped(request, COPY_MAX);
126 if (body === null || body.length === 0) return new Response("bad size\n", { status: 400 });
127 const at = new Date().toISOString();
128 await this.state.storage.put("resilience", { body, at });
129 return Response.json({ ok: true, at });
130 }
52131 async fetch(request) {
132 const { pathname } = new URL(request.url);
133 if (pathname === COPY_PATH) {
134 if (request.method !== "PUT") return new Response("PUT only\n", { status: 405, headers: { allow: "PUT" } });
135 return this.keep(request);
136 }
53137 try {
54138 const response = await fetch(forward(request, this.env.BODY_URL));
55139 this.heard = new Date().toISOString();
56140 return response;
57141 } catch {
58 const { pathname } = new URL(request.url);
59142 if (pathname === "/healthz")
60143 return Response.json({ ok: false, body: "unreachable" }, { status: 503 });
144 if (pathname === "/settings/resilience" && wantsPage(request)) {
145 const copy = await this.state.storage.get("resilience");
146 if (copy) return copyPage(copy, Date.now());
147 }
61148 if (wantsPage(request)) return restartingPage(this.heard);
62149 return new Response("the forge's body is not answering\n", { status: 502 });
63150 }
scripts/unused-exports-allow.json +1
@@ -1,4 +1,5 @@
11 [
2 "src/maintain/edge_copy.ts forgetPushed",
23 "src/apps/check-memory.ts usePodMemoryFile",
34 "src/apps/changes.ts openChanges",
45 "src/apps/room.ts openRooms",
src/maintain/duties/edge_resilience.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * Keeps the edge's copy of the Resilience map current (#16260). Each minute it renders the map and,
3 * when it differs from what the Worker last accepted (or the forge has just booted), PUTs it to
4 * FORGE_EDGE_COPY_URL with FORGE_EDGE_COPY_TOKEN. With either unset it does nothing: no edge, no
5 * copy. The only host called is the one the operator configured; it belongs in `forge.json`
6 * `egress`.
7 */
8
9 import type { Duty } from "../duty.ts";
10 import { copyFragment, pushCopy, type Put } from "../edge_copy.ts";
11
12 const TIMEOUT_MS = 8_000;
13
14 const put: Put = async (url, init) => {
15 const res = await fetch(url, { ...init, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
16 await res.body?.cancel();
17 return res;
18 };
19
20 export function edgeResilience(send: Put = put, env: Record<string, string | undefined> = process.env): Duty {
21 return {
22 name: "edge-resilience",
23 intervalMs: 60_000,
24 budget: { runsPerDay: 1500, dollarsPerDay: 0, reason: "once a minute is 1440 runs a day; it reads local files and spends no money" },
25 async run({ app }) {
26 const url = (env.FORGE_EDGE_COPY_URL ?? "").trim();
27 const token = (env.FORGE_EDGE_COPY_TOKEN ?? "").trim();
28 if (url === "" || token === "" || app === undefined) return { findings: [], actions: ["skipped: no FORGE_EDGE_COPY_URL and FORGE_EDGE_COPY_TOKEN, so no edge copy"] };
29 try {
30 // Loaded here, not at the top: the roster loads duty files with `require`, which refuses a
31 // chain with a top-level await.
32 const { readResilience } = await import("../../checks/resilience.ts");
33 const fragment = copyFragment(readResilience(app.config.dataDir));
34 return { findings: [], actions: [await pushCopy(url, token, fragment, send)] };
35 } catch (e) {
36 return { findings: [], actions: [`not pushed: ${e instanceof Error ? e.name : "error"}`] };
37 }
38 },
39 };
40 }
41
42 export const duty: Duty = edgeResilience();
src/maintain/edge_copy.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * The Resilience map as a copy for the edge (#16260): the protections and the
3 * backups line as one escaped fragment, and the push of it to the Worker
4 * (`infra/forge-cloudflare/worker.js`), which serves it at /settings/resilience
5 * while the body is down. Plain data in, a string out; the fetch is handed in.
6 */
7
8 import type { Row } from "../checks/resilience.ts";
9 import { escapeHtml } from "../web/html.ts";
10
11 /** Where the Worker keeps the copy, and the push's own limit. */
12 export const COPY_PATH = "/_edge/resilience";
13
14 /**
15 * The fragment the Worker wraps: one line a protection, as THREATS.md words it. The edge cannot
16 * tell an admin from anyone else, so the copy carries only what the docs already publish: no
17 * standing (a red line names what to attack), no test file, no backups line, no nightly output, no
18 * links.
19 */
20 export function copyFragment(rows: readonly Row[]): string {
21 const lis = rows.map(({ p }) => `<li>${escapeHtml(p.text)} <small>${escapeHtml(p.adversary)}</small></li>`).join("");
22 return `<h1>Resilience</h1><p>${rows.length} protections the forge keeps. Standings are for signed-in admins, on the forge itself.</p><ul>${lis}</ul>`;
23 }
24
25 export type Put = (url: string, init: { method: "PUT"; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number }>;
26
27 /** The last fragment the Worker accepted; a restart forgets it, so every boot pushes once. */
28 let lastPushed: string | undefined;
29 export const forgetPushed = (): void => {
30 lastPushed = undefined;
31 };
32
33 /** Push `fragment` when the Worker's last copy differs. Returns one line for the duty's actions. */
34 export async function pushCopy(edgeUrl: string, token: string, fragment: string, put: Put): Promise<string> {
35 if (fragment === lastPushed) return "the edge's copy is current";
36 const res = await put(new URL(COPY_PATH, edgeUrl).href, { method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": "text/html; charset=utf-8" }, body: fragment });
37 if (!res.ok) return `the edge refused the copy: ${res.status}`;
38 lastPushed = fragment;
39 return "pushed the Resilience map to the edge";
40 }
test/forge-cloudflare.test.ts +83 −1
@@ -2,7 +2,7 @@
22 import { describe, expect, test } from "bun:test";
33 import { readFileSync } from "node:fs";
44 // @ts-expect-error plain JS, deployed as is
5 import { Forge, forward } from "../infra/forge-cloudflare/worker.js";
5 import { Forge, ageWords, forward } from "../infra/forge-cloudflare/worker.js";
66
77 describe("forge-cloudflare worker", () => {
88 test("forward keeps path and query, swaps the origin, tells the public scheme", () => {
@@ -27,3 +27,85 @@ describe("forge-cloudflare worker", () => {
2727 expect(v).toContain('^spike-[a-z0-9-]{1,40}$');
2828 });
2929 });
30
31 describe("the edge keeps the last Resilience page (#16260)", () => {
32 const store = () => {
33 const m = new Map<string, unknown>();
34 return { storage: { get: async (k: string) => m.get(k), put: async (k: string, v: unknown) => void m.set(k, v) } };
35 };
36 const env = { BODY_URL: "http://127.0.0.1:1", COPY_TOKEN: "s3cret" };
37 const put = (token: string, body: string) =>
38 new Request("https://h/_edge/resilience", { method: "PUT", headers: { authorization: `Bearer ${token}` }, body });
39 const page = { headers: { accept: "text/html" } };
40
41 test("with the body down, /settings/resilience is the pushed copy, marked, with its age", async () => {
42 const f = new Forge(store(), env);
43 expect((await f.fetch(put("s3cret", "<h1>Resilience</h1><p>2 green</p>"))).status).toBe(200);
44 const res = await f.fetch(new Request("https://h/settings/resilience", page));
45 expect(res.status).toBe(200);
46 const text = await res.text();
47 expect(text).toContain("This is a copy.");
48 expect(text).toContain("<p>2 green</p>");
49 expect(text).toMatch(/\d+ seconds? ago/);
50 expect(res.headers.get("x-forge-edge-copy")).not.toBeNull();
51 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
52 });
53
54 test("a copy pushed minutes ago says its age in minutes", async () => {
55 const at = new Date(Date.now() - 3 * 60_000 - 5_000).toISOString();
56 const s = store();
57 await s.storage.put("resilience", { body: "<p>old</p>", at });
58 const res = await new Forge(s, env).fetch(new Request("https://h/settings/resilience", page));
59 expect(await res.text()).toContain("3 minutes ago");
60 expect(res.headers.get("age")).toBe("185");
61 });
62
63 test("an unauthenticated browser is served the copy, which holds only what the push carried", async () => {
64 const f = new Forge(store(), env);
65 await f.fetch(put("s3cret", "<h1>Resilience</h1><ul><li>a published protection</li></ul>"));
66 const res = await f.fetch(new Request("https://h/settings/resilience", page));
67 const text = await res.text();
68 expect(res.status).toBe(200);
69 expect(text).toContain("a published protection");
70 expect(text).not.toContain("backups line");
71 });
72
73 test("a push over the byte cap is refused 400 and keeps nothing; so is an empty one", async () => {
74 const f = new Forge(store(), env);
75 // 90,000 three-byte characters: 90 KB as characters, 270 KB as bytes.
76 const big = "€".repeat(90_000);
77 expect(big.length).toBeLessThan(256 * 1024);
78 const over = await f.fetch(put("s3cret", big));
79 expect([over.status, await over.text()]).toEqual([400, "bad size\n"]);
80 const empty = await f.fetch(put("s3cret", ""));
81 expect([empty.status, await empty.text()]).toEqual([400, "bad size\n"]);
82 expect((await f.fetch(new Request("https://h/settings/resilience", page))).status).toBe(503);
83 expect((await f.fetch(put("s3cret", "€".repeat(80_000)))).status).toBe(200);
84 });
85
86 test("anything but PUT at /_edge/resilience is 405", async () => {
87 const f = new Forge(store(), env);
88 for (const method of ["GET", "POST", "DELETE"]) {
89 const res = await f.fetch(new Request("https://h/_edge/resilience", { method }));
90 expect([method, res.status, res.headers.get("allow")]).toEqual([method, 405, "PUT"]);
91 }
92 });
93
94 test("ageWords says seconds, minutes, hours, days", () => {
95 expect([ageWords(1), ageWords(120), ageWords(7200), ageWords(172800)]).toEqual(["1 second", "2 minutes", "2 hours", "2 days"]);
96 });
97
98 test("a push without the token is refused and keeps nothing; no copy means the restarting page", async () => {
99 const f = new Forge(store(), env);
100 expect((await f.fetch(put("wrong", "<p>x</p>"))).status).toBe(403);
101 const res = await f.fetch(new Request("https://h/settings/resilience", page));
102 expect(res.status).toBe(503);
103 expect(await res.text()).toContain("restarting");
104 });
105
106 test("the copy is served only at /settings/resilience", async () => {
107 const f = new Forge(store(), env);
108 await f.fetch(put("s3cret", "<p>copy</p>"));
109 expect((await f.fetch(new Request("https://h/", page))).status).toBe(503);
110 });
111 });
test/maintain-edge-resilience.test.ts added +47
@@ -0,0 +1,47 @@
1 import { expect, test } from "bun:test";
2 import type { Row } from "../src/checks/resilience.ts";
3 import type { DutyContext } from "../src/maintain/duty.ts";
4 import { copyFragment, forgetPushed, pushCopy, type Put } from "../src/maintain/edge_copy.ts";
5 import { edgeResilience } from "../src/maintain/duties/edge_resilience.ts";
6 import { duties } from "../src/maintain/registry.ts";
7 import { createApp } from "../src/app.ts";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11
12 const rows: Row[] = [{ p: { text: "A <b>threat</b>", adversary: "me", test: "test/x.test.ts" }, s: "green" }];
13
14 test("the fragment carries only what the docs publish: no standing, test file or backups", () => {
15 const f = copyFragment(rows);
16 expect(f).toContain("A &lt;b&gt;threat&lt;/b&gt;");
17 expect(f).toContain("1 protections");
18 expect(f).not.toContain("green");
19 expect(f).not.toContain("test/x.test.ts");
20 expect(f).not.toContain("ackups");
21 });
22
23 test("it pushes on boot, again only when the map changes, and says when the edge refuses", async () => {
24 forgetPushed();
25 const sent: { url: string; auth: string }[] = [];
26 const put: Put = async (url, init) => (sent.push({ url, auth: init.headers.authorization! }), { ok: true, status: 200 });
27 expect(await pushCopy("https://edge.example", "t", "a", put)).toContain("pushed");
28 expect(await pushCopy("https://edge.example", "t", "a", put)).toContain("current");
29 expect(await pushCopy("https://edge.example", "t", "b", put)).toContain("pushed");
30 expect(sent.map((s) => s.url)).toEqual(["https://edge.example/_edge/resilience", "https://edge.example/_edge/resilience"]);
31 expect(sent[0]!.auth).toBe("Bearer t");
32 expect(await pushCopy("https://edge.example", "t", "c", async () => ({ ok: false, status: 403 }))).toContain("403");
33 });
34
35 test("the duty is on the roster, silent without an edge, and pushes the page with one", async () => {
36 forgetPushed();
37 expect(duties.find((d) => d.name === "edge-resilience")?.intervalMs).toBe(60_000);
38 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "edge-res-")), port: 0 });
39 const bodies: string[] = [];
40 const put: Put = async (_u, init) => (bodies.push(init.body), { ok: true, status: 200 });
41 const ctx: DutyContext = { db: app.db, bus: app.bus, now: new Date(), app };
42 const off = await edgeResilience(put, {}).run(ctx);
43 expect(off.actions[0]).toContain("skipped");
44 const on = await edgeResilience(put, { FORGE_EDGE_COPY_URL: "https://edge.example", FORGE_EDGE_COPY_TOKEN: "t" }).run(ctx);
45 expect(on.actions[0]).toContain("pushed");
46 expect(bodies[0]).toContain("<h1>Resilience</h1>");
47 });
test/outbound-sweep.test.ts +1
@@ -57,6 +57,7 @@ const ALLOWED: Record<string, { count: number; why: string }> = {
5757 "src/maintain/keeper/down.ts": { count: 1, why: "services the operator listed in the keeper's environment" },
5858 "src/maintain/duties/wait_split.ts": { count: 1, why: "the forge's own public URL, timed" },
5959 "src/maintain/duties/edge_kept.ts": { count: 1, why: "the forge's own public URL (config.url), never a host from a request" },
60 "src/maintain/duties/edge_resilience.ts": { count: 1, why: "the edge copy URL the operator configured (FORGE_EDGE_COPY_URL), never a host from a request" },
6061 };
6162
6263 /**

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs