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[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
injected?: Record<string, string>,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
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<string, string>,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
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<string, string>,
|
||||
): 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;
|
||||
|
||||
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);
|
||||
|
||||
+20
-17
@@ -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<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);
|
||||
|
||||
// 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;
|
||||
|
||||
+25
-17
@@ -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.
|
||||
|
||||
+6
-2
@@ -128,9 +128,13 @@ export function resolveCors(
|
||||
export function corsPreflightHeaders(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
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(
|
||||
', ',
|
||||
|
||||
@@ -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<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'));
|
||||
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 };
|
||||
|
||||
Reference in new issue
Block a user