fix(cors): deny the origin when the origins predicate throws
`CorsOptions.origins` accepts a predicate, and it runs on the request path above the region where errors convert to a response. A predicate that threw became a rejected promise nobody awaited, and Node's default for that is to exit — so one cross-origin GET took the process down, with `onError` never reaching it. The trigger is a browser: `originAllowed` only runs when an `Origin` header is present, so the crash is reachable by any cross-origin client and by no test that forgets the header, which is how it survived a green suite. Guard the call at `originAllowed`, the single point all four call sites funnel through (the Node handler, `computeInjected` on both adapters, and the preflight path). A predicate that throws denies the origin: a lookup that failed has not said yes, and a broken allowlist must never widen into an open one. The failure is reported through the app logger rather than swallowed — `HttpOptions` already carries one. The published behaviour changes for a throwing predicate only. Every other origin shape is untouched, and the security headers still land on the response. Amends one test from the `maxConcurrentRequests` contribution, which asserted the old crash as its baseline while proving the gate does not leak a slot. It still proves that, against a transient failure that is now answered rather than fatal. Closes #72. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+101
-15
No files matched your search
+2
-2
@@ -132,7 +132,7 @@ export function computeInjected(
|
||||
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
|
||||
): Record<string, string> {
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
|
||||
return injected;
|
||||
}
|
||||
|
||||
@@ -287,7 +287,7 @@ async function dispatch(
|
||||
}
|
||||
|
||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||
return { preflight: corsPreflightHeaders(opts.cors, req, opts.logger) };
|
||||
}
|
||||
|
||||
const matched = resolveRoute(routes, req.method, path);
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
|
||||
// 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));
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts?.logger));
|
||||
|
||||
let result: HandleResult | Preflight;
|
||||
let acquired = false;
|
||||
|
||||
+22
-5
@@ -1,5 +1,7 @@
|
||||
// src/security.ts — pure header computation, no server deps
|
||||
|
||||
import type { Logger } from './logger';
|
||||
|
||||
/** TLS material for an HTTPS server. */
|
||||
export interface TlsOptions {
|
||||
key: Buffer | string;
|
||||
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
|
||||
return headers;
|
||||
}
|
||||
|
||||
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
|
||||
function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
|
||||
if (spec === '*') return true;
|
||||
if (typeof spec === 'function') return spec(origin);
|
||||
if (Array.isArray(spec)) return spec.includes(origin);
|
||||
return spec === origin;
|
||||
if (typeof spec !== 'function') return spec === origin;
|
||||
|
||||
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
|
||||
// before the region where errors convert to a response, so a throw here would leave the request
|
||||
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
|
||||
// has not said yes, and a broken allowlist must never widen into an open one.
|
||||
try {
|
||||
return spec(origin);
|
||||
} catch (error) {
|
||||
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
|
||||
origin,
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
|
||||
export function resolveCors(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
logger?: Logger,
|
||||
): Headers {
|
||||
const headers: Headers = {};
|
||||
const rawOrigin = req.headers['origin'];
|
||||
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
|
||||
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers;
|
||||
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
|
||||
|
||||
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
|
||||
if (opts.credentials) {
|
||||
@@ -112,8 +128,9 @@ export function resolveCors(
|
||||
export function corsPreflightHeaders(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
logger?: Logger,
|
||||
): Headers {
|
||||
const headers = resolveCors(opts, req);
|
||||
const headers = resolveCors(opts, req, logger);
|
||||
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(
|
||||
', ',
|
||||
|
||||
Reference in new issue
Block a user