Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
24 changes: 24 additions & 0 deletions e2e/proxy-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
});
});
});
2 changes: 2 additions & 0 deletions src/http/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<iss>#<sub>`); `operator` → `admin`, `agent` → `agent`.
6. `deps.dispatch` — the daemon's own dispatcher, in process: `DaemonServer.dispatch`.
Expand Down
160 changes: 157 additions & 3 deletions src/http/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ function buildHarness(
readonly answerDownloadsEarly?: boolean;
readonly identities?: Readonly<Record<string, Identity>>;
readonly auth?: Auth;
readonly mounts?: HttpGatewayDeps["mounts"];
} = {},
) {
const clock = new FakeClock(1_000);
Expand Down Expand Up @@ -101,6 +102,7 @@ function buildHarness(
ownerRoutedFacts,
registry: overrides.registry ?? registry,
auth,
...(overrides.mounts === undefined ? {} : { mounts: overrides.mounts }),
...(overrides.answerDownloadsEarly === undefined
? {}
: { answerDownloadsEarly: overrides.answerDownloadsEarly }),
Expand Down Expand Up @@ -2534,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 });
},
],
Expand Down Expand Up @@ -2592,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");
Expand All @@ -2613,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");
Expand All @@ -2630,4 +2643,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<readonly [string, string, string, number]> = [
["POST", "/v1/workers/w/drain", "worker.drain", 200],
["DELETE", "/v1/leases/lse_1", "lease.release", 202],
];
const refused: ReadonlyArray<string | undefined> = [
"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<string, string> {
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("/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");
});
});
});
13 changes: 13 additions & 0 deletions src/http/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,23 @@ export function requireAuth(auth: Pick<Auth, "authenticateRequest">): Middleware
: { details: error.details, ...reasonOf(error.details) },
);
}
refuseCrossSiteChange(c);
await next();
};
}

const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);

function refuseCrossSiteChange(c: Context<AuthEnv>): 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 } : {};
Expand Down
Loading