perf(cors): resolve the request's headers once, not two or three times
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.
Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.
`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.
Measured against the built `dist/`, same script that produced the numbers in the issue:
GET with Origin 2x -> 1x
OPTIONS preflight 3x -> 1x
buildFetch, Origin 2x -> 1x
GET without Origin 0x -> 0x (never reached the predicate; unchanged)
The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.
Closes #77.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+120
-41
No files matched your search
+12
-5
@@ -212,6 +212,7 @@ export function handle(
|
|||||||
routes: RouteDef[],
|
routes: RouteDef[],
|
||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
|
injected?: Record<string, string>,
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
const bus = opts?.bus;
|
const bus = opts?.bus;
|
||||||
|
|
||||||
@@ -227,10 +228,10 @@ export function handle(
|
|||||||
bus.hasListeners('route:unmatched')
|
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(
|
async function observedDispatch(
|
||||||
@@ -238,6 +239,7 @@ async function observedDispatch(
|
|||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
bus: Bus,
|
bus: Bus,
|
||||||
|
injected?: Record<string, string>,
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
const watchingEnd = bus.hasListeners('request:end');
|
const watchingEnd = bus.hasListeners('request:end');
|
||||||
const startedAt = watchingEnd ? performance.now() : 0;
|
const startedAt = watchingEnd ? performance.now() : 0;
|
||||||
@@ -251,7 +253,7 @@ async function observedDispatch(
|
|||||||
traceId: req.traceId,
|
traceId: req.traceId,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await dispatch(routes, opts, req, bus, trace);
|
const result = await dispatch(routes, opts, req, bus, trace, injected);
|
||||||
|
|
||||||
if (watchingEnd) {
|
if (watchingEnd) {
|
||||||
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
// 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,
|
req: NeutralRequest,
|
||||||
bus: Bus | undefined,
|
bus: Bus | undefined,
|
||||||
trace: Trace | undefined,
|
trace: Trace | undefined,
|
||||||
|
precomputed?: Record<string, string>,
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
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;
|
let path: string;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -288,7 +295,7 @@ async function dispatch(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
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);
|
const matched = resolveRoute(routes, req.method, path);
|
||||||
|
|||||||
+20
-17
@@ -3,12 +3,11 @@ import type https from 'https';
|
|||||||
import { createRequestGate } from './request-gate';
|
import { createRequestGate } from './request-gate';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
|
||||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||||
import { pipeStream } from './stream';
|
import { pipeStream } from './stream';
|
||||||
import { attachWs } from './ws';
|
import { attachWs } from './ws';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
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 { BodyFailure, BodyReader } from './body';
|
||||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
@@ -95,13 +94,12 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
const secure = deriveSecure(req, trustProxy);
|
const secure = deriveSecure(req, trustProxy);
|
||||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||||
const correlation = correlateRequest(req.headers);
|
const correlation = correlateRequest(req.headers);
|
||||||
const injected: Record<string, string> = { ...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);
|
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 result: HandleResult | Preflight;
|
||||||
let acquired = false;
|
let acquired = false;
|
||||||
const watchingEnd = bus?.hasListeners('request:end') ?? false;
|
const watchingEnd = bus?.hasListeners('request:end') ?? false;
|
||||||
@@ -138,16 +136,21 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
gate.release();
|
gate.release();
|
||||||
});
|
});
|
||||||
|
|
||||||
result = await handle(routes, opts, {
|
result = await handle(
|
||||||
...correlation,
|
routes,
|
||||||
method: req.method ?? 'GET',
|
opts,
|
||||||
url: req.url ?? '/',
|
{
|
||||||
headers: req.headers,
|
...correlation,
|
||||||
readBody,
|
method: req.method ?? 'GET',
|
||||||
source: req,
|
url: req.url ?? '/',
|
||||||
secure,
|
headers: req.headers,
|
||||||
ip: deriveIp(req, trustProxy),
|
readBody,
|
||||||
});
|
source: req,
|
||||||
|
secure,
|
||||||
|
ip: deriveIp(req, trustProxy),
|
||||||
|
},
|
||||||
|
injected,
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
if (acquired) {
|
if (acquired) {
|
||||||
acquired = false;
|
acquired = false;
|
||||||
|
|||||||
+25
-17
@@ -173,23 +173,31 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
|
|
||||||
acquired = true;
|
acquired = true;
|
||||||
|
|
||||||
result = await handle(routes, opts, {
|
result = await handle(
|
||||||
...correlation,
|
routes,
|
||||||
method: request.method,
|
opts,
|
||||||
url: path,
|
{
|
||||||
headers,
|
...correlation,
|
||||||
readBody,
|
method: request.method,
|
||||||
source: request,
|
url: path,
|
||||||
secure,
|
headers,
|
||||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
readBody,
|
||||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
source: request,
|
||||||
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
secure,
|
||||||
ip: opts?.trustProxy
|
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
|
||||||
? String(headers['x-forwarded-for'] ?? '')
|
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
|
||||||
.split(',')[0]
|
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
|
||||||
.trim()
|
// 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 {
|
} finally {
|
||||||
// Release when routing/handling finishes, not when a returned stream finishes.
|
// Release when routing/handling finishes, not when a returned stream finishes.
|
||||||
// Long-lived streams therefore do not permanently consume the request budget.
|
// Long-lived streams therefore do not permanently consume the request budget.
|
||||||
|
|||||||
+6
-2
@@ -128,9 +128,13 @@ export function resolveCors(
|
|||||||
export function corsPreflightHeaders(
|
export function corsPreflightHeaders(
|
||||||
opts: CorsOptions,
|
opts: CorsOptions,
|
||||||
req: { headers: Record<string, string | string[] | undefined> },
|
req: { headers: Record<string, string | string[] | undefined> },
|
||||||
logger?: Logger,
|
resolved?: Headers,
|
||||||
): 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
|
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(
|
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
|
||||||
', ',
|
', ',
|
||||||
|
|||||||
@@ -384,4 +384,39 @@ describe('request hardening', () => {
|
|||||||
server.close();
|
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<void>((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();
|
||||||
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
@@ -166,6 +166,28 @@ describe('buildFetch request gate', () => {
|
|||||||
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
|
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
|
||||||
expect(afterRelease.status).toBe(200);
|
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 () => {
|
it('releases the slot when a streaming handler returns', async () => {
|
||||||
async function* stream() {
|
async function* stream() {
|
||||||
yield { n: 1 };
|
yield { n: 1 };
|
||||||
|
|||||||
Reference in new issue
Block a user