tests/sims/cors.test.ts
The automated tests for the /simulators/cors-preflight simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- The Fetch Standard rules: GET, HEAD and POST with safelisted headers skip the preflight; other methods, JSON bodies and custom headers need one.
- Credentials need the exact origin and Allow-Credentials, * never covers Authorization, and only safelisted or exposed response headers are readable.
- Over 300 random requests and server configurations, Chromium sends the same preflight, reaches the server, passes or fails, and exposes the same headers as the model.
// /simulators/cors-preflight: when the browser sends a preflight and whether the page gets the response.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { run, needsPreflight, type Req, type Server } from '../../src/lib/sims/cors.ts';
import { lcg } from './check.ts';
const O = 'http://localhost:8001';
const srv = (over: Partial<Server> = {}): Server => ({ optionsStatus: 204, allowOrigin: O, allowCredentials: false, allowMethods: '', allowHeaders: '', exposeHeaders: '', maxAge: null, extraHeaders: [{ name: 'X-Request-Id', value: 'abc' }], ...over });
const req = (method: Req['method'], headers: [string, string][] = [], credentials = false): Req => ({ origin: O, method, headers: headers.map(([name, value]) => ({ name, value })), credentials });
test('the Fetch Standard rules: GET, HEAD and POST with safelisted headers skip the preflight; other methods, JSON bodies and custom headers need one', () => {
assert.equal(needsPreflight(req('GET')).yes, false);
assert.equal(needsPreflight(req('POST', [['Content-Type', 'text/plain;charset=UTF-8']])).yes, false);
assert.equal(needsPreflight(req('POST', [['Content-Type', 'application/x-www-form-urlencoded']])).yes, false);
assert.equal(needsPreflight(req('POST', [['Content-Type', 'application/json']])).yes, true);
assert.equal(needsPreflight(req('PUT')).yes, true);
assert.equal(needsPreflight(req('GET', [['X-Api-Key', 'k']])).yes, true);
const pf = run(req('PUT', [['X-B', '1'], ['Content-Type', 'application/json'], ['X-A', '2']]), srv({ allowMethods: 'PUT', allowHeaders: 'x-a, x-b, content-type' }));
const acrh = pf.steps[0].sent.find((h) => h.name === 'Access-Control-Request-Headers')?.value;
assert.equal(acrh, 'content-type,x-a,x-b', 'request header names are lower-cased, sorted and comma-joined');
});
test('credentials need the exact origin and Allow-Credentials, * never covers Authorization, and only safelisted or exposed response headers are readable', () => {
assert.match(run(req('GET', [], true), srv({ allowOrigin: '*' })).error ?? '', /credentials/);
assert.match(run(req('GET', [], true), srv()).error ?? '', /Allow-Credentials/);
assert.equal(run(req('GET', [], true), srv({ allowCredentials: true })).ok, true);
assert.equal(run(req('GET', [['Authorization', 'Bearer t']]), srv({ allowHeaders: '*' })).ok, false);
assert.equal(run(req('GET', [['Authorization', 'Bearer t']]), srv({ allowHeaders: '*' }), { wildcardCoversAuthorization: true }).ok, true);
assert.deepEqual(run(req('GET'), srv()).readable, ['Content-Type']);
assert.deepEqual(run(req('GET'), srv({ exposeHeaders: 'x-request-id' })).readable, ['Content-Type', 'X-Request-Id']);
const blocked = run(req('POST', [['Content-Type', 'text/plain']]), srv({ allowOrigin: null }));
assert.ok(blocked.reachedServer && !blocked.ok, 'a simple request reaches the server even when the page cannot read the answer');
});
let chromium: any = null;
try { chromium = (await import(process.env.PLAYWRIGHT_MODULE ?? '/opt/npm-tools/node_modules/playwright/index.mjs')).chromium; } catch { /* no browser here */ }
test('over 300 random requests and server configurations, Chromium sends the same preflight, reaches the server, passes or fails, and exposes the same headers as the model', { skip: !chromium && 'Playwright is not available (set PLAYWRIGHT_MODULE)' }, async () => {
const log: { method: string; url: string; headers: http.IncomingHttpHeaders }[] = [];
const api = http.createServer((rq, res) => {
const m = rq.url!.match(/^\/api\/([^/]+)\//);
if (!m) { res.writeHead(404); return res.end(); }
const s: Server = JSON.parse(Buffer.from(m[1], 'base64url').toString());
log.push({ method: rq.method!, url: rq.url!, headers: rq.headers });
const h: Record<string, string> = {};
if (s.allowOrigin !== null) h['Access-Control-Allow-Origin'] = s.allowOrigin;
if (s.allowCredentials) h['Access-Control-Allow-Credentials'] = 'true';
if (rq.method === 'OPTIONS') {
if (s.allowMethods) h['Access-Control-Allow-Methods'] = s.allowMethods;
if (s.allowHeaders) h['Access-Control-Allow-Headers'] = s.allowHeaders;
if (s.maxAge !== null) h['Access-Control-Max-Age'] = String(s.maxAge);
res.writeHead(s.optionsStatus, h);
return res.end();
}
if (s.exposeHeaders) h['Access-Control-Expose-Headers'] = s.exposeHeaders;
h['Content-Type'] = 'application/json';
for (const x of s.extraHeaders) h[x.name] = x.value;
res.writeHead(200, h);
res.end('{"ok":true}');
});
const page = http.createServer((_, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>t</title>'); });
await new Promise<void>((ok) => api.listen(0, '127.0.0.1', ok));
await new Promise<void>((ok) => page.listen(0, 'localhost', ok));
const origin = `http://localhost:${(page.address() as AddressInfo).port}`, apiBase = `http://127.0.0.1:${(api.address() as AddressInfo).port}`;
const b = await chromium.launch({ args: ['--no-sandbox'] });
try {
const p = await b.newPage();
await p.goto(origin + '/');
const r = lcg(20);
const pick = <T,>(a: T[]) => a[Math.floor(r() * a.length)];
const HEADERSETS = [[], [['Content-Type', 'application/json']], [['Content-Type', 'text/plain']], [['X-Api-Key', 'k1']], [['Authorization', 'Bearer t']], [['Content-Type', 'application/json'], ['X-Api-Key', 'k1']]] as [string, string][][];
const diffs: string[] = [];
for (let i = 0; i < 300; i++) {
const q: Req = { origin, method: pick(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const), headers: pick(HEADERSETS).map(([name, value]) => ({ name, value })), credentials: r() < 0.4 };
if (q.method === 'GET') q.headers = q.headers.filter((h) => h.name !== 'Content-Type');
const s: Server = { optionsStatus: pick([204, 204, 204, 404]), allowOrigin: pick([null, '*', origin, origin, 'https://other.example']), allowCredentials: r() < 0.5, allowMethods: pick(['', 'PUT', '*', 'GET, POST, PUT, DELETE', 'GET, POST, PUT, PATCH, DELETE']), allowHeaders: pick(['', 'content-type', '*', 'x-api-key, content-type', 'x-api-key, authorization, content-type']), exposeHeaders: pick(['', 'x-request-id', '*']), maxAge: pick([null, 0]), extraHeaders: [{ name: 'X-Request-Id', value: 'abc' }, { name: 'Cache-Control', value: 'no-store' }] };
const nonce = `n${i}`;
const url = `${apiBase}/api/${Buffer.from(JSON.stringify(s)).toString('base64url')}/${nonce}`;
const got = await p.evaluate(async ({ url, q }: { url: string; q: Req }) => {
try {
const init: RequestInit = { method: q.method, headers: Object.fromEntries(q.headers.map((h) => [h.name, h.value])), credentials: q.credentials ? 'include' : 'same-origin' };
if (q.method !== 'GET' && q.method !== 'HEAD') init.body = 'x';
const res = await fetch(url, init);
return { ok: true, headers: [...res.headers.keys()] };
} catch { return { ok: false, headers: [] as string[] }; }
}, { url, q });
await new Promise((ok) => setTimeout(ok, 30));
const mine = log.filter((l) => l.url.endsWith('/' + nonce));
const browser = { preflight: mine.some((l) => l.method === 'OPTIONS'), reached: mine.some((l) => l.method !== 'OPTIONS'), ok: got.ok, readable: got.headers.map((h) => h.toLowerCase()).filter((h) => !['date', 'connection', 'keep-alive', 'transfer-encoding'].includes(h)).sort() };
// Chromium lets Access-Control-Allow-Headers: * cover Authorization; the page has a switch for it
const m = run(q, s, { wildcardCoversAuthorization: true });
const model = { preflight: m.preflight, reached: m.reachedServer, ok: m.ok, readable: m.readable.map((h) => h.toLowerCase()).sort() };
const acrh = mine.find((l) => l.method === 'OPTIONS')?.headers['access-control-request-headers'] ?? null;
const modelAcrh = m.steps.find((x) => x.kind === 'preflight')?.sent.find((h) => h.name === 'Access-Control-Request-Headers')?.value ?? null;
if (JSON.stringify(browser) !== JSON.stringify(model) || (browser.preflight && acrh !== modelAcrh)) diffs.push(`${q.method} ${JSON.stringify(q.headers)} creds ${q.credentials} vs ${JSON.stringify(s)}: browser ${JSON.stringify(browser)} ${acrh}, model ${JSON.stringify(model)} ${modelAcrh}`);
}
assert.deepEqual(diffs, []);
} finally {
await b.close();
api.close();
page.close();
}
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.