diff --git a/CHANGELOG.md b/CHANGELOG.md index da1c245..1c8937b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,7 +49,7 @@ npm treats versions as semver and semver forbids leading zeros. while the app runs needs a restart** to take effect. A link swapped inside the root between the check and the read can still escape; exploiting that needs write access to the served directory. -- **A request that fails past the error renderer no longer takes the Node process down.** The Node +- **A request that fails past the error renderer no longer takes the Node process down** (#108). The Node request listener was an `async` function, and `http.createServer` ignores the promise it returns, so anything that rejected outside the region where errors convert to a response — a custom static resolver, a handler header value Node refuses to write, a stream that fails before its first frame @@ -70,8 +70,6 @@ npm treats versions as semver and semver forbids leading zeros. with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before the socket finished opening now reaches the client instead of leaving it hanging. -### Fixed - - **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The fetch adapter read every request through `request.arrayBuffer()` and compared the length once the whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now @@ -85,6 +83,22 @@ npm treats versions as semver and semver forbids leading zeros. workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by the count rather than up front. The status is the same; only how early it comes differs. +- **`serveDeno()` and `serveBun()` populate `ctx.ip` with the client's address** (#116). The fetch + path had no way to learn the socket peer, so every HTTP request on Deno and Bun saw `ctx.ip` as + `''`, and anything keyed on it put every client in one bucket — the rate-limit plugin, where one + client could exhaust the limit for everyone, above all. Both adapters now hand the peer to + `app.fetch`, and `ctx.ip` follows the same rule as Node's `listen()`: the first + `x-forwarded-for` hop when `trustProxy` is on and the header is present, the socket peer + otherwise. That includes `trustProxy` with no `x-forwarded-for`, which used to answer `''` on + the fetch path and now falls back to the peer, as Node always has. + + Addresses are passed through as each runtime reports them, so the IPv6 loopback is `::1` on all + three but Node may report an IPv4 client as `::ffff:127.0.0.1`. A bare `app.fetch(request)` from + your own code has no socket to report and still answers `''` (or the forwarded hop), and so does + a `Request` copied from the one the adapter received. No signature changed. The edge adapter is + unchanged: trusting `cf-connecting-ip` is only correct behind Cloudflare, and needs its own + decision. + ## [26.9.0-beta.2] - 2026-09-22 ### Breaking diff --git a/src/bun.ts b/src/bun.ts index 286d9b7..a21f294 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -4,6 +4,7 @@ import type { App } from './app/types'; import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core'; import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; import { closeWithDeadline } from './http/shutdown'; +import { setPeer } from './http/peer'; // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. @@ -101,6 +102,8 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis return new Response('WebSocket upgrade failed', { status: 400 }); } + // The same object goes to `app.fetch`, which is what lets it find the peer again. + setPeer(request, server.requestIP(request)?.address ?? ''); return app.fetch(request); }, websocket: { diff --git a/src/deno.ts b/src/deno.ts index 097af95..a0dee16 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,6 +1,7 @@ import type { App } from './app/types'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { closeWithDeadline } from './http/shutdown'; +import { setPeer } from './http/peer'; // The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x) // doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. @@ -82,6 +83,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise }; +const peers = (registry[KEY] ??= new WeakMap()); + +/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */ +export function setPeer(request: Request, ip: string): void { + if (ip) peers.set(request, ip); +} + +/** The peer an adapter recorded for `request`, or `''` when none did. */ +export function peerOf(request: Request): string { + return peers.get(request) ?? ''; +} diff --git a/src/http/web.ts b/src/http/web.ts index 451c82c..82a070a 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -11,6 +11,7 @@ import { type Preflight, } from './core'; import { mergeInjectedHeaders } from './headers'; +import { peerOf } from './peer'; import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body'; import { HttpError } from '../signals'; import { renderError, type ErrorRequest } from '../transformers'; @@ -218,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla return new Response(body, { status: result.outcome.status, headers }); } +/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */ +function forwardedFor(headers: Record, opts: HttpOptions | undefined): string { + if (!opts?.trustProxy) return ''; + + return String(headers['x-forwarded-for'] ?? '') + .split(',')[0] + .trim(); +} + /** * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: * describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it @@ -286,14 +296,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { source: request, secure, // 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() - : '', + // 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), }, // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to // one call per request. diff --git a/test/bun/peer-ip.test.ts b/test/bun/peer-ip.test.ts new file mode 100644 index 0000000..fcc9a14 --- /dev/null +++ b/test/bun/peer-ip.test.ts @@ -0,0 +1,63 @@ +// #116 on the real Bun runtime: `serveBun` hands the socket's peer address to `ctx.ip`, the way +// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the +// address — the rate-limit plugin above all — put the whole internet in one bucket. +// +// Run with: npm run test:bun (or: bun test test/bun/) +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createServer } from 'node:net'; +import { createApp, Route, Get, Module, ctx } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +@Route('/') +class Ctl { + @Get('/ip') ip(@ctx() c: { ip: string }) { + return { ip: c.ip }; + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +async function ipVia( + hostname: string, + opts: { trustProxy?: boolean; headers?: Record } = {}, +): Promise { + const server = await serveBun(createApp({ modules: [M], trustProxy: opts.trustProxy }), { hostname, port: 0 }); + const host = hostname.includes(':') ? `[${hostname}]` : hostname; + + try { + const res = await fetch(`http://${host}:${server.port}/ip`, { headers: opts.headers }); + return ((await res.json()) as { ip: string }).ip; + } finally { + await server.close({ timeoutMs: 1000 }); + } +} + +/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */ +const ipv6Available = await new Promise((resolve) => { + const probe = createServer(); + probe.once('error', () => resolve(false)); + probe.listen(0, '::1', () => probe.close(() => resolve(true))); +}); + +test('T2 serveBun: ctx.ip is the socket peer address', async () => { + expect(await ipVia('127.0.0.1')).toBe('127.0.0.1'); +}); + +// Skipped, not failed: the host has no IPv6 loopback to connect over. +test.skipIf(!ipv6Available)('T3 serveBun: an IPv6 peer is passed through as Bun reports it', async () => { + expect(await ipVia('::1')).toBe('::1'); +}); + +test('T4 serveBun: trustProxy takes the first x-forwarded-for hop', async () => { + const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } }); + expect(ip).toBe('203.0.113.7'); +}); + +test('T5 serveBun: trustProxy without x-forwarded-for falls back to the peer', async () => { + expect(await ipVia('127.0.0.1', { trustProxy: true })).toBe('127.0.0.1'); +}); + +test('T6 serveBun: without trustProxy a spoofed x-forwarded-for is ignored', async () => { + expect(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } })).toBe('127.0.0.1'); +}); diff --git a/test/deno/peer-ip.test.ts b/test/deno/peer-ip.test.ts new file mode 100644 index 0000000..a126019 --- /dev/null +++ b/test/deno/peer-ip.test.ts @@ -0,0 +1,73 @@ +// #116 on the real Deno runtime: `serveDeno` hands the socket's peer address to `ctx.ip`, the way +// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the +// address — the rate-limit plugin above all — put the whole internet in one bucket. +// +// Run with: npm run test:deno +import 'reflect-metadata'; +import { assertEquals } from 'jsr:@std/assert'; +import { createApp, Route, Get, Module, ctx } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Route('/') +class Ctl { + @Get('/ip') ip(@ctx() c: { ip: string }) { + return { ip: c.ip }; + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +async function ipVia( + hostname: string, + opts: { trustProxy?: boolean; headers?: Record } = {}, +): Promise { + const server = await serveDeno(createApp({ modules: [M], trustProxy: opts.trustProxy }), { + hostname, + port: 0, + onListen: () => {}, + }); + const port = (server as unknown as { addr: { port: number } }).addr.port; + const host = hostname.includes(':') ? `[${hostname}]` : hostname; + + try { + const res = await fetch(`http://${host}:${port}/ip`, { headers: opts.headers }); + return ((await res.json()) as { ip: string }).ip; + } finally { + await server.close({ timeoutMs: 1000 }); + } +} + +/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */ +function ipv6Available(): boolean { + try { + Deno.listen({ hostname: '::1', port: 0 }).close(); + return true; + } catch { + return false; + } +} + +Deno.test('T1 serveDeno: ctx.ip is the socket peer address', async () => { + assertEquals(await ipVia('127.0.0.1'), '127.0.0.1'); +}); + +Deno.test({ + name: 'T3 serveDeno: an IPv6 peer is passed through as Deno reports it', + ignore: !ipv6Available(), // skipped, not failed: the host has no IPv6 loopback to connect over + fn: async () => { + assertEquals(await ipVia('::1'), '::1'); + }, +}); + +Deno.test('T4 serveDeno: trustProxy takes the first x-forwarded-for hop', async () => { + const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } }); + assertEquals(ip, '203.0.113.7'); +}); + +Deno.test('T5 serveDeno: trustProxy without x-forwarded-for falls back to the peer', async () => { + assertEquals(await ipVia('127.0.0.1', { trustProxy: true }), '127.0.0.1'); +}); + +Deno.test('T6 serveDeno: without trustProxy a spoofed x-forwarded-for is ignored', async () => { + assertEquals(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } }), '127.0.0.1'); +}); diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 5e27784..8f7304c 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -1,6 +1,7 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index'; import { countingStream } from './helpers/counting-stream'; +import { setPeer } from '../src/http/peer'; @Provider({ provides: 'store' }) class Store { @@ -109,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => { ); expect(await res.json()).toEqual({ ip: '' }); }); + + // #116: the Deno and Bun adapters now hand `buildFetch` the socket peer. A bare `app.fetch` from + // user code has none to hand, so it must keep answering exactly what it did before. + it('T7: bare app.fetch without peer metadata is unchanged', async () => { + const untrusting = createApp({ modules: [IpModule] }); + const trusting = createApp({ modules: [IpModule], trustProxy: true }); + + expect(await (await untrusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' }); + expect(await (await trusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' }); + expect( + await ( + await trusting.fetch(new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9' } })) + ).json(), + ).toEqual({ ip: '9.9.9.9' }); + }); + + it('the peer an adapter recorded reaches ctx.ip, and trustProxy without XFF falls back to it', async () => { + const untrusting = createApp({ modules: [IpModule] }); + const trusting = createApp({ modules: [IpModule], trustProxy: true }); + const spoofed = new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '1.2.3.4' } }); + const plain = new Request('http://x/ip/whoami'); + setPeer(spoofed, '127.0.0.1'); + setPeer(plain, '::1'); + + expect(await (await untrusting.fetch(spoofed)).json()).toEqual({ ip: '127.0.0.1' }); + expect(await (await trusting.fetch(plain)).json()).toEqual({ ip: '::1' }); + }); + + // The published CommonJS build bundles `index`, `deno` and `bun` as separate files, each with its + // own copy of every module they share, so `serveBun` from `@green-tea/core/bun` and `app.fetch` + // from `@green-tea/core` do not run the same `peer.ts`. A store private to the module would be two + // stores, and the peer recorded by one would never be found by the other. + it('a second copy of the peer module sees the peer the first one recorded', async () => { + const request = new Request('http://x/'); + setPeer(request, '192.0.2.1'); // through the copy this file imported + + vi.resetModules(); + const copy = await import('../src/http/peer'); + + expect(copy.setPeer).not.toBe(setPeer); // really a second instance of the module + expect(copy.peerOf(request)).toBe('192.0.2.1'); + }); + + it('T8: only the adapter\'s own Request carries the peer — a copy of it does not', async () => { + const original = new Request('http://x/ip/whoami'); + setPeer(original, '127.0.0.1'); + + const res = await createApp({ modules: [IpModule] }).fetch(new Request(original)); + + expect(await res.json()).toEqual({ ip: '' }); + }); }); describe('app.fetch on a mesh app', () => {