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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14419-a-cross-origin-write-is-refused-in-words → main 3 commits fork
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 | ||
| 49 | 49 | */ |
| 50 | 50 | export const readsJsonBody = (r: Pick<Route, "method" | "body">): boolean => r.method !== "get" && r.method !== "delete" && r.body !== undefined; |
| 51 | 51 | |
| 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"; | |
| 52 | 53 | const JSON_REFUSAL = "400 { error, message, hint }: the body is not JSON; the message names the first bad token and its byte offset"; |
| 53 | 54 | |
| 54 | 55 | /** 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 | ||
| 101 | 102 | const refusals = { |
| 102 | 103 | ...(pagesByCursor(r) ? { invalid_query: PAGE_REFUSAL } : {}), |
| 103 | 104 | ...(readsJsonBody(r) ? { invalid_json: JSON_REFUSAL } : {}), |
| 105 | ...(r.method !== "get" ? { cross_origin: CROSS_ORIGIN_REFUSAL } : {}), | |
| 104 | 106 | ...r.refusals, |
| 105 | 107 | }; |
| 106 | 108 | const params = [...r.path.matchAll(/\{(\w+)\}/g)].map((m) => ({ |
src/http/origin_gate.ts +13 −2
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | import type { App } from "../app.ts"; |
| 20 | 20 | import type { Auth } from "./context.ts"; |
| 21 | 21 | import { crossOrigin } from "./context.ts"; |
| 22 | import { forbidden } from "./respond.ts"; | |
| 22 | import { crossOriginRefused, prefersJson } from "./respond.ts"; | |
| 23 | 23 | |
| 24 | 24 | const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]); |
| 25 | 25 | |
| @@ -40,5 +40,16 @@ export function originGate(app: App, request: Request, url: URL, auth: Auth): Re | ||
| 40 | 40 | if (auth.via === "token") return undefined; |
| 41 | 41 | if (auth.via === "none" && Object.hasOwn(BROWSER_CLIENT_DOORS, url.pathname)) return undefined; |
| 42 | 42 | 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); | |
| 44 | 55 | } |
src/http/respond.ts +11
| @@ -180,6 +180,17 @@ export const tooManyAttempts = (retryAfter: number) => | ||
| 180 | 180 | tryAgain("too_many_attempts", 429, `too many sign-in attempts: try again in ${retryAfter} s`, retryAfter); |
| 181 | 181 | export const FORBIDDEN_MESSAGE = "your credentials lack the scope for this action"; |
| 182 | 182 | 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 | ); | |
| 183 | 194 | // A path matching no route at all — distinct from a missing resource, so a |
| 184 | 195 | // client can tell a typo'd URL from a resource that genuinely isn't there. |
| 185 | 196 | // 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"; | ||
| 566 | 566 | import { movedResponse } from "./moved.ts"; |
| 567 | 567 | import { archivedRepoAt } from "./archived_noindex.ts"; |
| 568 | 568 | import { slashless } from "./slash.ts"; |
| 569 | import { originGate } from "./origin_gate.ts"; | |
| 569 | import { originGate, refusesInJson } from "./origin_gate.ts"; | |
| 570 | 570 | import { proposalGate } from "./proposal_gate.ts"; |
| 571 | 571 | import { contributeGate } from "./contribute_gate.ts"; |
| 572 | 572 | import { runGate } from "./run_gate.ts"; |
| @@ -3397,7 +3397,7 @@ async function answer( | ||
| 3397 | 3397 | // the API keeps its terse JSON. |
| 3398 | 3398 | const originRefusal = originGate(app, request, url, auth); |
| 3399 | 3399 | if (originRefusal !== undefined) { |
| 3400 | if (isApiPath) return originRefusal; | |
| 3400 | if (isApiPath || refusesInJson(request, url)) return originRefusal; | |
| 3401 | 3401 | const themeCookie = cookieValue(request, "forge_theme") ?? ""; |
| 3402 | 3402 | const theme = isThemeName(themeCookie) ? themeCookie : undefined; |
| 3403 | 3403 | 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"; | ||
| 12 | 12 | import { createSession } from "../src/core/sessions.ts"; |
| 13 | 13 | import { createUser } from "../src/core/users.ts"; |
| 14 | 14 | 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"; | |
| 16 | 16 | import type { Ctx } from "../src/http/context.ts"; |
| 17 | 17 | import { quietLogs } from "./helpers/globals.ts"; |
| 18 | 18 | |
| @@ -88,7 +88,7 @@ describe("the 403 page", () => { | ||
| 88 | 88 | headers: { cookie: kim, origin: "https://evil.example", accept: "application/json" }, |
| 89 | 89 | }); |
| 90 | 90 | 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"); | |
| 92 | 92 | }); |
| 93 | 93 | |
| 94 | 94 | test("a script's cross-site post is told so without 'go back'", async () => { |
| @@ -98,7 +98,7 @@ describe("the 403 page", () => { | ||
| 98 | 98 | body: "username=kim&password=x", |
| 99 | 99 | }); |
| 100 | 100 | 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" }); | |
| 102 | 102 | }); |
| 103 | 103 | |
| 104 | 104 | 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"; | ||
| 20 | 20 | import { tmpdir } from "node:os"; |
| 21 | 21 | import { join } from "node:path"; |
| 22 | 22 | import { createApp, type App } from "../src/app.ts"; |
| 23 | import { createToken } from "../src/core/tokens.ts"; | |
| 23 | 24 | import { createRepo } from "../src/actions/repos.ts"; |
| 24 | 25 | import { BROWSER_CLIENT_DOORS } from "../src/http/origin_gate.ts"; |
| 25 | 26 | import { buildApiRouter, buildRouter, forgeHttp } from "../src/http/server.ts"; |
| @@ -47,7 +48,7 @@ const key = (r: { method: string; pattern: string }): string => `${r.method} ${r | ||
| 47 | 48 | const mutations = (): { method: string; pattern: string }[] => |
| 48 | 49 | [...buildRouter().routes(), ...buildApiRouter().routes()].filter((r) => MUTATING.has(r.method)); |
| 49 | 50 | |
| 50 | let dataDir = "", app: App; | |
| 51 | let dataDir = "", app: App, aliceId = ""; | |
| 51 | 52 | const cells = process.env["FORGE_CELLS"]; |
| 52 | 53 | |
| 53 | 54 | beforeAll(async () => { |
| @@ -56,6 +57,7 @@ beforeAll(async () => { | ||
| 56 | 57 | app = createApp({ dataDir, port: 0 }); |
| 57 | 58 | const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); |
| 58 | 59 | if (!admin.ok) throw new Error(admin.error); |
| 60 | aliceId = admin.value.id; | |
| 59 | 61 | const repo = await createRepo(app, admin.value, { name: "notes", visibility: "public", description: "" }); |
| 60 | 62 | if (!repo.ok) throw new Error(String(repo.error)); |
| 61 | 63 | }); |
| @@ -125,3 +127,45 @@ test("the gate refuses only a foreign Origin: same-origin and Origin-less (git, | ||
| 125 | 127 | expect(await send(clone)).toBe(403); |
| 126 | 128 | expect(await send(clone, null)).not.toBe(403); |
| 127 | 129 | }); |
| 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 | }); |
new above
offline