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

Every route that changes state refuses a cross-origin request, proven by one table-driven test over the route table #13500

Merged opened this

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

Merged

scout/forge:scout/13480-every-route-that-changes-state-refuses-a → main 2 commits fork

  • Merged. scout/13480-every-route-that-changes-state-refuses-a was merged into main as 7d318b3.

Review

Sign in to review this change.
3 files changed +48 −14
src/http/context.ts +15 −7
@@ -21,7 +21,10 @@ export interface Auth {
2121 readonly via: "session" | "edge" | "token" | "password" | "none";
2222 /** Which signed-in browser asked, when `via` is `session`. */
2323 readonly sessionId?: string;
24 /** A notice from an admin waits for this person; `page()` says it and marks it said (`core/access_link.ts`). */
24 /**
25 * A notice from an admin waits for this person; `page()` says it and marks it said
26 * (`core/access_link.ts`).
27 */
2528 readonly noticeWaiting?: true;
2629 /** Set for a token: the name its owner gave it, never its secret. */
2730 readonly tokenName?: string;
@@ -102,7 +105,9 @@ export function publicUrl(request: Request, base: string | undefined): URL {
102105 /**
103106 * Browser CSRF: a session-cookie mutation must originate from this forge.
104107 * Browsers always send Origin on cross-site requests; a missing Origin
105 * means a non-browser client, which cookies alone cannot impersonate.
108 * means a non-browser client, which cookies alone cannot impersonate —
109 * unless the browser's own `Sec-Fetch-Site` (which a page cannot set) says
110 * the request came from another site, which is refused too (#13480).
106111 *
107112 * A mismatch is logged — one line, the two origins, nothing else — because
108113 * the usual cause is `FORGE_URL` naming somewhere other than where the
@@ -111,17 +116,20 @@ export function publicUrl(request: Request, base: string | undefined): URL {
111116 */
112117 export function crossOrigin(request: Request, url: URL, log?: Log): boolean {
113118 const origin = request.headers.get("origin");
114 // `Origin: null` with the browser's own `Sec-Fetch-Site: same-origin` is one of our pages under a strict
115 // referrer policy; a page cannot set that header, so it stays a cross-site refusal everywhere else.
119 // `Origin: null` with the browser's own `Sec-Fetch-Site: same-origin` is one of our pages under a
120 // strict referrer policy; a page cannot set that header, so it stays a cross-site refusal
121 // everywhere else.
116122 const sameSite = origin === "null" && request.headers.get("sec-fetch-site") === "same-origin";
117 const mismatch = origin !== null && origin !== url.origin && !sameSite;
123 const site = request.headers.get("sec-fetch-site");
124 const foreignBrowser = origin === null && (site === "cross-site" || site === "same-site");
125 const mismatch = foreignBrowser || (origin !== null && origin !== url.origin && !sameSite);
118126 if (mismatch)
119127 log?.warn("refused cross-origin mutation", {
120 origin,
128 origin: origin ?? "-",
121129 expected: url.origin,
122130 method: request.method,
123131 path: url.pathname,
124 site: request.headers.get("sec-fetch-site") ?? "-",
132 site: site ?? "-",
125133 });
126134 return mismatch;
127135 }
test/origin-every-mutation.test.ts +23 −5
@@ -55,7 +55,10 @@ const mutations = (): { method: string; pattern: string }[] =>
5555 [...buildRouter().routes(), ...buildApiRouter().routes()].filter((r) => MUTATING.has(r.method));
5656
5757 let dataDir = "", app: App, cookie = "";
58 /** How many times an origin check has refused a request, read from the log line `crossOrigin` writes. */
58 /**
59 * How many times an origin check has refused a request, read from the log line `crossOrigin`
60 * writes.
61 */
5962 let originRefusals = 0;
6063 const cells = process.env["FORGE_CELLS"];
6164
@@ -94,8 +97,12 @@ afterAll(async () => {
9497
9598 const events = (): number => (app.db.query("select count(*) as n from event").get() as { n: number }).n;
9699
97 async function send(r: { method: string; pattern: string }, origin: string | undefined): Promise<number> {
98 const headers: Record<string, string> = { cookie, "content-type": "application/json" };
100 async function send(
101 r: { method: string; pattern: string },
102 origin: string | undefined,
103 extra: Record<string, string> = {},
104 ): Promise<number> {
105 const headers: Record<string, string> = { cookie, "content-type": "application/json", ...extra };
99106 if (origin !== undefined) headers["origin"] = origin;
100107 const res = await forgeHttp(app).handle(
101108 new Request(`http://forge.test${fill(r.pattern)}`, { method: r.method, headers, body: "{}" }),
@@ -104,7 +111,18 @@ async function send(r: { method: string; pattern: string }, origin: string | und
104111 return res.status;
105112 }
106113
107 test("every mutating route refuses a signed-in request from a foreign Origin, writing nothing", async () => {
114 /**
115 * The two shapes a forged browser request takes: a foreign Origin, and no
116 * Origin at all with the browser's own `Sec-Fetch-Site: cross-site` (a header
117 * a page cannot set or drop). A route added to either router is walked here
118 * the moment it is registered, so a new unlisted mutation without a check fails.
119 */
120 const FORGED: [string, string | undefined, Record<string, string>][] = [
121 ["a foreign Origin", "https://evil.example", {}],
122 ["no Origin, from another site's page", undefined, { "sec-fetch-site": "cross-site" }],
123 ];
124
125 test.each(FORGED)("every mutating route refuses a signed-in request with %s, writing nothing", async (_, origin, extra) => {
108126 const routes = mutations();
109127 expect(routes.length).toBeGreaterThan(100);
110128 const wrong: string[] = [];
@@ -112,7 +130,7 @@ test("every mutating route refuses a signed-in request from a foreign Origin, wr
112130 if (key(r) in EXEMPT || key(r) in UNCALLABLE) continue;
113131 const before = events();
114132 const refusedBefore = originRefusals;
115 const status = await send(r, "https://evil.example");
133 const status = await send(r, origin, extra);
116134 const checked = originRefusals > refusedBefore;
117135 if (status !== 403 || events() !== before || !checked)
118136 wrong.push(`${key(r)} → ${status}, ${events() - before} events${checked ? "" : ", no origin check"}`);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs