fix(mesh): hold the control channel to hello size until the peer authenticates
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / runtimes (edge) (pull_request) Successful in 14s

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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 01:13:37 -05:00
1 parent 6003280c83
commit dcbfafd47b
9 files changed
+231 -35

No files matched your search

+11 -7
View File
@@ -11,7 +11,7 @@ import { trustedProxyClient } from '../http/peer';
import { answerFetchProbe, buildFetch } from '../http/web';
import {
boundInbound,
controlLimits,
controlBounds,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
@@ -392,7 +392,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,
@@ -1548,10 +1548,10 @@ function nativeWsBytes(
mesh: MeshConfig | undefined,
registry: Registry,
limits: RequestLimits | undefined,
meshBounds: { maxWsMessageBytes: number },
meshBounds: ReturnType<typeof controlBounds>,
): number {
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
return servesControl ? meshBounds.maxWsMessageBytes : wsMessageBytes(limits);
return servesControl ? meshBounds.authed.maxWsMessageBytes : wsMessageBytes(limits);
}
/**
@@ -1783,7 +1783,7 @@ function buildAppUpgrade(
}: {
limits?: RequestLimits;
trustProxy?: boolean;
meshBounds: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>;
meshBounds: ReturnType<typeof controlBounds>;
},
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
@@ -1794,7 +1794,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
@@ -1806,7 +1807,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
+56 -16
View File
@@ -42,31 +42,60 @@ export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'>
}
/**
* 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<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | 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<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
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
+7 -7
View File
@@ -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) => {
+11 -5
View File
@@ -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;
}