Merge pull request 'feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)' (#139) from feature/fprd-001c-edge-cf-connecting-ip into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
This commit was merged in pull request #139.
This commit is contained in:
commit
a9e0555516
8 files changed
+244
-10
No files matched your search
@@ -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
|
||||
|
||||
+17
-3
@@ -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
@@ -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,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
@@ -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.
|
||||
|
||||
@@ -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