diff --git a/CHANGELOG.md b/CHANGELOG.md index f880364..1dea5eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,13 @@ npm treats versions as semver and semver forbids leading zeros. constraints at a later segment of an otherwise unreachable route. The route then boots, as before. +- **Edge WebSocket upgrades no longer trust `cf-connecting-ip` by default** (#119). `edgeHandler` + copied the header into `ctx.ip` on every upgrade, so any client that sent it chose its own + address. It now counts only under `trustProxy: true`, the same rule HTTP follows. Without it, + `ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer + address. An app behind Cloudflare that keys anything on the WebSocket IP needs + `createApp({ trustProxy: true })`. + ### Added - **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound @@ -89,6 +96,13 @@ npm treats versions as semver and semver forbids leading zeros. ### Fixed +- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler` + never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for + every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over + `x-forwarded-for`, because Cloudflare sets it itself while XFF can carry hops the client supplied. + Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a + bare `app.fetch`, ignore it as before. + - **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts` was served. Containment now compares real paths: the requested file, and a directory's diff --git a/src/app/index.ts b/src/app/index.ts index 5bd6e19..82e537e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -7,6 +7,7 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; +import { trustedProxyClient } from '../http/peer'; import { buildFetch } from '../http/web'; import { boundInbound, @@ -331,7 +332,10 @@ export function createApp(opts: { devRoutes, () => remoteRoutes, ); - const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits); + const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, { + limits: opts.limits, + trustProxy: opts.trustProxy, + }); const listen = async (port: number): Promise => { const deps = pipelineDeps; @@ -1395,7 +1399,7 @@ function buildAppUpgrade( streams: Set<() => void>, ensureBooted: () => Promise, getMeshControl: () => MeshControl | undefined, - limits?: RequestLimits, + { limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean }, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; @@ -1444,10 +1448,20 @@ function buildAppUpgrade( return; } - await runWsConnection(ready, request, route, deps.bus, streams); + await runWsConnection(ready, withProxyClient(request, trustProxy), route, deps.bus, streams); }; } +/** + * `request` with `ip` taken from the proxy header its adapter recorded, when `trustProxy` allows it + * (the edge adapter's `cf-connecting-ip`, CARD-23); otherwise `request` unchanged. The same check + * `app.fetch` runs, so an edge WebSocket upgrade and an edge HTTP request resolve `ctx.ip` alike. + */ +function withProxyClient(request: WsRequest, trustProxy: boolean | undefined): WsRequest { + const ip = trustedProxyClient(request, trustProxy); + return ip ? { ...request, ip } : request; +} + /** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */ function devGraphRoute(graph: () => GraphView): RouteDef { return { diff --git a/src/edge.ts b/src/edge.ts index 183a022..10fc771 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -1,5 +1,6 @@ import type { App } from './app/types'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; +import { setProxyClient } from './http/peer'; // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Declares only what we call; mirrors the real workerd signatures. @@ -30,7 +31,9 @@ export function edgeHandler( if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; server.accept(); - const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? ''); + // No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`. + const wsReq = toWsRequest(request, ''); + recordClient(wsReq, request); const lifecycle = upgradeSafely(app, wsReq, eventSocket(server)); if (ctx?.waitUntil) ctx.waitUntil(lifecycle); else void lifecycle; @@ -38,6 +41,18 @@ export function edgeHandler( return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket }); } + recordClient(request, request); return app.fetch(request); }; } + +/** + * Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this + * request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app + * option; HTTP and WebSocket both go through here and through the same check on the app side. + * Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address, + * and an untrusted header is whatever the client chose to send. + */ +function recordClient(source: object, request: Request): void { + setProxyClient(source, request.headers.get('cf-connecting-ip') ?? ''); +} diff --git a/src/http/peer.ts b/src/http/peer.ts index d5651fa..84f68e7 100644 --- a/src/http/peer.ts +++ b/src/http/peer.ts @@ -25,3 +25,28 @@ export function setPeer(request: Request, ip: string): void { export function peerOf(request: Request): string { return peers.get(request) ?? ''; } + +// The client address a runtime adapter read from a header its platform's proxy sets — today only the +// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied +// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot +// decide that, because the option lives on the app, so it records the value and the app decides. +// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for +// the same reasons as the peer: no handler-visible header, no extra public parameter. Same +// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too. +const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client'); +const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap }; +const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap()); + +/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */ +export function setProxyClient(source: object, ip: string): void { + if (ip) proxyClients.set(source, ip); +} + +/** + * The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on; + * `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot + * disagree about whether the header counts. + */ +export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string { + return trustProxy ? (proxyClients.get(source) ?? '') : ''; +} diff --git a/src/http/web.ts b/src/http/web.ts index 82a070a..7c9ec93 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -11,7 +11,7 @@ import { type Preflight, } from './core'; import { mergeInjectedHeaders } from './headers'; -import { peerOf } from './peer'; +import { peerOf, trustedProxyClient } from './peer'; import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body'; import { HttpError } from '../signals'; import { renderError, type ErrorRequest } from '../transformers'; @@ -299,7 +299,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { // proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable. // Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare // `app.fetch` has none, so there the answer is still ''. - ip: forwardedFor(headers, opts) || peerOf(request), + // Ahead of both, under `trustProxy` only: the address the edge adapter read from + // `cf-connecting-ip`. Cloudflare sets that header itself, while XFF can carry hops the + // client supplied, so on the edge it wins (CARD-23). + ip: trustedProxyClient(request, opts?.trustProxy) || forwardedFor(headers, opts) || peerOf(request), }, // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to // one call per request. diff --git a/test/edge-client-ip.test.ts b/test/edge-client-ip.test.ts new file mode 100644 index 0000000..8c7538b --- /dev/null +++ b/test/edge-client-ip.test.ts @@ -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, headers: Record) => + ((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(), + 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 { + 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((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(['']); + }); +}); diff --git a/test/edge/run.ts b/test/edge/run.ts index 8a523e6..c080839 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -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) => + ((await (await mf.dispatchFetch(`http://${host}/rt/ip`, { headers })).json()) as { ip: string }).ip; + const wsIp = async (host: string, headers: Record) => { + 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((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(); } diff --git a/test/edge/worker.ts b/test/edge/worker.ts index 0f82780..904f7e5 100644 --- a/test/edge/worker.ts +++ b/test/edge/worker.ts @@ -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> = { + default: edgeHandler(app), + limited: edgeHandler(limited), + trusted: edgeHandler(trusted), +}; export default { - fetch: (request: Request, env?: unknown, ctx?: Parameters[2]) => - (new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx), + fetch: (request: Request, env?: unknown, ctx?: Parameters>[2]) => + (handlers[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx), };