fix(runtime): give ctx.ip the socket peer on Deno and Bun
buildFetch had no channel for a peer address, so ctx.ip was '' for
every HTTP request served by serveDeno or serveBun unless trustProxy and
x-forwarded-for supplied one. Everything keyed on the address shared one
value: the rate-limit plugin put every client in a single bucket, and
one client could exhaust the limit for all of them.
The adapters now record the peer in a WeakMap keyed by the Request
object (src/http/peer.ts, not exported) and pass that same object to
app.fetch. A header would be visible to handlers and spoofable; a second
fetch parameter would be public API. buildFetch derives ctx.ip as Node's
deriveIp does: the first x-forwarded-for hop when trustProxy is on and
the header is present, the peer otherwise. trustProxy without the header
therefore falls back to the peer instead of answering ''.
The map hangs off globalThis under Symbol.for('@green-tea/core:peer')
rather than living in the module. tsup's CommonJS build bundles index,
deno and bun as separate files with no shared chunk, so each gets its
own copy of peer.ts; with a module-private map, serveBun from
@green-tea/core/bun recorded peers that app.fetch from @green-tea/core
never saw, and ctx.ip stayed ''. A test loads a second instance of the
module to pin this.
A bare app.fetch from user code, or a Request copied from the adapter's,
has no entry and answers exactly what it did before. Addresses are
passed through unnormalised. WebSocket and the edge adapter are
unchanged; trusting cf-connecting-ip is a separate decision.
Closes #116
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
8 files changed
+254
-12
No files matched your search
@@ -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<string, string> } = {},
|
||||
): Promise<string> {
|
||||
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<boolean>((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');
|
||||
});
|
||||
@@ -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<string, string> } = {},
|
||||
): Promise<string> {
|
||||
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');
|
||||
});
|
||||
+53
-1
@@ -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', () => {
|
||||
|
||||
Reference in new issue
Block a user