fix(fetch): gate x-forwarded-for on trustProxy in app.fetch

The Web-Standards fetch adapter read x-forwarded-for unconditionally to
seed ctx.ip, unlike Node's deriveIp which only honours it when
trustProxy is enabled. A client could spoof ctx.ip on any handler
relying on it. Mirror deriveIp's first-hop semantics and only trust
the header when trustProxy is set; otherwise ctx.ip is ''.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-09 14:45:27 -05:00
1 parent 1fee7de543
commit 43a4316a29
2 files changed
+36 -2

No files matched your search

+8 -1
View File
@@ -143,7 +143,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
headers,
body,
secure,
ip: headers['x-forwarded-for'] ?? '',
// 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()
: '',
});
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
+28 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Route, Get, Post, Module, needs, body } from '../src/index';
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
@Provider({ provides: 'store' })
class Store {
@@ -83,6 +83,33 @@ describe('app.fetch', () => {
});
});
@Route('/ip')
class IpCtl {
@Get('/whoami') whoami(@ctx() c: any) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [IpCtl] })
class IpModule {}
describe('app.fetch trustProxy gates x-forwarded-for', () => {
it('honors x-forwarded-for (first hop) when trustProxy is true', async () => {
const trustingApp = createApp({ modules: [IpModule], trustProxy: true });
const res = await trustingApp.fetch(
new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }),
);
expect(await res.json()).toEqual({ ip: '9.9.9.9' });
});
it('ignores x-forwarded-for when trustProxy is off (default)', async () => {
const untrustingApp = createApp({ modules: [IpModule] });
const res = await untrustingApp.fetch(
new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }),
);
expect(await res.json()).toEqual({ ip: '' });
});
});
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' } });