diff --git a/README.md b/README.md index 2f8d9fb..c54acaa 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. -- **Ceilings that are already on.** `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. 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. Configurable, and safe before you configure anything. +- **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. - **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, not a `SIGTERM` handler you write.** 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/http/request-gate.ts b/src/http/request-gate.ts new file mode 100644 index 0000000..e6e815c --- /dev/null +++ b/src/http/request-gate.ts @@ -0,0 +1,30 @@ +/** + * Per-server/adapter request budget. + * + * `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and + * handler execution finishes; a returned stream does not hold the slot for the stream's lifetime. + */ +export interface RequestGate { + acquire(): boolean; + release(): void; +} + +/** Creates an unlimited gate when `limit` is undefined or non-positive. */ +export function createRequestGate(limit: number | undefined): RequestGate { + let active = 0; + + return { + acquire(): boolean { + if (limit === undefined || limit <= 0) return true; + if (active >= limit) return false; + + active++; + return true; + }, + + release(): void { + if (limit === undefined || limit <= 0) return; + if (active > 0) active--; + }, + }; +} diff --git a/src/http/server.ts b/src/http/server.ts index 555ccd0..44b3aec 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -1,5 +1,6 @@ import type http from 'http'; import type https from 'https'; +import { createRequestGate } from './request-gate'; import { renderError, type ErrorRequest } from '../transformers'; import type { Bus } from '../bus'; import { buildSecurityHeaders, resolveCors } from '../security'; @@ -7,7 +8,7 @@ import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request'; import { pipeStream } from './stream'; import { attachWs } from './ws'; import { mergeInjectedHeaders } from './headers'; -import { handle, correlateRequest } from './core'; +import { handle, correlateRequest, type HandleResult, type Preflight } from './core'; import type { BodyFailure, BodyReader } from './body'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; @@ -87,6 +88,7 @@ function createRequestHandler(cfg: HandlerConfig) { const { routes, bus, opts, trustProxy } = cfg; // Built once per server, not once per request — see `BodyReader`. const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts); + const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); return async (req: http.IncomingMessage, res: http.ServerResponse): Promise => { // Install the security-header patch BEFORE any routing/response so every path @@ -101,16 +103,58 @@ function createRequestHandler(cfg: HandlerConfig) { // by reference at writeHead time, so keys added here still land on every response. if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); - const result = await handle(routes, opts, { - ...correlation, - method: req.method ?? 'GET', - url: req.url ?? '/', - headers: req.headers, - readBody, - source: req, - secure, - ip: deriveIp(req, trustProxy), - }); + let result: HandleResult | Preflight; + let acquired = false; + const watchingEnd = bus?.hasListeners('request:end') ?? false; + const startedAt = watchingEnd ? performance.now() : 0; + + try { + if (!gate.acquire()) { + if (watchingEnd) { + const method = req.method ?? 'GET'; + const url = req.url ?? '/'; + bus!.emit('request:end', { + name: `${method} ${url}`, + method, + status: 503, + durationMs: performance.now() - startedAt, + requestId: correlation.requestId, + traceId: correlation.traceId, + }); + } + + res.writeHead(503, { + 'content-type': 'application/json', + 'retry-after': '1', + connection: 'close', + }); + res.end(JSON.stringify({ error: 'Service Unavailable' })); + return; + } + + acquired = true; + res.once('close', () => { + if (!acquired) return; + acquired = false; + gate.release(); + }); + + result = await handle(routes, opts, { + ...correlation, + method: req.method ?? 'GET', + url: req.url ?? '/', + headers: req.headers, + readBody, + source: req, + secure, + ip: deriveIp(req, trustProxy), + }); + } finally { + if (acquired) { + acquired = false; + gate.release(); + } + } if ('preflight' in result) { res.writeHead(204, result.preflight); diff --git a/src/http/types.ts b/src/http/types.ts index d4be7cf..49c646b 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -11,6 +11,7 @@ import type { Logger } from '../logger'; export interface RequestLimits { maxBodyBytes?: number; // default 1_000_000 maxConnections?: number; // default 1000; <= 0 means unlimited (Node only) + maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited requestTimeoutMs?: number; // default 30_000 headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 diff --git a/src/http/web.ts b/src/http/web.ts index 8fd38db..69139a5 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -1,5 +1,6 @@ import type { StreamEncoder } from '../encoders'; -import { handle, computeInjected, correlateRequest, type HandleResult } from './core'; +import { createRequestGate } from './request-gate'; +import { handle, computeInjected, correlateRequest, type HandleResult, type Preflight } from './core'; import { mergeInjectedHeaders } from './headers'; import type { BodyFailure, BodyReader, MaybePromise } from './body'; import { HttpError } from '../signals'; @@ -127,6 +128,7 @@ function outcomeToResponse(result: HandleResult): Response { export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { // Built once per server, not once per request — see `BodyReader`. const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts); + const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); return async (request: Request): Promise => { const url = new URL(request.url); @@ -139,29 +141,68 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { // this adapter builds itself — carries the same security/CORS headers every other one does. const injected = computeInjected(opts, { secure, headers }); - const result = await handle(routes, opts, { - ...correlation, - method: request.method, - url: path, - headers, - readBody, - source: request, - secure, - // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is - // trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket - // peer address to fall back to on the fetch path, so the untrusted case is simply ''. - ip: opts?.trustProxy - ? String(headers['x-forwarded-for'] ?? '') - .split(',')[0] - .trim() - : '', - }); + let result: HandleResult | Preflight; + let acquired = false; + const watchingEnd = opts?.bus?.hasListeners('request:end') ?? false; + const startedAt = watchingEnd ? performance.now() : 0; + + try { + if (!gate.acquire()) { + if (watchingEnd) { + opts!.bus!.emit('request:end', { + name: `${request.method} ${path}`, + method: request.method, + status: 503, + durationMs: performance.now() - startedAt, + requestId: correlation.requestId, + traceId: correlation.traceId, + }); + } + + return new Response(JSON.stringify({ error: 'Service Unavailable' }), { + status: 503, + headers: mergeInjectedHeaders( + { + 'content-type': 'application/json', + 'retry-after': '1', + }, + injected, + ), + }); + } + + acquired = true; + + result = await handle(routes, opts, { + ...correlation, + method: request.method, + url: path, + headers, + readBody, + source: request, + secure, + // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is + // trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket + // peer address to fall back to on the fetch path, so the untrusted case is simply ''. + ip: opts?.trustProxy + ? String(headers['x-forwarded-for'] ?? '') + .split(',')[0] + .trim() + : '', + }); + } finally { + // Release when routing/handling finishes, not when a returned stream finishes. + // Long-lived streams therefore do not permanently consume the request budget. + if (acquired) gate.release(); + } // Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and - // so picks up the same authoritative security headers `injected` carries (Node's writeHead patch - // merges every response — including the 204 preflight — with `injected`; this adapter must too). + // so picks up the same authoritative security headers `injected` carries. if ('preflight' in result) { - return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) }); + return new Response(null, { + status: 204, + headers: mergeInjectedHeaders(result.preflight, injected), + }); } return outcomeToResponse(result); diff --git a/test/http.test.ts b/test/http.test.ts index 2787f87..01b5bdd 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, test, vi } from 'vitest'; import * as net from 'node:net'; import { once } from 'node:events'; +import { Bus } from '../src/bus'; import { matchRoute, parseQuery, createHttpServer } from '../src/http'; const handler = async () => ({ status: 200, headers: {}, body: 'ok' }); @@ -194,6 +195,136 @@ describe('request hardening', () => { } }); + it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => { + let release!: () => void; + let started!: () => void; + + const blocked = new Promise((resolve) => { + release = resolve; + }); + const firstStarted = new Promise((resolve) => { + started = resolve; + }); + + const bus = new Bus(); + const ended: Array<{ method?: string; status?: number; requestId?: string }> = []; + bus.on('request:end', (event) => { + ended.push(event); + }); + + const server = createHttpServer( + [ + { + method: 'GET', + pattern: '/slow', + transport: 'buffer', + handler: async () => { + started(); + await blocked; + return { status: 200, headers: {}, body: 'ok' }; + }, + }, + ], + [], + bus, + undefined, + { + limits: { maxConcurrentRequests: 1 }, + cors: { origins: 'https://example.com' }, + }, + ); + + await new Promise((resolve) => server.listen(0, resolve)); + + const first = fetch(`${getUrl(server)}/slow`); + await firstStarted; + + const rejected = await fetch(`${getUrl(server)}/slow`, { + headers: { origin: 'https://example.com' }, + }); + + expect(rejected.status).toBe(503); + expect(rejected.headers.get('content-type')).toBe('application/json'); + expect(rejected.headers.get('retry-after')).toBe('1'); + expect(rejected.headers.get('connection')).toBe('close'); + expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com'); + expect(rejected.headers.get('x-content-type-options')).toBe('nosniff'); + expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' }); + + expect(ended).toHaveLength(1); + expect(ended[0]).toMatchObject({ + method: 'GET', + status: 503, + }); + expect(ended[0].requestId).toBeTruthy(); + + release(); + + const firstResponse = await first; + expect(firstResponse.status).toBe(200); + + const afterRelease = await fetch(`${getUrl(server)}/slow`); + expect(afterRelease.status).toBe(200); + + server.close(); + }); + + it('releases a request slot when the client disconnects before the handler settles', async () => { + let started!: () => void; + const handlerStarted = new Promise((resolve) => { + started = resolve; + }); + + const server = createHttpServer( + [ + { + method: 'GET', + pattern: '/hang', + transport: 'buffer', + handler: async () => { + started(); + await new Promise(() => {}); + return { status: 200, headers: {}, body: 'never' }; + }, + }, + { + method: 'GET', + pattern: '/ok', + transport: 'buffer', + handler: async () => ({ status: 200, headers: {}, body: 'ok' }), + }, + ], + [], + undefined, + undefined, + { limits: { maxConcurrentRequests: 1 } }, + ); + + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port'); + + const responseClosed = new Promise((resolve) => { + server.once('request', (_req, res) => { + res.once('close', resolve); + }); + }); + + const client = net.createConnection({ host: '127.0.0.1', port: address.port }); + await once(client, 'connect'); + client.write('GET /hang HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n'); + + await handlerStarted; + client.destroy(); + await responseClosed; + + const afterDisconnect = await fetch(`${getUrl(server)}/ok`); + expect(afterDisconnect.status).toBe(200); + + await new Promise((resolve) => server.close(() => resolve())); + }); + it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => { async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } } const server = createHttpServer( diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts index a946b2a..4728c5a 100644 --- a/test/web-stream.test.ts +++ b/test/web-stream.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { asReadableStream, toBodyInit } from '../src/http/web'; +import { Bus } from '../src/bus'; +import { asReadableStream, buildFetch, toBodyInit } from '../src/http/web'; import { sseEncoder } from '../src/encoders'; async function* nums() { yield { n: 1 }; yield { n: 2 }; } @@ -46,4 +47,152 @@ describe('asReadableStream', () => { await new Promise((r) => setTimeout(r, 10)); expect(returned).toBe(true); }); + + +}); + +describe('buildFetch request gate', () => { + it('does not permanently exhaust the gate when CORS setup throws', async () => { + let attempts = 0; + + const fetchHandler = buildFetch( + [ + { + method: 'GET', + pattern: '/ok', + transport: 'buffer', + handler: async () => ({ status: 200, headers: {}, body: 'ok' }), + }, + ], + { + limits: { maxConcurrentRequests: 2 }, + cors: { + origins: () => { + attempts++; + if (attempts <= 2) throw new Error('transient CORS failure'); + return true; + }, + }, + }, + ); + + const request = () => + new Request('http://localhost/ok', { + headers: { origin: 'https://example.com' }, + }); + + await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure'); + await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure'); + + const recovered = await fetchHandler(request()); + expect(recovered.status).toBe(200); + }); + + it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => { + let release!: () => void; + let started!: () => void; + + const blocked = new Promise((resolve) => { + release = resolve; + }); + const firstStarted = new Promise((resolve) => { + started = resolve; + }); + + const bus = new Bus(); + const ended: Array<{ method?: string; status?: number; requestId?: string }> = []; + bus.on('request:end', (event) => { + ended.push(event); + }); + + const fetchHandler = buildFetch( + [ + { + method: 'GET', + pattern: '/slow', + transport: 'buffer', + handler: async () => { + started(); + await blocked; + return { status: 200, headers: {}, body: 'ok' }; + }, + }, + ], + { + bus, + limits: { maxConcurrentRequests: 1 }, + cors: { origins: 'https://example.com' }, + }, + ); + + const first = fetchHandler(new Request('http://localhost/slow')); + await firstStarted; + + const rejected = await fetchHandler( + new Request('http://localhost/slow', { + headers: { origin: 'https://example.com' }, + }), + ); + + expect(rejected.status).toBe(503); + expect(rejected.headers.get('content-type')).toBe('application/json'); + expect(rejected.headers.get('retry-after')).toBe('1'); + expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com'); + expect(rejected.headers.get('x-content-type-options')).toBe('nosniff'); + expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' }); + + expect(ended).toHaveLength(1); + expect(ended[0]).toMatchObject({ + method: 'GET', + status: 503, + }); + expect(ended[0].requestId).toBeTruthy(); + + release(); + + expect((await first).status).toBe(200); + + const afterRelease = await fetchHandler(new Request('http://localhost/slow')); + expect(afterRelease.status).toBe(200); + }); + it('releases the slot when a streaming handler returns', async () => { + async function* stream() { + yield { n: 1 }; + await new Promise(() => {}); + } + + const fetchHandler = buildFetch( + [ + { + method: 'GET', + pattern: '/stream', + transport: 'sse', + handler: async () => ({ stream: stream() }), + }, + ], + { limits: { maxConcurrentRequests: 1 } }, + ); + + const first = await fetchHandler( + new Request('http://localhost/stream', { + headers: { accept: 'text/event-stream' }, + }), + ); + + expect(first.status).toBe(200); + + // The first response stream is still open, but its request slot should + // already be released once handle() has returned. + const second = await fetchHandler( + new Request('http://localhost/stream', { + headers: { accept: 'text/event-stream' }, + }), + ); + + expect(second.status).toBe(200); + + await first.body?.cancel(); + await second.body?.cancel(); + }); });