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

A cross-origin write is refused in words that name the cause, not 'your credentials lack the scope' #14427

Merged opened this

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

Merged

scout/forge:scout/14419-a-cross-origin-write-is-refused-in-words → main 3 commits fork

  • Merged. scout/14419-a-cross-origin-write-is-refused-in-words was merged into main as fa0d888.

Review

Sign in to review this change.
6 files changed +76 −8
src/contract/openapi.ts +2
@@ -49,6 +49,7 @@ const PAGE_REFUSAL = "page or offset was sent: this list pages by cursor, pass n
4949 */
5050 export const readsJsonBody = (r: Pick<Route, "method" | "body">): boolean => r.method !== "get" && r.method !== "delete" && r.body !== undefined;
5151
52 const CROSS_ORIGIN_REFUSAL = "403: the request came from a browser page on another origin; send it without an `Origin` header or with a token";
5253 const JSON_REFUSAL = "400 { error, message, hint }: the body is not JSON; the message names the first bad token and its byte offset";
5354
5455 /** A route's operationId, and the name of the file that holds it. */
@@ -101,6 +102,7 @@ export function openapi(origin: string, version: string, role: Role): Record<str
101102 const refusals = {
102103 ...(pagesByCursor(r) ? { invalid_query: PAGE_REFUSAL } : {}),
103104 ...(readsJsonBody(r) ? { invalid_json: JSON_REFUSAL } : {}),
105 ...(r.method !== "get" ? { cross_origin: CROSS_ORIGIN_REFUSAL } : {}),
104106 ...r.refusals,
105107 };
106108 const params = [...r.path.matchAll(/\{(\w+)\}/g)].map((m) => ({
src/http/origin_gate.ts +13 −2
@@ -19,7 +19,7 @@
1919 import type { App } from "../app.ts";
2020 import type { Auth } from "./context.ts";
2121 import { crossOrigin } from "./context.ts";
22 import { forbidden } from "./respond.ts";
22 import { crossOriginRefused, prefersJson } from "./respond.ts";
2323
2424 const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
2525
@@ -40,5 +40,16 @@ export function originGate(app: App, request: Request, url: URL, auth: Auth): Re
4040 if (auth.via === "token") return undefined;
4141 if (auth.via === "none" && Object.hasOwn(BROWSER_CLIENT_DOORS, url.pathname)) return undefined;
4242 if (!crossOrigin(request, url, app.log)) return undefined;
43 return forbidden();
43 return crossOriginRefused(url.origin);
44 }
45
46 /**
47 * Whether the gate's refusal is JSON: the API, or a caller that sent or asked for JSON. A browser
48 * form keeps its page.
49 */
50 export function refusesInJson(request: Request, url: URL): boolean {
51 if (url.pathname === "/api" || url.pathname.startsWith("/api/")) return true;
52 const type = (request.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();
53 if (type === "application/json" || type.endsWith("+json")) return true;
54 return prefersJson(request);
4455 }
src/http/respond.ts +11
@@ -180,6 +180,17 @@ export const tooManyAttempts = (retryAfter: number) =>
180180 tryAgain("too_many_attempts", 429, `too many sign-in attempts: try again in ${retryAfter} s`, retryAfter);
181181 export const FORBIDDEN_MESSAGE = "your credentials lack the scope for this action";
182182 export const forbidden = () => apiError("forbidden", 403, FORBIDDEN_MESSAGE);
183 /**
184 * The origin gate's refusal in words that name the cause. `own` is this forge's origin; the
185 * caller's `Origin` (attacker text) is never echoed.
186 */
187 export const crossOriginRefused = (own: string) =>
188 apiError(
189 "cross_origin",
190 403,
191 `a browser page on another origin may not write here: this forge accepts writes from pages of ${own} only`,
192 "Send the request without an `Origin` header, or with a token (`Authorization: Bearer <token>`); a token is not refused for its origin.",
193 );
183194 // A path matching no route at all — distinct from a missing resource, so a
184195 // client can tell a typo'd URL from a resource that genuinely isn't there.
185196 // The message survives into the HTML 404 too (`src/web/chrome.ts`), as a
src/http/server.ts +2 −2
@@ -566,7 +566,7 @@ import { adminGate } from "./admin_gate.ts";
566566 import { movedResponse } from "./moved.ts";
567567 import { archivedRepoAt } from "./archived_noindex.ts";
568568 import { slashless } from "./slash.ts";
569 import { originGate } from "./origin_gate.ts";
569 import { originGate, refusesInJson } from "./origin_gate.ts";
570570 import { proposalGate } from "./proposal_gate.ts";
571571 import { contributeGate } from "./contribute_gate.ts";
572572 import { runGate } from "./run_gate.ts";
@@ -3397,7 +3397,7 @@ async function answer(
33973397 // the API keeps its terse JSON.
33983398 const originRefusal = originGate(app, request, url, auth);
33993399 if (originRefusal !== undefined) {
3400 if (isApiPath) return originRefusal;
3400 if (isApiPath || refusesInJson(request, url)) return originRefusal;
34013401 const themeCookie = cookieValue(request, "forge_theme") ?? "";
34023402 const theme = isThemeName(themeCookie) ? themeCookie : undefined;
34033403 return forbiddenPage({ app, request, url, params: {}, auth, theme }, SENT_FROM_ELSEWHERE, CAME_FROM_ELSEWHERE);
test/forbidden-page.test.ts +3 −3
@@ -12,7 +12,7 @@ import { createApp, type App } from "../src/app.ts";
1212 import { createSession } from "../src/core/sessions.ts";
1313 import { createUser } from "../src/core/users.ts";
1414 import { buildRouter, forgeHttp } from "../src/http/server.ts";
15 import { CAME_FROM_ELSEWHERE, forbiddenPage, NOT_ADMIN_HERE, SENT_FROM_ELSEWHERE } from "../src/web/chrome.ts";
15 import { forbiddenPage, NOT_ADMIN_HERE, SENT_FROM_ELSEWHERE } from "../src/web/chrome.ts";
1616 import type { Ctx } from "../src/http/context.ts";
1717 import { quietLogs } from "./helpers/globals.ts";
1818
@@ -88,7 +88,7 @@ describe("the 403 page", () => {
8888 headers: { cookie: kim, origin: "https://evil.example", accept: "application/json" },
8989 });
9090 expect(script.status).toBe(403);
91 expect(((await script.json()) as { error: string }).error).toBe("forbidden");
91 expect(((await script.json()) as { error: string }).error).toBe("cross_origin");
9292 });
9393
9494 test("a script's cross-site post is told so without 'go back'", async () => {
@@ -98,7 +98,7 @@ describe("the 403 page", () => {
9898 body: "username=kim&password=x",
9999 });
100100 expect(res.status).toBe(403);
101 expect(await res.json()).toMatchObject({ error: "forbidden", message: CAME_FROM_ELSEWHERE });
101 expect(await res.json()).toMatchObject({ error: "cross_origin" });
102102 });
103103
104104 test("asked for JSON, it is the API's shape; the reason is escaped on the page", async () => {
test/mutations-same-origin.test.ts +45 −1
@@ -20,6 +20,7 @@ import { mkdtemp, rm } from "node:fs/promises";
2020 import { tmpdir } from "node:os";
2121 import { join } from "node:path";
2222 import { createApp, type App } from "../src/app.ts";
23 import { createToken } from "../src/core/tokens.ts";
2324 import { createRepo } from "../src/actions/repos.ts";
2425 import { BROWSER_CLIENT_DOORS } from "../src/http/origin_gate.ts";
2526 import { buildApiRouter, buildRouter, forgeHttp } from "../src/http/server.ts";
@@ -47,7 +48,7 @@ const key = (r: { method: string; pattern: string }): string => `${r.method} ${r
4748 const mutations = (): { method: string; pattern: string }[] =>
4849 [...buildRouter().routes(), ...buildApiRouter().routes()].filter((r) => MUTATING.has(r.method));
4950
50 let dataDir = "", app: App;
51 let dataDir = "", app: App, aliceId = "";
5152 const cells = process.env["FORGE_CELLS"];
5253
5354 beforeAll(async () => {
@@ -56,6 +57,7 @@ beforeAll(async () => {
5657 app = createApp({ dataDir, port: 0 });
5758 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
5859 if (!admin.ok) throw new Error(admin.error);
60 aliceId = admin.value.id;
5961 const repo = await createRepo(app, admin.value, { name: "notes", visibility: "public", description: "" });
6062 if (!repo.ok) throw new Error(String(repo.error));
6163 });
@@ -125,3 +127,45 @@ test("the gate refuses only a foreign Origin: same-origin and Origin-less (git,
125127 expect(await send(clone)).toBe(403);
126128 expect(await send(clone, null)).not.toBe(403);
127129 });
130
131 const PAGE_POST = "/desk/clear";
132 async function post(path: string, headers: Record<string, string>, body: string): Promise<Response> {
133 return forgeHttp(app).handle(new Request(`http://forge.test${path}`, { method: "POST", headers: { origin: "https://evil.example", ...headers }, body }));
134 }
135
136 test("a foreign-origin JSON write is refused as cross_origin, with a hint, never echoing the Origin", async () => {
137 for (const [path, headers] of [
138 ["/api/v1/user/email/verify", { "content-type": "application/json" }],
139 ["/api/v1/user/email/verify", {}],
140 [PAGE_POST, { "content-type": "application/json" }],
141 [PAGE_POST, { accept: "application/json" }],
142 ] as const) {
143 const res = await post(path, headers, '{"name":"abc"}');
144 expect(res.status).toBe(403);
145 const text = await res.text();
146 const data = JSON.parse(text) as { error: string; message: string; hint: string };
147 expect(data.error).toBe("cross_origin");
148 expect(data.message).toContain("another origin");
149 expect(data.hint).toContain("without an `Origin` header");
150 expect(text).not.toContain("evil.example");
151 expect(text).not.toContain("scope");
152 }
153 });
154
155 test("a browser form post keeps its page answer and status", async () => {
156 const res = await post(PAGE_POST, { "content-type": "application/x-www-form-urlencoded", accept: "text/html" }, "a=b");
157 expect(res.status).toBe(403);
158 expect(res.headers.get("content-type")).toContain("text/html");
159 expect(await res.text()).not.toContain("evil.example");
160 });
161
162 test("a token caller is exempt from the origin gate", async () => {
163 const res = await post("/api/v1/user/email/verify", { authorization: `Bearer ${createToken(app.db, aliceId, "t", "rw").token}`, "content-type": "application/json" }, "{}");
164 expect(((await res.json()) as { error: string }).error).not.toBe("cross_origin");
165 });
166
167 test("the OpenAPI document lists cross_origin among a write's refusals", async () => {
168 const { openapi } = await import("../src/contract/openapi.ts");
169 const doc = JSON.stringify(openapi("http://forge.test", "0", "admin"));
170 expect(doc).toContain("`cross_origin`");
171 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs