diff --git a/src/http/core.ts b/src/http/core.ts index 357511e..977dfdf 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -132,7 +132,7 @@ export function computeInjected( req: { secure: boolean; headers: Record }, ): Record { const injected: Record = { ...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); diff --git a/src/http/server.ts b/src/http/server.ts index 44b3aec..32ad05e 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -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; diff --git a/src/security.ts b/src/security.ts index c48023d..8dee23a 100644 --- a/src/security.ts +++ b/src/security.ts @@ -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 }, + 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 }, + 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( ', ', diff --git a/test/http.test.ts b/test/http.test.ts index 01b5bdd..1e7bfc8 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -352,4 +352,36 @@ describe('request hardening', () => { expect(await res.json()).toEqual({ a: '1', b: 'two' }); server.close(); }); + + it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => { + const warn = vi.fn(); + const server = createHttpServer( + [{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }], + [], + undefined, + undefined, + { + cors: { + origins: () => { + throw new Error('lookup failed'); + }, + }, + logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() } as any, + }, + ); + await new Promise((r) => server.listen(0, r)); + + // Only a request carrying an Origin reaches the predicate — which is why a suite that forgets + // the header watches this crash in production instead. + const res = await fetch(`${getUrl(server)}/ping`, { headers: { origin: 'https://a.com' } }); + + expect(res.status).toBe(200); + expect(res.headers.get('access-control-allow-origin')).toBeNull(); + expect(warn).toHaveBeenCalled(); + + // The security headers still land: one broken predicate must not strip the rest. + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + server.close(); + }); + }); diff --git a/test/security.test.ts b/test/security.test.ts index 4cba1e9..4ddce20 100644 --- a/test/security.test.ts +++ b/test/security.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security'; describe('buildSecurityHeaders', () => { @@ -51,6 +51,33 @@ describe('resolveCors', () => { const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any); expect(r['access-control-allow-origin']).toBeUndefined(); }); + + // An `origins` predicate is the whole reason the option takes a function: an allowlist in Redis, a + // tenant lookup, a regex over a parsed URL. Every one of those has a failure mode, and it runs on + // the request path — so a throw must not leave the boundary. + describe('a predicate that throws', () => { + const boom = () => { + throw new Error('lookup failed'); + }; + + it('denies the origin rather than escaping the request path', () => { + expect(() => resolveCors({ origins: boom }, req('https://a.com') as any)).not.toThrow(); + expect(resolveCors({ origins: boom }, req('https://a.com') as any)).toEqual({}); + }); + + it('fails closed even when credentials are on — a broken allowlist is not an open one', () => { + const r = resolveCors({ origins: boom, credentials: true }, req('https://a.com') as any); + expect(r['access-control-allow-origin']).toBeUndefined(); + expect(r['access-control-allow-credentials']).toBeUndefined(); + }); + + it('reports the failure through the logger instead of swallowing it', () => { + const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; + resolveCors({ origins: boom }, req('https://a.com') as any, logger as any); + expect(logger.warn).toHaveBeenCalledOnce(); + expect(logger.warn.mock.calls[0][0]).toMatch(/cors/i); + }); + }); }); describe('isValidOrigin', () => { diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts index 4728c5a..54481f8 100644 --- a/test/web-stream.test.ts +++ b/test/web-stream.test.ts @@ -52,8 +52,10 @@ describe('asReadableStream', () => { }); describe('buildFetch request gate', () => { - it('does not permanently exhaust the gate when CORS setup throws', async () => { - let attempts = 0; + it('rides out a transient CORS predicate failure without leaking a gate slot', async () => { + // A flag rather than an attempt counter: `computeInjected` runs both in this adapter and again + // inside `handle()`, so the predicate is consulted more than once per request. + let lookupDown = true; const fetchHandler = buildFetch( [ @@ -68,8 +70,7 @@ describe('buildFetch request gate', () => { limits: { maxConcurrentRequests: 2 }, cors: { origins: () => { - attempts++; - if (attempts <= 2) throw new Error('transient CORS failure'); + if (lookupDown) throw new Error('transient CORS failure'); return true; }, }, @@ -81,11 +82,20 @@ describe('buildFetch request gate', () => { headers: { origin: 'https://example.com' }, }); - await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure'); - await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure'); + // While the lookup is down the origin is denied — the request is answered, just without the + // header that would let the browser read it. A failed lookup has not said yes. + for (let i = 0; i < 2; i++) { + const denied = await fetchHandler(request()); + expect(denied.status).toBe(200); + expect(denied.headers.get('access-control-allow-origin')).toBeNull(); + } + // Once the lookup recovers the origin is allowed again, which also proves the two failures + // returned their slots: a budget of 2 that leaked would have shed this one. + lookupDown = false; const recovered = await fetchHandler(request()); expect(recovered.status).toBe(200); + expect(recovered.headers.get('access-control-allow-origin')).toBe('https://example.com'); }); it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {