fix(mesh): cap what an unauthenticated control peer can send on Node (#120) #157

Merged
chrnx merged 1 commits from fix/mesh-preauth-wire-cap into develop 2026-10-24 19:45:34 +00:00
4 changed files with 111 additions and 4 deletions

No files matched your search

+7
View File
@@ -271,6 +271,13 @@ npm treats versions as semver and semver forbids leading zeros.
refused by the framework instead: still `1009`, on every Bun version, where Bun before 1.4
refused natively by dropping the connection (`1006`).
The larger bound applies only once the peer's `hello` is accepted. Until then the channel takes
hello-sized frames (64 KiB), and on Node a peer that sends more than that before its hello is
dropped before `ws` assembles the frame. Bun and Deno have no per-socket limit for the framework
to hold that to, so there an unauthenticated peer can still make the teapot receive one frame up
to the channel's bound before refusing it. If untrusted peers can reach a Bun or Deno teapot's
`/__mesh__/control`, limit frame size at the proxy in front of it.
- **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
+11 -2
View File
@@ -174,12 +174,14 @@ function exceedsBytes(msg: unknown, max: number): boolean {
* 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.
* mesh control channel starts at hello size and widens once its peer authenticates. `onWiden` runs
* then too, for an adapter that holds a bound of its own until that point.
*/
export function boundInbound(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
widened?: InboundLimits,
onWiden?: () => void,
): WsSocket {
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
@@ -189,7 +191,14 @@ export function boundInbound(
return Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }),
...(widened && {
[WIDEN_INBOUND]: {
value: () => {
fanout.widen(widened);
onWiden?.();
},
},
}),
}) as WsSocket;
}
+39 -2
View File
@@ -8,6 +8,7 @@ import {
boundInbound,
controlBounds,
wsMessageBytes,
HELLO_FRAME_BYTES,
WS_HIGH_WATER_MARK,
type WsSocket,
type WsRequest,
@@ -54,7 +55,8 @@ function handleMeshUpgrade(
// 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.
// as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size, and
// `capPreAuthBytes` keeps `ws` from assembling anything larger first.
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
@@ -63,13 +65,48 @@ 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.preAuth, bounds.authed);
const lift = capPreAuthBytes(ws, socket, head);
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed, lift);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
return true;
}
/** Bytes an unauthenticated control peer may send: one hello-sized frame plus headers and a close frame. */
const PRE_AUTH_WIRE_BYTES = HELLO_FRAME_BYTES + 1024;
/**
* Closes a control peer that sends more than a hello's worth of bytes before its hello is accepted.
* `maxPayload` is set once per `WebSocketServer`, and the control channel's must fit an
* authenticated RPC (about 7 MB at the defaults), so without this an unauthenticated peer could
* make `ws` assemble a frame that size before `boundInbound` sees it and refuses it. This counts
* raw socket bytes instead, so the peer is closed `1009` about 64 KiB in. Returns the function that
* stops counting, for when the peer authenticates.
*
* Installed in the `handleUpgrade` callback, after `ws` has attached its own `data` listener: a
* listener added earlier would switch the socket to flowing mode and lose chunks `ws` never saw.
*/
function capPreAuthBytes(ws: any, socket: any, head: Buffer): () => void {
let received = head.length;
const count = (chunk: Buffer) => {
received += chunk.length;
if (received > PRE_AUTH_WIRE_BYTES) {
socket.off('data', count);
// 1009, as every other runtime closes an oversized frame. Paused, so `ws` reads nothing more
// of it; `end` still flushes the close frame. `ws` destroys the socket at its close timeout.
ws.close(1009, 'message too big');
socket.pause();
socket.end();
}
};
socket.on('data', count);
return () => socket.off('data', count);
}
/** Accepts an upgrade to the reserved mesh path on an app without a control channel, then closes it 1008. */
function refuseMeshUpgrade(wss: any, req: http.IncomingMessage, socket: any, head: Buffer): void {
if (!wss) {
+54
View File
@@ -98,3 +98,57 @@ describe('mesh control channel before authentication', () => {
await app.close();
});
});
// The Node adapter's own half: `ws` assembles a frame up to its `maxPayload` before `boundInbound`
// sees it, and the control channel's must fit an authenticated RPC (~7 MB). A raw client shows
// what `ws` does with a frame it has only started to receive.
describe('mesh control channel before authentication, on Node', () => {
@Module({ mountpoint: '/api', steps: [Cfg] })
class NodeTeapot {}
/** Upgrades a raw TCP socket to the control path and resolves once the `101` is in. */
async function rawControl(port: number) {
const { connect } = await import('node:net');
const sock = connect(port, '127.0.0.1');
let closed = false;
const received: Buffer[] = [];
sock.on('close', () => (closed = true));
sock.on('error', () => {});
sock.write(
`GET ${MESH_CONTROL_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
);
await new Promise<void>((resolve) => sock.once('data', () => resolve()));
sock.on('data', (chunk: Buffer) => received.push(chunk));
sock.on('end', () => sock.end());
return { sock, closed: () => closed, received: () => Buffer.concat(received) };
}
/** The start of a masked text frame announcing `length` payload bytes (64-bit length form). */
const frameHeader = (length: number) => {
const header = Buffer.alloc(14);
header[0] = 0x81; // FIN, text
header[1] = 0x80 | 127; // masked, 64-bit length follows
header.writeBigUInt64BE(BigInt(length), 2);
return header; // mask key: the last four bytes, zero
};
it('closes 1009 a peer that sends more than a hello before its hello, instead of assembling the frame', async () => {
const app = createApp({ modules: [NodeTeapot], experimental: true, mesh: { secret: 's3cr3t' } });
const server = await app.listen(0);
const { sock, closed, received } = await rawControl((server.address() as { port: number }).port);
try {
// 5 MB announced, under the authenticated bound; 200 KiB of it sent, then nothing.
sock.write(frameHeader(5_000_000));
sock.write(Buffer.alloc(200 * 1024, 0x78));
await new Promise((resolve) => setTimeout(resolve, 200));
expect(closed()).toBe(true);
const close = received();
expect(close[0]).toBe(0x88); // FIN, close
expect(close.readUInt16BE(2)).toBe(1009);
} finally {
sock.destroy();
await app.close();
}
});
});