feat: request body-size limit (413) and configurable server timeouts
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+73
-10
No files matched your search
+3
-3
@@ -3,7 +3,7 @@ import { Bus } from './bus';
|
|||||||
import { Container } from './container';
|
import { Container } from './container';
|
||||||
import { topoSort, GraphNode } from './graph';
|
import { topoSort, GraphNode } from './graph';
|
||||||
import { runPipeline, PipelineStep } from './pipeline';
|
import { runPipeline, PipelineStep } from './pipeline';
|
||||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef } from './http';
|
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
|
||||||
import { isAsyncIterable } from './channel';
|
import { isAsyncIterable } from './channel';
|
||||||
import { JsonTransformer } from './transformers';
|
import { JsonTransformer } from './transformers';
|
||||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
|
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
|
||||||
@@ -43,7 +43,7 @@ export interface MeshConfig {
|
|||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig }): App {
|
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App {
|
||||||
const bus = new Bus();
|
const bus = new Bus();
|
||||||
const container = new Container();
|
const container = new Container();
|
||||||
const extraSteps: ScopeNode[] = [];
|
const extraSteps: ScopeNode[] = [];
|
||||||
@@ -279,7 +279,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl);
|
const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits });
|
||||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||||
await new Promise<void>((resolve) => server.listen(port, resolve));
|
await new Promise<void>((resolve) => server.listen(port, resolve));
|
||||||
return server;
|
return server;
|
||||||
|
|||||||
+28
-7
@@ -2,11 +2,20 @@ import http from 'http';
|
|||||||
import { once } from 'events';
|
import { once } from 'events';
|
||||||
import { channel } from './channel';
|
import { channel } from './channel';
|
||||||
import { errorToResponse } from './transformers';
|
import { errorToResponse } from './transformers';
|
||||||
|
import { HttpError } from './signals';
|
||||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||||
import type { Transport } from './metadata';
|
import type { Transport } from './metadata';
|
||||||
import type { Bus } from './bus';
|
import type { Bus } from './bus';
|
||||||
|
|
||||||
|
export interface RequestLimits {
|
||||||
|
maxBodyBytes?: number; // default 1_000_000
|
||||||
|
requestTimeoutMs?: number; // default 30_000
|
||||||
|
headersTimeoutMs?: number; // default 10_000
|
||||||
|
keepAliveTimeoutMs?: number; // default 5_000
|
||||||
|
}
|
||||||
|
export interface HttpOptions { limits?: RequestLimits }
|
||||||
|
|
||||||
export type RouteHandler = (req: {
|
export type RouteHandler = (req: {
|
||||||
method: string; url: string;
|
method: string; url: string;
|
||||||
headers: Record<string, string | string[] | undefined>;
|
headers: Record<string, string | string[] | undefined>;
|
||||||
@@ -58,9 +67,14 @@ export function parseQuery(url: string): Record<string, string> {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readBody(req: http.IncomingMessage): Promise<string | undefined> {
|
async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<string | undefined> {
|
||||||
const chunks: Buffer[] = [];
|
const chunks: Buffer[] = [];
|
||||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
let total = 0;
|
||||||
|
for await (const chunk of req) {
|
||||||
|
total += (chunk as Buffer).length;
|
||||||
|
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||||
|
chunks.push(chunk as Buffer);
|
||||||
|
}
|
||||||
if (chunks.length === 0) return undefined;
|
if (chunks.length === 0) return undefined;
|
||||||
const raw = Buffer.concat(chunks).toString('utf8');
|
const raw = Buffer.concat(chunks).toString('utf8');
|
||||||
return raw === '' ? undefined : raw;
|
return raw === '' ? undefined : raw;
|
||||||
@@ -154,7 +168,10 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl): http.Server {
|
export function createHttpServer(
|
||||||
|
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
||||||
|
): http.Server {
|
||||||
|
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||||
const server = http.createServer(async (req, res) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
const url = req.url ?? '/';
|
const url = req.url ?? '/';
|
||||||
const path = url.split('?')[0];
|
const path = url.split('?')[0];
|
||||||
@@ -166,10 +183,11 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = []
|
|||||||
}
|
}
|
||||||
let raw: string | undefined;
|
let raw: string | undefined;
|
||||||
try {
|
try {
|
||||||
raw = await readBody(req);
|
raw = await readBody(req, maxBody);
|
||||||
} catch {
|
} catch (error) {
|
||||||
res.writeHead(500, { 'content-type': 'application/json' });
|
const r = errorToResponse(error);
|
||||||
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
res.writeHead(r.status, { ...r.headers, connection: 'close' });
|
||||||
|
res.end(r.body);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let body: unknown = raw;
|
let body: unknown = raw;
|
||||||
@@ -200,6 +218,9 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = []
|
|||||||
res.writeHead(r.status, r.headers);
|
res.writeHead(r.status, r.headers);
|
||||||
res.end(r.body);
|
res.end(r.body);
|
||||||
});
|
});
|
||||||
|
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);
|
attachWs(server, wsRoutes, bus, meshControl);
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,7 @@ export { inbound, abort } from './params';
|
|||||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||||
export type { StreamEncoder } from './encoders';
|
export type { StreamEncoder } from './encoders';
|
||||||
export type { MeshConfig } from './app';
|
export type { MeshConfig } from './app';
|
||||||
|
export type { RequestLimits } from './http';
|
||||||
export { connectLink } from './mesh/link';
|
export { connectLink } from './mesh/link';
|
||||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||||
|
|||||||
@@ -97,3 +97,44 @@ describe('http streaming', () => {
|
|||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('request hardening', () => {
|
||||||
|
const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`;
|
||||||
|
|
||||||
|
it('rejects an over-size body with 413 and does not run the handler', async () => {
|
||||||
|
let ran = false;
|
||||||
|
const server = createHttpServer(
|
||||||
|
[{ method: 'POST', pattern: '/echo', transport: 'buffer',
|
||||||
|
handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }],
|
||||||
|
[], undefined, undefined, { limits: { maxBodyBytes: 16 } },
|
||||||
|
);
|
||||||
|
await new Promise<void>((r) => server.listen(0, r));
|
||||||
|
const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) });
|
||||||
|
expect(res.status).toBe(413);
|
||||||
|
expect(ran).toBe(false);
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets the configured server timeouts', async () => {
|
||||||
|
const server = createHttpServer([], [], undefined, undefined,
|
||||||
|
{ limits: { requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
|
||||||
|
expect(server.requestTimeout).toBe(12345);
|
||||||
|
expect(server.headersTimeout).toBe(6789);
|
||||||
|
expect(server.keepAliveTimeout).toBe(4321);
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
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(
|
||||||
|
[{ method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: feed() }) }],
|
||||||
|
[], undefined, undefined, { limits: { requestTimeoutMs: 100 } },
|
||||||
|
);
|
||||||
|
await new Promise<void>((r) => server.listen(0, r));
|
||||||
|
const res = await fetch(`${getUrl(server)}/feed`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
const text = await res.text();
|
||||||
|
expect(text).toContain('data: {"n":1}');
|
||||||
|
expect(text).toContain('data: {"n":3}');
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user