Public: anyone can read this; the crew can change it.
The edge answers when the forge does not: a static "the forge is restarting" page and the last Resilience page, served by the Worker itself #1484
scout/forge:scout/1194-the-edge-answers-when-the-forge-does-not → main 6 commits fork
12 files
changed +860
−17
infra/forge-cloudflare/README.md +31
| @@ -54,3 +54,34 @@ loopback, esbuild 0.28.2: | ||
| 54 | 54 | | Next request | ≈ 150 ms | |
| 55 | 55 | | p50 over 100 requests, through the Worker and Durable Object to the body | ≈ 29 ms | |
| 56 | 56 | | p99 | ≈ 126 ms | |
| 57 | ||
| 58 | ## When the body is down | |
| 59 | ||
| 60 | A browser GET (`Accept: text/html`) gets a static "the forge is restarting" | |
| 61 | page from the Worker itself: 503, `Retry-After: 30`, no script, the CSP floor, | |
| 62 | and when the edge last heard from the body. `/healthz` stays JSON 503; other | |
| 63 | requests stay a plain 502. | |
| 64 | ||
| 65 | The edge keeps a copy of the forge's Resilience map: | |
| 66 | `PUT /_edge/resilience` (five wrong tokens a minute per client address, then 429) with `Authorization: Bearer $EDGE_PUSH_TOKEN` and | |
| 67 | `{"domains":[{"name","breaks","says","back","owner"}]}` (at most 32 rows of | |
| 68 | strings up to 600 characters, body at most 64 KiB counted in bytes; other | |
| 69 | methods answer 405, bad JSON 400, too large 413). With the body down, | |
| 70 | `/settings/resilience` serves that copy to anyone, marked as a copy with its | |
| 71 | age; the restarting page links to it only once a copy exists. Pages are | |
| 72 | rendered by `src/cloud/edge.ts`, which `worker.js` imports. `wrangler deploy` bundles that itself; the Terraform module uploads one file, so it ships the committed bundle `worker.bundle.js`. After changing `worker.js` or `edge.ts`, run `bun scripts/build-edge.ts` (a test fails while the bundle is stale and loads it with no `src/` beside it). | |
| 73 | ||
| 74 | **Who pushes, and what.** The forge does, from `src/cloud/edge_push.ts`: on | |
| 75 | boot and hourly. Set `EDGE_PUSH_TOKEN` as a Worker secret and, on the forge, | |
| 76 | `FORGE_EDGE_PUSH_URL` (the edge's origin, e.g. `https://forge.example.com`) and | |
| 77 | `FORGE_EDGE_PUSH_TOKEN` (the same value). Either unset, nothing is pushed. | |
| 78 | Because the edge serves the copy without sign-in, what is pushed is public by | |
| 79 | construction: a fixed list of what each failure domain does, written in | |
| 80 | `edge_push.ts`, never read from an account, a setting or a signed-in page. | |
| 81 | (This repository has no signed-in Settings → Resilience page to mirror; if one | |
| 82 | is added, its rows must stay on this public list or be gated at the edge.) | |
| 83 | ||
| 84 | **The terminal.** The terminal has no part: the push has no state to show or | |
| 85 | trigger beyond the forge's log line (`edge resilience copy pushed` or `not | |
| 86 | pushed`, with the reason), and the settings are environment-only like every | |
| 87 | other boot setting. |
infra/forge-cloudflare/main.tf +1 −1
| @@ -9,7 +9,7 @@ locals { | ||
| 9 | 9 | resource "cloudflare_workers_script" "front" { |
| 10 | 10 | account_id = var.account_id |
| 11 | 11 | script_name = var.name |
| 12 | content = file("${path.module}/worker.js") | |
| 12 | content = file("${path.module}/worker.bundle.js") | |
| 13 | 13 | main_module = "worker.js" |
| 14 | 14 | |
| 15 | 15 | bindings = [ |
infra/forge-cloudflare/worker.bundle.js added +260
| @@ -0,0 +1,260 @@ | ||
| 1 | // src/cloud/edge.ts | |
| 2 | var EDGE_HEADERS = { | |
| 3 | "content-type": "text/html; charset=utf-8", | |
| 4 | "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", | |
| 5 | "x-content-type-options": "nosniff", | |
| 6 | "referrer-policy": "no-referrer", | |
| 7 | "cache-control": "no-store" | |
| 8 | }; | |
| 9 | var MAX_ROWS = 32; | |
| 10 | var MAX_FIELD = 600; | |
| 11 | var FIELDS = ["name", "breaks", "says", "back", "owner"]; | |
| 12 | function parseCopy(input, now) { | |
| 13 | if (typeof input !== "object" || input === null) | |
| 14 | return null; | |
| 15 | const list = input.domains; | |
| 16 | if (!Array.isArray(list) || list.length === 0 || list.length > MAX_ROWS) | |
| 17 | return null; | |
| 18 | const domains = []; | |
| 19 | for (const row of list) { | |
| 20 | if (typeof row !== "object" || row === null) | |
| 21 | return null; | |
| 22 | const out = {}; | |
| 23 | for (const f of FIELDS) { | |
| 24 | const v = row[f]; | |
| 25 | if (typeof v !== "string" || v.length > MAX_FIELD) | |
| 26 | return null; | |
| 27 | out[f] = v; | |
| 28 | } | |
| 29 | if (out.name === "") | |
| 30 | return null; | |
| 31 | domains.push(out); | |
| 32 | } | |
| 33 | return { at: now, domains }; | |
| 34 | } | |
| 35 | function esc(s) { | |
| 36 | return s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); | |
| 37 | } | |
| 38 | function ago(then, now) { | |
| 39 | if (then === null) | |
| 40 | return "never"; | |
| 41 | const s = Math.max(0, Math.round((now - then) / 1000)); | |
| 42 | if (s < 60) | |
| 43 | return `${s} second${s === 1 ? "" : "s"} ago`; | |
| 44 | const m = Math.floor(s / 60); | |
| 45 | if (m < 60) | |
| 46 | return `${m} minute${m === 1 ? "" : "s"} ago`; | |
| 47 | const h = Math.floor(m / 60); | |
| 48 | if (h < 48) | |
| 49 | return `${h} hour${h === 1 ? "" : "s"} ago`; | |
| 50 | const d = Math.floor(h / 24); | |
| 51 | return `${d} days ago`; | |
| 52 | } | |
| 53 | function shell(title, body) { | |
| 54 | return `<!doctype html><html lang="en"><head><meta charset="utf-8"> | |
| 55 | <meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title> | |
| 56 | <style>body{font:16px/1.5 system-ui,sans-serif;max-width:46rem;margin:12vh auto;padding:0 1rem;color:#222;background:#fafafa} | |
| 57 | h1{font-size:1.4rem}table{border-collapse:collapse;width:100%}th,td{text-align:left;vertical-align:top;border-top:1px solid #ccc;padding:.4rem} | |
| 58 | .wide{overflow-x:auto}table{min-width:36rem}a:focus-visible{outline:3px solid #b4533a;outline-offset:2px}.note{padding:.6rem .8rem;border:1px solid #b4533a;border-radius:6px}@media(prefers-color-scheme:dark){body{color:#ddd;background:#161616}th,td{border-color:#444}}</style> | |
| 59 | </head><body>${body}</body></html> | |
| 60 | `; | |
| 61 | } | |
| 62 | function restartingPage(lastHeard, now, hasCopy = false) { | |
| 63 | return shell("The forge is restarting", `<h1>The forge is restarting</h1> | |
| 64 | <p>This answer comes from the edge, not the forge. Nothing you have pushed is lost; try again in a minute.</p> | |
| 65 | <p>The edge last heard from the forge ${esc(ago(lastHeard, now))}.</p> | |
| 66 | ${hasCopy ? '<p><a href="/settings/resilience">What each part does when it fails</a></p>' : ""}`); | |
| 67 | } | |
| 68 | function resiliencePage(copy, now) { | |
| 69 | const rows = copy.domains.map((d) => `<tr><th scope="row">${esc(d.name)}</th><td>${esc(d.breaks)}</td><td>${esc(d.says)}</td><td>${esc(d.back)}</td><td>${esc(d.owner)}</td></tr>`).join(""); | |
| 70 | return shell("Resilience (copy)", `<h1>Resilience</h1> | |
| 71 | <p class="note">This is a copy served by the edge because the forge is not answering. It was pushed ${esc(ago(copy.at, now))} and may be out of date.</p> | |
| 72 | <div class="wide" tabindex="0" role="region" aria-label="Resilience table"><table><thead><tr><th>Domain</th><th>What breaks</th><th>What the forge says</th><th>Back in</th><th>What you do</th></tr></thead><tbody>${rows}</tbody></table></div>`); | |
| 73 | } | |
| 74 | ||
| 75 | // infra/forge-cloudflare/worker.js | |
| 76 | var SEEN_EVERY = 1e4; | |
| 77 | var MAX_PUSH = 64 * 1024; | |
| 78 | var RETRY_AFTER = "30"; | |
| 79 | var GUESSES = 5; | |
| 80 | var GUESS_WINDOW = 60000; | |
| 81 | var MAX_TRACKED = 1000; | |
| 82 | var GONE = new Set([502, 503, 504]); | |
| 83 | async function samePush(a, b) { | |
| 84 | const enc = new TextEncoder; | |
| 85 | const [x, y] = await Promise.all([ | |
| 86 | crypto.subtle.digest("SHA-256", enc.encode(a)), | |
| 87 | crypto.subtle.digest("SHA-256", enc.encode(b)) | |
| 88 | ]); | |
| 89 | const p = new Uint8Array(x); | |
| 90 | const q = new Uint8Array(y); | |
| 91 | let d = 0; | |
| 92 | for (let i = 0;i < p.length; i++) | |
| 93 | d |= p[i] ^ q[i]; | |
| 94 | return d === 0; | |
| 95 | } | |
| 96 | async function readCapped(request) { | |
| 97 | if (Number(request.headers.get("content-length") ?? 0) > MAX_PUSH) | |
| 98 | return null; | |
| 99 | if (!request.body) | |
| 100 | return ""; | |
| 101 | const reader = request.body.getReader(); | |
| 102 | const chunks = []; | |
| 103 | let n = 0; | |
| 104 | for (;; ) { | |
| 105 | const { done, value } = await reader.read(); | |
| 106 | if (done) | |
| 107 | break; | |
| 108 | n += value.byteLength; | |
| 109 | if (n > MAX_PUSH) { | |
| 110 | await reader.cancel(); | |
| 111 | return null; | |
| 112 | } | |
| 113 | chunks.push(value); | |
| 114 | } | |
| 115 | const all = new Uint8Array(n); | |
| 116 | let at = 0; | |
| 117 | for (const c of chunks) { | |
| 118 | all.set(c, at); | |
| 119 | at += c.byteLength; | |
| 120 | } | |
| 121 | return new TextDecoder().decode(all); | |
| 122 | } | |
| 123 | function wantsHtml(request) { | |
| 124 | return (request.method === "GET" || request.method === "HEAD") && (request.headers.get("accept") ?? "").includes("text/html"); | |
| 125 | } | |
| 126 | var HOP = ["host", "cf-connecting-ip", "x-forwarded-host"]; | |
| 127 | function forward(request, bodyUrl) { | |
| 128 | const from = new URL(request.url); | |
| 129 | const to = new URL(from.pathname + from.search, bodyUrl); | |
| 130 | const headers = new Headers(request.headers); | |
| 131 | for (const h of HOP) | |
| 132 | headers.delete(h); | |
| 133 | headers.set("x-forwarded-proto", "https"); | |
| 134 | headers.set("x-forwarded-host", from.host); | |
| 135 | const init = { method: request.method, headers, redirect: "manual" }; | |
| 136 | if (request.method !== "GET" && request.method !== "HEAD") | |
| 137 | init.body = request.body; | |
| 138 | return new Request(to, init); | |
| 139 | } | |
| 140 | ||
| 141 | class Forge { | |
| 142 | constructor(state, env) { | |
| 143 | this.env = env; | |
| 144 | this.storage = state?.storage; | |
| 145 | this.mem = new Map; | |
| 146 | this.sawAt = 0; | |
| 147 | this.guesses = new Map; | |
| 148 | } | |
| 149 | async get(key) { | |
| 150 | return this.storage ? this.storage.get(key) : this.mem.get(key); | |
| 151 | } | |
| 152 | async put(key, value) { | |
| 153 | if (this.storage) | |
| 154 | await this.storage.put(key, value); | |
| 155 | else | |
| 156 | this.mem.set(key, value); | |
| 157 | } | |
| 158 | tooMany(who, now) { | |
| 159 | const t = this.guesses.get(who); | |
| 160 | return Boolean(t && now - t.at < GUESS_WINDOW && t.n >= GUESSES); | |
| 161 | } | |
| 162 | missed(who, now) { | |
| 163 | const t = this.guesses.get(who); | |
| 164 | if (t && now - t.at < GUESS_WINDOW) | |
| 165 | t.n++; | |
| 166 | else { | |
| 167 | if (this.guesses.size >= MAX_TRACKED) | |
| 168 | this.guesses.clear(); | |
| 169 | this.guesses.set(who, { at: now, n: 1 }); | |
| 170 | } | |
| 171 | } | |
| 172 | async push(request) { | |
| 173 | const want = this.env.EDGE_PUSH_TOKEN; | |
| 174 | if (!want) | |
| 175 | return new Response(`not found | |
| 176 | `, { status: 404 }); | |
| 177 | const who = request.headers.get("cf-connecting-ip") ?? "unknown"; | |
| 178 | const now = Date.now(); | |
| 179 | if (this.tooMany(who, now)) | |
| 180 | return new Response(`slow down | |
| 181 | `, { status: 429, headers: { "retry-after": "60" } }); | |
| 182 | const given = (request.headers.get("authorization") ?? "").replace(/^Bearer /, ""); | |
| 183 | if (!await samePush(given, want)) { | |
| 184 | this.missed(who, now); | |
| 185 | return new Response(`forbidden | |
| 186 | `, { status: 403 }); | |
| 187 | } | |
| 188 | const text = await readCapped(request); | |
| 189 | if (text === null) | |
| 190 | return new Response(`too large | |
| 191 | `, { status: 413 }); | |
| 192 | let data; | |
| 193 | try { | |
| 194 | data = JSON.parse(text); | |
| 195 | } catch { | |
| 196 | return new Response(`bad json | |
| 197 | `, { status: 400 }); | |
| 198 | } | |
| 199 | const copy = parseCopy(data, Date.now()); | |
| 200 | if (!copy) | |
| 201 | return new Response(`bad map | |
| 202 | `, { status: 422 }); | |
| 203 | await this.put("resilience", copy); | |
| 204 | return new Response(null, { status: 204 }); | |
| 205 | } | |
| 206 | async down(request, pathname) { | |
| 207 | const res = await this.page(request, pathname); | |
| 208 | return request.method === "HEAD" ? new Response(null, { status: res.status, headers: res.headers }) : res; | |
| 209 | } | |
| 210 | async page(request, pathname) { | |
| 211 | const now = Date.now(); | |
| 212 | if (pathname === "/healthz") | |
| 213 | return Response.json({ ok: false, body: "unreachable" }, { status: 503 }); | |
| 214 | if (!wantsHtml(request)) | |
| 215 | return new Response(`the forge's body is not answering | |
| 216 | `, { status: 502 }); | |
| 217 | const copy = await this.get("resilience"); | |
| 218 | if (copy && pathname === "/settings/resilience") | |
| 219 | return new Response(resiliencePage(copy, now), { status: 200, headers: EDGE_HEADERS }); | |
| 220 | const heard = await this.get("heard") ?? null; | |
| 221 | return new Response(restartingPage(heard, now, Boolean(copy)), { | |
| 222 | status: 503, | |
| 223 | headers: { ...EDGE_HEADERS, "retry-after": RETRY_AFTER } | |
| 224 | }); | |
| 225 | } | |
| 226 | async fetch(request) { | |
| 227 | const { pathname } = new URL(request.url); | |
| 228 | if (pathname === "/_edge/resilience") { | |
| 229 | if (request.method === "PUT") | |
| 230 | return this.push(request); | |
| 231 | return new Response(`method not allowed | |
| 232 | `, { status: 405, headers: { allow: "PUT" } }); | |
| 233 | } | |
| 234 | let response; | |
| 235 | try { | |
| 236 | response = await fetch(forward(request, this.env.BODY_URL)); | |
| 237 | } catch { | |
| 238 | return this.down(request, pathname); | |
| 239 | } | |
| 240 | if (GONE.has(response.status) && wantsHtml(request) && pathname !== "/healthz") | |
| 241 | return this.down(request, pathname); | |
| 242 | const now = Date.now(); | |
| 243 | if (now - this.sawAt > SEEN_EVERY) { | |
| 244 | this.sawAt = now; | |
| 245 | await this.put("heard", now); | |
| 246 | } | |
| 247 | return response; | |
| 248 | } | |
| 249 | } | |
| 250 | var worker_default = { | |
| 251 | fetch(request, env) { | |
| 252 | const id = env.FORGE.idFromName("forge"); | |
| 253 | return env.FORGE.get(id).fetch(request); | |
| 254 | } | |
| 255 | }; | |
| 256 | export { | |
| 257 | forward, | |
| 258 | worker_default as default, | |
| 259 | Forge | |
| 260 | }; |
infra/forge-cloudflare/worker.js +142 −8
| @@ -1,6 +1,64 @@ | ||
| 1 | 1 | // The front door of one forge: a Worker that hands every request to the |
| 2 | 2 | // forge's Durable Object, which forwards it to the body (BODY_URL) and |
| 3 | // answers /healthz itself when the body is asleep. No dependencies. | |
| 3 | // answers /healthz itself when the body is asleep. When the body is down it | |
| 4 | // also serves a "restarting" page to browsers and the last Resilience map the | |
| 5 | // forge pushed (PUT /_edge/resilience, bearer EDGE_PUSH_TOKEN). No dependencies. | |
| 6 | ||
| 7 | import { EDGE_HEADERS, parseCopy, resiliencePage, restartingPage } from "../../src/cloud/edge.ts"; | |
| 8 | ||
| 9 | const SEEN_EVERY = 10_000; | |
| 10 | const MAX_PUSH = 64 * 1024; | |
| 11 | const RETRY_AFTER = "30"; | |
| 12 | const GUESSES = 5; | |
| 13 | const GUESS_WINDOW = 60_000; | |
| 14 | const MAX_TRACKED = 1000; | |
| 15 | const GONE = new Set([502, 503, 504]); | |
| 16 | ||
| 17 | // Compare fixed-length digests, so neither the content nor the length of the | |
| 18 | // token shows in the time taken. | |
| 19 | async function samePush(a, b) { | |
| 20 | const enc = new TextEncoder(); | |
| 21 | const [x, y] = await Promise.all([ | |
| 22 | crypto.subtle.digest("SHA-256", enc.encode(a)), | |
| 23 | crypto.subtle.digest("SHA-256", enc.encode(b)), | |
| 24 | ]); | |
| 25 | const p = new Uint8Array(x); | |
| 26 | const q = new Uint8Array(y); | |
| 27 | let d = 0; | |
| 28 | for (let i = 0; i < p.length; i++) d |= p[i] ^ q[i]; | |
| 29 | return d === 0; | |
| 30 | } | |
| 31 | ||
| 32 | // The body as text, or null once it passes MAX_PUSH bytes: counted as read, so | |
| 33 | // a large or unlabelled body is never held whole. | |
| 34 | async function readCapped(request) { | |
| 35 | if (Number(request.headers.get("content-length") ?? 0) > MAX_PUSH) return null; | |
| 36 | if (!request.body) return ""; | |
| 37 | const reader = request.body.getReader(); | |
| 38 | const chunks = []; | |
| 39 | let n = 0; | |
| 40 | for (;;) { | |
| 41 | const { done, value } = await reader.read(); | |
| 42 | if (done) break; | |
| 43 | n += value.byteLength; | |
| 44 | if (n > MAX_PUSH) { | |
| 45 | await reader.cancel(); | |
| 46 | return null; | |
| 47 | } | |
| 48 | chunks.push(value); | |
| 49 | } | |
| 50 | const all = new Uint8Array(n); | |
| 51 | let at = 0; | |
| 52 | for (const c of chunks) { | |
| 53 | all.set(c, at); | |
| 54 | at += c.byteLength; | |
| 55 | } | |
| 56 | return new TextDecoder().decode(all); | |
| 57 | } | |
| 58 | ||
| 59 | function wantsHtml(request) { | |
| 60 | return (request.method === "GET" || request.method === "HEAD") && (request.headers.get("accept") ?? "").includes("text/html"); | |
| 61 | } | |
| 4 | 62 | |
| 5 | 63 | const HOP = ["host", "cf-connecting-ip", "x-forwarded-host"]; |
| 6 | 64 | |
| @@ -20,16 +78,92 @@ export function forward(request, bodyUrl) { | ||
| 20 | 78 | export class Forge { |
| 21 | 79 | constructor(state, env) { |
| 22 | 80 | this.env = env; |
| 81 | this.storage = state?.storage; | |
| 82 | this.mem = new Map(); | |
| 83 | this.sawAt = 0; | |
| 84 | this.guesses = new Map(); | |
| 85 | } | |
| 86 | async get(key) { | |
| 87 | return this.storage ? this.storage.get(key) : this.mem.get(key); | |
| 88 | } | |
| 89 | async put(key, value) { | |
| 90 | if (this.storage) await this.storage.put(key, value); | |
| 91 | else this.mem.set(key, value); | |
| 92 | } | |
| 93 | // Failed token guesses per socket address in a minute; past GUESSES the | |
| 94 | // answer is 429 before the token is looked at. | |
| 95 | tooMany(who, now) { | |
| 96 | const t = this.guesses.get(who); | |
| 97 | return Boolean(t && now - t.at < GUESS_WINDOW && t.n >= GUESSES); | |
| 98 | } | |
| 99 | missed(who, now) { | |
| 100 | const t = this.guesses.get(who); | |
| 101 | if (t && now - t.at < GUESS_WINDOW) t.n++; | |
| 102 | else { | |
| 103 | if (this.guesses.size >= MAX_TRACKED) this.guesses.clear(); | |
| 104 | this.guesses.set(who, { at: now, n: 1 }); | |
| 105 | } | |
| 106 | } | |
| 107 | async push(request) { | |
| 108 | const want = this.env.EDGE_PUSH_TOKEN; | |
| 109 | if (!want) return new Response("not found\n", { status: 404 }); | |
| 110 | const who = request.headers.get("cf-connecting-ip") ?? "unknown"; | |
| 111 | const now = Date.now(); | |
| 112 | if (this.tooMany(who, now)) return new Response("slow down\n", { status: 429, headers: { "retry-after": "60" } }); | |
| 113 | const given = (request.headers.get("authorization") ?? "").replace(/^Bearer /, ""); | |
| 114 | if (!(await samePush(given, want))) { | |
| 115 | this.missed(who, now); | |
| 116 | return new Response("forbidden\n", { status: 403 }); | |
| 117 | } | |
| 118 | const text = await readCapped(request); | |
| 119 | if (text === null) return new Response("too large\n", { status: 413 }); | |
| 120 | let data; | |
| 121 | try { | |
| 122 | data = JSON.parse(text); | |
| 123 | } catch { | |
| 124 | return new Response("bad json\n", { status: 400 }); | |
| 125 | } | |
| 126 | const copy = parseCopy(data, Date.now()); | |
| 127 | if (!copy) return new Response("bad map\n", { status: 422 }); | |
| 128 | await this.put("resilience", copy); | |
| 129 | return new Response(null, { status: 204 }); | |
| 130 | } | |
| 131 | async down(request, pathname) { | |
| 132 | const res = await this.page(request, pathname); | |
| 133 | return request.method === "HEAD" ? new Response(null, { status: res.status, headers: res.headers }) : res; | |
| 134 | } | |
| 135 | async page(request, pathname) { | |
| 136 | const now = Date.now(); | |
| 137 | if (pathname === "/healthz") | |
| 138 | return Response.json({ ok: false, body: "unreachable" }, { status: 503 }); | |
| 139 | if (!wantsHtml(request)) return new Response("the forge's body is not answering\n", { status: 502 }); | |
| 140 | const copy = await this.get("resilience"); | |
| 141 | if (copy && pathname === "/settings/resilience") return new Response(resiliencePage(copy, now), { status: 200, headers: EDGE_HEADERS }); | |
| 142 | const heard = (await this.get("heard")) ?? null; | |
| 143 | return new Response(restartingPage(heard, now, Boolean(copy)), { | |
| 144 | status: 503, | |
| 145 | headers: { ...EDGE_HEADERS, "retry-after": RETRY_AFTER }, | |
| 146 | }); | |
| 23 | 147 | } |
| 24 | 148 | async fetch(request) { |
| 25 | try { | |
| 26 | return await fetch(forward(request, this.env.BODY_URL)); | |
| 27 | } catch { | |
| 28 | const { pathname } = new URL(request.url); | |
| 29 | if (pathname === "/healthz") | |
| 30 | return Response.json({ ok: false, body: "unreachable" }, { status: 503 }); | |
| 31 | return new Response("the forge's body is not answering\n", { status: 502 }); | |
| 149 | const { pathname } = new URL(request.url); | |
| 150 | if (pathname === "/_edge/resilience") { | |
| 151 | if (request.method === "PUT") return this.push(request); | |
| 152 | return new Response("method not allowed\n", { status: 405, headers: { allow: "PUT" } }); | |
| 32 | 153 | } |
| 154 | let response; | |
| 155 | try { | |
| 156 | response = await fetch(forward(request, this.env.BODY_URL)); | |
| 157 | } catch { | |
| 158 | return this.down(request, pathname); | |
| 159 | } | |
| 160 | if (GONE.has(response.status) && wantsHtml(request) && pathname !== "/healthz") return this.down(request, pathname); | |
| 161 | const now = Date.now(); | |
| 162 | if (now - this.sawAt > SEEN_EVERY) { | |
| 163 | this.sawAt = now; | |
| 164 | await this.put("heard", now); | |
| 165 | } | |
| 166 | return response; | |
| 33 | 167 | } |
| 34 | 168 | } |
| 35 | 169 |
scripts/build-edge.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | // Bundles infra/forge-cloudflare/worker.js and the edge pages it imports into | |
| 2 | // the one file the Terraform module uploads: `bun scripts/build-edge.ts`. | |
| 3 | import { join } from "node:path"; | |
| 4 | ||
| 5 | const dir = join(import.meta.dir, "../infra/forge-cloudflare"); | |
| 6 | ||
| 7 | /** The bundled Worker, as text. */ | |
| 8 | export async function bundle(): Promise<string> { | |
| 9 | const out = await Bun.build({ entrypoints: [join(dir, "worker.js")], target: "browser", format: "esm", minify: false }); | |
| 10 | if (!out.success) throw new Error(out.logs.join("\n")); | |
| 11 | const first = out.outputs[0]; | |
| 12 | if (!first) throw new Error("the edge bundle produced no output"); | |
| 13 | return await first.text(); | |
| 14 | } | |
| 15 | ||
| 16 | if (import.meta.main) { | |
| 17 | await Bun.write(join(dir, "worker.bundle.js"), await bundle()); | |
| 18 | console.log("wrote infra/forge-cloudflare/worker.bundle.js"); | |
| 19 | } |
scripts/gate.ts +2 −6
| @@ -134,6 +134,7 @@ export const GATE: readonly string[] = [ | ||
| 134 | 134 | "test/reserved-names.test.ts", |
| 135 | 135 | "test/forge-cloudflare.test.ts", |
| 136 | 136 | "test/forge-cloudflare-celld.test.ts", |
| 137 | "test/edge-push.test.ts", | |
| 137 | 138 | "test/branch_tell.test.ts", |
| 138 | 139 | "test/usage.test.ts", |
| 139 | 140 | "test/tokens.test.ts", |
| @@ -182,6 +183,7 @@ export const GATE: readonly string[] = [ | ||
| 182 | 183 | "test/live-pages.test.ts", |
| 183 | 184 | "test/live.test.ts", |
| 184 | 185 | "test/looks.test.ts", |
| 186 | "test/attach-look.test.ts", | |
| 185 | 187 | "test/mail-caps.test.ts", |
| 186 | 188 | "test/make-it-yours.test.ts", |
| 187 | 189 | "test/map.test.ts", |
| @@ -256,12 +258,6 @@ export const EXCLUDED: readonly Exclusion[] = [ | ||
| 256 | 258 | reason: "not yet admitted", |
| 257 | 259 | issue: 261, |
| 258 | 260 | }, |
| 259 | { | |
| 260 | file: "test/plan-route.test.ts", | |
| 261 | reason: | |
| 262 | "waits up to 30 s on a fake planner run under the crew sandbox, over the 1 s budget; red where the sandbox cannot nest", | |
| 263 | issue: 261, | |
| 264 | }, | |
| 265 | 261 | { file: "test/parity.test.ts", reason: "not yet admitted", issue: 261 }, |
| 266 | 262 | { file: "test/policy.test.ts", reason: "not yet admitted", issue: 261 }, |
| 267 | 263 | { file: "test/probe.test.ts", reason: "not yet admitted", issue: 261 }, |
src/cloud/edge.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * What the edge says when the forge's body cannot answer: two self-contained | |
| 3 | * HTML pages (no script, inline style) and the check of the one thing the | |
| 4 | * forge pushes to the edge, a copy of its Settings → Resilience map. Plain | |
| 5 | * data in, strings out, no imports, so the Worker can bundle it as is. | |
| 6 | */ | |
| 7 | ||
| 8 | export type DomainRow = { name: string; breaks: string; says: string; back: string; owner: string }; | |
| 9 | export type ResilienceCopy = { at: number; domains: DomainRow[] }; | |
| 10 | ||
| 11 | /** The floor on every page the edge writes itself. */ | |
| 12 | export const EDGE_HEADERS: Record<string, string> = { | |
| 13 | "content-type": "text/html; charset=utf-8", | |
| 14 | "content-security-policy": | |
| 15 | "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", | |
| 16 | "x-content-type-options": "nosniff", | |
| 17 | "referrer-policy": "no-referrer", | |
| 18 | "cache-control": "no-store", | |
| 19 | }; | |
| 20 | ||
| 21 | const MAX_ROWS = 32; | |
| 22 | const MAX_FIELD = 600; | |
| 23 | const FIELDS = ["name", "breaks", "says", "back", "owner"] as const; | |
| 24 | ||
| 25 | /** A pushed body, checked: null unless it is a bounded list of rows of short strings. */ | |
| 26 | export function parseCopy(input: unknown, now: number): ResilienceCopy | null { | |
| 27 | if (typeof input !== "object" || input === null) return null; | |
| 28 | const list = (input as { domains?: unknown }).domains; | |
| 29 | if (!Array.isArray(list) || list.length === 0 || list.length > MAX_ROWS) return null; | |
| 30 | const domains: DomainRow[] = []; | |
| 31 | for (const row of list) { | |
| 32 | if (typeof row !== "object" || row === null) return null; | |
| 33 | const out: Record<string, string> = {}; | |
| 34 | for (const f of FIELDS) { | |
| 35 | const v = (row as Record<string, unknown>)[f]; | |
| 36 | if (typeof v !== "string" || v.length > MAX_FIELD) return null; | |
| 37 | out[f] = v; | |
| 38 | } | |
| 39 | if (out.name === "") return null; | |
| 40 | domains.push(out as DomainRow); | |
| 41 | } | |
| 42 | return { at: now, domains }; | |
| 43 | } | |
| 44 | ||
| 45 | export function esc(s: string): string { | |
| 46 | return s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); | |
| 47 | } | |
| 48 | ||
| 49 | /** "3 minutes ago", "never": an age in words, from two instants in ms. */ | |
| 50 | export function ago(then: number | null, now: number): string { | |
| 51 | if (then === null) return "never"; | |
| 52 | const s = Math.max(0, Math.round((now - then) / 1000)); | |
| 53 | if (s < 60) return `${s} second${s === 1 ? "" : "s"} ago`; | |
| 54 | const m = Math.floor(s / 60); | |
| 55 | if (m < 60) return `${m} minute${m === 1 ? "" : "s"} ago`; | |
| 56 | const h = Math.floor(m / 60); | |
| 57 | if (h < 48) return `${h} hour${h === 1 ? "" : "s"} ago`; | |
| 58 | const d = Math.floor(h / 24); | |
| 59 | return `${d} days ago`; | |
| 60 | } | |
| 61 | ||
| 62 | function shell(title: string, body: string): string { | |
| 63 | return `<!doctype html><html lang="en"><head><meta charset="utf-8"> | |
| 64 | <meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title> | |
| 65 | <style>body{font:16px/1.5 system-ui,sans-serif;max-width:46rem;margin:12vh auto;padding:0 1rem;color:#222;background:#fafafa} | |
| 66 | h1{font-size:1.4rem}table{border-collapse:collapse;width:100%}th,td{text-align:left;vertical-align:top;border-top:1px solid #ccc;padding:.4rem} | |
| 67 | .wide{overflow-x:auto}table{min-width:36rem}a:focus-visible{outline:3px solid #b4533a;outline-offset:2px}.note{padding:.6rem .8rem;border:1px solid #b4533a;border-radius:6px}@media(prefers-color-scheme:dark){body{color:#ddd;background:#161616}th,td{border-color:#444}}</style> | |
| 68 | </head><body>${body}</body></html> | |
| 69 | `; | |
| 70 | } | |
| 71 | ||
| 72 | /** The page for any browser GET while the body is unreachable. */ | |
| 73 | export function restartingPage(lastHeard: number | null, now: number, hasCopy = false): string { | |
| 74 | return shell( | |
| 75 | "The forge is restarting", | |
| 76 | `<h1>The forge is restarting</h1> | |
| 77 | <p>This answer comes from the edge, not the forge. Nothing you have pushed is lost; try again in a minute.</p> | |
| 78 | <p>The edge last heard from the forge ${esc(ago(lastHeard, now))}.</p> | |
| 79 | ${hasCopy ? '<p><a href="/settings/resilience">What each part does when it fails</a></p>' : ""}`, | |
| 80 | ); | |
| 81 | } | |
| 82 | ||
| 83 | /** The last Resilience map the forge pushed, marked as a copy with its age. */ | |
| 84 | export function resiliencePage(copy: ResilienceCopy, now: number): string { | |
| 85 | const rows = copy.domains | |
| 86 | .map( | |
| 87 | (d) => | |
| 88 | `<tr><th scope="row">${esc(d.name)}</th><td>${esc(d.breaks)}</td><td>${esc(d.says)}</td><td>${esc(d.back)}</td><td>${esc(d.owner)}</td></tr>`, | |
| 89 | ) | |
| 90 | .join(""); | |
| 91 | return shell( | |
| 92 | "Resilience (copy)", | |
| 93 | `<h1>Resilience</h1> | |
| 94 | <p class="note">This is a copy served by the edge because the forge is not answering. It was pushed ${esc(ago(copy.at, now))} and may be out of date.</p> | |
| 95 | <div class="wide" tabindex="0" role="region" aria-label="Resilience table"><table><thead><tr><th>Domain</th><th>What breaks</th><th>What the forge says</th><th>Back in</th><th>What you do</th></tr></thead><tbody>${rows}</tbody></table></div>`, | |
| 96 | ); | |
| 97 | } |
src/cloud/edge_push.ts added +91
| @@ -0,0 +1,91 @@ | ||
| 1 | /** | |
| 2 | * The forge's half of the edge's Resilience copy: what is pushed, to where, | |
| 3 | * and when. The copy is public by construction — a fixed list of what each | |
| 4 | * failure domain does, written here, never read from an account, a setting or | |
| 5 | * a signed-in page — because the edge serves it to anyone while the body is | |
| 6 | * down. Configuration is two variables: FORGE_EDGE_PUSH_URL (the edge's | |
| 7 | * origin) and FORGE_EDGE_PUSH_TOKEN (the same value as the Worker's | |
| 8 | * EDGE_PUSH_TOKEN secret). Either unset, nothing is pushed. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { DomainRow } from "./edge.ts"; | |
| 12 | ||
| 13 | export const PUBLIC_RESILIENCE: DomainRow[] = [ | |
| 14 | { | |
| 15 | name: "Compute", | |
| 16 | breaks: "Pages, git over HTTP and SSH, the API", | |
| 17 | says: "The edge shows that the forge is restarting", | |
| 18 | back: "Usually under a minute", | |
| 19 | owner: "Wait and retry; nothing pushed is lost", | |
| 20 | }, | |
| 21 | { | |
| 22 | name: "Storage", | |
| 23 | breaks: "Repositories and the index are unreadable", | |
| 24 | says: "Pages answer with an error", | |
| 25 | back: "When the disk or volume is back", | |
| 26 | owner: "The operator restores from the nightly snapshot", | |
| 27 | }, | |
| 28 | { | |
| 29 | name: "Edge", | |
| 30 | breaks: "The public address stops answering", | |
| 31 | says: "Nothing: the edge is the thing that answers", | |
| 32 | back: "When the edge provider recovers", | |
| 33 | owner: "The operator reaches the body directly", | |
| 34 | }, | |
| 35 | ]; | |
| 36 | ||
| 37 | export type EdgePush = { url: string; token: string }; | |
| 38 | ||
| 39 | /** The push settings from the environment, or null when either is missing or the URL is not http(s). */ | |
| 40 | export function edgePushFrom(env: Record<string, string | undefined>): EdgePush | null { | |
| 41 | const raw = (env["FORGE_EDGE_PUSH_URL"] ?? "").trim(); | |
| 42 | const token = (env["FORGE_EDGE_PUSH_TOKEN"] ?? "").trim(); | |
| 43 | if (raw === "" || token === "") return null; | |
| 44 | let u: URL; | |
| 45 | try { | |
| 46 | u = new URL(raw); | |
| 47 | } catch { | |
| 48 | return null; | |
| 49 | } | |
| 50 | if (u.protocol !== "https:" && u.protocol !== "http:") return null; | |
| 51 | return { url: u.origin, token }; | |
| 52 | } | |
| 53 | ||
| 54 | export type PushResult = { ok: true } | { ok: false; reason: string }; | |
| 55 | ||
| 56 | /** One PUT of the public copy to the edge. Never throws. */ | |
| 57 | export async function pushResilience( | |
| 58 | to: EdgePush, | |
| 59 | doFetch: typeof fetch = fetch, | |
| 60 | ): Promise<PushResult> { | |
| 61 | try { | |
| 62 | const r = await doFetch(`${to.url}/_edge/resilience`, { | |
| 63 | method: "PUT", | |
| 64 | headers: { authorization: `Bearer ${to.token}`, "content-type": "application/json" }, | |
| 65 | body: JSON.stringify({ domains: PUBLIC_RESILIENCE }), | |
| 66 | redirect: "error", | |
| 67 | signal: AbortSignal.timeout(10_000), | |
| 68 | }); | |
| 69 | return r.status === 204 ? { ok: true } : { ok: false, reason: `the edge answered ${r.status}` }; | |
| 70 | } catch (error) { | |
| 71 | return { ok: false, reason: String(error) }; | |
| 72 | } | |
| 73 | } | |
| 74 | ||
| 75 | /** Push now and every hour (the edge keeps the copy's age). Returns a stop. */ | |
| 76 | export function startEdgePush( | |
| 77 | env: Record<string, string | undefined>, | |
| 78 | log: { info(m: string, f?: Record<string, string | number | boolean | undefined>): void; warn(m: string, f?: Record<string, string | number | boolean | undefined>): void }, | |
| 79 | doFetch: typeof fetch = fetch, | |
| 80 | ): (() => void) | undefined { | |
| 81 | const to = edgePushFrom(env); | |
| 82 | if (to === null) return undefined; | |
| 83 | const once = async (): Promise<void> => { | |
| 84 | const r = await pushResilience(to, doFetch); | |
| 85 | if (r.ok) log.info("edge resilience copy pushed", { edge: to.url }); | |
| 86 | else log.warn("edge resilience copy not pushed", { edge: to.url, reason: r.reason }); | |
| 87 | }; | |
| 88 | void once(); | |
| 89 | const timer = setInterval(() => void once(), 3_600_000); | |
| 90 | return () => clearInterval(timer); | |
| 91 | } |
src/main.ts +5
| @@ -38,6 +38,7 @@ import { recordAskLedger } from "./web/studio/asks.ts"; | ||
| 38 | 38 | import { startPromptRoutine } from "./crew/prompts.ts"; |
| 39 | 39 | import { pruneTokens } from "./core/tokens.ts"; |
| 40 | 40 | import { dataHomeRefusal } from "./kernel/data_home.ts"; |
| 41 | import { startEdgePush } from "./cloud/edge_push.ts"; | |
| 41 | 42 | import { running } from "./kernel/version.ts"; |
| 42 | 43 | |
| 43 | 44 | // `forge hook <name>` re-enters here from a git hook stub. It relays to the |
| @@ -315,6 +316,9 @@ function positive(value: string | undefined, fallback: number): number { | ||
| 315 | 316 | // asks who is due — so this costs one indexed read a minute when nothing is |
| 316 | 317 | // connected. Like runDelivery, runSync never throws into the timer. |
| 317 | 318 | const syncTimer = setInterval(() => runSync(app), 60_000); |
| 319 | // The public Resilience copy at the edge (cloud/edge_push.ts); off unless | |
| 320 | // FORGE_EDGE_PUSH_URL and FORGE_EDGE_PUSH_TOKEN are set. | |
| 321 | const stopEdgePush = startEdgePush(process.env, app.log); | |
| 318 | 322 | runSync(app); // one pass on boot: a forge that was down has fetching to do |
| 319 | 323 | |
| 320 | 324 | // Which green pulls no longer merge as they stand, so the asks can leave |
| @@ -401,6 +405,7 @@ function shutdown(signal: NodeJS.Signals): void { | ||
| 401 | 405 | drainStreams(); |
| 402 | 406 | clearInterval(deliveryTimer); |
| 403 | 407 | clearInterval(syncTimer); |
| 408 | stopEdgePush?.(); | |
| 404 | 409 | clearInterval(staleTimer); |
| 405 | 410 | clearInterval(leaseTimer); |
| 406 | 411 | Promise.all([ |
test/edge-push.test.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { PUBLIC_RESILIENCE, edgePushFrom, pushResilience, startEdgePush } from "../src/cloud/edge_push.ts"; | |
| 3 | import { parseCopy } from "../src/cloud/edge.ts"; | |
| 4 | ||
| 5 | describe("edge push", () => { | |
| 6 | test("settings need both variables and an http(s) URL; the URL is cut to its origin", () => { | |
| 7 | expect(edgePushFrom({})).toBeNull(); | |
| 8 | expect(edgePushFrom({ FORGE_EDGE_PUSH_URL: "https://e.example" })).toBeNull(); | |
| 9 | expect(edgePushFrom({ FORGE_EDGE_PUSH_TOKEN: "t" })).toBeNull(); | |
| 10 | expect(edgePushFrom({ FORGE_EDGE_PUSH_URL: "file:///etc", FORGE_EDGE_PUSH_TOKEN: "t" })).toBeNull(); | |
| 11 | expect(edgePushFrom({ FORGE_EDGE_PUSH_URL: "nonsense", FORGE_EDGE_PUSH_TOKEN: "t" })).toBeNull(); | |
| 12 | expect(edgePushFrom({ FORGE_EDGE_PUSH_URL: "https://e.example/x?y", FORGE_EDGE_PUSH_TOKEN: " t " })).toEqual({ | |
| 13 | url: "https://e.example", | |
| 14 | token: "t", | |
| 15 | }); | |
| 16 | }); | |
| 17 | ||
| 18 | test("the public copy is something the edge accepts", () => { | |
| 19 | expect(parseCopy({ domains: PUBLIC_RESILIENCE }, 1)).not.toBeNull(); | |
| 20 | }); | |
| 21 | ||
| 22 | test("a push is a bearer PUT of the public copy; failures are results, not throws", async () => { | |
| 23 | const seen: { url: string; init: RequestInit }[] = []; | |
| 24 | const ok = (async (url: string, init: RequestInit) => (seen.push({ url, init }), new Response(null, { status: 204 }))) as any; | |
| 25 | const to = { url: "https://e.example", token: "tok" }; | |
| 26 | expect(await pushResilience(to, ok)).toEqual({ ok: true }); | |
| 27 | expect(seen[0]!.url).toBe("https://e.example/_edge/resilience"); | |
| 28 | expect(seen[0]!.init.method).toBe("PUT"); | |
| 29 | expect((seen[0]!.init.headers as Record<string, string>).authorization).toBe("Bearer tok"); | |
| 30 | expect(JSON.parse(seen[0]!.init.body as string)).toEqual({ domains: PUBLIC_RESILIENCE }); | |
| 31 | const refused = await pushResilience(to, (async () => new Response("no", { status: 403 })) as any); | |
| 32 | expect(refused).toEqual({ ok: false, reason: "the edge answered 403" }); | |
| 33 | const down = await pushResilience(to, (async () => { throw new Error("boom"); }) as any); | |
| 34 | expect(down.ok).toBe(false); | |
| 35 | }); | |
| 36 | ||
| 37 | test("boot pushes once when configured and nothing when not", async () => { | |
| 38 | const lines: string[] = []; | |
| 39 | const log = { info: (m: string) => lines.push(m), warn: (m: string) => lines.push(m) }; | |
| 40 | let calls = 0; | |
| 41 | const f = (async () => (calls++, new Response(null, { status: 204 }))) as any; | |
| 42 | expect(startEdgePush({}, log, f)).toBeUndefined(); | |
| 43 | const stop = startEdgePush({ FORGE_EDGE_PUSH_URL: "https://e.example", FORGE_EDGE_PUSH_TOKEN: "t" }, log, f); | |
| 44 | await Bun.sleep(20); | |
| 45 | stop!(); | |
| 46 | expect(calls).toBe(1); | |
| 47 | expect(lines).toEqual(["edge resilience copy pushed"]); | |
| 48 | }); | |
| 49 | }); |
test/forge-cloudflare-celld.test.ts +6 −2
| @@ -32,6 +32,7 @@ const seen: { method: string; path: string; proto: string | null; body: string } | ||
| 32 | 32 | let stub: ReturnType<typeof Bun.serve> | undefined; |
| 33 | 33 | let proc: ReturnType<typeof Bun.spawn> | undefined; |
| 34 | 34 | let dir = ""; |
| 35 | let root = ""; | |
| 35 | 36 | let base = ""; |
| 36 | 37 | |
| 37 | 38 | async function until(path: string): Promise<Response> { |
| @@ -62,8 +63,11 @@ beforeAll(async () => { | ||
| 62 | 63 | return new Response("body ok"); |
| 63 | 64 | }, |
| 64 | 65 | }); |
| 65 | dir = mkdtempSync(join(tmpdir(), "forge-celld-test-")); | |
| 66 | root = mkdtempSync(join(tmpdir(), "forge-celld-test-")); | |
| 67 | dir = join(root, "infra/forge-cloudflare"); | |
| 66 | 68 | cpSync(join(import.meta.dir, "../infra/forge-cloudflare"), dir, { recursive: true }); |
| 69 | // the worker imports the edge pages from src/cloud, relative to itself | |
| 70 | cpSync(join(import.meta.dir, "../src/cloud/edge.ts"), join(root, "src/cloud/edge.ts")); | |
| 67 | 71 | // .dev.vars overrides the config's vars, as for wrangler dev |
| 68 | 72 | await Bun.write(join(dir, ".dev.vars"), `BODY_URL=http://127.0.0.1:${stub.port}\n`); |
| 69 | 73 | const port = freePort(); |
| @@ -78,7 +82,7 @@ afterAll(async () => { | ||
| 78 | 82 | proc?.kill("SIGKILL"); |
| 79 | 83 | await proc?.exited; |
| 80 | 84 | stub?.stop(true); |
| 81 | if (dir) rmSync(dir, { recursive: true, force: true }); | |
| 85 | if (root) rmSync(root, { recursive: true, force: true }); | |
| 82 | 86 | }, 15_000); |
| 83 | 87 | |
| 84 | 88 | describe.skipIf(!!skip)("forge-cloudflare worker on celld", () => { |
test/forge-cloudflare.test.ts +157
| @@ -22,8 +22,165 @@ describe("forge-cloudflare worker", () => { | ||
| 22 | 22 | expect((await f.fetch(new Request("https://h/mcp"))).status).toBe(502); |
| 23 | 23 | }); |
| 24 | 24 | |
| 25 | const html = { headers: { accept: "text/html" } }; | |
| 26 | const rows = { domains: [{ name: "compute <b>", breaks: "pages", says: "restarting", back: "1 min", owner: "wait" }] }; | |
| 27 | const push = (f: any, body: unknown, token = "tok") => | |
| 28 | f.fetch(new Request("https://h/_edge/resilience", { method: "PUT", headers: { authorization: `Bearer ${token}` }, body: JSON.stringify(body) })); | |
| 29 | ||
| 30 | test("a browser GET with the body down gets the restarting page, 503, Retry-After, the CSP floor", async () => { | |
| 31 | const f = new Forge({}, { BODY_URL: "http://127.0.0.1:1" }); | |
| 32 | const r = await f.fetch(new Request("https://h/some/page", html)); | |
| 33 | expect(r.status).toBe(503); | |
| 34 | expect(r.headers.get("retry-after")).toBe("30"); | |
| 35 | expect(r.headers.get("content-security-policy")).toContain("default-src 'none'"); | |
| 36 | expect(r.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 37 | expect(r.headers.get("referrer-policy")).toBe("no-referrer"); | |
| 38 | const t = await r.text(); | |
| 39 | expect(t).toContain("The forge is restarting"); | |
| 40 | expect(t).toContain("never"); | |
| 41 | expect(t).not.toContain("<script"); | |
| 42 | // no copy pushed: no link to a page that would say the same again | |
| 43 | expect(t).not.toContain("/settings/resilience"); | |
| 44 | // a POST is never answered with a page | |
| 45 | expect((await f.fetch(new Request("https://h/x", { method: "POST", ...html }))).status).toBe(502); | |
| 46 | }); | |
| 47 | ||
| 48 | test("the pushed Resilience map is served as an escaped, aged copy while the body is down", async () => { | |
| 49 | const f = new Forge({}, { BODY_URL: "http://127.0.0.1:1", EDGE_PUSH_TOKEN: "tok" }); | |
| 50 | expect((await push(f, rows, "wrong")).status).toBe(403); | |
| 51 | expect((await push(f, { domains: [] })).status).toBe(422); | |
| 52 | expect((await push(f, rows)).status).toBe(204); | |
| 53 | const r = await f.fetch(new Request("https://h/settings/resilience", html)); | |
| 54 | expect(r.status).toBe(200); | |
| 55 | const t = await r.text(); | |
| 56 | expect(t).toContain("a copy served by the edge"); | |
| 57 | expect(t).toContain("0 seconds ago"); | |
| 58 | expect(t).toContain("compute <b>"); | |
| 59 | expect(t).not.toContain("<b>"); | |
| 60 | // other pages still get the restarting page, now linking to the copy | |
| 61 | const home = await f.fetch(new Request("https://h/", html)); | |
| 62 | expect(home.status).toBe(503); | |
| 63 | expect(await home.text()).toContain('href="/settings/resilience"'); | |
| 64 | expect(t).toContain("overflow-x:auto"); | |
| 65 | expect(t).toContain(":focus-visible"); | |
| 66 | }); | |
| 67 | ||
| 68 | test("the push refuses a large body by bytes, bad JSON, and any other method", async () => { | |
| 69 | const f = new Forge({}, { BODY_URL: "http://127.0.0.1:1", EDGE_PUSH_TOKEN: "tok" }); | |
| 70 | const put = (body: string, extra: Record<string, string> = {}) => | |
| 71 | f.fetch(new Request("https://h/_edge/resilience", { method: "PUT", headers: { authorization: "Bearer tok", ...extra }, body })); | |
| 72 | // 40,000 characters of 2 bytes each: under the cap as characters, over it as bytes | |
| 73 | expect((await put("é".repeat(40_000))).status).toBe(413); | |
| 74 | // no content-length to trust: a stream that passes the cap is stopped | |
| 75 | const big = new ReadableStream({ pull(c) { c.enqueue(new Uint8Array(16 * 1024)); } }); | |
| 76 | const streamed = await f.fetch(new Request("https://h/_edge/resilience", { method: "PUT", headers: { authorization: "Bearer tok" }, body: big, duplex: "half" } as any)); | |
| 77 | expect(streamed.status).toBe(413); | |
| 78 | expect((await put("{nope")).status).toBe(400); | |
| 79 | for (const method of ["GET", "POST", "DELETE"]) { | |
| 80 | const r = await f.fetch(new Request("https://h/_edge/resilience", { method, headers: { authorization: "Bearer tok" }, ...(method === "POST" ? { body: "{}" } : {}) })); | |
| 81 | expect(r.status).toBe(405); | |
| 82 | expect(r.headers.get("allow")).toBe("PUT"); | |
| 83 | } | |
| 84 | // a token of another length is refused like any other wrong one | |
| 85 | expect((await push(f, rows, "t")).status).toBe(403); | |
| 86 | expect((await push(f, rows, "tok-and-more")).status).toBe(403); | |
| 87 | }); | |
| 88 | ||
| 89 | test("with no push token the push is not found; with the body up nothing changes", async () => { | |
| 90 | const f = new Forge({}, { BODY_URL: "http://127.0.0.1:1" }); | |
| 91 | expect((await push(f, rows)).status).toBe(404); | |
| 92 | const stub = Bun.serve({ port: 0, fetch: () => new Response("body ok") }); | |
| 93 | try { | |
| 94 | const g = new Forge({}, { BODY_URL: `http://127.0.0.1:${stub.port}` }); | |
| 95 | const r = await g.fetch(new Request("https://h/settings/resilience", html)); | |
| 96 | expect(await r.text()).toBe("body ok"); | |
| 97 | stub.stop(true); | |
| 98 | const t = await (await g.fetch(new Request("https://h/", html))).text(); | |
| 99 | expect(t).not.toContain("never"); | |
| 100 | } finally { | |
| 101 | stub.stop(true); | |
| 102 | } | |
| 103 | }); | |
| 104 | ||
| 25 | 105 | test("the module refuses names outside the spike- prefix", () => { |
| 26 | 106 | const v = readFileSync("infra/forge-cloudflare/variables.tf", "utf8"); |
| 27 | 107 | expect(v).toContain('^spike-[a-z0-9-]{1,40}$'); |
| 28 | 108 | }); |
| 29 | 109 | }); |
| 110 | ||
| 111 | describe("forge-cloudflare worker, as the module uploads it", () => { | |
| 112 | const dir = "../infra/forge-cloudflare"; | |
| 113 | ||
| 114 | test("main.tf uploads the bundle, and the bundle is current", async () => { | |
| 115 | const { bundle } = await import("../scripts/build-edge"); | |
| 116 | expect(readFileSync(new URL(`${dir}/main.tf`, import.meta.url), "utf8")).toContain("worker.bundle.js"); | |
| 117 | expect(readFileSync(new URL(`${dir}/worker.bundle.js`, import.meta.url), "utf8")).toBe(await bundle()); | |
| 118 | }); | |
| 119 | ||
| 120 | test("worker.bundle.js alone, with no src/ beside it, loads and serves the restarting page", async () => { | |
| 121 | const { mkdtempSync, copyFileSync, rmSync } = await import("node:fs"); | |
| 122 | const { tmpdir } = await import("node:os"); | |
| 123 | const { join } = await import("node:path"); | |
| 124 | const lone = mkdtempSync(join(tmpdir(), "worker-alone-")); | |
| 125 | try { | |
| 126 | copyFileSync(new URL(`${dir}/worker.bundle.js`, import.meta.url), join(lone, "worker.js")); | |
| 127 | const m = await import(join(lone, "worker.js")); | |
| 128 | const f = new m.Forge({}, { BODY_URL: "http://127.0.0.1:1" }); | |
| 129 | const r = await f.fetch(new Request("https://h/x", { headers: { accept: "text/html" } })); | |
| 130 | expect(r.status).toBe(503); | |
| 131 | expect(await r.text()).toContain("The forge is restarting"); | |
| 132 | } finally { | |
| 133 | rmSync(lone, { recursive: true, force: true }); | |
| 134 | } | |
| 135 | }); | |
| 136 | }); | |
| 137 | ||
| 138 | describe("forge-cloudflare worker, body answering 5xx and abuse", () => { | |
| 139 | const html = { headers: { accept: "text/html" } }; | |
| 140 | const withBody = (status: number) => { | |
| 141 | const s = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("raw", { status }) }); | |
| 142 | return { s, f: new Forge({}, { BODY_URL: `http://127.0.0.1:${s.port}`, EDGE_PUSH_TOKEN: "tok" }) }; | |
| 143 | }; | |
| 144 | ||
| 145 | for (const status of [502, 503, 504]) { | |
| 146 | test(`a ${status} from the body on an HTML GET is the restarting page; other requests pass through`, async () => { | |
| 147 | const { s, f } = withBody(status); | |
| 148 | try { | |
| 149 | const r = await f.fetch(new Request("https://h/p", html)); | |
| 150 | expect(await r.text()).toContain("The forge is restarting"); | |
| 151 | expect(r.headers.get("retry-after")).toBe("30"); | |
| 152 | const api = await f.fetch(new Request("https://h/p")); | |
| 153 | expect(await api.text()).toBe("raw"); | |
| 154 | } finally { | |
| 155 | s.stop(true); | |
| 156 | } | |
| 157 | }); | |
| 158 | } | |
| 159 | ||
| 160 | test("a 500 from the body is passed through", async () => { | |
| 161 | const { s, f } = withBody(500); | |
| 162 | try { | |
| 163 | expect(await (await f.fetch(new Request("https://h/p", html))).text()).toBe("raw"); | |
| 164 | } finally { | |
| 165 | s.stop(true); | |
| 166 | } | |
| 167 | }); | |
| 168 | ||
| 169 | test("HEAD with the body down has the headers and no body", async () => { | |
| 170 | const f = new Forge({}, { BODY_URL: "http://127.0.0.1:1" }); | |
| 171 | const r = await f.fetch(new Request("https://h/p", { method: "HEAD", ...html })); | |
| 172 | expect(r.status).toBe(503); | |
| 173 | expect(r.headers.get("retry-after")).toBe("30"); | |
| 174 | expect(await r.text()).toBe(""); | |
| 175 | }); | |
| 176 | ||
| 177 | test("the sixth wrong token in a minute from one address is 429, even with the right token; others are not held", async () => { | |
| 178 | const f = new Forge({}, { BODY_URL: "http://127.0.0.1:1", EDGE_PUSH_TOKEN: "tok" }); | |
| 179 | const put = (token: string, ip: string) => | |
| 180 | f.fetch(new Request("https://h/_edge/resilience", { method: "PUT", headers: { authorization: `Bearer ${token}`, "cf-connecting-ip": ip }, body: "{}" })); | |
| 181 | for (let i = 0; i < 5; i++) expect((await put("bad", "9.9.9.9")).status).toBe(403); | |
| 182 | expect((await put("bad", "9.9.9.9")).status).toBe(429); | |
| 183 | expect((await put("tok", "9.9.9.9")).status).toBe(429); | |
| 184 | expect((await put("tok", "8.8.8.8")).status).toBe(422); | |
| 185 | }); | |
| 186 | }); |
new above
offline