From 713122d53ad7611aa9186f86b3faa5b4ea86ec44 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 22 Oct 2026 23:57:57 -0500 Subject: [PATCH 1/4] fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120) The 1 MiB inbound cap from #107 applied to every WebSocket, the mesh control channel included. An RPC carries a whole request body, so a body inside maxBodyBytes could still overflow the cap once wrapped in an rpc-req frame, and the teapot then closed the whole channel with 1009: every request through that link failed 503 until it reconnected. The test asked for by the card (T1, a 1 MB JSON body at defaults) passes on Node, Deno and Bun, because a JSON body re-encodes to about its own size. Two other cases fail on all three before this change: - T1b: a 999 KB text body of quotes doubles under JSON escaping; - T4: maxBodyBytes raised to 4 MB, a 3.9 MB JSON body. The control channel's bound is now derived from the teapot's limits.maxBodyBytes via controlFrameLimit(): MAX_FRAME_CHARS (4,000,000) at the 1 MB default, scaled by the same ratio above it, never below maxWsMessageBytes. No new option. User @Ws routes keep maxWsMessageBytes: Node gets a second WebSocketServer for the control path, app.upgrade picks the bound from the path before subscribing, and Bun's single native maxPayloadLength is raised on a teapot only, leaving app.upgrade to close user routes 1009 itself. Signed-off-by: Diego Resendez --- CHANGELOG.md | 15 ++++ src/app/index.ts | 70 ++++++++++++--- src/bun.ts | 2 + src/http/types.ts | 6 ++ src/http/ws-core.ts | 12 +++ src/http/ws.ts | 24 +++++- src/mesh/teapot.ts | 40 ++++++++- test/bun/mesh-large-body.test.ts | 136 ++++++++++++++++++++++++++++++ test/deno/mesh-large-body.test.ts | 132 +++++++++++++++++++++++++++++ test/mesh/large-body.test.ts | 117 +++++++++++++++++++++++++ 10 files changed, 536 insertions(+), 18 deletions(-) create mode 100644 test/bun/mesh-large-body.test.ts create mode 100644 test/deno/mesh-large-body.test.ts create mode 100644 test/mesh/large-body.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e404038..ba4040d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -227,6 +227,21 @@ npm treats versions as semver and semver forbids leading zeros. ### Fixed +- **A mesh RPC whose body is within `maxBodyBytes` reaches the teapot again** (#120). The 1 MiB + WebSocket cap from #107 also bounded the mesh control channel, so a request body that fit the + HTTP limit could still exceed it once the teacup wrapped it in an RPC frame. A text body near + 1 MB was enough, because JSON escaping doubles every `"` and backslash, and any body limit raised + above 1 MiB was capped at 1 MiB on the channel. Either way the teapot closed the whole channel + with `1009`, and every request through that link failed with `503` until it reconnected. + + The control channel is now bounded by the teapot's `limits.maxBodyBytes`: 4,000,000 bytes at the + 1 MB default, the figure its frame parser already used, and four times the body limit when that + is raised. `limits.maxWsMessageBytes` still governs every user `@Ws` route, unchanged. On Bun, + which takes one native payload limit for all sockets, a teapot raises that limit to the control + channel's bound, so an oversized frame on a user route is refused by the framework instead: still + `1009`, on every Bun version, where Bun before 1.4 refused natively by dropping the connection + (`1006`). + - **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 ee0aca9..41bb24b 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -12,6 +12,7 @@ import { answerFetchProbe, buildFetch } from '../http/web'; import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression'; import { boundInbound, + controlLimits, validateWsLimits, WS_MAX_MESSAGE_BYTES, wsMessageBytes, @@ -46,7 +47,13 @@ import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; -import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot'; +import { + buildManifest, + controlFrameLimit, + createMeshControl, + MESH_CONTROL_DISABLED_REASON, + MESH_CONTROL_PATH, +} from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; @@ -342,6 +349,7 @@ export function createApp(opts: { orderedProviders, orderedSteps, deps: pipelineDeps, + maxBodyBytes: opts.limits?.maxBodyBytes, }); }; @@ -411,9 +419,13 @@ export function createApp(opts: { etag: opts.etag, }; 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 upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, { limits: opts.limits, trustProxy: opts.trustProxy, + meshBounds, }); const listen = async (port: number): Promise => { @@ -509,7 +521,7 @@ export function createApp(opts: { }; return Object.assign(app, { - [WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits), + [WS_MAX_MESSAGE_BYTES]: nativeWsBytes(opts.mesh, registry, opts.limits, meshBounds), [HEALTH_DRAIN]: drain, // `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded. @@ -1560,6 +1572,21 @@ function makeAppBooter( return once(runBoot); } +/** + * The one inbound bound Bun applies natively to every socket (`WS_MAX_MESSAGE_BYTES`). A teapot + * raises it to its control channel's (#120); user routes still close at `maxWsMessageBytes`, + * because `app.upgrade` bounds them itself. + */ +function nativeWsBytes( + mesh: MeshConfig | undefined, + registry: Registry, + limits: RequestLimits | undefined, + meshBounds: { maxWsMessageBytes: number }, +): number { + const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length); + return servesControl ? meshBounds.maxWsMessageBytes : wsMessageBytes(limits); +} + /** * Builds the mesh control gateway that exposes this node's declared exports over the control channel. * Returns undefined when there is nothing to export; throws if exports are declared without a gating secret. @@ -1567,7 +1594,13 @@ function makeAppBooter( function buildMeshControl( mesh: MeshConfig | undefined, registry: Registry, - deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps }, + deps: { + container: Container; + orderedProviders: GraphNode[]; + orderedSteps: GraphNode[]; + deps: PipelineDeps; + maxBodyBytes?: number; + }, ): MeshControl | undefined { const { exportedSteps, exportedRoutes, routePlans, runners } = registry; const hasExports = exportedSteps.length || exportedRoutes.length; @@ -1638,7 +1671,14 @@ function buildMeshControl( return result; }; - return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus }); + return createMeshControl({ + secret: mesh.secret, + manifest, + resolveScope, + resolveRoute, + bus, + maxBodyBytes: deps.maxBodyBytes, + }); } /** @@ -1769,7 +1809,15 @@ function buildAppUpgrade( streams: Set<() => void>, ensureBooted: () => Promise, getMeshControl: () => MeshControl | undefined, - { limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean }, + { + limits, + trustProxy, + meshBounds, + }: { + limits?: RequestLimits; + trustProxy?: boolean; + meshBounds: Pick; + }, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; @@ -1778,10 +1826,8 @@ function buildAppUpgrade( // with no subscriber is dropped, so anything the peer sends while providers are still booting // 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. - const ready = boundInbound(socket, limits); - - await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted - + // 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). let path: string; // The same normalization HTTP and the Node upgrade listener run. A malformed escape would @@ -1789,10 +1835,14 @@ function buildAppUpgrade( try { path = normalizeRequestPath(request.url.split('?')[0]); } catch { - ready.close(1008, 'invalid request path'); + socket.close(1008, 'invalid request path'); return; } + const ready = boundInbound(socket, path === MESH_CONTROL_PATH ? meshBounds : limits); + + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + const meshControl = getMeshControl(); // The reserved mesh path, checked before route matching: this is what lets a teapot export diff --git a/src/bun.ts b/src/bun.ts index 104d82a..cc09ed9 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -112,6 +112,8 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis // assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer // saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009. // `app.upgrade` checks the same bound again on the decoded text. + // On a teapot the value is the mesh control channel's larger bound (#120), and `app.upgrade` + // alone holds user routes to `maxWsMessageBytes`, closing 1009 on every Bun version. maxPayloadLength: (app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES, open(ws) { diff --git a/src/http/types.ts b/src/http/types.ts index b962e42..c467ad8 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -132,6 +132,12 @@ export interface WsRouteDef { /** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ export interface MeshControl { path: string; + /** + * Inbound bound for this channel's socket, in bytes, used in place of + * `limits.maxWsMessageBytes` when larger (#120): an RPC carries a whole request body, which + * `maxBodyBytes` bounds, not the WebSocket message limit. + */ + maxFrameBytes?: number; /** * Serves one control connection over the neutral socket — the same capability every other ws * consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it. diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 2c1853e..7d18173 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -41,6 +41,18 @@ export function wsMessageBytes(limits: Pick return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES; } +/** + * The limits the mesh control channel's socket is bounded by (#120): `limits` with + * `maxWsMessageBytes` raised to the channel's own frame bound when that is larger. A user route + * never goes through this, so it keeps `maxWsMessageBytes` as configured. + */ +export function controlLimits( + limits: Pick | undefined, + maxFrameBytes: number | undefined, +): Pick & { maxWsMessageBytes: number } { + return { ...limits, maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0) }; +} + /** 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) { diff --git a/src/http/ws.ts b/src/http/ws.ts index c5d7130..76e8ba0 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -6,6 +6,7 @@ import { matchWsRoute, trackUntil, boundInbound, + controlLimits, wsMessageBytes, type WsSocket, type WsRequest, @@ -50,13 +51,18 @@ 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); + // 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. // Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so // 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), limits); + const neutral = boundInbound(nodeSocket(ws), bounds); void trackUntil(neutral, meshControl.handle(neutral), streams); }); @@ -128,6 +134,14 @@ export function attachWs( // fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the // check on the decoded text, which is the only half Deno and the edge have. const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null; + // The control channel's own server, so its larger bound (#120) never reaches a user route. + const meshWss = + WebSocketServer && meshControl + ? new WebSocketServer({ + noServer: true, + maxPayload: controlLimits(limits, meshControl.maxFrameBytes).maxWsMessageBytes, + }) + : null; server.on('upgrade', (req, socket, head) => { // A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody // else is listening to yet: that is as fatal as a throw. @@ -136,7 +150,7 @@ export function attachWs( // Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an // uncaught exception that takes the whole process down, not a 500 for one client. try { - routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head); + routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head); } catch { if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error'); else socket.destroy(); @@ -147,6 +161,8 @@ export function attachWs( /** What every upgrade on one server shares. */ interface UpgradeEnv { wss: any; + /** The mesh control channel's server, bounded by its own frame limit (#120). */ + meshWss: any; wsRoutes: WsRouteDef[]; bus?: Bus; meshControl?: MeshControl; @@ -156,7 +172,7 @@ interface UpgradeEnv { /** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void { - const { wss, wsRoutes, bus, meshControl, streams, limits } = env; + const { wss, meshWss, wsRoutes, bus, meshControl, streams, limits } = env; let path: string; // The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed @@ -168,7 +184,7 @@ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, h return; } - if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return; + if (meshControl && handleMeshUpgrade(meshWss, meshControl, path, req, socket, head, streams, limits)) return; // The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno, // Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 014fcf4..501f42e 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -49,11 +49,28 @@ const HANDSHAKE_TIMEOUT_MS = 10_000; * as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no * documented ceiling on the platform sockets Deno and Bun provide). * - * Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON - * overhead of the envelope around it. + * Sized for the 1 MB default body limit an RPC can legitimately carry, with room for the JSON + * overhead of the envelope around it. That overhead is not a constant: a JSON body re-encodes to + * about its own size, but a text body doubles wherever it holds a `"` or a backslash, since the + * envelope escapes it as a JSON string. {@link controlFrameLimit} scales this figure with a raised + * limit. */ const MAX_FRAME_CHARS = 4_000_000; +/** The body limit {@link MAX_FRAME_CHARS} is sized for: `limits.maxBodyBytes`'s default. */ +const DEFAULT_MAX_BODY_BYTES = 1_000_000; + +/** + * Largest control frame a teapot accepts when the largest body it may be sent is `maxBodyBytes` + * (#120): {@link MAX_FRAME_CHARS}, scaled by the same ratio for a body limit raised above the + * default. Never below it, because the frame also carries headers, params and query, which do not + * shrink with a lowered body limit. Applies to the control channel only: user WebSocket routes keep + * `limits.maxWsMessageBytes`. + */ +export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number { + return Math.max(MAX_FRAME_CHARS, Math.ceil((MAX_FRAME_CHARS / DEFAULT_MAX_BODY_BYTES) * maxBodyBytes)); +} + /** Assemble a {@link Manifest} from exported step tokens and buffered routes. */ export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest { return { steps: [...args.steps], routes: args.routes }; @@ -73,6 +90,11 @@ export interface MeshControlDeps { resolveScope: (name: string, env: RequestEnvelope) => Promise; resolveRoute: (name: string, env: RequestEnvelope) => Promise; bus?: Bus; + /** + * The largest request body this teapot accepts, which sizes the control frames it parses + * ({@link controlFrameLimit}). Defaults to the 1 MB body default. + */ + maxBodyBytes?: number; } /** The rpc-req member of the {@link Frame} union. */ @@ -187,6 +209,7 @@ async function serveFrames( deps: MeshControlDeps, exportedScopes: Set, exportedRoutes: Set, + maxFrameChars: number, ): Promise { let authed = false; // Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply @@ -201,7 +224,7 @@ async function serveFrames( const raw = String(data); // Checked before `decode`, because decoding is the expensive part being defended. - if (raw.length > MAX_FRAME_CHARS) { + if (raw.length > maxFrameChars) { socket.close(1009, 'mesh frame too large'); break; } @@ -244,13 +267,22 @@ async function serveFrames( /** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */ export function createMeshControl(deps: MeshControlDeps): { path: string; + maxFrameBytes: number; handle: (socket: WsSocket) => Promise; } { const exportedScopes = new Set(deps.manifest.steps); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); + const maxFrameChars = controlFrameLimit(deps.maxBodyBytes); return { path: MESH_CONTROL_PATH, + /** + * The inbound bound a server puts on this channel's WebSocket in place of + * `limits.maxWsMessageBytes` (#120). The same figure as the character check below: the two agree + * on ASCII, and on other text the byte bound is the one that binds — a body measured in bytes by + * `maxBodyBytes` stays about that many bytes inside the envelope, so it still fits. + */ + maxFrameBytes: maxFrameChars, /** * Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await * the control channel's lifetime the same way it awaits a regular ws route's. @@ -258,7 +290,7 @@ export function createMeshControl(deps: MeshControlDeps): { * does synchronously, so the loop is live before any frame can arrive. */ handle(socket: WsSocket): Promise { - return serveFrames(socket, deps, exportedScopes, exportedRoutes); + return serveFrames(socket, deps, exportedScopes, exportedRoutes, maxFrameChars); }, }; } diff --git a/test/bun/mesh-large-body.test.ts b/test/bun/mesh-large-body.test.ts new file mode 100644 index 0000000..c6e5f9c --- /dev/null +++ b/test/bun/mesh-large-body.test.ts @@ -0,0 +1,136 @@ +// #120 (CARD-24, D22) on Bun: an RPC whose body is within `maxBodyBytes` reaches the teapot, +// although the control channel is a WebSocket bounded like every other. Node twin: +// test/mesh/large-body.test.ts, which explains the cases. +// +// Run with: npm run test:bun +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +const SECRET = 's3cr3t'; +const WRAP = '{"data":""}'.length; + +@Route('/big') +class BigCtl { + @Post('/echo', { export: true }) + echo(@body() b: { data: string } | string) { + return { length: typeof b === 'string' ? b.length : b.data.length }; + } + + @Ws('/sock') + sock(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${String(msg).length}`; + })(); + } +} +@Module({ mountpoint: '/api', controllers: [BigCtl] }) +class TeapotModule {} + +@Module({ mountpoint: '/api' }) +class TeacupModule {} + +async function serve(app: ReturnType) { + const server = await serveBun(app, { port: 0 }); + return { server, port: server.port }; +} + +async function pair(maxBodyBytes?: number) { + const limits = maxBodyBytes ? { maxBodyBytes } : undefined; + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits }); + const t = await serve(teapot); + const url = `ws://127.0.0.1:${t.port}/__mesh__/control`; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + limits, + }); + const c = await serve(teacup); + const post = (payload: string, type = 'application/json') => + fetch(`http://127.0.0.1:${c.port}/api/big/echo`, { + method: 'POST', + headers: { 'content-type': type }, + body: payload, + }); + const close = async () => { + await teacup.close(); + await teapot.close(); + c.server.stop(true); + t.server.stop(true); + }; + return { post, close, tPort: t.port, teacup }; +} + +const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) }); + +test('mesh on Bun: a 1 MB JSON body reaches the teapot (T1)', async () => { + const { post, close } = await pair(); + try { + const res = await post(json(1_000_000)); + expect(res.status).toEqual(200); + expect(await res.json()).toEqual({ length: 1_000_000 - WRAP }); + expect((await post(json(1_000_000))).status).toEqual(200); + } finally { + await close(); + } +}); + +test('mesh on Bun: a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => { + const { post, close } = await pair(); + try { + const res = await post('"'.repeat(999_000), 'text/plain'); + expect(res.status).toEqual(200); + expect(await res.json()).toEqual({ length: 999_000 }); + expect((await post('ok', 'text/plain')).status).toEqual(200); + } finally { + await close(); + } +}); + +test('mesh on Bun: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => { + const { post, close, teacup } = await pair(); + try { + // Through `app.fetch`, not the socket: a client still writing a 1 MB body when Bun's 413 lands + // can stall or reset (see body-limits.test.ts). That race is the transport's, not the mesh's. + const over = new Request('http://x/api/big/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: json(1_000_001), + }); + expect((await teacup.fetch(over)).status).toEqual(413); + expect((await post(json(1_000))).status).toEqual(200); + } finally { + await close(); + } +}); + + +// A teapot raises Bun's native `maxPayloadLength` to the control channel's bound, so a user route's +// oversized frame is refused by `app.upgrade` instead, with a real 1009 close frame rather than the +// 1006 drop the native bound gives (see ws.test.ts). +test('mesh on Bun: a user ws route on the same teapot still closes 1009 over 1 MiB (T3)', async () => { + const { close, tPort } = await pair(); + try { + const code = await new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`); + ws.onopen = () => ws.send('x'.repeat(1_048_577)); + ws.onclose = (e) => resolve(e.code); + }); + expect(code).toEqual(1009); + } finally { + await close(); + } +}); + +test('mesh on Bun: the control-channel cap follows a raised maxBodyBytes (T4)', async () => { + const { post, close } = await pair(4_000_000); + try { + const res = await post(json(3_900_000)); + expect(res.status).toEqual(200); + expect(await res.json()).toEqual({ length: 3_900_000 - WRAP }); + } finally { + await close(); + } +}); diff --git a/test/deno/mesh-large-body.test.ts b/test/deno/mesh-large-body.test.ts new file mode 100644 index 0000000..064a4e1 --- /dev/null +++ b/test/deno/mesh-large-body.test.ts @@ -0,0 +1,132 @@ +// #120 (CARD-24, D22) on Deno: an RPC whose body is within `maxBodyBytes` reaches the teapot, +// although the control channel is a WebSocket bounded like every other. Node twin: +// test/mesh/large-body.test.ts, which explains the cases. +// +// Run with: npm run test:deno +import 'npm:reflect-metadata'; +import { assertEquals } from 'jsr:@std/assert'; +import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +const SECRET = 's3cr3t'; +const WRAP = '{"data":""}'.length; + +@Route('/big') +class BigCtl { + @Post('/echo', { export: true }) + echo(@body() b: { data: string } | string) { + return { length: typeof b === 'string' ? b.length : b.data.length }; + } + + @Ws('/sock') + sock(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${String(msg).length}`; + })(); + } +} +@Module({ mountpoint: '/api', controllers: [BigCtl] }) +class TeapotModule {} + +@Module({ mountpoint: '/api' }) +class TeacupModule {} + +async function serve(app: ReturnType) { + let port = 0; + const server = await serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + return { server, port }; +} + +async function pair(maxBodyBytes?: number) { + const limits = maxBodyBytes ? { maxBodyBytes } : undefined; + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits }); + const t = await serve(teapot); + const url = `ws://127.0.0.1:${t.port}/__mesh__/control`; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + limits, + }); + const c = await serve(teacup); + const post = (payload: string, type = 'application/json') => + fetch(`http://127.0.0.1:${c.port}/api/big/echo`, { + method: 'POST', + headers: { 'content-type': type }, + body: payload, + }); + const close = async () => { + await teacup.close(); + await teapot.close(); + await c.server.shutdown(); + await t.server.shutdown(); + }; + return { post, close, tPort: t.port }; +} + +const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) }); + +Deno.test('mesh on Deno: a 1 MB JSON body reaches the teapot (T1)', async () => { + const { post, close } = await pair(); + try { + const res = await post(json(1_000_000)); + assertEquals(res.status, 200); + assertEquals(await res.json(), { length: 1_000_000 - WRAP }); + assertEquals((await post(json(1_000_000))).status, 200); + } finally { + await close(); + } +}); + +Deno.test('mesh on Deno: a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => { + const { post, close } = await pair(); + try { + const res = await post('"'.repeat(999_000), 'text/plain'); + assertEquals(res.status, 200); + assertEquals(await res.json(), { length: 999_000 }); + assertEquals((await post('ok', 'text/plain')).status, 200); + } finally { + await close(); + } +}); + +Deno.test('mesh on Deno: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => { + const { post, close } = await pair(); + try { + assertEquals((await post(json(1_000_001))).status, 413); + assertEquals((await post(json(1_000))).status, 200); + } finally { + await close(); + } +}); + +Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1009 over 1 MiB (T3)', async () => { + const { close, tPort } = await pair(); + try { + const code = await new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`); + ws.onopen = () => ws.send('x'.repeat(1_048_577)); + ws.onclose = (e) => resolve(e.code); + }); + assertEquals(code, 1009); + } finally { + await close(); + } +}); + +Deno.test('mesh on Deno: the control-channel cap follows a raised maxBodyBytes (T4)', async () => { + const { post, close } = await pair(4_000_000); + try { + const res = await post(json(3_900_000)); + assertEquals(res.status, 200); + assertEquals(await res.json(), { length: 3_900_000 - WRAP }); + } finally { + await close(); + } +}); diff --git a/test/mesh/large-body.test.ts b/test/mesh/large-body.test.ts new file mode 100644 index 0000000..9ed8aba --- /dev/null +++ b/test/mesh/large-body.test.ts @@ -0,0 +1,117 @@ +// #120 (CARD-24, D22): an RPC whose body is within `maxBodyBytes` must reach the teapot. +// +// The control channel is a WebSocket, and every WebSocket was bounded by +// `limits.maxWsMessageBytes` (1 MiB by default, #107). A body at the HTTP limit (1,000,000 B by +// default) travels inside an `rpc-req` envelope, re-encoded as JSON: +// - a JSON body re-encodes to about its own size, so 1 MB fits under 1 MiB (T1); +// - a text body does not: every `"` or `\` doubles under JSON escaping, so a 999 KB text body +// became a ~2 MB frame and the teapot hung up the whole channel with 1009 (T1b); +// - a raised `maxBodyBytes` was capped at 1 MiB on the channel regardless (T4). +// The Deno and Bun twins live in test/deno and test/bun. +import { describe, it, expect } from 'vitest'; +import WebSocket from 'ws'; +import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index'; + +const SECRET = 's3cr3t'; +const WRAP = '{"data":""}'.length; + +@Route('/big') +class BigCtl { + @Post('/echo', { export: true }) + echo(@body() b: { data: string } | string) { + return { length: typeof b === 'string' ? b.length : b.data.length }; + } + + @Ws('/sock') + sock(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${String(msg).length}`; + })(); + } +} +@Module({ mountpoint: '/api', controllers: [BigCtl] }) +class TeapotModule {} + +@Module({ mountpoint: '/api' }) +class TeacupModule {} + +/** A JSON body of exactly `bytes` bytes: `{"data":"xxx…"}`. */ +const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) }); + +async function pair(maxBodyBytes?: number) { + const limits = maxBodyBytes ? { maxBodyBytes } : undefined; + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits }); + const tServer = await teapot.listen(0); + const tPort = (tServer.address() as any).port; + const url = `ws://127.0.0.1:${tPort}/__mesh__/control`; + const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] }, limits }); + const cServer = await teacup.listen(0); + const cPort = (cServer.address() as any).port; + const post = (payload: string, type = 'application/json') => + fetch(`http://127.0.0.1:${cPort}/api/big/echo`, { method: 'POST', headers: { 'content-type': type }, body: payload }); + const close = async () => { + await teacup.close(); + await teapot.close(); + }; + return { post, close, tPort }; +} + +describe('mesh RPC body near maxBodyBytes (#120)', () => { + it('a 1 MB JSON body reaches the teapot, and the channel stays open (T1)', async () => { + const { post, close } = await pair(); + try { + const res = await post(json(1_000_000)); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ length: 1_000_000 - WRAP }); + expect((await post(json(1_000_000))).status).toBe(200); + } finally { + await close(); + } + }); + + it('a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => { + const { post, close } = await pair(); + try { + const res = await post('"'.repeat(999_000), 'text/plain'); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ length: 999_000 }); + expect((await post('ok', 'text/plain')).status).toBe(200); + } finally { + await close(); + } + }); + + it('a body over maxBodyBytes is refused 413 by the teacup, and the channel stays open (T2)', async () => { + const { post, close } = await pair(); + try { + expect((await post(json(1_000_001))).status).toBe(413); + expect((await post(json(1_000))).status).toBe(200); + } finally { + await close(); + } + }); + + it("a user ws route on the same teapot still closes 1009 over maxWsMessageBytes (T3)", async () => { + const { close, tPort } = await pair(); + try { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`); + await new Promise((resolve) => ws.once('open', resolve)); + const closed = new Promise((resolve) => ws.once('close', (code) => resolve(code))); + ws.send('x'.repeat(1_048_577)); + expect(await closed).toBe(1009); + } finally { + await close(); + } + }); + + it('the control-channel cap follows a raised maxBodyBytes (T4)', async () => { + const { post, close } = await pair(4_000_000); + try { + const res = await post(json(3_900_000)); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ length: 3_900_000 - WRAP }); + } finally { + await close(); + } + }); +}); -- 2.54.1 From cad81223e544644d58077d383c891543573df05b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 23 Oct 2026 00:29:31 -0500 Subject: [PATCH 2/4] fix(mesh): give the control channel its own inbound queue bound (#148) The control channel also inherited limits.maxWsQueue (16 undelivered frames, close 1013) from #107. On Node, ws emits every frame of one socket read synchronously, so a teacup with more than 16 RPCs in flight sent a burst the teapot's queue refused: the link dropped and every pending request failed 503. Deno and Bun deliver one frame per task and did not trip. controlLimits() now also raises maxWsQueue for the control channel, to an internal 4,096 frames or maxWsQueue if larger, alongside the size bound from #120. The teapot's frame loop never awaits between frames, so the queue only holds one delivery burst, and one read (at most 64 KiB) holds fewer than 4,096 of the smallest control frame. The bound stays finite, so a peer flooding a channel nobody is reading is still cut off. No new option. User @Ws routes keep closing 1013 at maxWsQueue. Tests: 64 RPCs in one tick through app.fetch on one link all answer 200 (red on Node before), and a user route on the same teapot still closes 1013, on Node, Deno and Bun. Signed-off-by: Diego Resendez --- CHANGELOG.md | 8 ++++++ src/http/ws-core.ts | 24 ++++++++++++---- test/bun/mesh-large-body.test.ts | 46 +++++++++++++++++++++++++++++ test/deno/mesh-large-body.test.ts | 48 ++++++++++++++++++++++++++++++- test/mesh/large-body.test.ts | 47 ++++++++++++++++++++++++++++-- 5 files changed, 165 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba4040d..11333c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -242,6 +242,14 @@ npm treats versions as semver and semver forbids leading zeros. `1009`, on every Bun version, where Bun before 1.4 refused natively by dropping the connection (`1006`). +- **More than 16 mesh RPCs in flight on one link no longer drop the control channel** (#148). The + 16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On + Node, `ws` delivers every frame of one socket read at once, so a teacup sending a burst of RPCs + got the channel closed with `1013`, and every pending request failed with `503`. The control + channel now has its own queue bound of 4,096 frames, or `maxWsQueue` if that is larger, which is + 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. + - **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/http/ws-core.ts b/src/http/ws-core.ts index 7d18173..ceff854 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -42,15 +42,29 @@ export function wsMessageBytes(limits: Pick } /** - * The limits the mesh control channel's socket is bounded by (#120): `limits` with - * `maxWsMessageBytes` raised to the channel's own frame bound when that is larger. A user route - * never goes through this, so it keeps `maxWsMessageBytes` as configured. + * 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. + */ +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. */ export function controlLimits( limits: Pick | undefined, maxFrameBytes: number | undefined, -): Pick & { maxWsMessageBytes: number } { - return { ...limits, maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0) }; +): { maxWsMessageBytes: number; maxWsQueue: number } { + return { + maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0), + maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE), + }; } /** Throws when a WebSocket limit is present but not a positive safe integer (#107). */ diff --git a/test/bun/mesh-large-body.test.ts b/test/bun/mesh-large-body.test.ts index c6e5f9c..7e35bdb 100644 --- a/test/bun/mesh-large-body.test.ts +++ b/test/bun/mesh-large-body.test.ts @@ -24,6 +24,15 @@ class BigCtl { for await (const msg of inbound) yield `echo:${String(msg).length}`; })(); } + + // Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107). + @Ws('/stall') + stall() { + return (async function* () { + await new Promise(() => {}); + yield ''; + })(); + } } @Module({ mountpoint: '/api', controllers: [BigCtl] }) class TeapotModule {} @@ -134,3 +143,40 @@ test('mesh on Bun: the control-channel cap follows a raised maxBodyBytes (T4)', await close(); } }); + +test('mesh on Bun: 64 concurrent RPCs on one link all succeed (#148)', async () => { + const { post, close, teacup } = await pair(); + try { + // In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read, + // which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in. + const rpc = () => + teacup.fetch( + new Request('http://x/api/big/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: json(100), + }), + ); + const res = await Promise.all(Array.from({ length: 64 }, rpc)); + expect(res.map((r) => r.status)).toEqual(Array(64).fill(200)); + expect((await post(json(1_000))).status).toEqual(200); + } finally { + await close(); + } +}); + +test('mesh on Bun: a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => { + const { close, tPort } = await pair(); + try { + const code = await new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`); + ws.onopen = () => { + for (let i = 0; i < 17; i++) ws.send(String(i)); + }; + ws.onclose = (e) => resolve(e.code); + }); + expect(code).toEqual(1013); + } finally { + await close(); + } +}); diff --git a/test/deno/mesh-large-body.test.ts b/test/deno/mesh-large-body.test.ts index 064a4e1..cdd3d77 100644 --- a/test/deno/mesh-large-body.test.ts +++ b/test/deno/mesh-large-body.test.ts @@ -24,6 +24,15 @@ class BigCtl { for await (const msg of inbound) yield `echo:${String(msg).length}`; })(); } + + // Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107). + @Ws('/stall') + stall() { + return (async function* () { + await new Promise(() => {}); + yield ''; + })(); + } } @Module({ mountpoint: '/api', controllers: [BigCtl] }) class TeapotModule {} @@ -67,7 +76,7 @@ async function pair(maxBodyBytes?: number) { await c.server.shutdown(); await t.server.shutdown(); }; - return { post, close, tPort: t.port }; + return { post, close, tPort: t.port, teacup }; } const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) }); @@ -130,3 +139,40 @@ Deno.test('mesh on Deno: the control-channel cap follows a raised maxBodyBytes ( await close(); } }); + +Deno.test('mesh on Deno: 64 concurrent RPCs on one link all succeed (#148)', async () => { + const { post, close, teacup } = await pair(); + try { + // In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read, + // which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in. + const rpc = () => + teacup.fetch( + new Request('http://x/api/big/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: json(100), + }), + ); + const res = await Promise.all(Array.from({ length: 64 }, rpc)); + assertEquals(res.map((r) => r.status), Array(64).fill(200)); + assertEquals((await post(json(1_000))).status, 200); + } finally { + await close(); + } +}); + +Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => { + const { close, tPort } = await pair(); + try { + const code = await new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`); + ws.onopen = () => { + for (let i = 0; i < 17; i++) ws.send(String(i)); + }; + ws.onclose = (e) => resolve(e.code); + }); + assertEquals(code, 1013); + } finally { + await close(); + } +}); diff --git a/test/mesh/large-body.test.ts b/test/mesh/large-body.test.ts index 9ed8aba..0b9a953 100644 --- a/test/mesh/large-body.test.ts +++ b/test/mesh/large-body.test.ts @@ -7,7 +7,8 @@ // - a text body does not: every `"` or `\` doubles under JSON escaping, so a 999 KB text body // became a ~2 MB frame and the teapot hung up the whole channel with 1009 (T1b); // - a raised `maxBodyBytes` was capped at 1 MiB on the channel regardless (T4). -// The Deno and Bun twins live in test/deno and test/bun. +// Its queue bound had the same problem (#148): `maxWsQueue` (16) closed it 1013 under a burst of +// RPCs, which Node's `ws` delivers in one go. The Deno and Bun twins live in test/deno and test/bun. import { describe, it, expect } from 'vitest'; import WebSocket from 'ws'; import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index'; @@ -28,6 +29,15 @@ class BigCtl { for await (const msg of inbound) yield `echo:${String(msg).length}`; })(); } + + // Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107). + @Ws('/stall') + stall() { + return (async function* () { + await new Promise(() => {}); + yield ''; + })(); + } } @Module({ mountpoint: '/api', controllers: [BigCtl] }) class TeapotModule {} @@ -53,7 +63,7 @@ async function pair(maxBodyBytes?: number) { await teacup.close(); await teapot.close(); }; - return { post, close, tPort }; + return { post, close, tPort, teacup }; } describe('mesh RPC body near maxBodyBytes (#120)', () => { @@ -114,4 +124,37 @@ describe('mesh RPC body near maxBodyBytes (#120)', () => { await close(); } }); + it('64 concurrent RPCs on one link all succeed: the control channel has its own queue bound (#148)', async () => { + const { post, close, teacup } = await pair(); + try { + // In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read, + // which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in. + const rpc = () => + teacup.fetch( + new Request('http://x/api/big/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: json(100), + }), + ); + const res = await Promise.all(Array.from({ length: 64 }, rpc)); + expect(res.map((r) => r.status)).toEqual(Array(64).fill(200)); + expect((await post(json(1_000))).status).toBe(200); + } finally { + await close(); + } + }); + + it('a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => { + const { close, tPort } = await pair(); + try { + const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`); + await new Promise((resolve) => ws.once('open', resolve)); + const closed = new Promise((resolve) => ws.once('close', (code) => resolve(code))); + for (let i = 0; i < 17; i++) ws.send(String(i)); + expect(await closed).toBe(1013); + } finally { + await close(); + } + }); }); -- 2.54.1 From e98d5d33eb122c28c01ff60f8fadafd0843e02fc Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 23 Oct 2026 00:49:34 -0500 Subject: [PATCH 3/4] fix(mesh): size control frames for the worst escaping a body can get (#120) A 999,000-byte text/plain body of U+0001, within maxBodyBytes, still failed 503: the envelope carries a text body as a JSON string, each control character escapes to six characters, and the ~6 MB frame was over the 4,000,000 the channel was sized to. controlFrameLimit() is now 6 x maxBodyBytes plus 1 MiB for headers, params, query and the envelope: 7,048,576 at the 1 MB default. Six is the worst growth of any body byte; quotes and backslashes double, JSON numbers like 1e20 grow about fivefold, multipart Buffers at most fourfold, and non-ASCII text is not escaped. The fixed MAX_FRAME_CHARS goes away with it. Test (T1c) on Node, Deno and Bun: the control-character body now answers 200 and the channel stays open. Signed-off-by: Diego Resendez --- CHANGELOG.md | 15 ++++++----- src/mesh/teapot.ts | 43 ++++++++++++++----------------- test/bun/mesh-large-body.test.ts | 12 +++++++++ test/deno/mesh-large-body.test.ts | 12 +++++++++ test/mesh/envelope.test.ts | 4 +-- test/mesh/large-body.test.ts | 13 ++++++++++ 6 files changed, 67 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11333c4..91def26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -234,13 +234,14 @@ npm treats versions as semver and semver forbids leading zeros. above 1 MiB was capped at 1 MiB on the channel. Either way the teapot closed the whole channel with `1009`, and every request through that link failed with `503` until it reconnected. - The control channel is now bounded by the teapot's `limits.maxBodyBytes`: 4,000,000 bytes at the - 1 MB default, the figure its frame parser already used, and four times the body limit when that - is raised. `limits.maxWsMessageBytes` still governs every user `@Ws` route, unchanged. On Bun, - which takes one native payload limit for all sockets, a teapot raises that limit to the control - channel's bound, so an oversized frame on a user route is refused by the framework instead: still - `1009`, on every Bun version, where Bun before 1.4 refused natively by dropping the connection - (`1006`). + The control channel is now bounded by the teapot's `limits.maxBodyBytes`: six times the body + limit, the most JSON escaping can grow a body (a control character becomes `\u0001`), plus 1 MiB + for headers and the rest of the envelope. That is 7,048,576 bytes at the 1 MB default, up from + the frame parser's former fixed 4,000,000. `limits.maxWsMessageBytes` still governs every user + `@Ws` route, unchanged. On Bun, which takes one native payload limit for all sockets, a teapot + raises that limit to the control channel's bound, so an oversized frame on a user route is + refused by the framework instead: still `1009`, on every Bun version, where Bun before 1.4 + refused natively by dropping the connection (`1006`). - **More than 16 mesh RPCs in flight on one link no longer drop the control channel** (#148). The 16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 501f42e..d505275 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -41,34 +41,31 @@ export const MESH_CONTROL_DISABLED_REASON = */ const HANDSHAKE_TIMEOUT_MS = 10_000; -/** - * Largest control frame the teapot will parse, in characters. - * - * `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer - * is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse - * as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no - * documented ceiling on the platform sockets Deno and Bun provide). - * - * Sized for the 1 MB default body limit an RPC can legitimately carry, with room for the JSON - * overhead of the envelope around it. That overhead is not a constant: a JSON body re-encodes to - * about its own size, but a text body doubles wherever it holds a `"` or a backslash, since the - * envelope escapes it as a JSON string. {@link controlFrameLimit} scales this figure with a raised - * limit. - */ -const MAX_FRAME_CHARS = 4_000_000; - -/** The body limit {@link MAX_FRAME_CHARS} is sized for: `limits.maxBodyBytes`'s default. */ +/** `limits.maxBodyBytes`'s default, which a teapot without one is sized for. */ const DEFAULT_MAX_BODY_BYTES = 1_000_000; /** - * Largest control frame a teapot accepts when the largest body it may be sent is `maxBodyBytes` - * (#120): {@link MAX_FRAME_CHARS}, scaled by the same ratio for a body limit raised above the - * default. Never below it, because the frame also carries headers, params and query, which do not - * shrink with a lowered body limit. Applies to the control channel only: user WebSocket routes keep - * `limits.maxWsMessageBytes`. + * The most a body byte can grow inside an `rpc-req` envelope. The envelope is JSON, and a text + * body travels as a JSON string, so a control character (`\u0001`) becomes the six characters of its + * escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as + * `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and + * non-ASCII text is not escaped at all. + */ +const WORST_ESCAPE = 6; + +/** Room in a frame for everything but the body: headers, params, query, url and the envelope. */ +const ENVELOPE_HEADROOM = 1_048_576; + +/** + * Largest control frame a teapot accepts, in characters, when the largest body it may be sent is + * `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`. */ export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number { - return Math.max(MAX_FRAME_CHARS, Math.ceil((MAX_FRAME_CHARS / DEFAULT_MAX_BODY_BYTES) * maxBodyBytes)); + return WORST_ESCAPE * maxBodyBytes + ENVELOPE_HEADROOM; } /** Assemble a {@link Manifest} from exported step tokens and buffered routes. */ diff --git a/test/bun/mesh-large-body.test.ts b/test/bun/mesh-large-body.test.ts index 7e35bdb..b2cdd97 100644 --- a/test/bun/mesh-large-body.test.ts +++ b/test/bun/mesh-large-body.test.ts @@ -98,6 +98,18 @@ test('mesh on Bun: a text body that JSON escaping doubles still reaches the teap } }); +test('mesh on Bun: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => { + const { post, close } = await pair(); + try { + const res = await post('\u0001'.repeat(999_000), 'text/plain'); + expect(res.status).toEqual(200); + expect(await res.json()).toEqual({ length: 999_000 }); + expect((await post('ok', 'text/plain')).status).toEqual(200); + } finally { + await close(); + } +}); + test('mesh on Bun: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => { const { post, close, teacup } = await pair(); try { diff --git a/test/deno/mesh-large-body.test.ts b/test/deno/mesh-large-body.test.ts index cdd3d77..b54d714 100644 --- a/test/deno/mesh-large-body.test.ts +++ b/test/deno/mesh-large-body.test.ts @@ -105,6 +105,18 @@ Deno.test('mesh on Deno: a text body that JSON escaping doubles still reaches th } }); +Deno.test('mesh on Deno: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => { + const { post, close } = await pair(); + try { + const res = await post('\u0001'.repeat(999_000), 'text/plain'); + assertEquals(res.status, 200); + assertEquals(await res.json(), { length: 999_000 }); + assertEquals((await post('ok', 'text/plain')).status, 200); + } finally { + await close(); + } +}); + Deno.test('mesh on Deno: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => { const { post, close } = await pair(); try { diff --git a/test/mesh/envelope.test.ts b/test/mesh/envelope.test.ts index df375ad..8dcffe1 100644 --- a/test/mesh/envelope.test.ts +++ b/test/mesh/envelope.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; import { envelopeFrom } from '../../src/mesh/teacup'; -import { createMeshControl } from '../../src/mesh/teapot'; +import { controlFrameLimit, createMeshControl } from '../../src/mesh/teapot'; import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol'; import { Bus } from '../../src/bus'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; @@ -139,7 +139,7 @@ describe('teapot hardening', () => { const fake = fakeSocket(); const running = control().handle(fake.socket as never); - fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`); + fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(controlFrameLimit() + 1)}"}`); await running; expect(fake.closes[0]?.code).toBe(1009); diff --git a/test/mesh/large-body.test.ts b/test/mesh/large-body.test.ts index 0b9a953..7d3c370 100644 --- a/test/mesh/large-body.test.ts +++ b/test/mesh/large-body.test.ts @@ -91,6 +91,19 @@ describe('mesh RPC body near maxBodyBytes (#120)', () => { } }); + it('a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => { + const { post, close } = await pair(); + try { + // `\u0001` re-encodes as the six characters `\u0001`: the worst escaping a body can get. + const res = await post('\u0001'.repeat(999_000), 'text/plain'); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ length: 999_000 }); + expect((await post('ok', 'text/plain')).status).toBe(200); + } finally { + await close(); + } + }); + it('a body over maxBodyBytes is refused 413 by the teacup, and the channel stays open (T2)', async () => { const { post, close } = await pair(); try { -- 2.54.1 From 8f73779a210e7969069c5684d66920bf9559b659 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 23 Oct 2026 00:52:20 -0500 Subject: [PATCH 4/4] fix(mesh): hold the control channel to hello size until the peer authenticates boundInbound(socket, meshBounds) runs before ensureBooted() and before the hello is checked, and meshBounds allowed 4,096 queued frames of up to 7 MB each. During a slow boot nothing reads that queue, so an unauthenticated peer could make the process buffer tens of GB. The control channel's bounds are now phased (controlBounds() replaces controlLimits()): - until the hello is accepted: frames of at most HELLO_FRAME_BYTES (64 KiB) and the default 16-frame queue, so about 1 MiB per connection; - after: the frame bound from #120 and the queue bound from #148. boundInbound takes the second set as an optional `widened` argument and keeps the switch on the bounded socket under a Symbol.for key. The teapot calls widenInbound() when the handshake succeeds. The teapot's own parse check follows the same phases, so a standalone createMeshControl also refuses a pre-auth frame over hello size. This is an auth-phased bound rather than a total-bytes cap: the only unauthenticated frame with a purpose is the hello, and phasing keeps the trusted path free of a second accounting rule. No new option. On Node the control path's native maxPayload stays at the authed bound, because ws cannot change it per phase. A pre-auth peer can still make ws assemble one frame of up to that size before boundInbound closes the connection with 1009. That frame is transient and never queued. Tests: during a delayed boot, a 1 MB pre-auth frame closes 1009 at once and a flood closes 1013 within 17 frames; after the hello, large frames and a 64-ping burst are accepted. On Node, Deno and Bun, an unauthenticated 1 MB frame over a real socket closes 1009. The #148 64-RPC test stays green. Signed-off-by: Diego Resendez --- CHANGELOG.md | 6 ++ src/app/index.ts | 18 +++--- src/http/ws-core.ts | 72 ++++++++++++++++----- src/http/ws.ts | 14 ++--- src/mesh/teapot.ts | 16 +++-- test/bun/mesh-large-body.test.ts | 14 +++++ test/deno/mesh-large-body.test.ts | 14 +++++ test/mesh/control-preauth.test.ts | 100 ++++++++++++++++++++++++++++++ test/mesh/large-body.test.ts | 12 ++++ 9 files changed, 231 insertions(+), 35 deletions(-) create mode 100644 test/mesh/control-preauth.test.ts 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(); + } + }); }); -- 2.54.1