From 0540bef07b77e75d0dd21dcfb4f3538038d16df9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 9 Oct 2026 13:39:46 -0500 Subject: [PATCH] feat(ws)!: bound inbound WebSocket message size and queue Inbound WebSocket traffic was unbounded per connection: Node used ws's 100 MiB default payload, the other runtimes had no cap of their own, and the queue behind `inbound` was an unbounded channel on every runtime, so one client could exhaust memory with large messages or a slow consumer. Add `limits.maxWsMessageBytes` (default 1 MiB, close 1009) and `limits.maxWsQueue` (default 16 unread messages, close 1013), as recorded in D1. Both are server-wide and validated by createApp, which throws a TypeError for anything but a positive integer. Enforcement is shared in `boundInbound`, which subscribes immediately and replaces the subscribe-before-boot trick in app.upgrade. Node and Bun also get the native pre-buffer cap; Bun drops the connection without a close frame, so its peer sees 1006, which is documented and tested. Deno and workerd expose no such option and check the size after receipt. BREAKING CHANGE: messages over 1 MiB now close the connection with 1009, and a connection with 16 unread inbound messages is closed with 1013 on the next one, including a handler that never reads `inbound`. Closes #107 Signed-off-by: Diego Resendez --- CHANGELOG.md | 24 ++++ README.md | 2 +- src/app/index.ts | 36 +++-- src/bun.ts | 9 +- src/http/server.ts | 2 +- src/http/types.ts | 25 ++++ src/http/ws-core.ts | 144 ++++++++++++++++++- src/http/ws.ts | 49 ++++--- test/bun/ws.test.ts | 64 +++++++++ test/deno/ws.test.ts | 76 ++++++++++ test/edge/run.ts | 36 ++++- test/edge/worker.ts | 17 ++- test/ws-limits.test.ts | 312 +++++++++++++++++++++++++++++++++++++++++ 13 files changed, 762 insertions(+), 34 deletions(-) create mode 100644 test/ws-limits.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 866836d..3c3b4e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,30 @@ npm treats versions as semver and semver forbids leading zeros. ## [Unreleased] +### Breaking + +- **Inbound WebSocket messages are capped at 1 MiB by default** (#107). Node used `ws`'s own + default of 100 MiB, and Deno, Bun and the edge applied no cap of their own, so one client could + make the server hold a message of any size the runtime would accept. A larger message now closes + the connection with `1009` (`message too large`). Raise it with `limits.maxWsMessageBytes`. + +- **A connection with 16 unread inbound messages is closed on the 17th** (#107), with `1013` + (`inbound queue full`). The queue behind `inbound` was unbounded on every runtime, so a handler + that read slowly — or never — let a client grow it without limit. This also reaches a `@Ws` + handler that never reads `inbound` at all: on Node those frames used to be discarded, and they + now count. Raise the bound with `limits.maxWsQueue`. + +### Added + +- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound + WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp` + throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message + before buffering it; Bun does so by dropping the connection, so its peer sees `1006` rather than + `1009`. Deno and workerd expose no such option, so there the message is received in full and then + refused, and its memory is bounded by the platform's own cap. Worst-case buffered inbound memory is + about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and + Bun have no connection cap, so set one at the platform or proxy there. + ### Fixed - **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard diff --git a/README.md b/README.md index 92f2514..4e02c1c 100644 --- a/README.md +++ b/README.md @@ -141,7 +141,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. -- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. +- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun drops the connection, so its peer sees `1006`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. - **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. diff --git a/src/app/index.ts b/src/app/index.ts index 8241506..01fc592 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -8,7 +8,17 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; import { buildFetch } from '../http/web'; -import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core'; +import { + boundInbound, + validateWsLimits, + WS_MAX_MESSAGE_BYTES, + wsMessageBytes, + matchWsRoute, + runWsConnection, + trackUntil, + type WsRequest, + type WsSocket, +} from '../http/ws-core'; import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; @@ -195,6 +205,8 @@ export function createApp(opts: { ); } + validateWsLimits(opts.limits); + const bus = new Bus(); const logger = opts.logger ?? createDefaultLogger(); if (opts.logRequests) logRequests(bus, logger); @@ -318,7 +330,7 @@ export function createApp(opts: { devRoutes, () => remoteRoutes, ); - const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl); + const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits); const listen = async (port: number): Promise => { const deps = pipelineDeps; @@ -387,7 +399,7 @@ export function createApp(opts: { return wrapped; }; - return { + const app: App = { listen, close, handleSignals, @@ -405,6 +417,10 @@ export function createApp(opts: { bus, logger, }; + + return Object.assign(app, { + [WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits), + }); } /** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */ @@ -1275,18 +1291,16 @@ function buildAppUpgrade( streams: Set<() => void>, ensureBooted: () => Promise, getMeshControl: () => MeshControl | undefined, + limits?: RequestLimits, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { - // Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed 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 frames = socket.inbound[Symbol.asyncIterator](); - const ready: WsSocket = Object.create(socket, { - inbound: { value: { [Symbol.asyncIterator]: () => frames } }, - }) as WsSocket; + // Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed + // 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 diff --git a/src/bun.ts b/src/bun.ts index 99fec60..286d9b7 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -1,7 +1,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; -import type { WsSocket, WsRequest } from './http/ws-core'; +import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core'; import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; import { closeWithDeadline } from './http/shutdown'; @@ -15,6 +15,7 @@ interface BunServerWebSocket { terminate?(): void; } interface BunWebSocketHandler { + maxPayloadLength?: number; open?(ws: BunServerWebSocket): void; message(ws: BunServerWebSocket, message: string | Uint8Array): void; close?(ws: BunServerWebSocket, code: number, reason: string): void; @@ -103,6 +104,12 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis return app.fetch(request); }, websocket: { + // The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before + // assembling it. It drops the connection without a close frame, so the peer sees 1006 rather + // than 1009 — verified on Bun 1.3, and the price of not buffering the message at all. + // `app.upgrade` checks the same bound again on the decoded text. + maxPayloadLength: + (app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES, open(ws) { const { wsReq } = ws.data as BunConnData; diff --git a/src/http/server.ts b/src/http/server.ts index 5ae0d39..bf82c08 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -79,7 +79,7 @@ export function createHttpServer( server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl, opts?.streams); + attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits); return server; } diff --git a/src/http/types.ts b/src/http/types.ts index 49c646b..5c432de 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -16,6 +16,31 @@ export interface RequestLimits { headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 maxParts?: number; // default 1000 + /** + * Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default + * `1_048_576` (1 MiB). A larger message closes the connection with `1009` (`message too large`); + * a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws. + * + * Node and Bun refuse an oversized frame before buffering it (`ws`'s `maxPayload`, Bun's + * `maxPayloadLength`). Bun then drops the connection without a close frame, so on Bun the peer + * sees `1006` instead of `1009`. Deno and the edge offer no such option: there the runtime + * receives the whole message first, so its memory is bounded by the platform's own cap, and this + * limit is checked after receipt — the connection still closes `1009`. + * + * Server-level only; there is no per-route override. + */ + maxWsMessageBytes?: number; + /** + * Inbound WebSocket messages a connection may hold that the handler has not read yet. Default + * `16`. One more closes the connection with `1013` (`inbound queue full`) rather than dropping + * anything, so a handler that never reads `inbound` is closed once its peer sends 17 messages. + * Must be a positive integer, or `createApp` throws. Applies on every runtime. + * + * Worst-case buffered inbound memory is about `maxConnections × maxWsQueue × maxWsMessageBytes`: + * ≈ 15.6 GiB at the defaults on Node. Deno and Bun have no connection cap, so cap connections at + * the platform or proxy there. Server-level only; there is no per-route override. + */ + maxWsQueue?: number; } /** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */ diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 15414af..f911adb 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -2,7 +2,7 @@ import { isHttpError } from '../signals'; import type { Bus } from '../bus'; import { correlateRequest } from './core'; import { matchPattern } from './router'; -import type { WsRouteDef } from './types'; +import type { WsRouteDef, RequestLimits } from './types'; /** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */ export interface WsRequest { @@ -22,6 +22,148 @@ export interface WsSocket { terminate(): void; } +/** Default for `limits.maxWsMessageBytes`: 1 MiB. */ +export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576; +/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */ +export const DEFAULT_MAX_WS_QUEUE = 16; + +/** + * Where `createApp` leaves the resolved `maxWsMessageBytes` for `serveBun`, which needs it as + * Bun's native `maxPayloadLength` and has no other path to the app's options. Internal, not part + * of the public `App` type; `Symbol.for` because each tsup entry carries its own copy of this + * module, and only the global registry resolves to one symbol across them. + */ +export const WS_MAX_MESSAGE_BYTES: unique symbol = Symbol.for('green-tea.ws-max-message-bytes'); + +/** The effective `limits.maxWsMessageBytes`. */ +export function wsMessageBytes(limits: Pick | undefined): number { + return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES; +} + +/** 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) { + const value: unknown = limits?.[key]; + if (value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)) continue; + const shown = typeof value === 'string' ? `'${value}'` : String(value); + throw new TypeError(`limits.${key} must be a positive integer, got ${shown}`); + } +} + +const encoder = new TextEncoder(); + +/** True when `msg`'s UTF-8 encoding is longer than `max` bytes. */ +function exceedsBytes(msg: unknown, max: number): boolean { + if (typeof msg !== 'string') return false; // every adapter delivers strings; nothing else to measure + // A UTF-16 unit encodes to 1–3 UTF-8 bytes, so both bounds below are exact. Only a string in + // between pays for the encode — which is never one of the short messages that dominate. + if (msg.length * 3 <= max) return false; + if (msg.length > max) return true; + return encoder.encode(msg).byteLength > max; +} + +/** + * Bounds a socket's inbound side (#107): a frame over `maxWsMessageBytes` closes `1009`, and a + * frame that arrives while `maxWsQueue` frames are still undelivered closes `1013`. Nothing is + * dropped silently — the peer learns which bound it hit from the close code. + * + * Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no + * subscriber is lost; subscribing here, before any boot or step runs, is what keeps the first + * frames — for the mesh control channel, the `hello` itself. The returned socket's `inbound` is a + * single-consumer FIFO over those frames, and every other capability is the original socket's. + */ +export function boundInbound( + socket: WsSocket, + limits?: Pick, +): WsSocket { + const fifo = new InboundFifo(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE); + + void fifo.pump(); + + return Object.create(socket, { + inbound: { value: { [Symbol.asyncIterator]: () => fifo } }, + }) as WsSocket; +} + +/** The single-consumer queue behind {@link boundInbound}; it is its own async iterator. */ +class InboundFifo implements AsyncIterator { + private readonly queue: unknown[] = []; + private waiter: { resolve: (r: IteratorResult) => void; reject: (e: unknown) => void } | null = null; + private ended = false; + private failure: { err: unknown } | null = null; + + constructor( + private readonly socket: WsSocket, + private readonly maxBytes: number, + private readonly maxQueue: number, + ) {} + + async pump(): Promise { + try { + for await (const msg of this.socket.inbound) { + if (this.ended || !this.accept(msg)) break; + } + + this.settle(); + } catch (err) { + this.settle({ err }); + } + } + + next(): Promise> { + if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false }); + if (this.failure) return Promise.reject(this.failure.err); + if (this.ended) return Promise.resolve({ value: undefined, done: true }); + return new Promise((resolve, reject) => { + this.waiter = { resolve, reject }; + }); + } + + // A consumer that stops reading has said it wants no more; queueing for it would only close + // the connection for a bound it no longer cares about. + return(): Promise> { + this.queue.length = 0; + this.settle(); + return Promise.resolve({ value: undefined, done: true }); + } + + /** Delivers or queues one frame; returns false once the frame has closed the socket. */ + private accept(msg: unknown): boolean { + if (exceedsBytes(msg, this.maxBytes)) { + this.socket.close(1009, 'message too large'); + return false; + } + + const waiter = this.waiter; + + if (waiter) { + this.waiter = null; + waiter.resolve({ value: msg, done: false }); + return true; + } + + if (this.queue.length >= this.maxQueue) { + this.socket.close(1013, 'inbound queue full'); + return false; + } + + this.queue.push(msg); + return true; + } + + /** Ends the queue once, cleanly or with a failure; whatever is still queued is delivered first. */ + private settle(failure?: { err: unknown }): void { + if (this.ended) return; + this.ended = true; + this.failure = failure ?? null; + const waiter = this.waiter; + this.waiter = null; + if (!waiter) return; + if (failure) waiter.reject(failure.err); + else waiter.resolve({ value: undefined, done: true }); + } +} + /** Finds the first ws route whose pattern matches `path`, capturing its params. */ export function matchWsRoute( wsRoutes: WsRouteDef[], diff --git a/src/http/ws.ts b/src/http/ws.ts index 21a4dc8..cfc7e7a 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -1,8 +1,16 @@ import type http from 'http'; import { channel } from '../channel'; import type { Bus } from '../bus'; -import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; -import type { WsRouteDef, MeshControl } from './types'; +import { + runWsConnection, + matchWsRoute, + trackUntil, + boundInbound, + wsMessageBytes, + type WsSocket, + type WsRequest, +} from './ws-core'; +import type { WsRouteDef, MeshControl, RequestLimits } from './types'; import { normalizeRequestPath } from './router'; import { nodeRequire } from '../node-require'; @@ -32,6 +40,7 @@ function handleMeshUpgrade( socket: any, head: Buffer, streams?: Set<() => void>, + limits?: RequestLimits, ): boolean { if (path !== meshControl.path) return false; @@ -46,7 +55,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 = nodeSocket(ws); + const neutral = boundInbound(nodeSocket(ws), limits); void trackUntil(neutral, meshControl.handle(neutral), streams); }); @@ -98,10 +107,14 @@ export function attachWs( bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>, + limits?: RequestLimits, ): void { if (wsRoutes.length === 0 && !meshControl) return; const WebSocketServer = loadWss(); - const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null; + // `maxPayload` is the pre-buffer half of `maxWsMessageBytes`: `ws` refuses an oversized frame, + // 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; 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. @@ -110,7 +123,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, req, socket, head, bus, meshControl, streams); + routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head); } catch { if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error'); else socket.destroy(); @@ -118,17 +131,19 @@ export function attachWs( }); } +/** What every upgrade on one server shares. */ +interface UpgradeEnv { + wss: any; + wsRoutes: WsRouteDef[]; + bus?: Bus; + meshControl?: MeshControl; + streams?: Set<() => void>; + limits?: RequestLimits; +} + /** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */ -function routeUpgrade( - wss: any, - wsRoutes: WsRouteDef[], - req: http.IncomingMessage, - socket: any, - head: Buffer, - bus?: Bus, - meshControl?: MeshControl, - streams?: Set<() => void>, -): void { +function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void { + const { wss, wsRoutes, bus, meshControl, streams, limits } = env; let path: string; // The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed @@ -140,7 +155,7 @@ function routeUpgrade( return; } - if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return; + if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return; const route = matchWsRoute(wsRoutes, path); @@ -155,6 +170,6 @@ function routeUpgrade( } wss.handleUpgrade(req, socket, head, (ws: any) => { - void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); + void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams); }); } diff --git a/test/bun/ws.test.ts b/test/bun/ws.test.ts index 4b2ce97..399af48 100644 --- a/test/bun/ws.test.ts +++ b/test/bun/ws.test.ts @@ -21,6 +21,15 @@ class Rt { })(); } + // Never reads `inbound`, so every frame the client sends stays queued (#107). + @Ws('/stall') + stall() { + return (async function* () { + await new Promise(() => {}); + yield ''; + })(); + } + @Ws('/room/:name') room(@ctx() { inbound }: any) { return (async function* () { @@ -73,3 +82,58 @@ test('serveBun: a malformed upgrade path closes 1008 and the server keeps servin server.stop(true); } }); + +/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */ +function exchange(port: number, path: string, frames: string[], until = 2000) { + const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`); + const replies: string[] = []; + return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => { + const timer = setTimeout(() => { + ws.close(); + resolve({ replies }); + }, until); + ws.onopen = () => frames.forEach((f) => ws.send(f)); + ws.onmessage = (e) => replies.push(String(e.data)); + ws.onclose = (e) => { + clearTimeout(timer); + resolve({ replies, close: { code: e.code, reason: e.reason } }); + }; + }); +} + +// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Its +// uWebSockets core drops the TCP connection without a close frame, so the peer sees `1006`, not +// the `1009` Node, Deno and the edge send. Asserted rather than papered over: it is the documented +// Bun difference, and a Bun upgrade that starts sending 1009 should fail here and be noticed. +test('serveBun: ws message size and inbound queue limits', async () => { + const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } }); + const server = await serveBun(app, { port: 0 }); + const port = server.port; + try { + const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300); + expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]); + + const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]); + expect(over.close?.code).toBe(1006); + + const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']); + expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' }); + } finally { + server.stop(true); + } +}); + +test('serveBun: ws message size default is 1 MiB', async () => { + const app = createApp({ modules: [M] }); + const server = await serveBun(app, { port: 0 }); + const port = server.port; + try { + const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500); + expect(atLimit.replies.length).toBe(1); + + const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]); + expect(over.close?.code).toBe(1006); + } finally { + server.stop(true); + } +}); diff --git a/test/deno/ws.test.ts b/test/deno/ws.test.ts index e0710f7..d713b90 100644 --- a/test/deno/ws.test.ts +++ b/test/deno/ws.test.ts @@ -29,6 +29,15 @@ class Rt { })(); } + // Never reads `inbound`, so every frame the client sends stays queued (#107). + @Ws('/stall') + stall() { + return (async function* () { + await new Promise(() => {}); + yield ''; + })(); + } + @Ws('/room/:name') room(@ctx() { inbound }: any) { return (async function* () { @@ -105,3 +114,70 @@ Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps await server.shutdown(); } }); + +/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */ +function exchange(port: number, path: string, frames: string[], until = 2000) { + const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`); + const replies: string[] = []; + return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => { + const timer = setTimeout(() => { + ws.close(); + resolve({ replies }); + }, until); + ws.onopen = () => frames.forEach((f) => ws.send(f)); + ws.onmessage = (e) => replies.push(String(e.data)); + ws.onclose = (e) => { + clearTimeout(timer); + resolve({ replies, close: { code: e.code, reason: e.reason } }); + }; + }); +} + +// #107: on Deno the runtime receives the whole message before user code sees it, so the size +// bound is checked after receipt — the close code is the same as on Node and Bun. +Deno.test('serveDeno: ws message size and inbound queue limits', async () => { + const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } }); + let port = 0; + const server = await serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + + try { + const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300); + assertEquals(atLimit.replies, [`echo:${'a'.repeat(1024)}`]); + + const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]); + assertEquals(over.close, { code: 1009, reason: 'message too large' }); + + const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']); + assertEquals(full.close, { code: 1013, reason: 'inbound queue full' }); + } finally { + await server.shutdown(); + } +}); + +Deno.test('serveDeno: ws message size default is 1 MiB', async () => { + const app = createApp({ modules: [M] }); + let port = 0; + const server = await serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + + try { + const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500); + assertEquals(atLimit.replies.length, 1); + + const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]); + assertEquals(over.close?.code, 1009); + } finally { + await server.shutdown(); + } +}); diff --git a/test/edge/run.ts b/test/edge/run.ts index 7e72f3f..01efd9f 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -97,12 +97,46 @@ async function main() { assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' }); assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200); - console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS'); + // #107: workerd delivers the whole message before user code sees it, so the size bound is + // checked after receipt; the close codes match Node and Deno. + const limitedEcho = async (frames: string[]) => exchange(mf, 'http://limited/rt/echo', frames); + assert.deepEqual((await limitedEcho(['a'.repeat(1024)])).replies, [`echo:${'a'.repeat(1024)}`]); + assert.deepEqual((await limitedEcho(['a'.repeat(1025)])).close, { code: 1009, reason: 'message too large' }); + assert.deepEqual((await exchange(mf, 'http://limited/rt/stall', ['1', '2', '3', '4', '5'])).close, { + code: 1013, + reason: 'inbound queue full', + }); + assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1); + assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009); + + console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi + ws limits — PASS'); } finally { await mf.dispose(); } } +/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */ +async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) { + const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } }); + const ws = res.webSocket; + assert.ok(ws, `expected a client webSocket on the 101 response for ${url}`); + const replies: string[] = []; + const result = new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => { + const timer = setTimeout(() => { + ws.close(); + resolve({ replies }); + }, ms); + ws.addEventListener('message', (e: { data: unknown }) => replies.push(String(e.data))); + ws.addEventListener('close', (e: { code: number; reason: string }) => { + clearTimeout(timer); + resolve({ replies, close: { code: e.code, reason: e.reason } }); + }); + }); + ws.accept(); + for (const frame of frames) ws.send(frame); + return result; +} + main().catch((err) => { console.error(err); process.exit(1); diff --git a/test/edge/worker.ts b/test/edge/worker.ts index 268bde2..c8eb00d 100644 --- a/test/edge/worker.ts +++ b/test/edge/worker.ts @@ -18,6 +18,15 @@ class Rt { })(); } + // Never reads `inbound`, so every frame the client sends stays queued (#107). + @Ws('/stall') + stall() { + return (async function* () { + await new Promise(() => {}); + yield ''; + })(); + } + @Ws('/room/:name') room(@ctx() { inbound }: any) { return (async function* () { @@ -30,5 +39,11 @@ class Rt { class M {} const app = createApp({ modules: [M] }); +// #107: the same graph with tight ws limits, reached through the `limited` host. +const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } }); +const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) }; -export default { fetch: edgeHandler(app) }; +export default { + fetch: (request: Request, env?: unknown, ctx?: Parameters[2]) => + (new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx), +}; diff --git a/test/ws-limits.test.ts b/test/ws-limits.test.ts new file mode 100644 index 0000000..d12ae61 --- /dev/null +++ b/test/ws-limits.test.ts @@ -0,0 +1,312 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import type http from 'http'; +import WebSocket from 'ws'; +import { createApp, Route, Ws, Module, ctx } from '../src/index'; +import type { RequestLimits } from '../src/index'; +import { channel } from '../src/channel'; +import { boundInbound, type WsSocket } from '../src/http/ws-core'; + +// #107 / D1: per-connection bounds on inbound WebSocket messages. Node runs the real `ws` server +// behind `listen(0)`; the other runtimes are covered in test/deno, test/bun and test/edge. + +const never = new Promise(() => {}); + +@Route('/rt') +class Rt { + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${(msg as string).length}`; + })(); + } + + // Never reads `inbound`: every frame the client sends stays queued. + @Ws('/stall') + stall() { + return (async function* () { + await never; + yield ''; + })(); + } + + // Reads exactly one frame, acknowledges it, then stalls. + @Ws('/one') + one(@ctx() { inbound }: any) { + return (async function* () { + const it = (inbound as AsyncIterable)[Symbol.asyncIterator](); + await it.next(); + yield 'took-one'; + await never; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Rt] }) +class M {} + +const servers: http.Server[] = []; +const clients: WebSocket[] = []; +afterEach(async () => { + clients.splice(0).forEach((c) => c.terminate()); + await Promise.all(servers.splice(0).map((s) => new Promise((r) => s.close(r)))); +}); + +async function serve(limits?: RequestLimits): Promise { + const server = await createApp({ modules: [M], limits }).listen(0); + servers.push(server); + return (server.address() as { port: number }).port; +} + +async function connect(port: number, path: string) { + const client = new WebSocket(`ws://127.0.0.1:${port}${path}`); + clients.push(client); + const messages: string[] = []; + client.on('message', (d) => messages.push(d.toString())); + const closed = new Promise<{ code: number; reason: string }>((r) => + client.on('close', (code, reason) => r({ code, reason: reason.toString() })), + ); + await new Promise((r) => client.on('open', r)); + return { client, messages, closed }; +} + +/** Resolves with the close if it happens within `ms`, else 'open'. */ +const closedWithin = (closed: Promise<{ code: number; reason: string }>, ms = 150) => + Promise.race([closed, new Promise<'open'>((r) => setTimeout(() => r('open'), ms))]); + +const until = async (cond: () => boolean) => { + for (let i = 0; i < 100 && !cond(); i++) await new Promise((r) => setTimeout(r, 10)); +}; + +/** Binary payload of `n` bytes that is valid UTF-8 (ASCII), so its decoded size equals its wire size. */ +const binary = (n: number) => Buffer.alloc(n, 0x62); + +describe('limits.maxWsMessageBytes on Node (#107)', () => { + const limits = { maxWsMessageBytes: 1024 }; + + it('T1: a text message of exactly the limit is delivered', async () => { + const { client, messages } = await connect(await serve(limits), '/rt/echo'); + client.send('a'.repeat(1024)); + await until(() => messages.length > 0); + expect(messages).toEqual(['echo:1024']); + client.close(); + }); + + it('T2: a binary message of exactly the limit is delivered', async () => { + const { client, messages } = await connect(await serve(limits), '/rt/echo'); + client.send(binary(1024)); + await until(() => messages.length > 0); + expect(messages).toEqual(['echo:1024']); + client.close(); + }); + + it('T3: one byte of text over the limit closes 1009', async () => { + const { client, closed } = await connect(await serve(limits), '/rt/echo'); + client.send('a'.repeat(1025)); + expect((await closed).code).toBe(1009); + }); + + it('T4: one byte of binary over the limit closes 1009', async () => { + const { client, closed } = await connect(await serve(limits), '/rt/echo'); + client.send(binary(1025)); + expect((await closed).code).toBe(1009); + }); + + it('T5: the limit counts UTF-8 bytes, not characters', async () => { + const { client, closed } = await connect(await serve(limits), '/rt/echo'); + client.send('€'.repeat(342)); // 342 UTF-16 units, 1026 UTF-8 bytes + expect((await closed).code).toBe(1009); + }); + + it('T6: a fragmented message is measured whole', async () => { + const { client, closed } = await connect(await serve(limits), '/rt/echo'); + client.send('a'.repeat(400), { fin: false }); + client.send('a'.repeat(400), { fin: false }); + client.send('a'.repeat(400), { fin: true }); + expect((await closed).code).toBe(1009); + }); +}); + +describe('limits.maxWsQueue on Node (#107)', () => { + const limits = { maxWsQueue: 4 }; + + it('T7: a stalled consumer with the queue exactly full stays open', async () => { + const { client, closed } = await connect(await serve(limits), '/rt/stall'); + for (let i = 0; i < 4; i++) client.send(`m${i}`); + expect(await closedWithin(closed)).toBe('open'); + client.close(); + }); + + it('T8: one more frame than the queue holds closes 1013, inbound queue full', async () => { + const { client, closed } = await connect(await serve(limits), '/rt/stall'); + for (let i = 0; i < 5; i++) client.send(`m${i}`); + expect(await closed).toEqual({ code: 1013, reason: 'inbound queue full' }); + }); + + it('T9: the bound counts undelivered frames, so a delivered one frees a slot', async () => { + const { client, messages, closed } = await connect(await serve(limits), '/rt/one'); + for (let i = 0; i < 4; i++) client.send(`m${i}`); + await until(() => messages.length > 0); + expect(messages).toEqual(['took-one']); + client.send('m4'); // 3 left queued + this one = 4 + expect(await closedWithin(closed)).toBe('open'); + client.close(); + }); +}); + +describe('ws limit defaults on Node (#107)', () => { + it('T10: 1 MiB is accepted and 1 MiB + 1 closes 1009', async () => { + const port = await serve(); + const ok = await connect(port, '/rt/echo'); + ok.client.send('a'.repeat(1_048_576)); + await until(() => ok.messages.length > 0); + expect(ok.messages).toEqual(['echo:1048576']); + ok.client.close(); + + const over = await connect(port, '/rt/echo'); + over.client.send('a'.repeat(1_048_577)); + expect((await over.closed).code).toBe(1009); + }); + + it('T10: 16 queued frames are held and the 17th closes 1013', async () => { + const port = await serve(); + const held = await connect(port, '/rt/stall'); + for (let i = 0; i < 16; i++) held.client.send(`m${i}`); + expect(await closedWithin(held.closed)).toBe('open'); + held.client.close(); + + const over = await connect(port, '/rt/stall'); + for (let i = 0; i < 17; i++) over.client.send(`m${i}`); + expect((await over.closed).code).toBe(1013); + }); +}); + +describe('ws limit validation (#107)', () => { + it.each([ + ['maxWsQueue', 0], + ['maxWsQueue', -1], + ['maxWsQueue', 1.5], + ['maxWsQueue', '16'], + ['maxWsQueue', NaN], + ['maxWsMessageBytes', 0], + ['maxWsMessageBytes', -1], + ['maxWsMessageBytes', 1.5], + ['maxWsMessageBytes', '16'], + ['maxWsMessageBytes', Infinity], + ])('T11: limits.%s = %s fails createApp with a TypeError naming the key', (key, value) => { + expect(() => createApp({ modules: [M], limits: { [key]: value } as RequestLimits })).toThrow( + new RegExp(`^limits\\.${key} must be a positive integer`), + ); + expect(() => createApp({ modules: [M], limits: { [key]: value } as RequestLimits })).toThrow(TypeError); + }); + + it('accepts positive integers and absent keys', () => { + expect(() => createApp({ modules: [M], limits: { maxWsQueue: 1, maxWsMessageBytes: 1 } })).not.toThrow(); + expect(() => createApp({ modules: [M], limits: {} })).not.toThrow(); + }); +}); + +/** A WsSocket over a channel that records closes. */ +function fakeSocket() { + const inbound = channel(); + const closes: Array<[number | undefined, string | undefined]> = []; + const socket: WsSocket = { + inbound, + abort: new AbortController().signal, + isOpen: true, + send: () => {}, + close: (code, reason) => closes.push([code, reason]), + terminate: () => {}, + }; + return { socket, inbound, closes }; +} + +const tick = () => new Promise((r) => setTimeout(r, 0)); + +describe('boundInbound (#107)', () => { + it('T15: delivers frames in order to a waiting consumer and to a late one', async () => { + const { socket, inbound } = fakeSocket(); + const bounded = boundInbound(socket, { maxWsQueue: 4 }); + const it = bounded.inbound[Symbol.asyncIterator](); + const first = it.next(); + inbound.push('a'); + expect(await first).toEqual({ value: 'a', done: false }); + inbound.push('b'); + inbound.push('c'); + await tick(); + expect(await it.next()).toEqual({ value: 'b', done: false }); + expect(await it.next()).toEqual({ value: 'c', done: false }); + }); + + it('T15: subscribes immediately, so frames sent before the consumer arrives are kept', async () => { + const { socket, inbound } = fakeSocket(); + const bounded = boundInbound(socket); + await tick(); + inbound.push('early'); + await tick(); + expect(await bounded.inbound[Symbol.asyncIterator]().next()).toEqual({ value: 'early', done: false }); + }); + + it('T15: closes 1009 on an oversized frame and never delivers it', async () => { + const { socket, inbound, closes } = fakeSocket(); + const bounded = boundInbound(socket, { maxWsMessageBytes: 3 }); + await tick(); + inbound.push('€'); // 3 bytes: fits + inbound.push('€a'); // 4 bytes + await tick(); + expect(closes).toEqual([[1009, 'message too large']]); + const it = bounded.inbound[Symbol.asyncIterator](); + expect(await it.next()).toEqual({ value: '€', done: false }); + expect((await it.next()).done).toBe(true); + }); + + it('T15: closes 1013 on overflow, delivers what was queued, then ends', async () => { + const { socket, inbound, closes } = fakeSocket(); + const bounded = boundInbound(socket, { maxWsQueue: 2 }); + await tick(); + for (const m of ['a', 'b', 'c']) inbound.push(m); + await tick(); + expect(closes).toEqual([[1013, 'inbound queue full']]); + const got: unknown[] = []; + for await (const m of bounded.inbound) got.push(m); + expect(got).toEqual(['a', 'b']); + }); + + it('T15: ends when the socket inbound ends', async () => { + const { socket, inbound } = fakeSocket(); + const bounded = boundInbound(socket); + const it = bounded.inbound[Symbol.asyncIterator](); + const pending = it.next(); + inbound.close(); + expect((await pending).done).toBe(true); + expect((await it.next()).done).toBe(true); + }); + + it('T15: propagates a socket failure to a waiting and a later consumer', async () => { + const { socket, inbound } = fakeSocket(); + const bounded = boundInbound(socket); + const it = bounded.inbound[Symbol.asyncIterator](); + const pending = it.next(); + const boom = new Error('boom'); + inbound.fail(boom); + await expect(pending).rejects.toBe(boom); + await expect(it.next()).rejects.toBe(boom); + }); + + it('T15: a consumer that returns stops queueing, so it is never closed for not reading', async () => { + const { socket, inbound, closes } = fakeSocket(); + const bounded = boundInbound(socket, { maxWsQueue: 1 }); + const it = bounded.inbound[Symbol.asyncIterator](); + await it.return?.(); + for (const m of ['a', 'b', 'c']) inbound.push(m); + await tick(); + expect(closes).toEqual([]); + expect((await it.next()).done).toBe(true); + }); + + it('T15: keeps the socket capabilities other than inbound', () => { + const { socket } = fakeSocket(); + const bounded = boundInbound(socket); + expect(bounded.isOpen).toBe(true); + expect(bounded.abort).toBe(socket.abort); + bounded.close(1000, 'bye'); + }); +});