feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket upgrade, so any client that sent the header chose its own address, and it never read the header for HTTP, so IP-keyed plugins saw '' there. D21 settles both: the header counts only under trustProxy, on both paths, with no new option. The adapter cannot make that call, because trustProxy is an app option. So edgeHandler records the header against the object it hands the app (the Request for HTTP, the WsRequest for an upgrade) in an internal registry next to the Deno/Bun peer one, and app.fetch and app.upgrade both consult it through one helper, trustedProxyClient(), which returns '' unless trustProxy is on. Under trustProxy it takes precedence over x-forwarded-for, since Cloudflare sets it itself and XFF can carry client-supplied hops. Nothing else records into the registry, so the Node, Deno and Bun adapters, and a bare app.fetch or app.upgrade, ignore the header as before. BREAKING CHANGE: an edge WebSocket upgrade no longer takes ctx.ip from cf-connecting-ip unless the app sets trustProxy: true; without it, ctx.ip is ''. Refs: #119 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
8 files changed
+244
-10
No files matched your search
@@ -0,0 +1,119 @@
|
||||
// CARD-23 (#119, D21): on the edge, `cf-connecting-ip` sets `ctx.ip` only under `trustProxy`, for HTTP
|
||||
// and WebSocket alike, and wins over `x-forwarded-for`. The full WebSocket path through workerd
|
||||
// (`WebSocketPair`, a 101 response) cannot run under Node, so it is covered in `test/edge/run.ts`;
|
||||
// here the edge HTTP path runs through `edgeHandler` itself, and the WebSocket side through
|
||||
// `app.upgrade` with the value recorded the way `edgeHandler` records it.
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
|
||||
import { edgeHandler } from '../src/edge';
|
||||
import { channel } from '../src/channel';
|
||||
import { setProxyClient } from '../src/http/peer';
|
||||
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||
|
||||
@Route('/ip')
|
||||
class IpCtl {
|
||||
@Get('/whoami') whoami(@ctx() c: any) {
|
||||
return { ip: c.ip };
|
||||
}
|
||||
|
||||
@Ws('/ws')
|
||||
ws(@ctx() c: any) {
|
||||
return (async function* () {
|
||||
yield String(c.ip);
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [IpCtl] })
|
||||
class IpModule {}
|
||||
|
||||
const trusting = createApp({ modules: [IpModule], trustProxy: true });
|
||||
const untrusting = createApp({ modules: [IpModule] });
|
||||
|
||||
const whoami = async (handler: (r: Request) => Response | Promise<Response>, headers: Record<string, string>) =>
|
||||
((await (await handler(new Request('http://x/ip/whoami', { headers }))).json()) as { ip: string }).ip;
|
||||
|
||||
describe('edge HTTP: cf-connecting-ip', () => {
|
||||
it('T1: under trustProxy it sets ctx.ip', async () => {
|
||||
expect(await whoami(edgeHandler(trusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('1.2.3.4');
|
||||
});
|
||||
|
||||
it('T2: under trustProxy it wins over x-forwarded-for', async () => {
|
||||
const headers = { 'cf-connecting-ip': '1.2.3.4', 'x-forwarded-for': '9.9.9.9' };
|
||||
expect(await whoami(edgeHandler(trusting), headers)).toBe('1.2.3.4');
|
||||
});
|
||||
|
||||
it('under trustProxy without the header, x-forwarded-for still applies', async () => {
|
||||
expect(await whoami(edgeHandler(trusting), { 'x-forwarded-for': '9.9.9.9' })).toBe('9.9.9.9');
|
||||
});
|
||||
|
||||
it('T3: without trustProxy it is ignored and ctx.ip stays empty', async () => {
|
||||
expect(await whoami(edgeHandler(untrusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
function fakeSocket() {
|
||||
const ac = new AbortController();
|
||||
const sent: string[] = [];
|
||||
const socket: WsSocket = {
|
||||
inbound: channel<unknown>(),
|
||||
abort: ac.signal,
|
||||
isOpen: true,
|
||||
send: (d) => sent.push(d),
|
||||
close: () => ac.abort(),
|
||||
terminate: () => ac.abort(),
|
||||
};
|
||||
return { socket, sent };
|
||||
}
|
||||
|
||||
/** Upgrades the way `edgeHandler` does: `ip` empty, the header recorded on the `WsRequest`. */
|
||||
async function edgeWsIp(app: typeof trusting, cfConnectingIp: string): Promise<string> {
|
||||
const headers = { 'cf-connecting-ip': cfConnectingIp };
|
||||
const req: WsRequest = { url: '/ip/ws', headers, protocol: 'http', ip: '' };
|
||||
setProxyClient(req, cfConnectingIp);
|
||||
const { socket, sent } = fakeSocket();
|
||||
await app.upgrade(req, socket);
|
||||
return sent[0];
|
||||
}
|
||||
|
||||
describe('edge WebSocket: cf-connecting-ip', () => {
|
||||
it('T4: without trustProxy it is ignored and ctx.ip stays empty', async () => {
|
||||
expect(await edgeWsIp(untrusting, '1.2.3.4')).toBe('');
|
||||
});
|
||||
|
||||
it('T5: under trustProxy it sets ctx.ip', async () => {
|
||||
expect(await edgeWsIp(trusting, '1.2.3.4')).toBe('1.2.3.4');
|
||||
});
|
||||
|
||||
it('an adapter-supplied ip with nothing recorded is passed through unchanged', async () => {
|
||||
const { socket, sent } = fakeSocket();
|
||||
await trusting.upgrade({ url: '/ip/ws', headers: {}, protocol: 'http', ip: '203.0.113.7' }, socket);
|
||||
expect(sent).toEqual(['203.0.113.7']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('outside the edge adapter the header means nothing', () => {
|
||||
it('T6: the Node listener under trustProxy ignores cf-connecting-ip', async () => {
|
||||
const server = await createApp({ modules: [IpModule], trustProxy: true }).listen(0);
|
||||
try {
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const res = await fetch(`http://127.0.0.1:${port}/ip/whoami`, { headers: { 'cf-connecting-ip': '1.2.3.4' } });
|
||||
const { ip } = (await res.json()) as { ip: string };
|
||||
expect(ip).not.toBe('1.2.3.4');
|
||||
expect(ip).toMatch(/127\.0\.0\.1|::1/);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it('a bare app.fetch under trustProxy ignores cf-connecting-ip', async () => {
|
||||
expect(await whoami((r) => trusting.fetch(r), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
|
||||
});
|
||||
|
||||
it('a bare app.upgrade under trustProxy ignores the header in WsRequest.headers', async () => {
|
||||
const { socket, sent } = fakeSocket();
|
||||
await trusting.upgrade({ url: '/ip/ws', headers: { 'cf-connecting-ip': '1.2.3.4' }, protocol: 'http', ip: '' }, socket);
|
||||
expect(sent).toEqual(['']);
|
||||
});
|
||||
});
|
||||
+26
-1
@@ -138,7 +138,32 @@ async function main() {
|
||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
|
||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
||||
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
|
||||
// CARD-23 (#119): `cf-connecting-ip` sets ctx.ip only under trustProxy, for HTTP and WS alike,
|
||||
// and wins over x-forwarded-for.
|
||||
const cf = { 'cf-connecting-ip': '1.2.3.4' };
|
||||
const httpIp = async (host: string, headers: Record<string, string>) =>
|
||||
((await (await mf.dispatchFetch(`http://${host}/rt/ip`, { headers })).json()) as { ip: string }).ip;
|
||||
const wsIp = async (host: string, headers: Record<string, string>) => {
|
||||
const res = await mf.dispatchFetch(`http://${host}/rt/ws-ip`, { headers: { Upgrade: 'websocket', ...headers } });
|
||||
const socket = res.webSocket;
|
||||
assert.ok(socket, 'expected a client webSocket on the 101 response');
|
||||
const reply = new Promise<string>((resolve) =>
|
||||
socket.addEventListener('message', (e: { data: unknown }) => resolve(String(e.data))),
|
||||
);
|
||||
socket.accept();
|
||||
const got = await reply;
|
||||
socket.close();
|
||||
return got;
|
||||
};
|
||||
assert.equal(await httpIp('trusted', cf), '1.2.3.4', 'T1 edge HTTP under trustProxy');
|
||||
assert.equal(await httpIp('trusted', { ...cf, 'x-forwarded-for': '9.9.9.9' }), '1.2.3.4', 'T2 cf wins over XFF');
|
||||
assert.equal(await httpIp('localhost', cf), '', 'T3 edge HTTP without trustProxy');
|
||||
assert.equal(await wsIp('localhost', cf), 'ip:', 'T4 edge WS without trustProxy');
|
||||
assert.equal(await wsIp('trusted', cf), 'ip:1.2.3.4', 'T5 edge WS under trustProxy');
|
||||
|
||||
console.log(
|
||||
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy — PASS',
|
||||
);
|
||||
} finally {
|
||||
await mf.dispose();
|
||||
}
|
||||
|
||||
+22
-3
@@ -35,6 +35,19 @@ class Rt {
|
||||
})();
|
||||
}
|
||||
|
||||
// CARD-23: what `ctx.ip` resolved to, over HTTP and over a WebSocket upgrade.
|
||||
@Get('/ip')
|
||||
ip(@ctx() c: any) {
|
||||
return { ip: c.ip };
|
||||
}
|
||||
|
||||
@Ws('/ws-ip')
|
||||
wsIp(@ctx() c: any) {
|
||||
return (async function* () {
|
||||
yield `ip:${c.ip}`;
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
@@ -49,9 +62,15 @@ class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
||||
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
|
||||
// CARD-23: the same graph under `trustProxy`, reached through the `trusted` host.
|
||||
const trusted = createApp({ modules: [M], trustProxy: true });
|
||||
const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
|
||||
default: edgeHandler(app),
|
||||
limited: edgeHandler(limited),
|
||||
trusted: edgeHandler(trusted),
|
||||
};
|
||||
|
||||
export default {
|
||||
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
|
||||
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
|
||||
fetch: (request: Request, env?: unknown, ctx?: Parameters<ReturnType<typeof edgeHandler>>[2]) =>
|
||||
(handlers[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx),
|
||||
};
|
||||
Reference in new issue
Block a user