Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd85bf67bc | ||
|
|
de798771e4 |
No files matched your search
+14
-7
@@ -90,13 +90,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
|
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.
|
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
|
The control channel is now bounded by the teapot's `limits.maxBodyBytes`: six times the body
|
||||||
1 MB default, the figure its frame parser already used, and four times the body limit when that
|
limit, the most JSON escaping can grow a body (a control character becomes `\u0001`), plus 1 MiB
|
||||||
is raised. `limits.maxWsMessageBytes` still governs every user `@Ws` route, unchanged. On Bun,
|
for headers and the rest of the envelope. That is 7,048,576 bytes at the 1 MB default, up from
|
||||||
which takes one native payload limit for all sockets, a teapot raises that limit to the control
|
the frame parser's former fixed 4,000,000. `limits.maxWsMessageBytes` still governs every user
|
||||||
channel's bound, so an oversized frame on a user route is refused by the framework instead: still
|
`@Ws` route, unchanged. On Bun, which takes one native payload limit for all sockets, a teapot
|
||||||
`1009`, on every Bun version, where Bun before 1.4 refused natively by dropping the connection
|
raises that limit to the control channel's bound, so an oversized frame on a user route is
|
||||||
(`1006`).
|
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
|
- **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
|
16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On
|
||||||
@@ -106,6 +107,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
|
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.
|
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.
|
||||||
|
|
||||||
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
||||||
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
||||||
was served. Containment now compares real paths: the requested file, and a directory's
|
was served. Containment now compares real paths: the requested file, and a directory's
|
||||||
|
|||||||
+11
-7
@@ -10,7 +10,7 @@ import type { HttpOptions } from '../http';
|
|||||||
import { buildFetch } from '../http/web';
|
import { buildFetch } from '../http/web';
|
||||||
import {
|
import {
|
||||||
boundInbound,
|
boundInbound,
|
||||||
controlLimits,
|
controlBounds,
|
||||||
validateWsLimits,
|
validateWsLimits,
|
||||||
WS_MAX_MESSAGE_BYTES,
|
WS_MAX_MESSAGE_BYTES,
|
||||||
wsMessageBytes,
|
wsMessageBytes,
|
||||||
@@ -335,7 +335,7 @@ export function createApp(opts: {
|
|||||||
);
|
);
|
||||||
// Known at construction, unlike the control channel itself, because `app.upgrade` must bound a
|
// Known at construction, unlike the control channel itself, because `app.upgrade` must bound a
|
||||||
// socket before it awaits the boot (#120).
|
// 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, {
|
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
|
||||||
limits: opts.limits,
|
limits: opts.limits,
|
||||||
meshBounds,
|
meshBounds,
|
||||||
@@ -1242,10 +1242,10 @@ function nativeWsBytes(
|
|||||||
mesh: MeshConfig | undefined,
|
mesh: MeshConfig | undefined,
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
limits: RequestLimits | undefined,
|
limits: RequestLimits | undefined,
|
||||||
meshBounds: { maxWsMessageBytes: number },
|
meshBounds: ReturnType<typeof controlBounds>,
|
||||||
): number {
|
): number {
|
||||||
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
|
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
|
||||||
return servesControl ? meshBounds.maxWsMessageBytes : wsMessageBytes(limits);
|
return servesControl ? meshBounds.authed.maxWsMessageBytes : wsMessageBytes(limits);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1431,7 +1431,7 @@ function buildAppUpgrade(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
ensureBooted: () => Promise<void>,
|
ensureBooted: () => Promise<void>,
|
||||||
getMeshControl: () => MeshControl | undefined,
|
getMeshControl: () => MeshControl | undefined,
|
||||||
bounds: { limits?: RequestLimits; meshBounds: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> },
|
bounds: { limits?: RequestLimits; meshBounds: ReturnType<typeof controlBounds> },
|
||||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||||
let wsRoutes: WsRouteDef[] | undefined;
|
let wsRoutes: WsRouteDef[] | undefined;
|
||||||
|
|
||||||
@@ -1441,7 +1441,8 @@ function buildAppUpgrade(
|
|||||||
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
|
// 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.
|
// 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
|
// 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;
|
let path: string;
|
||||||
|
|
||||||
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
|
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
|
||||||
@@ -1453,7 +1454,10 @@ function buildAppUpgrade(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ready = boundInbound(socket, path === MESH_CONTROL_PATH ? bounds.meshBounds : bounds.limits);
|
const ready =
|
||||||
|
path === MESH_CONTROL_PATH
|
||||||
|
? boundInbound(socket, bounds.meshBounds.preAuth, bounds.meshBounds.authed)
|
||||||
|
: boundInbound(socket, bounds.limits);
|
||||||
|
|
||||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||||
|
|
||||||
|
|||||||
+56
-16
@@ -42,31 +42,60 @@ export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Undelivered inbound frames the mesh control channel may hold (#148), in place of
|
* Undelivered inbound frames the mesh control channel may hold once its peer is authenticated
|
||||||
* `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never awaits between
|
* (#148), in place of `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never
|
||||||
* frames, so its queue only ever holds one delivery burst: `ws` emits every frame of one socket
|
* awaits between frames, so its queue only ever holds one delivery burst: `ws` emits every frame of
|
||||||
* read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control frame
|
* one socket read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control
|
||||||
* (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the
|
* 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
|
* 16-frame user default closed with 1013.
|
||||||
* nothing reads it — before the boot finishes, say — is still cut off.
|
|
||||||
*/
|
*/
|
||||||
const CONTROL_QUEUE = 4096;
|
const CONTROL_QUEUE = 4096;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The limits the mesh control channel's socket is bounded by: `limits` with `maxWsMessageBytes`
|
* Largest frame the mesh control channel accepts before its peer's `hello` is accepted. A hello
|
||||||
* raised to the channel's own frame bound (#120) and `maxWsQueue` to {@link CONTROL_QUEUE} (#148),
|
* is a version and a secret; nothing larger has a reason to arrive first.
|
||||||
* each only when larger. A user route never goes through this, so it keeps both as configured.
|
|
||||||
*/
|
*/
|
||||||
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,
|
limits: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | undefined,
|
||||||
maxFrameBytes: number | undefined,
|
maxFrameBytes: number | undefined,
|
||||||
): { maxWsMessageBytes: number; maxWsQueue: number } {
|
): { preAuth: InboundLimits; authed: InboundLimits } {
|
||||||
return {
|
return {
|
||||||
maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0),
|
preAuth: { maxWsMessageBytes: HELLO_FRAME_BYTES, maxWsQueue: DEFAULT_MAX_WS_QUEUE },
|
||||||
maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_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). */
|
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
|
||||||
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
||||||
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
|
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
|
* 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.
|
* 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.
|
* 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(
|
export function boundInbound(
|
||||||
socket: WsSocket,
|
socket: WsSocket,
|
||||||
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
||||||
|
widened?: InboundLimits,
|
||||||
): WsSocket {
|
): WsSocket {
|
||||||
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
||||||
|
|
||||||
@@ -113,6 +146,7 @@ export function boundInbound(
|
|||||||
|
|
||||||
return Object.create(socket, {
|
return Object.create(socket, {
|
||||||
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
||||||
|
...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }),
|
||||||
}) as WsSocket;
|
}) as WsSocket;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,12 +160,18 @@ class InboundFanout {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly socket: WsSocket,
|
private readonly socket: WsSocket,
|
||||||
private readonly maxBytes: number,
|
private maxBytes: number,
|
||||||
private readonly maxQueue: number,
|
private maxQueue: number,
|
||||||
) {
|
) {
|
||||||
this.first = this.add();
|
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
|
* 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
|
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
|
||||||
|
|||||||
+7
-7
@@ -6,7 +6,7 @@ import {
|
|||||||
matchWsRoute,
|
matchWsRoute,
|
||||||
trackUntil,
|
trackUntil,
|
||||||
boundInbound,
|
boundInbound,
|
||||||
controlLimits,
|
controlBounds,
|
||||||
wsMessageBytes,
|
wsMessageBytes,
|
||||||
type WsSocket,
|
type WsSocket,
|
||||||
type WsRequest,
|
type WsRequest,
|
||||||
@@ -50,10 +50,10 @@ function handleMeshUpgrade(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// An RPC carries a whole request body, so the channel is bounded by the teapot's body limit
|
// An RPC carries a whole request body, so once the peer authenticates the channel is bounded by
|
||||||
// rather than `maxWsMessageBytes` (#120). `wss` is built with that bound as `maxPayload`, and
|
// the teapot's body limit rather than `maxWsMessageBytes` (#120). `wss` is built with that bound
|
||||||
// `boundInbound` repeats it on the decoded text, as it does for every route.
|
// as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size.
|
||||||
const bounds = controlLimits(limits, meshControl.maxFrameBytes);
|
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
|
||||||
|
|
||||||
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
|
// 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.
|
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
|
||||||
@@ -61,7 +61,7 @@ function handleMeshUpgrade(
|
|||||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
// 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.
|
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
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);
|
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||||
});
|
});
|
||||||
@@ -126,7 +126,7 @@ export function attachWs(
|
|||||||
WebSocketServer && meshControl
|
WebSocketServer && meshControl
|
||||||
? new WebSocketServer({
|
? new WebSocketServer({
|
||||||
noServer: true,
|
noServer: true,
|
||||||
maxPayload: controlLimits(limits, meshControl.maxFrameBytes).maxWsMessageBytes,
|
maxPayload: controlBounds(limits, meshControl.maxFrameBytes).authed.maxWsMessageBytes,
|
||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
server.on('upgrade', (req, socket, head) => {
|
server.on('upgrade', (req, socket, head) => {
|
||||||
|
|||||||
+29
-26
@@ -3,7 +3,7 @@
|
|||||||
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
|
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import type { Bus } from '../bus';
|
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 type { ResponseShape } from '../pipeline';
|
||||||
import { isHttpError } from '../signals';
|
import { isHttpError } from '../signals';
|
||||||
import {
|
import {
|
||||||
@@ -29,34 +29,33 @@ export const MESH_CONTROL_PATH = '/__mesh__/control';
|
|||||||
*/
|
*/
|
||||||
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||||
|
|
||||||
/**
|
/** `limits.maxBodyBytes`'s default, which a teapot without one is sized for. */
|
||||||
* 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. */
|
|
||||||
const DEFAULT_MAX_BODY_BYTES = 1_000_000;
|
const DEFAULT_MAX_BODY_BYTES = 1_000_000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Largest control frame a teapot accepts when the largest body it may be sent is `maxBodyBytes`
|
* The most a body byte can grow inside an `rpc-req` envelope. The envelope is JSON, and a text
|
||||||
* (#120): {@link MAX_FRAME_CHARS}, scaled by the same ratio for a body limit raised above the
|
* body travels as a JSON string, so a control character (`\u0001`) becomes the six characters of its
|
||||||
* default. Never below it, because the frame also carries headers, params and query, which do not
|
* escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as
|
||||||
* shrink with a lowered body limit. Applies to the control channel only: user WebSocket routes keep
|
* `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and
|
||||||
* `limits.maxWsMessageBytes`.
|
* 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 — 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 {
|
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. */
|
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
||||||
@@ -123,6 +122,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
|
|||||||
return false;
|
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(
|
socket.send(
|
||||||
encode({
|
encode({
|
||||||
type: 'manifest',
|
type: 'manifest',
|
||||||
@@ -211,8 +213,9 @@ async function serveFrames(
|
|||||||
for await (const data of socket.inbound) {
|
for await (const data of socket.inbound) {
|
||||||
const raw = String(data);
|
const raw = String(data);
|
||||||
|
|
||||||
// Checked before `decode`, because decoding is the expensive part being defended.
|
// Checked before `decode`, because decoding is the expensive part being defended. Until the
|
||||||
if (raw.length > maxFrameChars) {
|
// 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');
|
socket.close(1009, 'mesh frame too large');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 () => {
|
test('mesh on Bun: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
|
||||||
const { post, close, teacup } = await pair();
|
const { post, close, teacup } = await pair();
|
||||||
try {
|
try {
|
||||||
@@ -180,3 +192,17 @@ test('mesh on Bun: a user ws route on the same teapot still closes 1013 at maxWs
|
|||||||
await close();
|
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<number>((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();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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 () => {
|
Deno.test('mesh on Deno: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
|
||||||
const { post, close } = await pair();
|
const { post, close } = await pair();
|
||||||
try {
|
try {
|
||||||
@@ -176,3 +188,17 @@ Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1013 at
|
|||||||
await close();
|
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<number>((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();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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<unknown>();
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
|
|||||||
import { WebSocketServer } from 'ws';
|
import { WebSocketServer } from 'ws';
|
||||||
import { connectLink } from '../../src/mesh/link';
|
import { connectLink } from '../../src/mesh/link';
|
||||||
import { envelopeFrom } from '../../src/mesh/teacup';
|
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 { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
|
||||||
import { Bus } from '../../src/bus';
|
import { Bus } from '../../src/bus';
|
||||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||||
@@ -139,7 +139,7 @@ describe('teapot hardening', () => {
|
|||||||
const fake = fakeSocket();
|
const fake = fakeSocket();
|
||||||
const running = control().handle(fake.socket as never);
|
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;
|
await running;
|
||||||
|
|
||||||
expect(fake.closes[0]?.code).toBe(1009);
|
expect(fake.closes[0]?.code).toBe(1009);
|
||||||
|
|||||||
@@ -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 () => {
|
it('a body over maxBodyBytes is refused 413 by the teacup, and the channel stays open (T2)', async () => {
|
||||||
const { post, close } = await pair();
|
const { post, close } = await pair();
|
||||||
try {
|
try {
|
||||||
@@ -157,4 +170,16 @@ describe('mesh RPC body near maxBodyBytes (#120)', () => {
|
|||||||
await close();
|
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<number>((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();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user