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

Every mutating route refuses a cross-origin request, proven by a test that walks the route table #13621

Merged opened this

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

Merged

scout/forge:scout/13578-every-mutating-route-refuses-a-cross-ori → main 2 commits fork

  • Merged. scout/13578-every-mutating-route-refuses-a-cross-ori was merged into main as 20676a0.

Review

Sign in to review this change.
3 files changed +157 −13
src/http/origin_gate.ts +27 −11
@@ -1,28 +1,44 @@
11 /**
2 * The one gate for browser CSRF: a POST, PUT, PATCH or DELETE made with a
3 * identity a browser attaches by itself (a session cookie, the platform edge's
4 * login, or the account password cached after the forge's Basic challenge) whose
5 * `Origin` is not this forge is refused with a 403 before any handler runs,
6 * so a route added next year is covered without remembering to check.
2 * The one gate for browser CSRF: a POST, PUT, PATCH or DELETE whose `Origin`
3 * is not this forge is refused with a 403 before any handler runs, unless a
4 * token made it, so a route added next year is covered without remembering
5 * to check. That holds for an identity a browser attaches by itself (a
6 * session cookie, the platform edge's login, or the account password cached
7 * after the forge's Basic challenge) and for no identity at all (#13578): a
8 * sign-up, a reset or a sign-in another site's page submits is refused here,
9 * not sent on to a redirect.
710 *
811 * Only token callers (Bearer, or Basic with a `forge_` secret) are exempt: no
912 * browser attaches a token on its own. A request without an `Origin` is no
10 * browser's either (git, curl), so it passes, as `crossOrigin` (`context.ts`)
11 * has always judged. The handlers' own checks stay as a second
12 * lock; this is the floor under them.
13 * browser's either (git, curl, a webhook sender), so it passes, as
14 * `crossOrigin` (`context.ts`) has always judged. The doors in
15 * BROWSER_CLIENT_DOORS are called from other origins by design. The
16 * handlers' own checks stay as a second lock; this is the floor under them.
1317 */
1418
1519 import type { App } from "../app.ts";
1620 import type { Auth } from "./context.ts";
17 import { crossOrigin, isAccountItself } from "./context.ts";
21 import { crossOrigin } from "./context.ts";
1822 import { forbidden } from "./respond.ts";
1923
2024 const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
2125
22 /** The refusal for a cross-origin mutation by a cookie identity, or undefined to carry on. */
26 /**
27 * Paths a browser-based OAuth client (an MCP client in a web page) posts to from its own origin,
28 * each with what authenticates it; `oauth.ts` answers them with `Access-Control-Allow-Origin: *`.
29 * `test/mutations-same-origin.test.ts` holds each to one sentence and a registered route.
30 */
31 export const BROWSER_CLIENT_DOORS: Readonly<Record<string, string>> = {
32 "/oauth/token": "trades a one-time code proven by its PKCE verifier, or a refresh token, never a cookie",
33 "/oauth/revoke": "ends only the token it is sent, and answers the same whether or not it was one",
34 "/oauth/register": "registers a public client that holds no identity until a person consents on the forge's own page",
35 };
36
37 /** The refusal for a cross-origin mutation not made by a token, or undefined to carry on. */
2338 export function originGate(app: App, request: Request, url: URL, auth: Auth): Response | undefined {
2439 if (!MUTATING.has(request.method)) return undefined;
25 if (!isAccountItself(auth)) return undefined;
40 if (auth.via === "token") return undefined;
41 if (auth.via === "none" && Object.hasOwn(BROWSER_CLIENT_DOORS, url.pathname)) return undefined;
2642 if (!crossOrigin(request, url, app.log)) return undefined;
2743 return forbidden();
2844 }
src/http/server.ts +3 −2
@@ -3307,10 +3307,11 @@ async function answerGet(
33073307 }
33083308
33093309 // A cookie's identity never acts for another site: one door for every route.
3310 // A browser's form gets the forge's own page saying why; a script keeps the JSON.
3310 // A browser's form gets the forge's own page saying why, a page's script the same reason as JSON;
3311 // the API keeps its terse JSON.
33113312 const originRefusal = originGate(app, request, url, auth);
33123313 if (originRefusal !== undefined) {
3313 if (isApiPath || !prefersHtml(request, url.pathname)) return originRefusal;
3314 if (isApiPath) return originRefusal;
33143315 const themeCookie = cookieValue(request, "forge_theme") ?? "";
33153316 const theme = isThemeName(themeCookie) ? themeCookie : undefined;
33163317 return forbiddenPage({ app, request, url, params: {}, auth, theme }, SENT_FROM_ELSEWHERE, CAME_FROM_ELSEWHERE);
test/mutations-same-origin.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * Every mutating route refuses a cross-origin request that carries no token
3 * (#13578). The routers' own tables (`routes()`, the same ones
4 * `src/http/route_marks.ts` marks) are walked: each POST, PUT, PATCH and
5 * DELETE is sent with `Origin: https://evil.example`, no cookie and no token,
6 * and must answer something that is neither 2xx nor 3xx, writing no event.
7 *
8 * `test/origin-every-mutation.test.ts` proves the signed-in half (a cookie
9 * with a foreign Origin is refused by the origin check); this is the
10 * anonymous half, so a route that acts for nobody — a sign-up, a reset, a
11 * receiver — cannot be driven from another site's page.
12 *
13 * A route with a reason to answer is in ALLOWED, one sentence each naming
14 * what authenticates it. The list is checked against the routers, and each
15 * entry must still answer as listed, so it cannot keep a route that is gone
16 * or hide one that now refuses.
17 */
18 import { afterAll, beforeAll, expect, test } from "bun:test";
19 import { mkdtemp, rm } from "node:fs/promises";
20 import { tmpdir } from "node:os";
21 import { join } from "node:path";
22 import { createApp, type App } from "../src/app.ts";
23 import { createRepo } from "../src/actions/repos.ts";
24 import { BROWSER_CLIENT_DOORS } from "../src/http/origin_gate.ts";
25 import { buildApiRouter, buildRouter, forgeHttp } from "../src/http/server.ts";
26 import { seedAdmin } from "./helpers/admin.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 /**
32 * Mutations that may answer an anonymous foreign-origin request, each with its authentication: the
33 * gate's own list, so the test and the code cannot drift apart.
34 */
35 const ALLOWED: Record<string, string> = Object.fromEntries(
36 Object.entries(BROWSER_CLIENT_DOORS).map(([path, why]) => [`POST ${path}`, why]),
37 );
38
39 const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
40 const FILL: Record<string, string> = {
41 owner: "alice", username: "alice", name: "notes", number: "1", org: "alice", slug: "main",
42 id: "1", team: "core", scope: "alice", job: "1", oid: "0", env: "prod",
43 };
44 const fill = (pattern: string): string =>
45 pattern.replace(/:([a-z_]+)/g, (_, k: string) => FILL[k] ?? "x").replace(/\*[a-z_]+/, "x");
46 const key = (r: { method: string; pattern: string }): string => `${r.method} ${r.pattern}`;
47 const mutations = (): { method: string; pattern: string }[] =>
48 [...buildRouter().routes(), ...buildApiRouter().routes()].filter((r) => MUTATING.has(r.method));
49
50 let dataDir = "", app: App;
51 const cells = process.env["FORGE_CELLS"];
52
53 beforeAll(async () => {
54 process.env["FORGE_CELLS"] = "off";
55 dataDir = await mkdtemp(join(tmpdir(), "forge-anon-xo-"));
56 app = createApp({ dataDir, port: 0 });
57 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
58 if (!admin.ok) throw new Error(admin.error);
59 const repo = await createRepo(app, admin.value, { name: "notes", visibility: "public", description: "" });
60 if (!repo.ok) throw new Error(String(repo.error));
61 });
62
63 afterAll(async () => {
64 app.close();
65 await rm(dataDir, { recursive: true, force: true });
66 if (cells === undefined) delete process.env["FORGE_CELLS"];
67 else process.env["FORGE_CELLS"] = cells;
68 });
69
70 const events = (): number => (app.db.query("select count(*) as n from event").get() as { n: number }).n;
71
72 async function send(r: { method: string; pattern: string }, origin: string | null = "https://evil.example"): Promise<number> {
73 const headers: Record<string, string> = { "content-type": "application/json" };
74 if (origin !== null) headers["origin"] = origin;
75 const res = await forgeHttp(app).handle(
76 new Request(`http://forge.test${fill(r.pattern)}`, {
77 method: r.method,
78 headers,
79 body: "{}",
80 }),
81 );
82 await res.body?.cancel();
83 return res.status;
84 }
85
86 const refused = (status: number): boolean => status >= 400;
87
88 test("every mutating route refuses an anonymous request from a foreign Origin, writing nothing", async () => {
89 const routes = mutations();
90 expect(routes.length).toBeGreaterThan(100);
91 const wrong: string[] = [];
92 for (const r of routes) {
93 if (key(r) in ALLOWED) continue;
94 const before = events();
95 const status = await send(r);
96 if (!refused(status) || events() !== before) wrong.push(`${key(r)} → ${status}, ${events() - before} events`);
97 }
98 expect(wrong).toEqual([]);
99 });
100
101 test("every allowed route is a registered mutation with one sentence naming its authentication", () => {
102 const registered = new Set(mutations().map(key));
103 for (const [route, why] of Object.entries(ALLOWED)) {
104 expect(registered.has(route)).toBe(true);
105 expect(why.length).toBeGreaterThan(20);
106 expect(why.split(/[.;] /).length).toBe(1);
107 }
108 });
109
110 test("the allow list stays short: OAuth doors only, never a prefix", () => {
111 expect(Object.keys(ALLOWED).length).toBeLessThanOrEqual(3);
112 for (const route of Object.keys(ALLOWED)) expect(route).toMatch(/^POST \/oauth\/[a-z]+$/);
113 });
114
115 test("an allowed door still answers a browser client on another origin", async () => {
116 // The gate lets it through; the handler judges the (empty) grant itself.
117 expect(await send({ method: "POST", pattern: "/oauth/revoke" })).toBe(200);
118 });
119
120 test("the gate refuses only a foreign Origin: same-origin and Origin-less (git, a webhook) carry on", async () => {
121 const signUp = { method: "POST", pattern: "/api/v1/user/email/verify" };
122 expect(await send(signUp)).toBe(403);
123 expect(await send(signUp, "http://forge.test")).not.toBe(403);
124 const clone = { method: "POST", pattern: "/:owner/:name.git/git-upload-pack" };
125 expect(await send(clone)).toBe(403);
126 expect(await send(clone, null)).not.toBe(403);
127 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs