feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s

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:
chrnx committed 2026-10-23 00:47:58 -05:00
1 parent 89ac955072
commit 88cbe41f72
8 files changed
+244 -10

No files matched your search

+17 -3
View File
@@ -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<http.Server> => {
const deps = pipelineDeps;
@@ -1395,7 +1399,7 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
): (request: WsRequest, socket: WsSocket) => Promise<void> {
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 {
+16 -1
View File
@@ -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') ?? '');
}
+25
View File
@@ -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<object, string> };
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
/** 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) ?? '') : '';
}
+5 -2
View File
@@ -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.