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 <diego.resendez@zero-oneit.com>
This commit is contained in:
10 files changed
+536
-18
No files matched your search
+60
-10
@@ -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<http.Server> => {
|
||||
@@ -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<void>,
|
||||
getMeshControl: () => MeshControl | undefined,
|
||||
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
|
||||
{
|
||||
limits,
|
||||
trustProxy,
|
||||
meshBounds,
|
||||
}: {
|
||||
limits?: RequestLimits;
|
||||
trustProxy?: boolean;
|
||||
meshBounds: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>;
|
||||
},
|
||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||
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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -41,6 +41,18 @@ export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'>
|
||||
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<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | undefined,
|
||||
maxFrameBytes: number | undefined,
|
||||
): Pick<RequestLimits, 'maxWsQueue'> & { 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) {
|
||||
|
||||
+20
-4
@@ -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
|
||||
|
||||
+36
-4
@@ -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<unknown>;
|
||||
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
|
||||
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<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
maxFrameChars: number,
|
||||
): Promise<void> {
|
||||
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<void>;
|
||||
} {
|
||||
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<void> {
|
||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
|
||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes, maxFrameChars);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user