Compare commits
3
Commits
a4245458c3
...
88cbe41f72
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88cbe41f72 | ||
|
|
89ac955072 | ||
|
|
8bf54ec168 |
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
|
constraints at a later segment of an otherwise unreachable route. The route then boots, as
|
||||||
before.
|
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
|
### Added
|
||||||
|
|
||||||
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
|
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
|
||||||
@@ -81,8 +88,21 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
|
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
|
||||||
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
|
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
|
||||||
|
|
||||||
|
- **A query string keeps every `?` after the first** (GitHub #48). `parseQuery` took the text
|
||||||
|
between the first and second `?`, so `/search?q=what?now` gave `q: 'what'` and dropped the rest.
|
||||||
|
RFC 3986 §3.4 allows `?` inside a query, so the query string is now everything after the first
|
||||||
|
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
|
||||||
|
with a single `?` parse as before. Path extraction is unchanged.
|
||||||
|
|
||||||
### Fixed
|
### 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
|
- **`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`
|
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
|
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 { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||||
import type { HttpOptions } from '../http';
|
import type { HttpOptions } from '../http';
|
||||||
|
import { trustedProxyClient } from '../http/peer';
|
||||||
import { buildFetch } from '../http/web';
|
import { buildFetch } from '../http/web';
|
||||||
import {
|
import {
|
||||||
boundInbound,
|
boundInbound,
|
||||||
@@ -331,7 +332,10 @@ export function createApp(opts: {
|
|||||||
devRoutes,
|
devRoutes,
|
||||||
() => remoteRoutes,
|
() => 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 listen = async (port: number): Promise<http.Server> => {
|
||||||
const deps = pipelineDeps;
|
const deps = pipelineDeps;
|
||||||
@@ -1395,7 +1399,7 @@ function buildAppUpgrade(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
ensureBooted: () => Promise<void>,
|
ensureBooted: () => Promise<void>,
|
||||||
getMeshControl: () => MeshControl | undefined,
|
getMeshControl: () => MeshControl | undefined,
|
||||||
limits?: RequestLimits,
|
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
|
||||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||||
let wsRoutes: WsRouteDef[] | undefined;
|
let wsRoutes: WsRouteDef[] | undefined;
|
||||||
|
|
||||||
@@ -1444,10 +1448,20 @@ function buildAppUpgrade(
|
|||||||
return;
|
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. */
|
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
||||||
function devGraphRoute(graph: () => GraphView): RouteDef {
|
function devGraphRoute(graph: () => GraphView): RouteDef {
|
||||||
return {
|
return {
|
||||||
|
|||||||
+16
-1
@@ -1,5 +1,6 @@
|
|||||||
import type { App } from './app/types';
|
import type { App } from './app/types';
|
||||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
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.
|
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
||||||
// Declares only what we call; mirrors the real workerd signatures.
|
// Declares only what we call; mirrors the real workerd signatures.
|
||||||
@@ -30,7 +31,9 @@ export function edgeHandler(
|
|||||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||||
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
||||||
server.accept();
|
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));
|
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
||||||
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
||||||
else void lifecycle;
|
else void lifecycle;
|
||||||
@@ -38,6 +41,18 @@ export function edgeHandler(
|
|||||||
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
recordClient(request, request);
|
||||||
return app.fetch(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 {
|
export function peerOf(request: Request): string {
|
||||||
return peers.get(request) ?? '';
|
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) ?? '') : '';
|
||||||
|
}
|
||||||
+15
-10
@@ -743,18 +743,23 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
/**
|
||||||
|
* Parses a URL's query string into a flat string map (last value wins for repeated keys).
|
||||||
|
*
|
||||||
|
* The query string is everything after the **first** `?` and before a `#`, if one is present.
|
||||||
|
* A `?` inside the query is a legal character (RFC 3986 §3.4), so `/search?q=what?now` gives
|
||||||
|
* `{ q: 'what?now' }`.
|
||||||
|
*/
|
||||||
export function parseQuery(url: string): Record<string, string> {
|
export function parseQuery(url: string): Record<string, string> {
|
||||||
// Most requests carry no query string, and the work below is not free for them: `split` builds
|
// Most requests carry no query string, and the work below is not free for them:
|
||||||
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
|
// `new URLSearchParams('')` builds an object and the loop runs zero times, to arrive at `{}`.
|
||||||
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
|
// Measured at 92.3 ns against 18.6 ns for this check.
|
||||||
//
|
const start = url.indexOf('?');
|
||||||
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
|
if (start < 0) return {};
|
||||||
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
|
|
||||||
// means, and that is a behaviour question rather than a performance one.
|
|
||||||
if (!url.includes('?')) return {};
|
|
||||||
|
|
||||||
const queryString = url.split('?')[1] ?? '';
|
// `split('?')[1]` used to stop at a second `?` and drop the rest of the value (GitHub #48).
|
||||||
|
const hash = url.indexOf('#', start + 1);
|
||||||
|
const queryString = hash < 0 ? url.slice(start + 1) : url.slice(start + 1, hash);
|
||||||
const out: Record<string, string> = {};
|
const out: Record<string, string> = {};
|
||||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||||
return out;
|
return out;
|
||||||
|
|||||||
+5
-2
@@ -11,7 +11,7 @@ import {
|
|||||||
type Preflight,
|
type Preflight,
|
||||||
} from './core';
|
} from './core';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
import { peerOf } from './peer';
|
import { peerOf, trustedProxyClient } from './peer';
|
||||||
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
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.
|
// 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
|
// 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 ''.
|
// `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
|
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
||||||
// one call per request.
|
// 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_576)])).replies.length, 1);
|
||||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
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 {
|
} finally {
|
||||||
await mf.dispose();
|
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')
|
@Ws('/room/:name')
|
||||||
room(@ctx() { inbound }: any) {
|
room(@ctx() { inbound }: any) {
|
||||||
return (async function* () {
|
return (async function* () {
|
||||||
@@ -49,9 +62,15 @@ class M {}
|
|||||||
const app = createApp({ modules: [M] });
|
const app = createApp({ modules: [M] });
|
||||||
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
||||||
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
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 {
|
export default {
|
||||||
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
|
fetch: (request: Request, env?: unknown, ctx?: Parameters<ReturnType<typeof edgeHandler>>[2]) =>
|
||||||
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
|
(handlers[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx),
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
|
import type { Server } from 'node:http';
|
||||||
|
import { Get, Module, Route, Transformer } from '../src/metadata';
|
||||||
|
import { JsonTransformer } from '../src/transformers';
|
||||||
|
import { createApp } from '../src/app';
|
||||||
|
import { parseQuery } from '../src/http';
|
||||||
|
import { query } from '../src/params';
|
||||||
|
|
||||||
|
// CARD-25 / GitHub #48: the query string is everything after the FIRST `?` (and before `#`).
|
||||||
|
const CASES: Array<[string, Record<string, string>]> = [
|
||||||
|
['/search?q=what?now', { q: 'what?now' }], // T1
|
||||||
|
['/search?a=1&b=?', { a: '1', b: '?' }], // T2
|
||||||
|
['/search?', {}], // T3
|
||||||
|
['/search', {}], // T4
|
||||||
|
];
|
||||||
|
|
||||||
|
describe('parseQuery', () => {
|
||||||
|
test.each(CASES)('%s', (url, expected) => {
|
||||||
|
expect(parseQuery(url)).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops at a fragment', () => {
|
||||||
|
expect(parseQuery('/search?q=a?b#frag?x=1')).toEqual({ q: 'a?b' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
@Route('/search')
|
||||||
|
class SearchCtl {
|
||||||
|
@Get('/')
|
||||||
|
@Transformer(JsonTransformer)
|
||||||
|
search(@query() q: Record<string, string>) {
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [SearchCtl] })
|
||||||
|
class SearchModule {}
|
||||||
|
|
||||||
|
describe('query string with more than one `?`', () => {
|
||||||
|
const app = createApp({ modules: [SearchModule] });
|
||||||
|
let server: Server;
|
||||||
|
let base: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
server = await app.listen(0);
|
||||||
|
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||||
|
});
|
||||||
|
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
|
||||||
|
|
||||||
|
test.each(CASES)('app.fetch %s', async (url, expected) => {
|
||||||
|
const res = await app.fetch(new Request(`http://x${url}`));
|
||||||
|
expect(await res.json()).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each(CASES)('Node listener %s', async (url, expected) => {
|
||||||
|
const res = await fetch(`${base}${url}`);
|
||||||
|
expect(await res.json()).toEqual(expected);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user