diff --git a/src/client/link-request-compression.ts b/src/client/link-request-compression.ts index 9eda494f6df..db6992b61c5 100644 --- a/src/client/link-request-compression.ts +++ b/src/client/link-request-compression.ts @@ -32,7 +32,10 @@ export function linkRequestCompressible(url: URL, req: Request, declaredLength: return length > LINK_REQUEST_COMPRESSION_MIN_BYTES && length <= LINK_REQUEST_COMPRESSION_MAX_BYTES; } -/** Read exactly the declared bytes into one buffer; more than declared is refused, fewer is a short body. */ +/** + * Read exactly the declared bytes into one buffer. More than declared is refused, and so is a body + * that ends cleanly with fewer: forwarding that shorter slice would tell the Home it is complete. + */ export async function readDeclaredBody(body: ReadableStream, declared: number, signal: AbortSignal): Promise> { const reader = body.getReader(); const out = new Uint8Array(declared); @@ -53,7 +56,8 @@ export async function readDeclaredBody(body: ReadableStream, declare signal.removeEventListener("abort", onAbort); try { reader.releaseLock(); } catch { /* a pending cancel may hold it */ } } - return filled === declared ? out : out.slice(0, filled); + if (filled !== declared) throw new RangeError("link request body shorter than declared"); + return out; } /** diff --git a/structure/remote-link.md b/structure/remote-link.md index 59a8efdebe8..b4f82e0cd70 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -169,7 +169,7 @@ The traffic book does not count what the link WebSocket gate handles. A verified A Child compresses a request body with zstd before it crosses the link only when its Home accepts it (#3023). The capability is `link-request-zstd/1` (`src/link/request-compression.ts`), listed in `PEER_FEATURES` (`src/remote/features.ts`, so `GET /readyz` names it) and in `LINK_PROTOCOL_RELEASES`. A Home names its served features on every relay-auth answer in `x-opencodex-link-home-features` (the `homeFeatures` option of `src/server/index/link-relay-sessions.ts`, wired to `buildPeerFeatures` by `src/server/index/link-listener.ts`); the header sits beside the proof on the authenticated socket and is not covered by it, which costs nothing: a wrong value can only change whether the next body is coded, and these routes decode a zstd body through the shared reader on every Home that speaks relay-auth/2. The Child's transport records the list per link after each verified answer (`src/client/link-home-features.ts`, at most 256 links), from the data path and the readiness probe alike. -`src/client/link-relay.ts` prepares a body only when all of these hold: compression is not disabled in the relay deps, the request is a POST to `/v1/responses`, `/v1/responses/compact`, `/v1/messages` or `/v1/chat/completions` (the routes whose Home handler decodes Content-Encoding through `readBoundedJsonRequestBody`), it carries no Content-Encoding, it declares a Content-Length above 1 KiB and at most 16 MiB (`LINK_REQUEST_COMPRESSION_MAX_BYTES`) and within the body limit, and the Home's last verified answer for this link named the capability. It then reads exactly the declared bytes into one buffer, which is the whole bound on what it holds, and compresses them once with `Bun.zstdCompress` at level 3 (`src/client/link-request-compression.ts`): one frame per body, no dictionary and no context kept across requests or links, so the link key, which travels in a header, never shares a compression context with request text. The zstd form is kept only when it is smaller and stays within the Home decoder's ratio bound (`compressedBodyDecodeLimit`, the policy `link-request-zstd/1` stands for), so a Child never sends a coded body its Home would refuse; such a body goes as it is. All bodies being prepared share one allowance (`linkRequestPrepareBudget`, 128 MiB): each reserves twice its declared length for as long as the relay can still send it: until the Home answered (a refused connection or a timed-out preflight sends the prepared bytes again) and the transport flushed that body to the Home's socket or tore the request down (`onBodySettled`; a Home may answer before it reads an upload, so response headers alone do not free it). The relay then drops its references with the charge, and the transport keeps no reference to a body once its write completed (it never retains the request init in the listeners that live until the connection closes). A body that does not fit at once streams unchanged instead of waiting, and a request cancelled while its body is being compressed keeps its charge until the compressor returns, then releases it without sending. After this connection's proof, `fetchBoundLinkRelay` asks `selectBody` for the body with the features this very answer named: the zstd form with `content-encoding: zstd` and its own Content-Length when the answer names the capability, the original bytes otherwise. A compression failure, a larger result, or a Home that stopped naming the capability sends the original bytes. Every other body, including the first one a Child sends before it has heard its Home, a chunked upload and one above the bound, streams exactly as before, and an older Home never names the capability, so it never receives a coded body. A buffered body can be sent again after a refused connection, which a streamed one already could while untouched. The SSH tunnel itself is never compressed (no `ssh -C`), which would mix the link key and outside text in one compression context. A Home names the capability only while `linkRequestCompression` (top-level `config.json`, `src/types/link.ts`) is absent or true: `linkHomeFeatures` in `src/remote/features.ts`, wired through the listener start context by `src/server/index/optional-listeners.ts` and read at start, leaves it out when the key is false, and its Children then send identity bodies exactly as before; the Home still decodes a zstd body from any client, and `GET /readyz` still lists the build's features. The residual threat is a length oracle: someone who can influence repeated requests and measure their sizes can test guesses at a secret that shares a body with their text, because a correct guess compresses better; on a link that is the relay operator or anyone on the path, since the tunnel hides content but not sizes. It is on by default because the attack needs both chosen text inside the conversation and per-request sizes, while compression roughly halves the bytes toward the Home; an operator whose threat model includes such an observer turns it off. The Child leaves optional features it uses only when its Home names them (`LINK_OPTIONAL_CHILD_FEATURES` in `src/link/compatibility.ts`) out of its peer report, and a Home never counts one against itself, so a Home that predates per-body zstd does not report a compatible Child as degraded. Coverage: `tests/clients/link-request-zstd.test.ts` (real hub-link sessions and the bound transport: a compressed body that decodes to the same bytes and counts on both ends, the bodies that stay as sent, an older Home, a Home that stops naming the capability, a failing compressor, an identity body to a capable Home, three uploads the Home has read while it holds its response headers, a cancel during compression, the Home's `linkRequestCompression` switch through a real listener lifecycle), `tests/clients/link-peer-compatibility.test.ts` (the Child's report leaves the optional feature out, and a Home never counts it against itself), `tests/usage/request-body-log.test.ts` (a Child-compressed body's log row carries its wire size, `zstd` and its decoded size). +`src/client/link-relay.ts` prepares a body only when all of these hold: compression is not disabled in the relay deps, the request is a POST to `/v1/responses`, `/v1/responses/compact`, `/v1/messages` or `/v1/chat/completions` (the routes whose Home handler decodes Content-Encoding through `readBoundedJsonRequestBody`), it carries no Content-Encoding, it declares a Content-Length above 1 KiB and at most 16 MiB (`LINK_REQUEST_COMPRESSION_MAX_BYTES`) and within the body limit, and the Home's last verified answer for this link named the capability. It then reads exactly the declared bytes into one buffer, which is the whole bound on what it holds (a body that runs past its declared length, or ends cleanly before it, is answered 400 and nothing reaches the Home; a streamed body keeps the caller's Content-Length, so there a short body is a short upload the Home sees), and compresses them once with `Bun.zstdCompress` at level 3 (`src/client/link-request-compression.ts`): one frame per body, no dictionary and no context kept across requests or links, so the link key, which travels in a header, never shares a compression context with request text. The zstd form is kept only when it is smaller and stays within the Home decoder's ratio bound (`compressedBodyDecodeLimit`, the policy `link-request-zstd/1` stands for), so a Child never sends a coded body its Home would refuse; such a body goes as it is. All bodies being prepared share one allowance (`linkRequestPrepareBudget`, 128 MiB): each reserves twice its declared length for as long as the relay can still send it: until the Home answered (a refused connection or a timed-out preflight sends the prepared bytes again) and the transport flushed that body to the Home's socket or tore the request down (`onBodySettled`; a Home may answer before it reads an upload, so response headers alone do not free it). The relay then drops its references with the charge, and the transport keeps no reference to a body once its write completed (it never retains the request init in the listeners that live until the connection closes). A body that does not fit at once streams unchanged instead of waiting, and a request cancelled while its body is being compressed keeps its charge until the compressor returns, then releases it without sending. After this connection's proof, `fetchBoundLinkRelay` asks `selectBody` for the body with the features this very answer named: the zstd form with `content-encoding: zstd` and its own Content-Length when the answer names the capability, the original bytes otherwise. A compression failure, a larger result, or a Home that stopped naming the capability sends the original bytes. Every other body, including the first one a Child sends before it has heard its Home, a chunked upload and one above the bound, streams exactly as before, and an older Home never names the capability, so it never receives a coded body. A buffered body can be sent again after a refused connection, which a streamed one already could while untouched. The SSH tunnel itself is never compressed (no `ssh -C`), which would mix the link key and outside text in one compression context. A Home names the capability only while `linkRequestCompression` (top-level `config.json`, `src/types/link.ts`) is absent or true: `linkHomeFeatures` in `src/remote/features.ts`, wired through the listener start context by `src/server/index/optional-listeners.ts` and read at start, leaves it out when the key is false, and its Children then send identity bodies exactly as before; the Home still decodes a zstd body from any client, and `GET /readyz` still lists the build's features. The residual threat is a length oracle: someone who can influence repeated requests and measure their sizes can test guesses at a secret that shares a body with their text, because a correct guess compresses better; on a link that is the relay operator or anyone on the path, since the tunnel hides content but not sizes. It is on by default because the attack needs both chosen text inside the conversation and per-request sizes, while compression roughly halves the bytes toward the Home; an operator whose threat model includes such an observer turns it off. The Child leaves optional features it uses only when its Home names them (`LINK_OPTIONAL_CHILD_FEATURES` in `src/link/compatibility.ts`) out of its peer report, and a Home never counts one against itself, so a Home that predates per-body zstd does not report a compatible Child as degraded. Coverage: `tests/clients/link-request-zstd.test.ts` (real hub-link sessions and the bound transport: a compressed body that decodes to the same bytes and counts on both ends, the bodies that stay as sent, an older Home, a Home that stops naming the capability, a failing compressor, an identity body to a capable Home, three uploads the Home has read while it holds its response headers, a cancel during compression, the Home's `linkRequestCompression` switch through a real listener lifecycle), `tests/clients/link-peer-compatibility.test.ts` (the Child's report leaves the optional feature out, and a Home never counts it against itself), `tests/usage/request-body-log.test.ts` (a Child-compressed body's log row carries its wire size, `zstd` and its decoded size). ## Responses WebSocket over the link diff --git a/tests/clients/link-request-zstd.test.ts b/tests/clients/link-request-zstd.test.ts index 3f9de37f5e1..2a778e5843d 100644 --- a/tests/clients/link-request-zstd.test.ts +++ b/tests/clients/link-request-zstd.test.ts @@ -3,6 +3,7 @@ import type { Server } from "bun"; import { zstdDecompressSync } from "node:zlib"; import { randomBytes } from "node:crypto"; import { relayLinkDataRequest, HOME_INITIATED_LINK_TUNNEL, type LinkRelayDeps } from "../../src/client/link-relay"; +import { readDeclaredBody } from "../../src/client/link-request-compression"; import { createLinkRelaySessions } from "../../src/server/index/link-relay-sessions"; import { serviceApiTokenFingerprint } from "../../src/lib/service-secrets"; import { createLinkTrafficBook } from "../../src/link/traffic"; @@ -215,6 +216,32 @@ describe("per-body zstd from Child to Home (#3023)", () => { expect(budget.snapshot()).toEqual({ reservedBytes: 0, activeLeases: 0, queuedRequests: 0 }); expect(h.seen).toHaveLength(1); }); + + const bigBytes = encoder.encode(big); + const shortBody = () => new ReadableStream({ start(c) { c.enqueue(bigBytes.subarray(0, bigBytes.byteLength - 10)); c.close(); } }); + + test("a body that ends cleanly before its declared length is unreadable, never a shorter complete body", async () => { + const bytes = bigBytes; + await expect(readDeclaredBody(shortBody(), bytes.byteLength, new AbortController().signal)).rejects.toThrow(RangeError); + const whole = new ReadableStream({ start(c) { c.enqueue(bytes); c.close(); } }); + expect(await readDeclaredBody(whole, bytes.byteLength, new AbortController().signal)).toEqual(bytes); + }); + + test("a prepared body shorter than its declared Content-Length answers 400 and reaches no Home", async () => { + const bytes = bigBytes; + const h = home(() => [LINK_REQUEST_ZSTD_FEATURE]); + await relay(post("/v1/responses", big), h.port); + const budget = createInboundBodyBudget(64 * 1024 * 1024, 0); + const req = new Request("http://127.0.0.1/v1/responses", { method: "POST", duplex: "half", body: shortBody(), + headers: { "content-type": "application/json", "content-length": String(bytes.byteLength) } } as RequestInit); + expect(req.headers.get("content-length")).toBe(String(bytes.byteLength)); + const res = await relay(req, h.port, { requestCompression: { budget } }); + // The Home's session layer counts every request it dispatched: only the first one got there. + expect(h.book.snapshot(linkId)).toMatchObject({ requests: 1 }); + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ error: "link relay request body unreadable" }); + expect(budget.snapshot()).toEqual({ reservedBytes: 0, activeLeases: 0, queuedRequests: 0 }); + }); }); describe("the Home's switch for per-body zstd (#3023)", () => {