diff --git a/CHANGELOG.md b/CHANGELOG.md index 91def26..088813e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -251,6 +251,12 @@ npm treats versions as semver and semver forbids leading zeros. more than one socket read can carry. User `@Ws` routes keep closing `1013` at `maxWsQueue`. Deno and Bun deliver frames one at a time and did not hit this, but they now share the same bound. + Both larger bounds, this one and the frame size from #120, **apply only once the peer's `hello` + is accepted**. Until then the control channel takes frames of at most 64 KiB and queues at most + 16, and closes with `1009` or `1013` past that. An unauthenticated peer can therefore make a + teapot hold about 1 MiB per connection, including while `app.upgrade` waits for a slow boot, + instead of thousands of multi-megabyte frames. + - **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler` never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over diff --git a/src/app/index.ts b/src/app/index.ts index 41bb24b..bba3800 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -12,7 +12,7 @@ import { answerFetchProbe, buildFetch } from '../http/web'; import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression'; import { boundInbound, - controlLimits, + controlBounds, validateWsLimits, WS_MAX_MESSAGE_BYTES, wsMessageBytes, @@ -421,7 +421,7 @@ export function createApp(opts: { const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable); // Known at construction, unlike the control channel itself, because `app.upgrade` must bound a // socket before it awaits the boot (#120). - const meshBounds = controlLimits(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes)); + const meshBounds = controlBounds(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes)); const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, { limits: opts.limits, trustProxy: opts.trustProxy, @@ -1581,10 +1581,10 @@ function nativeWsBytes( mesh: MeshConfig | undefined, registry: Registry, limits: RequestLimits | undefined, - meshBounds: { maxWsMessageBytes: number }, + meshBounds: ReturnType, ): number { const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length); - return servesControl ? meshBounds.maxWsMessageBytes : wsMessageBytes(limits); + return servesControl ? meshBounds.authed.maxWsMessageBytes : wsMessageBytes(limits); } /** @@ -1816,7 +1816,7 @@ function buildAppUpgrade( }: { limits?: RequestLimits; trustProxy?: boolean; - meshBounds: Pick; + meshBounds: ReturnType; }, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; @@ -1827,7 +1827,8 @@ function buildAppUpgrade( // would be lost. For the mesh control channel that is the `hello` itself — the handshake would // hang until timeout against a teapot whose providers happened to boot slowly. // The path comes first, though, because it decides the bound: the mesh control channel carries - // whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120). + // whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120) — once + // its peer authenticates. Until then, and so throughout the boot, it takes hello-sized frames. let path: string; // The same normalization HTTP and the Node upgrade listener run. A malformed escape would @@ -1839,7 +1840,10 @@ function buildAppUpgrade( return; } - const ready = boundInbound(socket, path === MESH_CONTROL_PATH ? meshBounds : limits); + const ready = + path === MESH_CONTROL_PATH + ? boundInbound(socket, meshBounds.preAuth, meshBounds.authed) + : boundInbound(socket, limits); await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index ceff854..ac029b6 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -42,31 +42,60 @@ export function wsMessageBytes(limits: Pick } /** - * Undelivered inbound frames the mesh control channel may hold (#148), in place of - * `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never awaits between - * frames, so its queue only ever holds one delivery burst: `ws` emits every frame of one socket - * read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control frame - * (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the - * 16-frame user default closed with 1013. Still finite, so a peer flooding the channel while - * nothing reads it — before the boot finishes, say — is still cut off. + * Undelivered inbound frames the mesh control channel may hold once its peer is authenticated + * (#148), in place of `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never + * awaits between frames, so its queue only ever holds one delivery burst: `ws` emits every frame of + * one socket read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control + * frame (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the + * 16-frame user default closed with 1013. */ const CONTROL_QUEUE = 4096; /** - * The limits the mesh control channel's socket is bounded by: `limits` with `maxWsMessageBytes` - * raised to the channel's own frame bound (#120) and `maxWsQueue` to {@link CONTROL_QUEUE} (#148), - * each only when larger. A user route never goes through this, so it keeps both as configured. + * Largest frame the mesh control channel accepts before its peer's `hello` is accepted. A hello + * is a version and a secret; nothing larger has a reason to arrive first. */ -export function controlLimits( +export const HELLO_FRAME_BYTES = 65_536; + +/** Inbound bounds for one socket, as {@link boundInbound} takes them. */ +type InboundLimits = { maxWsMessageBytes: number; maxWsQueue: number }; + +/** + * The bounds of the mesh control channel's socket, in two phases. + * + * - `preAuth`, until the peer's `hello` is accepted: hello-sized frames and the default 16-frame + * queue, so an unauthenticated peer can make the process hold about 1 MiB at most — including + * while `app.upgrade` waits for a slow boot, before anything reads the queue. + * - `authed`, after: `maxWsMessageBytes` raised to the channel's frame bound (#120) and `maxWsQueue` + * to {@link CONTROL_QUEUE} (#148), each only when larger. The peer holds the mesh secret by then. + * + * A user route never goes through this, so it keeps both limits as configured. + */ +export function controlBounds( limits: Pick | undefined, maxFrameBytes: number | undefined, -): { maxWsMessageBytes: number; maxWsQueue: number } { +): { preAuth: InboundLimits; authed: InboundLimits } { return { - maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0), - maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE), + preAuth: { maxWsMessageBytes: HELLO_FRAME_BYTES, maxWsQueue: DEFAULT_MAX_WS_QUEUE }, + authed: { + maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0), + maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE), + }, }; } +/** Where a socket bounded with a second phase keeps the switch to it; `Symbol.for`, as above. */ +const WIDEN_INBOUND: unique symbol = Symbol.for('green-tea.widen-inbound'); + +/** + * Switches a socket from {@link boundInbound}'s first bounds to the `widened` ones it was given — + * for the mesh control channel, once the peer has authenticated. A no-op on any other socket. + * Frames already queued stay; the new bounds apply to the frames that arrive next. + */ +export function widenInbound(socket: WsSocket): void { + (socket as { [WIDEN_INBOUND]?: () => void })[WIDEN_INBOUND]?.(); +} + /** Throws when a WebSocket limit is present but not a positive safe integer (#107). */ export function validateWsLimits(limits: RequestLimits | undefined): void { for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) { @@ -100,10 +129,14 @@ function exceedsBytes(msg: unknown, max: number): boolean { * consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every * frame from the moment it subscribes, through its own queue, and the bound applies to each queue. * Every other capability is the original socket's. + * + * `widened`, when given, is a second set of bounds that {@link widenInbound} switches to later: the + * mesh control channel starts at hello size and widens once its peer authenticates. */ export function boundInbound( socket: WsSocket, limits?: Pick, + widened?: InboundLimits, ): WsSocket { const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE); @@ -113,6 +146,7 @@ export function boundInbound( return Object.create(socket, { inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } }, + ...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }), }) as WsSocket; } @@ -126,12 +160,18 @@ class InboundFanout { constructor( private readonly socket: WsSocket, - private readonly maxBytes: number, - private readonly maxQueue: number, + private maxBytes: number, + private maxQueue: number, ) { this.first = this.add(); } + /** Applies the second phase's bounds; see {@link widenInbound}. */ + widen(limits: InboundLimits): void { + this.maxBytes = limits.maxWsMessageBytes; + this.maxQueue = limits.maxWsQueue; + } + /** * Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames * synchronously — `ws` does — so a bound checked after the event loop yields is checked after an diff --git a/src/http/ws.ts b/src/http/ws.ts index 76e8ba0..41b153c 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -6,7 +6,7 @@ import { matchWsRoute, trackUntil, boundInbound, - controlLimits, + controlBounds, wsMessageBytes, type WsSocket, type WsRequest, @@ -51,10 +51,10 @@ function handleMeshUpgrade( return true; } - // An RPC carries a whole request body, so the channel is bounded by the teapot's body limit - // rather than `maxWsMessageBytes` (#120). `wss` is built with that bound as `maxPayload`, and - // `boundInbound` repeats it on the decoded text, as it does for every route. - const bounds = controlLimits(limits, meshControl.maxFrameBytes); + // An RPC carries a whole request body, so once the peer authenticates the channel is bounded by + // the teapot's body limit rather than `maxWsMessageBytes` (#120). `wss` is built with that bound + // as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size. + const bounds = controlBounds(limits, meshControl.maxFrameBytes); // nodeSocket, not the raw ws: the control channel is the last consumer that spoke the // `ws` EventEmitter API directly. It now takes the same neutral socket every route does. @@ -62,7 +62,7 @@ function handleMeshUpgrade( // an untracked control channel leaves the teapot's server.close() waiting on it forever. // serveFrames swallows its own failures, so the floating promise cannot reject. wss.handleUpgrade(req, socket, head, (ws: any) => { - const neutral = boundInbound(nodeSocket(ws), bounds); + const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed); void trackUntil(neutral, meshControl.handle(neutral), streams); }); @@ -139,7 +139,7 @@ export function attachWs( WebSocketServer && meshControl ? new WebSocketServer({ noServer: true, - maxPayload: controlLimits(limits, meshControl.maxFrameBytes).maxWsMessageBytes, + maxPayload: controlBounds(limits, meshControl.maxFrameBytes).authed.maxWsMessageBytes, }) : null; server.on('upgrade', (req, socket, head) => { diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index d505275..9372028 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -3,7 +3,7 @@ // under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec). import crypto from 'node:crypto'; import type { Bus } from '../bus'; -import type { WsSocket } from '../http/ws-core'; +import { HELLO_FRAME_BYTES, widenInbound, type WsSocket } from '../http/ws-core'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; import { @@ -61,8 +61,10 @@ const ENVELOPE_HEADROOM = 1_048_576; * `maxBodyBytes` (#120): the body at its worst escaping plus {@link ENVELOPE_HEADROOM}, so any body * within the limit fits. 7,048,576 at the 1 MB default. * - * `decode` runs `JSON.parse` on peer-controlled input, so the parse is capped by this figure. - * Applies to the control channel only: user WebSocket routes keep `limits.maxWsMessageBytes`. + * `decode` runs `JSON.parse` on peer-controlled input, so the parse is capped by this figure — and + * an unauthenticated peer never gets near it: until its `hello` is accepted, the channel takes only + * hello-sized frames (`HELLO_FRAME_BYTES`, `controlBounds` in `ws-core`). Applies to the control + * channel only: user WebSocket routes keep `limits.maxWsMessageBytes`. */ export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number { return WORST_ESCAPE * maxBodyBytes + ENVELOPE_HEADROOM; @@ -132,6 +134,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): return false; } + // The peer holds the secret now: lift the hello-sized bounds its socket was given to the ones + // that carry RPC bodies (#120, #148). A socket bounded without a second phase is left as it is. + widenInbound(socket); socket.send( encode({ type: 'manifest', @@ -220,8 +225,9 @@ async function serveFrames( for await (const data of socket.inbound) { const raw = String(data); - // Checked before `decode`, because decoding is the expensive part being defended. - if (raw.length > maxFrameChars) { + // Checked before `decode`, because decoding is the expensive part being defended. Until the + // handshake, nothing larger than a hello is parsed, whatever the socket in front allowed. + if (raw.length > (authed ? maxFrameChars : HELLO_FRAME_BYTES)) { socket.close(1009, 'mesh frame too large'); break; } diff --git a/test/bun/mesh-large-body.test.ts b/test/bun/mesh-large-body.test.ts index b2cdd97..03a16ac 100644 --- a/test/bun/mesh-large-body.test.ts +++ b/test/bun/mesh-large-body.test.ts @@ -192,3 +192,17 @@ test('mesh on Bun: a user ws route on the same teapot still closes 1013 at maxWs await close(); } }); + +test('mesh on Bun: an unauthenticated peer sending a frame over hello size is closed 1009', async () => { + const { close, tPort } = await pair(); + try { + const code = await new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`); + ws.onopen = () => ws.send('x'.repeat(1_000_000)); + ws.onclose = (e) => resolve(e.code); + }); + expect(code).toEqual(1009); + } finally { + await close(); + } +}); diff --git a/test/deno/mesh-large-body.test.ts b/test/deno/mesh-large-body.test.ts index b54d714..39987cb 100644 --- a/test/deno/mesh-large-body.test.ts +++ b/test/deno/mesh-large-body.test.ts @@ -188,3 +188,17 @@ Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1013 at await close(); } }); + +Deno.test('mesh on Deno: an unauthenticated peer sending a frame over hello size is closed 1009', async () => { + const { close, tPort } = await pair(); + try { + const code = await new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`); + ws.onopen = () => ws.send('x'.repeat(1_000_000)); + ws.onclose = (e) => resolve(e.code); + }); + assertEquals(code, 1009); + } finally { + await close(); + } +}); diff --git a/test/mesh/control-preauth.test.ts b/test/mesh/control-preauth.test.ts new file mode 100644 index 0000000..e47175c --- /dev/null +++ b/test/mesh/control-preauth.test.ts @@ -0,0 +1,100 @@ +// Before a peer's `hello` is accepted, the mesh control channel takes only hello-sized frames and +// a small queue. The large bounds that carry RPC bodies (#120, #148) apply after authentication +// only, so an unauthenticated peer cannot make the process buffer `queue × frame` bytes — which +// at 4,096 × 7 MB was tens of GB, reachable while `app.upgrade` waits for a slow boot. +import { describe, it, expect } from 'vitest'; +import { createApp, Module, Provider, Step } from '../../src/index'; +import { channel } from '../../src/channel'; +import { MESH_CONTROL_PATH } from '../../src/mesh/teapot'; +import { encode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; +import type { WsSocket, WsRequest } from '../../src/http/ws-core'; + +@Provider({ provides: 'slow' }) +class Slow { + async provide() { + await new Promise((resolve) => setTimeout(resolve, 300)); + return { slow: true }; + } +} +@Step({ provides: 'cfg', needs: [], export: true }) +class Cfg { + run() { + return { cfg: 1 }; + } +} +@Module({ mountpoint: '/api', providers: [Slow], steps: [Cfg] }) +class SlowTeapot {} + +function fakeSocket() { + const inbound = channel(); + const ac = new AbortController(); + const sent: string[] = []; + const closes: number[] = []; + const socket: WsSocket = { + inbound, + abort: ac.signal, + get isOpen() { + return !ac.signal.aborted; + }, + send: (d) => sent.push(d), + close: (code) => { + if (ac.signal.aborted) return; + closes.push(code ?? 1005); + ac.abort(); + inbound.close(); + }, + terminate: () => ac.abort(), + }; + return { socket, inbound, sent, closes }; +} + +const req: WsRequest = { url: MESH_CONTROL_PATH, headers: {}, protocol: 'http', ip: '' }; +const teapot = () => createApp({ modules: [SlowTeapot], experimental: true, mesh: { secret: 's3cr3t' } }); + +describe('mesh control channel before authentication', () => { + it('closes 1009 on a frame over hello size while the boot is still running', async () => { + const app = teapot(); + const { socket, inbound, closes } = fakeSocket(); + const run = app.upgrade(req, socket); + + inbound.push('x'.repeat(1_000_000)); + expect(closes).toEqual([1009]); // at once: the boot has not finished, nothing was buffered + await run; + await app.close(); + }); + + it('closes 1013 when an unauthenticated peer floods frames during the boot', async () => { + const app = teapot(); + const { socket, inbound, closes } = fakeSocket(); + const run = app.upgrade(req, socket); + + let accepted = 0; + for (let i = 0; i < 64 && !closes.length; i++, accepted++) inbound.push('x'.repeat(1024)); + expect(closes).toEqual([1013]); + expect(accepted).toBeLessThanOrEqual(17); // the user default, not the authenticated 4,096 + await run; + await app.close(); + }); + + it('lifts the bounds once the hello is accepted', async () => { + const app = teapot(); + const { socket, inbound, sent, closes } = fakeSocket(); + const run = app.upgrade(req, socket); + + inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 's3cr3t' })); + await new Promise((resolve) => setTimeout(resolve, 400)); // boot, then the handshake + expect(JSON.parse(sent[0]).type).toBe('manifest'); + + // A frame far over hello size is accepted now (undecodable, so ignored), and a burst of 64 + // fits the authenticated queue. + inbound.push('x'.repeat(1_000_000)); + for (let i = 0; i < 64; i++) inbound.push(encode({ type: 'ping' })); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(closes).toEqual([]); + expect(sent.filter((s) => s.includes('pong'))).toHaveLength(64); + + socket.close(1000); + await run; + await app.close(); + }); +}); diff --git a/test/mesh/large-body.test.ts b/test/mesh/large-body.test.ts index 7d3c370..838989f 100644 --- a/test/mesh/large-body.test.ts +++ b/test/mesh/large-body.test.ts @@ -170,4 +170,16 @@ describe('mesh RPC body near maxBodyBytes (#120)', () => { await close(); } }); + it('an unauthenticated peer sending a frame over hello size is closed 1009', async () => { + const { close, tPort } = await pair(); + try { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`); + await new Promise((resolve) => ws.once('open', resolve)); + const closed = new Promise((resolve) => ws.once('close', (code) => resolve(code))); + ws.send('x'.repeat(1_000_000)); // within the authenticated bound, far over a hello + expect(await closed).toBe(1009); + } finally { + await close(); + } + }); });