From 08cb8554e6797b0cf6423fecf37a581e454b4e6f Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:26:45 -0500 Subject: [PATCH] fix(fetch): security headers on early failures, live mesh boot gate app.fetch's 413/400/501 body-acquisition failures were returned without the injected security/CORS headers Node's writeHead patch always applies, breaking byte-identical parity with the listen() path. Extract computeInjected() (shared by handle() and buildFetch()) and merge it into every error response, not just handle()'s outcomes. Also, buildAppFetch captured `booted` by value at createApp() time, so mesh apps (whose finalize() is deferred into listen()) had app.fetch permanently throw even after a successful listen(). Read booted live via a getter, mirroring explain()/graph()/inspect(), and lazily build/cache the fetch handler on first call after boot. Signed-off-by: Diego Resendez --- src/app/index.ts | 21 +++++++++++------- src/http/core.ts | 18 ++++++++++++++-- src/http/web.ts | 33 +++++++++++++++++++++------- test/fetch.test.ts | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 18 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index a05c755..d156c21 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -141,7 +141,7 @@ export function createApp(opts: { onError: opts.onError, }; const fetchFn = buildAppFetch( - booted, + () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, fetchOpts, @@ -617,22 +617,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps /** * Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so * `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`. - * Non-mesh apps finalize eagerly, so `booted` is already `true` and the route table is ready - * immediately. Mesh apps defer finalize to `listen()` (remote scopes must splice into the graph - * first), so the returned function throws until then — mirroring the explain()/graph()/inspect() - * "unavailable before listen()" guard. + * Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built + * on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the + * graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like + * `explain()`/`graph()`/`inspect()` do — so the returned function throws until `listen()` finalizes, + * then starts working from the next call on, without ever needing to be rebuilt. */ function buildAppFetch( - booted: boolean, + getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, ): (request: Request) => Promise { - const handler = booted ? buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts) : undefined; + let handler: ((request: Request) => Promise) | undefined; return async (request: Request): Promise => { - if (!handler) throw new Error('fetch() unavailable before listen() for mesh apps'); + if (!handler) { + if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); + handler = buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts); + } + await ensureBooted(); // idempotent: no-op if listen() already booted the providers return handler(request); }; diff --git a/src/http/core.ts b/src/http/core.ts index 76fab22..a6771bb 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -34,6 +34,21 @@ export interface Preflight { preflight: Record; } +/** + * Computes the security + CORS headers that get injected into every response for a request — the same + * authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts) + * so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's + * `patchResponseHeaders` would have installed up-front. + */ +export function computeInjected( + opts: HttpOptions | undefined, + 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)); + return injected; +} + /** * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the @@ -45,8 +60,7 @@ export async function handle( req: NeutralRequest, ): Promise { const path = req.url.split('?')[0]; - const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; - if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + const injected = computeInjected(opts, req); if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { return { preflight: corsPreflightHeaders(opts.cors, req) }; diff --git a/src/http/web.ts b/src/http/web.ts index d146b42..e8d073a 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -1,5 +1,5 @@ import type { StreamEncoder } from '../encoders'; -import { handle, type HandleResult } from './core'; +import { handle, computeInjected, type HandleResult } from './core'; import { mergeInjectedHeaders } from './headers'; import { parseRequestBody } from './server'; import { matchRoute } from './router'; @@ -43,9 +43,15 @@ function headersToRecord(headers: Headers): Record { return out; } -/** Turns a rendered error (or any {status, headers, body}) into a web `Response`. */ -function errorResponse(rendered: ErrorResponse): Response { - return new Response(rendered.body, { status: rendered.status, headers: rendered.headers }); +/** + * Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the + * authoritative `injected` security/CORS headers — mirrors the Node adapter, where + * `patchResponseHeaders` installs these before body acquisition even runs, so early failures + * (413/400/501) carry them too. + */ +function errorResponse(rendered: ErrorResponse, injected: Record): Response { + const headers = mergeInjectedHeaders(rendered.headers, injected); + return new Response(rendered.body, { status: rendered.status, headers }); } /** @@ -59,6 +65,7 @@ async function acquireFetchBody( path: string, maxBody: number, opts: HttpOptions | undefined, + injected: Record, ): Promise<{ body: unknown } | { response: Response }> { const errReq: ErrorRequest = { method: request.method, url: path, headers }; let buf: Buffer | undefined; @@ -68,7 +75,9 @@ async function acquireFetchBody( const bodyLimit = matched.def.maxBodyBytes ?? maxBody; if (arrayBuffer.byteLength > bodyLimit) { - return { response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError)) }; + return { + response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected), + }; } buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer); @@ -81,7 +90,10 @@ async function acquireFetchBody( if ('error' in parsed) { return { - response: errorResponse(renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError)), + response: errorResponse( + renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError), + injected, + ), }; } @@ -112,10 +124,15 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { const path = url.pathname + url.search; const headers = headersToRecord(request.headers); const matched = matchRoute(routes, request.method, url.pathname); + const secure = url.protocol === 'https:'; + // Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501, + // before a route handler even runs) carry the same security/CORS headers Node's writeHead patch + // would have installed before body acquisition. + const injected = computeInjected(opts, { secure, headers }); let body: unknown; if (matched) { - const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts); + const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected); if ('response' in acquired) return acquired.response; body = acquired.body; } @@ -125,7 +142,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { url: path, headers, body, - secure: url.protocol === 'https:', + secure, ip: headers['x-forwarded-for'] ?? '', }); diff --git a/test/fetch.test.ts b/test/fetch.test.ts index fd96008..9b1a253 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -15,11 +15,23 @@ class Ctl { @Post('/echo') echo(@body() b: any) { return { got: b }; } + @Post('/tiny', { maxBodyBytes: 10 }) tiny(@body() b: any) { + return { got: b }; + } } @Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] }) class M {} const app = createApp({ modules: [M] }); +@Route('/mesh') +class MeshCtl { + @Get('/ping') ping() { + return { pong: true }; + } +} +@Module({ mountpoint: '/api', controllers: [MeshCtl] }) +class MeshModule {} + describe('app.fetch', () => { it('handles GET and returns JSON 200', async () => { const res = await app.fetch(new Request('http://x/api/hello')); @@ -44,4 +56,46 @@ describe('app.fetch', () => { const res = await app.fetch(new Request('http://x/api/hello')); expect(res.headers.get('x-content-type-options')).toBe('nosniff'); }); + + it('a 413 (oversized body) still carries the injected security headers', async () => { + const res = await app.fetch( + new Request('http://x/api/tiny', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ x: 'well over ten bytes' }), + }), + ); + expect(res.status).toBe(413); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + }); + + it('a 400 (invalid JSON) still carries the injected security headers', async () => { + const res = await app.fetch( + new Request('http://x/api/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{not json', + }), + ); + expect(res.status).toBe(400); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); +}); + +describe('app.fetch mesh gating (live `booted` read)', () => { + it('throws before listen() and starts working after listen() finalizes', async () => { + const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); + + await expect(meshApp.fetch(new Request('http://x/api/mesh/ping'))).rejects.toThrow(/unavailable before listen/); + + const server = await meshApp.listen(0); + try { + const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ pong: true }); + } finally { + server.close(); + } + }); });