// Every API write is refused cross-site (writeGuard.mjs, umtool/proxy.ts): the proxy's decision, and a sweep of // every route file that exports a write, each of which the proxy must cover. import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { BODY_CAP, bodyRefusal, EXEMPT, GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs"; const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const APP = path.join(UMTOOL, "app"); const h = (o) => ({ get: (k) => o[k.toLowerCase()] ?? null }); const NO_ENV = {}; test("writeRefusal: another site's, a sibling site's and a rebound page's writes are refused; the app's own, a non-browser's and every read pass", () => { const post = (headers, env = NO_ENV, p = "/api/projects/new") => writeRefusal("POST", p, h(headers), env); // Refused. assert.match(String(post({ origin: "https://evil.example", host: "localhost:3050" })), /evil\.example/, "a cross-site Origin"); assert.match(String(post({ origin: "https://evil.example", host: "localhost:3050", "sec-fetch-site": "cross-site" })), /cross-site/); assert.match(String(post({ "sec-fetch-site": "cross-site", host: "localhost:3050" })), /cross-site/, "Sec-Fetch-Site: cross-site, no Origin"); assert.match(String(post({ "sec-fetch-site": "same-site", origin: "http://localhost:3001", host: "localhost:3050" })), /same-site/, "the editor's page"); assert.match(String(post({ origin: "http://evil.example:3050", host: "evil.example:3050", "sec-fetch-site": "same-origin" })), /UMTOOL_ALLOWED_HOSTS/, "Host: evil.example (DNS rebinding)"); assert.match(String(post({ origin: "http://localhost:3050", host: "localhost:3050", "x-forwarded-host": "rebind.example:3050" })), /rebind\.example/, "a rebound X-Forwarded-Host"); assert.match(String(post({ origin: "null", host: "localhost:3050" })), /opaque/); for (const m of ["PUT", "PATCH", "DELETE", "post"]) { assert.ok(writeRefusal(m, "/api/report/manifest", h({ origin: "https://evil.example", host: "localhost:3050" }), NO_ENV), m); } // Pass. assert.equal(post({ origin: "http://localhost:3050", host: "localhost:3050", "sec-fetch-site": "same-origin" }), null, "the app's own page"); assert.equal(post({ origin: "http://127.0.0.1:3050", host: "127.0.0.1:3050" }), null, "by address"); assert.equal(post({ host: "localhost:3050" }), null, "curl, the CLI"); assert.equal(post({ host: "localhost:3050", authorization: "Bearer t" }), null, "an agent with its Bearer"); assert.equal(post({ host: "umtool:3050", authorization: "Bearer t" }), null, "the editor's server in docker (UMTOOL_URL=http://umtool:3050)"); assert.equal(post({ host: "box.lan:3050" }), null, "a terminal on the LAN: no browser, its Host is its own"); assert.equal(post({ origin: "https://umtool.lan", host: "umtool.lan", "sec-fetch-site": "same-origin" }, { UMTOOL_ALLOWED_HOSTS: "umtool.lan" }), null, "a listed host"); assert.ok(post({ origin: "https://umtool.lan", host: "umtool.lan", "sec-fetch-site": "same-origin" }), "the same, unlisted"); for (const m of ["GET", "HEAD", "OPTIONS", "get"]) { assert.equal(writeRefusal(m, "/api/projects/new", h({ origin: "https://evil.example", "sec-fetch-site": "cross-site", host: "evil.example" }), NO_ENV), null, `${m} from anywhere`); } assert.equal(post({ origin: "https://evil.example", host: "localhost:3050" }, NO_ENV, "/projects"), null, "not under /api/"); }); test("guardedPath: writes under /api/ only", () => { assert.equal(guardedPath("POST", "/api"), true); assert.equal(guardedPath("POST", "/api/cli"), true); assert.equal(guardedPath("DELETE", "/api/a/b/c"), true); assert.equal(guardedPath("GET", "/api/cli"), false); assert.equal(guardedPath("POST", "/apix"), false); assert.equal(guardedPath("POST", "/reports/x"), false); assert.equal(guardedPath("POST", "/%61pi/projects/new"), true, "an encoded spelling"); assert.equal(guardedPath("POST", "/API/projects/new"), true, "another case"); assert.equal(guardedPath("POST", "/api/%E0%A4%A"), true, "undecodable, judged as sent"); }); /** Every route.ts under app/, as [file, url, write methods]. */ function routes() { const out = []; const walk = (dir) => { for (const e of fs.readdirSync(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) walk(p); else if (/^route\.(ts|tsx|js|mjs)$/.test(e.name)) out.push(p); } }; walk(APP); return out.map((file) => { const src = fs.readFileSync(file, "utf8"); const methods = new Set(); for (const m of src.matchAll(/export\s+(?:async\s+)?(?:function\s*\*?|const|let|var)\s+(POST|PUT|PATCH|DELETE)\b/g)) methods.add(m[1]); for (const m of src.matchAll(/export\s+(?:const|let|var)\s*\{([^}]*)\}\s*=/g)) { for (const w of m[1].matchAll(/\b(POST|PUT|PATCH|DELETE)\b/g)) methods.add(w[1]); // export const { POST } = h } for (const m of src.matchAll(/export\s*\{([^}]*)\}/g)) { for (const w of m[1].matchAll(/\b(POST|PUT|PATCH|DELETE)\b/g)) methods.add(w[1]); } if (/export\s+\*\s+from/.test(src)) methods.add("POST"); // a re-export may carry a write: count it as one const segs = path.relative(APP, path.dirname(file)).split(path.sep).filter(Boolean) .filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@")) .map((s) => (/^\[\[?\.\.\./.test(s) ? "a/b" : /^\[.*\]$/.test(s) ? "x" : s)); return { file: path.relative(UMTOOL, file), url: "/" + segs.join("/"), methods: [...methods] }; }); } /** Next's matcher, as the regular expression its source is (a `/…((?!…).*)` pattern has no named parameters). */ function matcherCovers(matcher, url) { assert.ok(!/:/.test(matcher), `the sweep reads a matcher as a plain regular expression, not ${matcher}`); return new RegExp(`^${matcher}$`).test(url); } /** A handler's source: from `export … function (` to the next top-level export. */ function handlerSource(src, method) { const at = src.search(new RegExp(`export\\s+(?:async\\s+)?function\\s+${method}\\s*\\(`)); if (at < 0) return null; const next = src.slice(at + 1).search(/\nexport\s/); return next < 0 ? src.slice(at) : src.slice(at, at + 1 + next); } test("every route that exports a write is behind the proxy", () => { const proxySrc = fs.readFileSync(path.join(UMTOOL, "proxy.ts"), "utf8"); const said = /matcher:\s*(["'])([^"']+)\1/.exec(proxySrc); assert.ok(said, "proxy.ts names a literal matcher"); assert.equal(said[2], GUARD_MATCHER, "proxy.ts's matcher is GUARD_MATCHER"); for (const p of ["/api/cli", "/api/projects/new", "/api/report/voices/x", "/api/report/post-narration/other", "/api/report/voicesx"]) { assert.ok(matcherCovers(GUARD_MATCHER, p), `the matcher covers ${p}`); } for (const p of EXEMPT) assert.ok(!matcherCovers(GUARD_MATCHER, p), `the matcher leaves out ${p}`); assert.match(proxySrc, /export function proxy\b/, "proxy.ts exports proxy"); assert.match(proxySrc, /writeRefusal\(request\.method, request\.nextUrl\.pathname, request\.headers\)/, "proxy.ts asks writeRefusal"); assert.match(proxySrc, /bodyRefusal\(request\.method, request\.nextUrl\.pathname, request\.headers\)[\s\S]*status: 413/, "proxy.ts asks bodyRefusal, 413"); assert.ok(!fs.existsSync(path.join(UMTOOL, "middleware.ts")), "no middleware.ts beside proxy.ts"); const all = routes(); const writers = all.filter((r) => r.methods.length); assert.ok(writers.length >= 140, `the sweep found ${writers.length} write routes: too few, so the walk is wrong`); const uncovered = []; const exempt = []; for (const r of writers) { for (const m of r.methods) { if (!guardedPath(m, r.url)) uncovered.push(`${m} ${r.url} (${r.file}): not a guarded path`); else if (matcherCovers(GUARD_MATCHER, r.url)) continue; else if (!EXEMPT.includes(r.url)) uncovered.push(`${m} ${r.url} (${r.file}): outside the matcher and not EXEMPT`); else { // An exempt write refuses cross-site itself, as the FIRST use of its request: before any body read. exempt.push(`${m} ${r.url}`); const src = handlerSource(fs.readFileSync(path.join(UMTOOL, r.file), "utf8"), m); if (!src) { uncovered.push(`${m} ${r.url} (${r.file}): exempt, but not a plain \`export async function ${m}\` the sweep can read`); continue; } const body = src.slice(src.indexOf("{")); const firstUse = body.search(/\brequest\b/); if (firstUse < 0 || !body.slice(firstUse).startsWith("request.headers") || !/crossSiteRefusal\(\s*$/.test(body.slice(0, firstUse))) { uncovered.push(`${m} ${r.url} (${r.file}): exempt, but its first use of the request is not crossSiteRefusal(request.headers)`); } } } } assert.deepEqual(uncovered, [], "a write the proxy does not guard"); assert.deepEqual(exempt.sort(), EXEMPT.map((p) => `POST ${p}`).sort(), "every EXEMPT path is a POST route the sweep checked"); }); test("bodyRefusal: a write declaring a body over the proxy's cap is refused (413, a sentence); at the cap, a read, or no length passes -- and the cap is next.config.ts's", () => { const cfg = fs.readFileSync(path.join(UMTOOL, "next.config.ts"), "utf8"); const said = /proxyClientMaxBodySize:\s*"(\d+)mb"/.exec(cfg); assert.ok(said, "next.config.ts names proxyClientMaxBodySize in mb"); assert.equal(Number(said[1]) * 1024 * 1024, BODY_CAP, "BODY_CAP is next.config.ts's cap"); const len = (n) => h({ "content-length": String(n) }); assert.match(String(bodyRefusal("POST", "/api/projects/new", len(BODY_CAP + 1))), /over the 16777216 \(16 MB\)/); assert.match(String(bodyRefusal("PUT", "/api/report/window", len(20 * 1024 * 1024))), /20971520 bytes/); assert.equal(bodyRefusal("POST", "/api/projects/new", len(BODY_CAP)), null, "at the cap"); assert.equal(bodyRefusal("POST", "/api/projects/new", h({})), null, "no length (chunked): the route judges what it gets"); assert.equal(bodyRefusal("POST", "/api/projects/new", h({ "content-length": "1e9" })), null, "not a length"); assert.equal(bodyRefusal("GET", "/api/projects/new", len(BODY_CAP + 1)), null, "a read"); assert.equal(bodyRefusal("POST", "/projects", len(BODY_CAP + 1)), null, "not under /api/"); }); // THE READS WRITE NO MANIFEST (umtool redesign E5 A4): a GET or HEAD is what a tab, a prefetch, a crawler or a // cross-site may send without asking -- the proxy lets every read through -- so no GET/HEAD handler under // app/api/ calls a writer of the project's manifest, its draft, its versions or its undo stack, nor writes a file // itself, but for the cache writers named below with why each is only a cache. const MANIFEST_WRITERS = [ // lib/report/manifest.mjs "updateClip", "updateClaim", "addLedgerRow", "updateLedgerRow", "removeLedgerRow", "updateOnscreen", "updateChrome", "updatePreset", "addDeckChrome", "updateRenderKeys", "updateRender", "updatePosts", "updateStorage", "updateArticleLink", "updateLinkPolicy", "updateClaimKnobs", "updateMarks", "updateVariants", "replaceManifest", "undoStructural", "redoStructural", "moveEntry", "removeEntry", "insertEntry", "duplicateEntry", "upsertPost", "removePost", "updateFactcheck", "updateTeaser", "autoSnapshot", "pruneAutoSnapshots", // lib/report/snapshots.mjs "createSnapshot", "writeSnapshotRaw", // lib/report/versions.mjs "writeDraft", "saveVersion", "judgeDraft", "openVersion", "freezeTakes", // lib/report/takeEdit.mjs, takes.mjs, takeManifest.mjs "undoTakeEdit", "setTakeVerdict", "writePlayManifest", ]; const FILE_WRITES = ["writeFile", "writeFileSync", "rename", "renameSync", "writeFileAtomic", "writeFileAtomicSync", "writeJsonAtomic", "ensureWindowFile"]; /** ` ` -> why it is only a cache. */ const CACHE_ONLY_GET = { "app/api/clip/[key]/audio/route.ts GET writeFile": "the clip's audio window, level-normalised, cached under the clip cache by its stamp", "app/api/clip/[key]/audio/route.ts GET rename": "the same cache file put in place", "app/api/clip/[key]/video/route.ts GET rename": "the clip's video window cut once into the clip cache", "app/api/face/frame/route.ts GET rename": "one extracted frame, cached by its source and second", "app/api/report/audio/route.ts GET ensureWindowFile": "a recording's excerpt cut into out/clips-raw (serve.mjs, a cache any read may make)", "app/api/report/clip/route.ts GET ensureWindowFile": "the same excerpt, started early for the bench's player", "app/api/report/peaks/route.ts GET ensureWindowFile": "the same excerpt, for its waveform", "app/api/report/raw/route.ts GET ensureWindowFile": "the same excerpt, served", }; test("no GET or HEAD handler under app/api/ writes a manifest (MANIFEST_WRITERS), nor a file but the named caches", () => { const sources = ["manifest.mjs", "snapshots.mjs", "versions.mjs", "takeEdit.mjs", "takes.mjs", "takeManifest.mjs"].map((f) => fs.readFileSync(path.join(UMTOOL, "lib", "report", f), "utf8"), ); for (const w of MANIFEST_WRITERS) { assert.ok(sources.some((src) => new RegExp(`export (?:async )?function ${w}\\b`).test(src)), `${w} is still a writer lib/report exports`); } const found = []; const allowedSeen = new Set(); for (const file of routes().map((r) => r.file)) { const src = fs.readFileSync(path.join(UMTOOL, file), "utf8"); for (const m of ["GET", "HEAD"]) { const body = handlerSource(src, m); if (!body) continue; for (const w of [...MANIFEST_WRITERS, ...FILE_WRITES]) { if (!new RegExp(`\\b${w}\\(`).test(body)) continue; const key = `${file} ${m} ${w}`; if (!MANIFEST_WRITERS.includes(w) && CACHE_ONLY_GET[key]) allowedSeen.add(key); else found.push(key); } } } assert.deepEqual(found, [], "a read that writes"); assert.deepEqual([...allowedSeen].sort(), Object.keys(CACHE_ONLY_GET).sort(), "every cache-only GET writer named is still one (a stale entry is removed)"); });