diff --git a/src/http/core.ts b/src/http/core.ts index f0264fb..ad7e732 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -212,6 +212,7 @@ export function handle( routes: RouteDef[], opts: HttpOptions | undefined, req: NeutralRequest, + injected?: Record, ): Promise { const bus = opts?.bus; @@ -227,10 +228,10 @@ export function handle( bus.hasListeners('route:unmatched') ) ) { - return dispatch(routes, opts, req, undefined, undefined); + return dispatch(routes, opts, req, undefined, undefined, injected); } - return observedDispatch(routes, opts, req, bus); + return observedDispatch(routes, opts, req, bus, injected); } async function observedDispatch( @@ -238,6 +239,7 @@ async function observedDispatch( opts: HttpOptions | undefined, req: NeutralRequest, bus: Bus, + injected?: Record, ): Promise { const watchingEnd = bus.hasListeners('request:end'); const startedAt = watchingEnd ? performance.now() : 0; @@ -251,7 +253,7 @@ async function observedDispatch( traceId: req.traceId, }); - const result = await dispatch(routes, opts, req, bus, trace); + const result = await dispatch(routes, opts, req, bus, trace, injected); if (watchingEnd) { // A preflight is a 204 the router never routed; a stream has no status of its own and is a 200 @@ -277,8 +279,13 @@ async function dispatch( req: NeutralRequest, bus: Bus | undefined, trace: Trace | undefined, + precomputed?: Record, ): Promise { - const injected = computeInjected(opts, req); + // Both adapters compute this before routing, because a response written above `handle()` — a + // shed 503, a 413 from the body reader — has to carry the same headers as one written below it. + // Recomputing here would run `security` and, worse, the `origins` predicate a second time for + // one request. `computeInjected` stays as the fallback for callers that have nothing yet. + const injected = precomputed ?? computeInjected(opts, req); let path: string; try { @@ -288,7 +295,7 @@ async function dispatch( } if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { - return { preflight: corsPreflightHeaders(opts.cors, req, opts.logger) }; + return { preflight: corsPreflightHeaders(opts.cors, req, injected) }; } const matched = resolveRoute(routes, req.method, path); diff --git a/src/http/server.ts b/src/http/server.ts index 6f9033d..7b5202e 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -3,12 +3,11 @@ 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'; import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request'; import { pipeStream } from './stream'; import { attachWs } from './ws'; import { mergeInjectedHeaders } from './headers'; -import { handle, correlateRequest, type HandleResult, type Preflight } from './core'; +import { handle, correlateRequest, computeInjected, type HandleResult, type Preflight } from './core'; import type { BodyFailure, BodyReader } from './body'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import { nodeRequire } from '../node-require'; @@ -95,13 +94,12 @@ function createRequestHandler(cfg: HandlerConfig) { const secure = deriveSecure(req, trustProxy); // Derived before the body is read, so a 413 rejected below still carries an identity. const correlation = correlateRequest(req.headers); - const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; + // One computation for the whole request: this object is patched into every response below, and + // handed to `handle()` so routing does not derive it a second time — `security` is pure, but + // `cors.origins` may be a predicate with a network call in it. + const injected = computeInjected(opts, { secure, headers: req.headers }); patchResponseHeaders(res, injected); - // CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily - // by reference at writeHead time, so keys added here still land on every response. - if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts?.logger)); - let result: HandleResult | Preflight; let acquired = false; const watchingEnd = bus?.hasListeners('request:end') ?? false; @@ -138,16 +136,21 @@ function createRequestHandler(cfg: HandlerConfig) { 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), - }); + result = await handle( + routes, + opts, + { + ...correlation, + method: req.method ?? 'GET', + url: req.url ?? '/', + headers: req.headers, + readBody, + source: req, + secure, + ip: deriveIp(req, trustProxy), + }, + injected, + ); } finally { if (acquired) { acquired = false; diff --git a/src/http/web.ts b/src/http/web.ts index 69139a5..15bfdc5 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -173,23 +173,31 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { 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() - : '', - }); + 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() + : '', + }, + // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to + // one call per request. + injected, + ); } finally { // Release when routing/handling finishes, not when a returned stream finishes. // Long-lived streams therefore do not permanently consume the request budget. diff --git a/src/security.ts b/src/security.ts index 8dee23a..f36e809 100644 --- a/src/security.ts +++ b/src/security.ts @@ -128,9 +128,13 @@ export function resolveCors( export function corsPreflightHeaders( opts: CorsOptions, req: { headers: Record }, - logger?: Logger, + resolved?: Headers, ): Headers { - const headers = resolveCors(opts, req, logger); + // The caller has almost always resolved CORS already, one layer up, to seed the headers every + // response carries. Re-deriving here would consult `origins` a second time for the same request — + // and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the + // preflight-only keys below belong to this 204, not to the shared object. + const headers: Headers = { ...resolved }; if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204 headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join( ', ', diff --git a/test/http.test.ts b/test/http.test.ts index 1e7bfc8..ff92d89 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -384,4 +384,39 @@ describe('request hardening', () => { server.close(); }); + + // `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a + // tenant query. Running one twice for a GET and three times for a preflight charges the caller's + // latency budget and their backend for an answer whose inputs did not change in between. + it('consults a cors.origins predicate once per request, not once per header computation', async () => { + let calls = 0; + const server = createHttpServer( + [{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }], + [], undefined, undefined, + { cors: { origins: () => { calls++; return true; } } }, + ); + await new Promise((r) => server.listen(0, r)); + const origin = { origin: 'https://a.com' }; + + const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin }); + expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(calls).toBe(1); + + calls = 0; + const preflight = await fetch(`${getUrl(server)}/ping`, { + method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' }, + }); + expect(preflight.status).toBe(204); + expect(preflight.headers.get('access-control-allow-methods')).toContain('GET'); + expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(calls).toBe(1); + + // No Origin header never reaches the predicate at all — that part was already right. + calls = 0; + await fetch(`${getUrl(server)}/ping`); + expect(calls).toBe(0); + + server.close(); + }); + }); diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts index 54481f8..cbb2991 100644 --- a/test/web-stream.test.ts +++ b/test/web-stream.test.ts @@ -166,6 +166,28 @@ describe('buildFetch request gate', () => { const afterRelease = await fetchHandler(new Request('http://localhost/slow')); expect(afterRelease.status).toBe(200); }); + it('consults a cors.origins predicate once per request on the fetch path too', async () => { + let calls = 0; + const fetchHandler = buildFetch( + [{ method: 'GET', pattern: '/ok', transport: 'buffer', + handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }], + { cors: { origins: () => { calls++; return true; } } }, + ); + + const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } })); + expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(calls).toBe(1); + + calls = 0; + const preflight = await fetchHandler(new Request('http://localhost/ok', { + method: 'OPTIONS', + headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' }, + })); + expect(preflight.status).toBe(204); + expect(preflight.headers.get('access-control-allow-methods')).toContain('GET'); + expect(calls).toBe(1); + }); + it('releases the slot when a streaming handler returns', async () => { async function* stream() { yield { n: 1 };