Files
core/test/edge/run.ts
T
chrnx 7f9a0eef0f
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:08:24 -05:00

292 lines
13 KiB
TypeScript

// Real Miniflare (workerd) integration test for edgeHandler: bundles test/edge/worker.ts
// for the Cloudflare Workers runtime and boots it in the actual workerd engine (via the
// `miniflare` npm package — no CF account/deploy needed), then round-trips HTTP + WS
// through the real graph.
//
// Run with: npm run test:edge
//
// NODEJS_COMPAT: workerd's `nodejs_compat` genuinely does NOT implement `node:http`/
// `node:https` (confirmed in isolation: `node:crypto`, `node:stream`, `node:net`, `node:tls`,
// `node:events`, `node:util`, `node:buffer` all load fine under the same flags/compat date;
// only `http`/`https` fail with "Uncaught Error: No such module 'node:http'" at worker LOAD
// time) — a real platform gap, not a bundler misconfiguration. The barrel used to statically
// VALUE-import `http`/`https` for the Node `listen()` path even though `edgeHandler` never
// touches them, which broke worker load with no shim. The fix (see src/http/server.ts,
// src/app/index.ts, and the other src/http/*.ts files) converts every `http`/`https` import
// to `import type` (zero runtime code) and lazy-`require()`s them only inside
// `createHttpServer`, which the edge path never calls. That means the real barrel now loads
// on workerd with no test-time stub — this run exercises it as-is.
import { strict as assert } from 'node:assert';
import { build } from 'esbuild';
import { Miniflare } from 'miniflare';
const BUNDLE = 'test/edge/_worker.mjs';
async function main() {
// Bundle the worker for workerd: ESM, Node builtins left external + aliased to node:*
// so workerd's nodejs_compat provides them (not esbuild). `http`/`https` are no longer
// imported as VALUES by the barrel at module-eval time (see comment above) — they're now
// `import type` (erased) plus a lazy `require()` reached only from `createHttpServer`,
// which `edgeHandler` never calls. esbuild still needs a resolution for that bare
// `require('http')`/`require('https')` text even though it's dead code on this path, so
// they're marked external here (left unresolved, exactly like the `node:*` builtins) rather
// than stubbed — no fake implementation is provided, and the real barrel is what's tested.
await build({
entryPoints: ['test/edge/worker.ts'],
bundle: true,
format: 'esm',
outfile: BUNDLE,
platform: 'browser', // workerd is not node; keep esbuild from injecting node shims
target: 'esnext',
// Leave Node builtins for workerd's nodejs_compat to resolve; http/https are external
// too (unresolved, never called by edgeHandler) since workerd has no node:http/https.
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
const mf = new Miniflare({
modules: true,
scriptPath: BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: ['nodejs_compat'],
});
try {
// HTTP
const httpRes = await mf.dispatchFetch('http://localhost/rt/hello');
assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true });
// CARD-14 (#113): a Set-Cookie array leaves workerd as one line per cookie; other arrays join.
const cookieRes = await mf.dispatchFetch('http://localhost/rt/cookies');
await cookieRes.arrayBuffer();
assert.deepEqual(cookieRes.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
assert.equal(cookieRes.headers.get('x-custom'), 'a, b');
const cookieErr = await mf.dispatchFetch('http://localhost/rt/cookie-error');
await cookieErr.arrayBuffer();
assert.equal(cookieErr.status, 401);
assert.deepEqual(cookieErr.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
const readCookie = await mf.dispatchFetch('http://localhost/rt/cookie', { headers: { cookie: 'a=1; b=%41' } });
assert.deepEqual(await readCookie.json(), { b: 'A' });
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
const post = async (body: Uint8Array | string | ReadableStream<Uint8Array>): Promise<number> => {
const res = await mf.dispatchFetch('http://localhost/rt/body', {
method: 'POST',
headers: { 'content-type': 'text/plain' },
body,
duplex: 'half',
} as Parameters<typeof mf.dispatchFetch>[1]);
await res.arrayBuffer();
return res.status;
};
const chunks = (count: number, size: number): ReadableStream<Uint8Array> => {
let sent = 0;
return new ReadableStream({
pull(controller) {
if (sent++ === count) controller.close();
else controller.enqueue(new Uint8Array(size).fill(0x61));
},
});
};
assert.equal(await post(new Uint8Array(2 * LIMIT)), 413, 'declared content-length over the limit');
assert.equal(await post(chunks(10, 300)), 413, 'streamed body over the limit');
assert.equal(await post('x'.repeat(LIMIT)), 200, 'exactly the limit');
assert.equal(await post('x'.repeat(LIMIT + 1)), 413, 'one byte over the limit');
// WebSocket
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
headers: { Upgrade: 'websocket' },
});
assert.equal(wsRes.status, 101);
const ws = wsRes.webSocket;
assert.ok(ws, 'expected a client webSocket on the 101 response');
ws.accept();
const got = await new Promise<string>((resolve, reject) => {
ws.addEventListener('message', (e: { data: unknown }) => {
resolve(String(e.data));
ws.close();
});
ws.addEventListener('error', () => reject(new Error('ws error')));
ws.send('hi');
});
assert.equal(got, 'echo:hi');
// #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves.
const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', {
headers: { Upgrade: 'websocket' },
});
const bad = badRes.webSocket;
assert.ok(bad, 'expected a client webSocket on the 101 response');
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
bad.addEventListener('close', (e: { code: number; reason: string }) =>
resolve({ code: e.code, reason: e.reason }),
),
);
bad.accept();
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
// #107: workerd delivers the whole message before user code sees it, so the size bound is
// checked after receipt; the close codes match Node and Deno.
const limitedEcho = async (frames: string[]) => exchange(mf, 'http://limited/rt/echo', frames);
assert.deepEqual((await limitedEcho(['a'.repeat(1024)])).replies, [`echo:${'a'.repeat(1024)}`]);
assert.deepEqual((await limitedEcho(['a'.repeat(1025)])).close, { code: 1009, reason: 'message too large' });
assert.deepEqual((await exchange(mf, 'http://limited/rt/stall', ['1', '2', '3', '4', '5'])).close, {
code: 1013,
reason: 'inbound queue full',
});
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);
// 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');
// CARD-21 (D17): the reserved mesh path closes 1008 with the Node listener's reason, and a route
// that claims it fails createApp.
assert.deepEqual((await exchange(mf, 'http://localhost/__mesh__/control', [])).close, {
code: 1008,
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
});
const reservedRes = await mf.dispatchFetch('http://reserved/');
assert.equal(reservedRes.status, 500);
assert.match(await reservedRes.text(), /^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/);
// CARD-17 T10: live 200; ready booting → ok, with only probes reaching the isolate. There is no
// close() on workerd, so draining is never reported here (documented, not tested for). Any probe
// starts the boot, so ready is asked first to see `booting`.
const first = await mf.dispatchFetch('http://health/__ready__');
assert.equal(first.status, 503);
assert.deepEqual(await first.json(), { status: 'booting' });
const live = await mf.dispatchFetch('http://health/__live__');
assert.equal(live.status, 200);
assert.deepEqual(await live.json(), { status: 'ok' });
let ready = await mf.dispatchFetch('http://health/__ready__');
for (let i = 0; i < 20 && ready.status !== 200; i++) {
await ready.arrayBuffer();
await new Promise((resolve) => setTimeout(resolve, 25));
ready = await mf.dispatchFetch('http://health/__ready__');
}
assert.equal(ready.status, 200);
assert.deepEqual(await ready.json(), { status: 'ok' });
assert.equal(ready.headers.get('cache-control'), 'no-store');
console.log(
'edge (workerd via miniflare): HTTP 200 + cookies + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
);
} finally {
await mf.dispose();
}
}
const PARITY_BUNDLE = 'test/edge/_parity-worker.mjs';
/**
* The frozen router-parity differential inside workerd (test/router-parity/README.md). Same bundling
* as the main worker; the worker runs every case itself and answers with its mismatch report.
*/
async function parity() {
await build({
entryPoints: ['test/edge/parity-worker.ts'],
bundle: true,
format: 'esm',
outfile: PARITY_BUNDLE,
platform: 'browser',
target: 'esnext',
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
const mf = new Miniflare({
modules: true,
scriptPath: PARITY_BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: ['nodejs_compat'],
});
try {
const res = await mf.dispatchFetch('http://localhost/');
const report = (await res.json()) as {
matcher: { sets: Array<{ name: string; requests: number }>; mismatches: string[] };
app: { requests: number; mismatches: string[] };
};
assert.deepEqual(report.matcher.mismatches, [], 'matcher differential mismatches under workerd');
assert.deepEqual(report.app.mismatches, [], 'app.fetch parity mismatches under workerd');
const requests = report.matcher.sets.reduce((sum, set) => sum + set.requests, 0);
console.log(
`edge (workerd): router parity — ${requests} matcher cases + ${report.app.requests} app.fetch cases — PASS`,
);
} finally {
await mf.dispose();
}
}
/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */
async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) {
const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } });
const ws = res.webSocket;
assert.ok(ws, `expected a client webSocket on the 101 response for ${url}`);
const replies: string[] = [];
const result = new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, ms);
ws.addEventListener('message', (e: { data: unknown }) => replies.push(String(e.data)));
ws.addEventListener('close', (e: { code: number; reason: string }) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
});
});
ws.accept();
for (const frame of frames) ws.send(frame);
return result;
}
main()
.then(parity)
.catch((err) => {
console.error(err);
process.exit(1);
});