From 7b7db026383a793478929eeabd69d5bf409ae82a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:05:09 +0200 Subject: [PATCH 1/3] test: Refuse cross-site changing requests from a proxy sign-in (#715) --- e2e/proxy-auth.test.ts | 24 +++++++ src/http/app.test.ts | 143 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 167 insertions(+) diff --git a/e2e/proxy-auth.test.ts b/e2e/proxy-auth.test.ts index cf31fa18d..207638e5b 100644 --- a/e2e/proxy-auth.test.ts +++ b/e2e/proxy-auth.test.ts @@ -183,4 +183,28 @@ describe("sign-in proxy JWT against a real gateway", () => { expect(issuer.code, issuer.stderr).toBe(0); expect(issuer.stdout.trim()).toBe(JSON.stringify(ISSUER)); }); + + it("a good JWT on POST /v1/workers/no-such-worker/drain is 403 with cross-site and reaches the dispatcher with same-origin", async () => { + const key = await createTestKey("ES256", "k1"); + const gateway = await gatewayTrusting(await startKeyServer(key)); + const drain = async (site: string) => + fetch(`${gateway.baseUrl}/v1/workers/no-such-worker/drain`, { + headers: { [HEADER]: await key.sign(claims()), "sec-fetch-site": site }, + method: "POST", + }); + + const same = await drain("same-origin"); + expect(same.status).toBe(404); + expect(await same.json()).toMatchObject({ error: { code: "UNKNOWN_WORKER" } }); + + const cross = await drain("cross-site"); + expect(cross.status).toBe(403); + expect(await cross.json()).toEqual({ + error: { + code: "FORBIDDEN", + message: + "Cross-site request refused: a request signed in through a sign-in proxy must come from the console", + }, + }); + }); }); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index b560bd5c9..484d33aa3 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -55,6 +55,7 @@ function buildHarness( readonly answerDownloadsEarly?: boolean; readonly identities?: Readonly>; readonly auth?: Auth; + readonly mounts?: HttpGatewayDeps["mounts"]; } = {}, ) { const clock = new FakeClock(1_000); @@ -101,6 +102,7 @@ function buildHarness( ownerRoutedFacts, registry: overrides.registry ?? registry, auth, + ...(overrides.mounts === undefined ? {} : { mounts: overrides.mounts }), ...(overrides.answerDownloadsEarly === undefined ? {} : { answerDownloadsEarly: overrides.answerDownloadsEarly }), @@ -2630,4 +2632,145 @@ describe("a person the sign-in proxy signed in", () => { expect(frames.map((frame) => frame.event)).toEqual(["progress", "result"]); }); }); + + describe("changing requests", () => { + const CSRF_BODY = { + error: { + code: "FORBIDDEN", + message: + "Cross-site request refused: a request signed in through a sign-in proxy must come from the console", + }, + }; + const changing: ReadonlyArray = [ + ["POST", "/v1/workers/w/drain", "worker.drain", 200], + ["DELETE", "/v1/leases/lse_1", "lease.release", 202], + ]; + const refused: ReadonlyArray = [ + "cross-site", + "same-site", + "none", + "Same-Origin", + "same-origin, cross-site", + undefined, + ]; + + function changingHarness() { + const harness = harnessFor(proxyPerson(signedInAt + 120_000)); + harness.registry.devices = [makeDevice({ id: "dev_1" })]; + harness.registry.leases = [ + makeLease({ deviceId: "dev_1", id: "lse_1", ownerId: "tok_other" }), + ]; + harness.dispatcher.handlers["worker.drain"] = () => ({ workerId: "w" }); + harness.dispatcher.handlers["lease.release"] = () => ({ leaseId: "lse_1" }); + return harness; + } + + function withSite(site: string | undefined): Record { + return site === undefined ? proxyHeaders : { ...proxyHeaders, "sec-fetch-site": site }; + } + + describe.each(changing)("%s %s", (method, path, operation, accepted) => { + it("is dispatched with Sec-Fetch-Site same-origin", async () => { + const { app, dispatcher } = changingHarness(); + + const response = await app.request(path, { headers: withSite("same-origin"), method }); + + expect(response.status).toBe(accepted); + expect(dispatcher.calls.map((call) => call.operation)).toContain(operation); + }); + + it.each(refused)("is 403 and dispatches nothing with Sec-Fetch-Site %s", async (site) => { + const { app, dispatcher } = changingHarness(); + + const response = await app.request(path, { headers: withSite(site), method }); + + expect(response.status).toBe(403); + expect(await response.json()).toEqual(CSRF_BODY); + expect(dispatcher.calls).toEqual([]); + }); + }); + + describe("to a mount", () => { + function mountedHarness() { + const seen: string[] = []; + const harness = buildHarness({ + identities: { slk_proxy: proxyPerson(signedInAt + 120_000) }, + mounts: [ + { + prefix: "stream", + handle: (request: Request) => { + seen.push(request.method); + return new Response("ok"); + }, + }, + ] as never, + }); + return { ...harness, seen }; + } + + it.each(["PUT", "PATCH"])( + "refuses %s with cross-site and does not call it", + async (method) => { + const { app, seen } = mountedHarness(); + + const response = await app.request("/v1/stream/x", { + headers: withSite("cross-site"), + method, + }); + + expect(response.status).toBe(403); + expect(await response.json()).toEqual(CSRF_BODY); + expect(seen).toEqual([]); + }, + ); + + it.each(["PUT", "PATCH"])("calls it for %s with same-origin", async (method) => { + const { app, seen } = mountedHarness(); + + const response = await app.request("/v1/stream/x", { + headers: withSite("same-origin"), + method, + }); + + expect(response.status).toBe(200); + expect(seen).toEqual([method]); + }); + + it.each(["GET", "HEAD", "OPTIONS"])("calls it for %s with cross-site", async (method) => { + const { app, seen } = mountedHarness(); + + const response = await app.request("/v1/stream/x", { + headers: withSite("cross-site"), + method, + }); + + expect(response.status).toBe(200); + expect(seen).toEqual([method]); + }); + }); + + it("dispatches GET /v1/leases with cross-site", async () => { + const { app, dispatcher } = changingHarness(); + + const response = await app.request("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/v1/leases", { headers: withSite("cross-site") }); + + expect(response.status).toBe(200); + expect(dispatcher.calls.map((call) => call.operation)).toContain("lease.list"); + }); + + it("dispatches DELETE /v1/leases/x from a token identity with cross-site", async () => { + const { app, dispatcher, registry } = buildHarness(); + registry.devices = [makeDevice({ id: "dev_1" })]; + registry.leases = [makeLease({ deviceId: "dev_1", id: "lse_1", ownerId: "tok_agent" })]; + dispatcher.handlers["lease.release"] = () => ({ leaseId: "lse_1" }); + + const response = await app.request("/v1/leases/lse_1", { + headers: { ...agentAuth, "sec-fetch-site": "cross-site" }, + method: "DELETE", + }); + + expect(response.status).toBe(202); + expect(dispatcher.calls.map((call) => call.operation)).toContain("lease.release"); + }); + }); }); From 11f7894113f887018514cbd88cf178514f3fdd52 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:06:54 +0200 Subject: [PATCH 2/3] feat: Refuse cross-site changing requests from a proxy sign-in (#715) 3 failing -> 0 failing. Existing #714 POST tests now send same-origin. --- docs/HTTP-API.md | 8 ++++++++ src/http/app.test.ts | 17 ++++++++++++++--- src/http/auth.ts | 13 +++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index dcf3c1cf7..3af630f3d 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -88,6 +88,14 @@ A JWT Simlock cannot trust is `401 UNAUTHENTICATED` with a `reason` beside `code A follow stream (`GET /v1/events/stream`, `GET /v1/leases/{id}/events`, `GET /v1/lease-requests/{id}/events`) opened by a person ends when their JWT expires (`exp` plus 60 s), or after 2^31-1 ms if that is sooner; the client reconnects with a fresh JWT. Command streams (exec, component install) are not ended. +A request signed in by the proxy (not by a token) that is not `GET`, `HEAD` or `OPTIONS` must carry `Sec-Fetch-Site: same-origin`, which the browser sets itself; any other value, or none, is refused before anything runs: + +```json +{"error":{"code":"FORBIDDEN","message":"Cross-site request refused: a request signed in through a sign-in proxy must come from the console"}} +``` + +Requests signed in by a token are not affected. Browsers send `Sec-Fetch-Site` only to an `https://` address or to loopback, so serve the proxy over HTTPS (or on loopback): behind plain `http://` on a network name every changing request signed in through the proxy is `403`. + The proxy must let `/v1/uplink` and `/v1/healthz` through: a worker joins with its join token and a health probe sends no credential, and neither carries a proxy JWT. Three roles: diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 484d33aa3..96686e9da 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -2536,7 +2536,10 @@ describe("a person the sign-in proxy signed in", () => { [ "GET /v1/lease-requests/{id}/events", async ({ app, dispatcher }) => { - const { id } = await createLeaseRequest(app, dispatcher, defaultBody, proxyHeaders); + const { id } = await createLeaseRequest(app, dispatcher, defaultBody, { + ...proxyHeaders, + "sec-fetch-site": "same-origin", + }); return app.request(`/v1/lease-requests/${id}/events`, { headers: proxyHeaders }); }, ], @@ -2594,7 +2597,11 @@ describe("a person the sign-in proxy signed in", () => { const harness = harnessFor(proxyPerson(signedInAt + 2 * 60_000)); const responsePromise = harness.app.request("/v1/leases/lse_1/exec", { body: JSON.stringify({ args: ["list"], tool: "simctl" }), - headers: { ...proxyHeaders, "content-type": "application/json" }, + headers: { + ...proxyHeaders, + "sec-fetch-site": "same-origin", + "content-type": "application/json", + }, method: "POST", }); const call = await waitForDispatch(harness.dispatcher, "device.exec"); @@ -2615,7 +2622,11 @@ describe("a person the sign-in proxy signed in", () => { const harness = harnessFor(proxyPerson(signedInAt + 2 * 60_000)); const responsePromise = harness.app.request("/v1/components/install", { body: JSON.stringify({ platform: "android", version: "35" }), - headers: { ...proxyHeaders, "content-type": "application/json" }, + headers: { + ...proxyHeaders, + "sec-fetch-site": "same-origin", + "content-type": "application/json", + }, method: "POST", }); const call = await waitForDispatch(harness.dispatcher, "component.install"); diff --git a/src/http/auth.ts b/src/http/auth.ts index 6e07cb604..3571062c8 100644 --- a/src/http/auth.ts +++ b/src/http/auth.ts @@ -24,10 +24,23 @@ export function requireAuth(auth: Pick): Middleware : { details: error.details, ...reasonOf(error.details) }, ); } + refuseCrossSiteChange(c); await next(); }; } +const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); + +function refuseCrossSiteChange(c: Context): void { + if (!c.get("identity").ambient || SAFE_METHODS.has(c.req.method)) return; + if (c.req.header("sec-fetch-site") === "same-origin") return; + throw new HttpApiError( + 403, + "FORBIDDEN", + "Cross-site request refused: a request signed in through a sign-in proxy must come from the console", + ); +} + function reasonOf(details: unknown): { reason?: string } { const reason = (details as { reason?: unknown } | null)?.reason; return typeof reason === "string" ? { reason } : {}; From 0acf9f83e4c082e3e37b8857051c4d02614945b3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:10:01 +0200 Subject: [PATCH 3/3] docs: Say in the HTTP manual that a proxy sign-in needs Sec-Fetch-Site same-origin to change anything (#715) --- src/http/AGENTS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 7876647a1..c6b43139d 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -32,6 +32,8 @@ Surface: [HTTP-API.md](../../docs/HTTP-API.md), [CONSOLE.md](../../docs/CONSOLE. 3. `requireAuth` on every route but `GET /v1/healthz`. It asks `src/auth` with the request's headers: a bearer token, or the JWT the sign-in proxy adds when `http.proxyAuth` is set. Neither valid → 401 `UNAUTHENTICATED`. A `worker` join token → 403 on every route. + A proxy-signed (`ambient`) identity on any method but GET, HEAD or OPTIONS needs + `Sec-Fetch-Site: same-origin` exactly, else 403 `FORBIDDEN` (mounts included). Tokens are exempt. 4. Body — strict zod schema (`jsonBody`), else 400 `BAD_REQUEST`. 5. `buildHttpSession` — principal = the identity's (a token's id, or `proxy:#`); `operator` → `admin`, `agent` → `agent`. 6. `deps.dispatch` — the daemon's own dispatcher, in process: `DaemonServer.dispatch`.