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

Every route that changes state refuses a request from another origin, proven by a test that walks the route table #14494

Merged opened this

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

Merged

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

  • Merged. scout/14478-every-route-that-changes-state-refuses-a was merged into main as b1fe982.

Review

Sign in to review this change.
4 files changed +61 −33
src/http/origin_exempt.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * Every mutation that may be called from another origin, each named exactly
3 * (never by pattern) with what authenticates it instead (#14478). This is the
4 * one exemption list: the gate in `origin_gate.ts` reads its browserClientDoors,
5 * and `test/origin-every-mutation.test.ts` and
6 * `test/mutations-same-origin.test.ts` read both lists, checking each entry is
7 * a registered route that still answers as its reason says. Add a line only
8 * with a reason a reviewer can check.
9 */
10
11 /**
12 * Mutations with no origin check because they read only `Authorization:
13 * Bearer`, never a cookie: a browser cannot be made to call them as someone,
14 * so a cookie alone gets a 401 (or 405).
15 */
16 const BEARER_ONLY_ROUTES: Readonly<Record<string, string>> = {
17 "POST /mcp": "the MCP endpoint reads a bearer token only; a cookie is never an identity there",
18 "DELETE /mcp": "ends an MCP session named by a bearer's session header; a cookie is never an identity there",
19 "POST /oauth/userinfo": "OAuth userinfo answers the bearer access token it is sent, never a cookie",
20 };
21
22 /**
23 * Paths a browser-based OAuth client (an MCP client in a web page) posts to from its own origin,
24 * each with what authenticates it; `oauth.ts` answers them with `Access-Control-Allow-Origin: *`.
25 * The gate lets an anonymous request through to these and no others.
26 */
27 const BROWSER_CLIENT_DOORS: Readonly<Record<string, string>> = {
28 "/oauth/token": "trades a one-time code proven by its PKCE verifier, or a refresh token, never a cookie",
29 "/oauth/revoke": "ends only the token it is sent, and answers the same whether or not it was one",
30 "/oauth/register": "registers a public client that holds no identity until a person consents on the forge's own page",
31 };
32
33 /** Both lists, as the one thing the gate and the tests import. */
34 export const CROSS_ORIGIN_EXEMPT = {
35 bearerOnly: BEARER_ONLY_ROUTES,
36 browserClientDoors: BROWSER_CLIENT_DOORS,
37 } as const;
src/http/origin_gate.ts +4 −14
@@ -12,33 +12,23 @@
1212 * browser attaches a token on its own. A request without an `Origin` is no
1313 * browser's either (git, curl, a webhook sender), so it passes, as
1414 * `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.
15 * `CROSS_ORIGIN_EXEMPT.browserClientDoors` (`origin_exempt.ts`) are called from other origins by
16 * design. The handlers' own checks stay as a second lock; this is the floor under them.
1717 */
1818
1919 import type { App } from "../app.ts";
2020 import type { Auth } from "./context.ts";
2121 import { crossOrigin } from "./context.ts";
22 import { CROSS_ORIGIN_EXEMPT } from "./origin_exempt.ts";
2223 import { crossOriginRefused, prefersJson } from "./respond.ts";
2324
2425 const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
2526
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
3727 /** The refusal for a cross-origin mutation not made by a token, or undefined to carry on. */
3828 export function originGate(app: App, request: Request, url: URL, auth: Auth): Response | undefined {
3929 if (!MUTATING.has(request.method)) return undefined;
4030 if (auth.via === "token") return undefined;
41 if (auth.via === "none" && Object.hasOwn(BROWSER_CLIENT_DOORS, url.pathname)) return undefined;
31 if (auth.via === "none" && Object.hasOwn(CROSS_ORIGIN_EXEMPT.browserClientDoors, url.pathname)) return undefined;
4232 if (!crossOrigin(request, url, app.log)) return undefined;
4333 return crossOriginRefused(url.origin);
4434 }
test/mutations-same-origin.test.ts +10 −5
@@ -3,7 +3,7 @@
33 * (#13578). The routers' own tables (`routes()`, the same ones
44 * `src/http/route_marks.ts` marks) are walked: each POST, PUT, PATCH and
55 * 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.
6 * and must answer 403 or 401, writing no event.
77 *
88 * `test/origin-every-mutation.test.ts` proves the signed-in half (a cookie
99 * with a foreign Origin is refused by the origin check); this is the
@@ -22,7 +22,7 @@ import { join } from "node:path";
2222 import { createApp, type App } from "../src/app.ts";
2323 import { createToken } from "../src/core/tokens.ts";
2424 import { createRepo } from "../src/actions/repos.ts";
25 import { BROWSER_CLIENT_DOORS } from "../src/http/origin_gate.ts";
25 import { CROSS_ORIGIN_EXEMPT } from "../src/http/origin_exempt.ts";
2626 import { buildApiRouter, buildRouter, forgeHttp } from "../src/http/server.ts";
2727 import { seedAdmin } from "./helpers/admin.ts";
2828 import { quietLogs } from "./helpers/globals.ts";
@@ -34,7 +34,7 @@ quietLogs();
3434 * gate's own list, so the test and the code cannot drift apart.
3535 */
3636 const ALLOWED: Record<string, string> = Object.fromEntries(
37 Object.entries(BROWSER_CLIENT_DOORS).map(([path, why]) => [`POST ${path}`, why]),
37 Object.entries(CROSS_ORIGIN_EXEMPT.browserClientDoors).map(([path, why]) => [`POST ${path}`, why]),
3838 );
3939
4040 const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
@@ -71,10 +71,12 @@ afterAll(async () => {
7171
7272 const events = (): number => (app.db.query("select count(*) as n from event").get() as { n: number }).n;
7373
74 /** One server for the file: built per request, the walk spent most of its time building routers. */
75 let http: ReturnType<typeof forgeHttp> | undefined;
7476 async function send(r: { method: string; pattern: string }, origin: string | null = "https://evil.example"): Promise<number> {
7577 const headers: Record<string, string> = { "content-type": "application/json" };
7678 if (origin !== null) headers["origin"] = origin;
77 const res = await forgeHttp(app).handle(
79 const res = await (http ??= forgeHttp(app)).handle(
7880 new Request(`http://forge.test${fill(r.pattern)}`, {
7981 method: r.method,
8082 headers,
@@ -85,7 +87,10 @@ async function send(r: { method: string; pattern: string }, origin: string | nul
8587 return res.status;
8688 }
8789
88 const refused = (status: number): boolean => status >= 400;
90 /**
91 * 403 from the gate or 401 from a handler; never a 429, which would hide a route the gate missed.
92 */
93 const refused = (status: number): boolean => status === 403 || status === 401;
8994
9095 test("every mutating route refuses an anonymous request from a foreign Origin, writing nothing", async () => {
9196 const routes = mutations();
test/origin-every-mutation.test.ts +10 −14
@@ -7,8 +7,8 @@
77 * src/http/origin_gate.ts and the handlers' second locks share) — a 403 for
88 * any other reason would hide a route with no check at all.
99 *
10 * A route with no origin check is named in EXEMPT, one line each with its
11 * reason, and proven to refuse a cookie-only request. Routes the test cannot
10 * A route with no origin check is named in `src/http/origin_exempt.ts`, one
11 * line each with its reason, and proven to refuse a cookie-only request. Routes the test cannot
1212 * reach are named in UNCALLABLE with why. Both lists are checked against the
1313 * routers, so neither can name a route that is gone or grow without a reason.
1414 */
@@ -21,23 +21,15 @@ import { openPull } from "../src/actions/pulls.ts";
2121 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
2222 import { createToken } from "../src/core/tokens.ts";
2323 import { createSession } from "../src/core/sessions.ts";
24 import { CROSS_ORIGIN_EXEMPT } from "../src/http/origin_exempt.ts";
2425 import { buildApiRouter, buildRouter, forgeHttp } from "../src/http/server.ts";
2526 import { seedAdmin } from "./helpers/admin.ts";
2627 import { quietLogs } from "./helpers/globals.ts";
2728
2829 quietLogs();
2930
30 /**
31 * Mutations with no origin check, each with why. Every one reads only
32 * `Authorization: Bearer`, never a cookie, so a browser cannot be made to call
33 * it as someone: a cookie alone must get a 401 (or 405), which a test proves.
34 * Add a line here only with a reason a reviewer can check.
35 */
36 const EXEMPT: Record<string, string> = {
37 "POST /mcp": "the MCP endpoint reads a bearer token only; a cookie is never an identity there",
38 "DELETE /mcp": "ends an MCP session named by a bearer's session header; a cookie is never an identity there",
39 "POST /oauth/userinfo": "OAuth userinfo answers the bearer access token it is sent, never a cookie",
40 };
31 /** Mutations with no origin check, each with why: the one exemption file. */
32 const EXEMPT = CROSS_ORIGIN_EXEMPT.bearerOnly;
4133
4234 /** Routes the test cannot call, with why. Each must be a registered mutation. */
4335 const UNCALLABLE: Record<string, string> = {};
@@ -97,6 +89,10 @@ afterAll(async () => {
9789
9890 const events = (): number => (app.db.query("select count(*) as n from event").get() as { n: number }).n;
9991
92 /**
93 * One server for the file, not one per request: building the routers was most of the walk's time.
94 */
95 let http: ReturnType<typeof forgeHttp> | undefined;
10096 async function send(
10197 r: { method: string; pattern: string },
10298 origin: string | undefined,
@@ -104,7 +100,7 @@ async function send(
104100 ): Promise<number> {
105101 const headers: Record<string, string> = { cookie, "content-type": "application/json", ...extra };
106102 if (origin !== undefined) headers["origin"] = origin;
107 const res = await forgeHttp(app).handle(
103 const res = await (http ??= forgeHttp(app)).handle(
108104 new Request(`http://forge.test${fill(r.pattern)}`, { method: r.method, headers, body: "{}" }),
109105 );
110106 await res.body?.cancel();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs