diff --git a/packages/studio-server/src/createStudioApi.originGuard.test.ts b/packages/studio-server/src/createStudioApi.originGuard.test.ts new file mode 100644 index 0000000000..895b6f3d1e --- /dev/null +++ b/packages/studio-server/src/createStudioApi.originGuard.test.ts @@ -0,0 +1,113 @@ +// @vitest-environment node +// Node environment on purpose: the package default (happy-dom) implements +// the browser fetch spec, which drops forbidden request headers such as +// Origin and Sec-Fetch-Site when a Request is constructed. A test that +// simulates cross-origin browser traffic has to set exactly those headers, +// so it needs Node's fetch classes, which keep them. +import { afterEach, describe, expect, it } from "vitest"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createStudioApi } from "./createStudioApi"; +import { stubAdapter } from "./routes/stubAdapter.test-helpers"; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +function createApp(): { app: ReturnType; projectDir: string } { + const projectDir = mkdtempSync(join(tmpdir(), "hf-origin-guard-")); + tempDirs.push(projectDir); + return { app: createStudioApi(stubAdapter(projectDir)), projectDir }; +} + +const EVIL_ORIGIN = "http://evil.example:9999"; + +function createFile( + app: ReturnType, + headers: Record, + name = "planted.html", +): Promise { + // A real browser request always carries a Host header; app.request does + // not derive one in this environment, so send it explicitly. That keeps + // every case exercising the Origin comparison itself. + return app.request(`http://localhost/projects/demo/files/${name}`, { + method: "POST", + headers: { Host: "localhost", ...headers }, + body: "planted", + }); +} + +describe("createStudioApi cross-origin write guard", () => { + it("rejects a cross-origin POST file create and writes nothing", async () => { + const { app, projectDir } = createApp(); + const res = await createFile(app, { Origin: EVIL_ORIGIN, "Content-Type": "text/plain" }); + expect(res.status).toBe(403); + expect(existsSync(join(projectDir, "planted.html"))).toBe(false); + }); + + it("rejects a cross-origin multipart upload", async () => { + const { app, projectDir } = createApp(); + const form = new FormData(); + form.append("files", new File(["planted"], "planted.html", { type: "text/html" })); + const res = await app.request("http://localhost/projects/demo/upload", { + method: "POST", + headers: { Host: "localhost", Origin: EVIL_ORIGIN }, + body: form, + }); + expect(res.status).toBe(403); + expect(existsSync(join(projectDir, "planted.html"))).toBe(false); + }); + + it("rejects a write whose Origin is the opaque literal null", async () => { + const { app } = createApp(); + const res = await createFile(app, { Origin: "null", "Content-Type": "text/plain" }); + expect(res.status).toBe(403); + }); + + it("rejects a write marked cross-site by Fetch Metadata even without Origin", async () => { + const { app } = createApp(); + const res = await createFile(app, { "Sec-Fetch-Site": "cross-site" }); + expect(res.status).toBe(403); + }); + + it("rejects a cross-origin PUT overwrite", async () => { + const { app } = createApp(); + const res = await app.request("http://localhost/projects/demo/files/planted.html", { + method: "PUT", + headers: { Host: "localhost", Origin: EVIL_ORIGIN, "If-None-Match": "*" }, + body: "overwritten", + }); + expect(res.status).toBe(403); + }); + + it("allows a same-origin write (Origin host matches Host)", async () => { + const { app, projectDir } = createApp(); + const res = await createFile(app, { + Origin: "http://localhost", + "Content-Type": "text/plain", + }); + expect(res.status).toBe(201); + expect(existsSync(join(projectDir, "planted.html"))).toBe(true); + }); + + it("allows a write with no Origin header (non-browser callers)", async () => { + const { app, projectDir } = createApp(); + const res = await createFile(app, { "Content-Type": "text/plain" }); + expect(res.status).toBe(201); + expect(existsSync(join(projectDir, "planted.html"))).toBe(true); + }); + + it("does not block reads from any origin", async () => { + const { app } = createApp(); + await createFile(app, { "Content-Type": "text/plain" }); + const res = await app.request("http://localhost/projects/demo/files/planted.html", { + headers: { Origin: EVIL_ORIGIN }, + }); + expect(res.status).toBe(200); + }); +}); diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index 3ca2db4d9a..24b83b4b34 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -20,6 +20,24 @@ import { registerHistoryRoutes } from "./routes/history.js"; import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js"; import { folderGone, isProjectRootMissing } from "./helpers/safePath.js"; +/** + * Whether a state-changing request's Origin names the host the request was + * sent to. No Origin header means a non-browser caller (curl, tests, + * in-process), which is allowed. An unparseable Origin (including the + * literal "null" a sandboxed page sends) names no host this server serves, + * so it never matches. + */ +function writeOriginAllowed(origin: string | undefined, host: string | undefined): boolean { + if (origin === undefined) return true; + let originHost: string | null = null; + try { + originHost = new URL(origin).host; + } catch { + originHost = null; + } + return !!originHost && !!host && originHost.toLowerCase() === host.toLowerCase(); +} + /** * Create a Hono sub-app with all studio API routes. * @@ -28,6 +46,30 @@ import { folderGone, isProjectRootMissing } from "./helpers/safePath.js"; */ export function createStudioApi(adapter: StudioApiAdapter): Hono { const api = new Hono(); + // The studio API is unauthenticated and its only legitimate caller is the + // Studio page this same server serves. A state-changing request that + // carries an Origin naming a different host than the request's Host did + // not come from that page: it is a cross-origin request from some other + // website open in the user's browser. CORS does not stop such requests + // from being SENT: POST with a text/plain or form body is "simple" and + // needs no preflight. It only stops the page reading the response, which + // a fire-and-forget file write or render trigger does not need. Reject + // those writes outright. Requests with no Origin header (curl, tests, + // in-process callers) are not browser traffic and keep working, as do + // reads: the guard covers state changes only. + api.use(async function rejectCrossOriginWrites(c, next) { + if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") { + return next(); + } + // Fetch Metadata: a cross-site request is refused even when the Origin + // header was stripped (some same-site-but-cross-origin setups send + // Sec-Fetch-Site: same-site, which stays allowed). + const crossSite = c.req.header("sec-fetch-site") === "cross-site"; + if (crossSite || !writeOriginAllowed(c.req.header("origin"), c.req.header("host"))) { + return c.json({ error: "forbidden" }, 403); + } + return next(); + }); api.use(async function answerProjectDirMissingAfterErrorHandlers(c, next) { const hostHeaders = new Headers(c.res.headers); await next();