Adds prettier 3.9.8 (exact) with a shared config (single quotes, 120 columns, trailing commas), .prettierignore, .editorconfig and the `format` / `format:check` scripts, then formats all TypeScript, JavaScript, CSS, JSON and YAML sources. Purely mechanical: no behaviour change. Typecheck passes, the vitest suite and the 74 IDE node tests produce the same results as before (socket-binding tests still cannot run inside this sandbox). Previously the longest source line was ~3000 characters; reviewing the following semantic changes now produces readable diffs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
477 lines
16 KiB
JavaScript
477 lines
16 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import http from 'node:http';
|
|
import net from 'node:net';
|
|
import { createHash, generateKeyPairSync } from 'node:crypto';
|
|
import { once } from 'node:events';
|
|
import { createPreviewGateway } from '../server.mjs';
|
|
import { bodySha256, verifyPreviewProof } from '../proof.mjs';
|
|
const serviceToken = 'local-fixture-preview-service-token-32-plus',
|
|
launch = 'L'.repeat(43),
|
|
session = 'S'.repeat(43),
|
|
probe = 'P'.repeat(43),
|
|
challenge = 'C'.repeat(43);
|
|
const listen = async (server, host = '127.0.0.1') => {
|
|
server.listen(0, host);
|
|
await once(server, 'listening');
|
|
return server.address().port;
|
|
};
|
|
const close = server =>
|
|
new Promise(resolve => {
|
|
server.closeAllConnections?.();
|
|
server.close(resolve);
|
|
});
|
|
async function fixture({ secure = false, entryPath = '/' } = {}) {
|
|
const keys = generateKeyPairSync('ed25519'),
|
|
privateKey = keys.privateKey.export({ type: 'pkcs8', format: 'pem' }),
|
|
publicKey = keys.publicKey.export({ type: 'spki', format: 'pem' });
|
|
let authorized = true,
|
|
role = 'developer',
|
|
used = false,
|
|
expiryOverride;
|
|
const seen = [],
|
|
upgraded = new Set();
|
|
const application = http.createServer((req, res) => {
|
|
seen.push({ headers: req.headers, path: req.url, method: req.method });
|
|
if (req.url === '/login' && req.method === 'POST') {
|
|
res.writeHead(200, { 'set-cookie': 'application_session=logged-in; HttpOnly; Domain=internal.invalid; Path=/' });
|
|
res.end('logged in');
|
|
return;
|
|
}
|
|
if (req.url === '/account') {
|
|
res.writeHead(req.headers.cookie === 'application_session=logged-in' ? 200 : 401, {
|
|
'content-type': 'text/plain',
|
|
});
|
|
res.end(
|
|
req.headers.cookie === 'application_session=logged-in'
|
|
? 'private application account'
|
|
: 'application login required',
|
|
);
|
|
return;
|
|
}
|
|
if (req.url === '/stream') {
|
|
res.writeHead(200, { 'content-type': 'text/plain' });
|
|
res.write('first');
|
|
const timer = setInterval(() => res.write('next'), 30);
|
|
res.on('close', () => clearInterval(timer));
|
|
return;
|
|
}
|
|
if (req.url === '/redirect') {
|
|
res.writeHead(302, { location: `http://127.0.0.1:${application.address().port}/actual` });
|
|
res.end();
|
|
return;
|
|
}
|
|
res.writeHead(req.url === '/app-401' ? 401 : 200, {
|
|
'content-type': 'text/plain',
|
|
'x-wishforge-preview-proof': 'forged-application-proof',
|
|
'set-cookie': ['app=allowed; Domain=internal.invalid; HttpOnly', 'WF_PREVIEW_SESSION=malicious; Path=/'],
|
|
});
|
|
res.end('fixture application');
|
|
});
|
|
application.on('upgrade', (req, socket) => {
|
|
seen.push({ headers: req.headers, path: req.url, method: 'WS' });
|
|
upgraded.add(socket);
|
|
socket.on('close', () => upgraded.delete(socket));
|
|
const accept = createHash('sha1')
|
|
.update(req.headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
|
.digest('base64');
|
|
socket.write(
|
|
`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n${req.url === '/bad-socket-headers' ? 'Location: https://external.invalid/\r\n' : ''}\r\n`,
|
|
);
|
|
});
|
|
const upstreamPort = await listen(application);
|
|
let publicOrigin;
|
|
const api = http.createServer(async (req, res) => {
|
|
let input = '';
|
|
for await (const chunk of req) input += chunk;
|
|
const body = JSON.parse(input);
|
|
if (
|
|
req.url !== '/preview-control/authorize' ||
|
|
req.headers.authorization !== `Bearer ${serviceToken}` ||
|
|
body.tenantId !== 'tenant-a' ||
|
|
body.environmentId !== 'environment-a'
|
|
) {
|
|
res.writeHead(403);
|
|
res.end('{}');
|
|
return;
|
|
}
|
|
let granted = authorized;
|
|
if (body.kind === 'launch') {
|
|
granted &&= body.credential === launch && !used;
|
|
if (granted) used = true;
|
|
} else if (body.kind === 'probe')
|
|
granted &&= body.credential === probe && body.challenge === challenge && ['GET', 'HEAD'].includes(body.method);
|
|
else granted &&= body.credential === session && !(role === 'viewer' && !['GET', 'HEAD'].includes(body.method));
|
|
if (!granted) {
|
|
res.writeHead(403);
|
|
res.end('{}');
|
|
return;
|
|
}
|
|
res.setHeader('content-type', 'application/json');
|
|
res.end(
|
|
JSON.stringify({
|
|
data: {
|
|
tenantId: 'tenant-a',
|
|
projectId: 'project-a',
|
|
environmentId: 'environment-a',
|
|
publicOrigin,
|
|
applicationUrl: publicOrigin + entryPath,
|
|
role: body.kind === 'probe' ? 'probe' : role,
|
|
releaseId: 'release-a',
|
|
bindingDigest: 'sha256:' + 'a'.repeat(64),
|
|
policyDigest: 'sha256:' + 'b'.repeat(64),
|
|
expiresAt: expiryOverride ?? new Date(Date.now() + 60000).toISOString(),
|
|
...(body.kind === 'launch' ? { sessionToken: session } : {}),
|
|
},
|
|
}),
|
|
);
|
|
});
|
|
const apiPort = await listen(api, 'localhost');
|
|
const reservation = net.createServer();
|
|
const gatewayPort = await listen(reservation);
|
|
await close(reservation);
|
|
const requestOrigin = `http://127.0.0.1:${gatewayPort}`;
|
|
publicOrigin = `${secure ? 'https' : 'http'}://127.0.0.1:${gatewayPort}`;
|
|
const gateway = createPreviewGateway({
|
|
tenantId: 'tenant-a',
|
|
projectId: 'project-a',
|
|
environmentId: 'environment-a',
|
|
publicOrigin,
|
|
upstreamOrigin: `http://127.0.0.1:${upstreamPort}`,
|
|
apiOrigin: `http://localhost:${apiPort}`,
|
|
serviceToken,
|
|
proofPrivateKey: privateKey,
|
|
production: false,
|
|
reauthorizeMs: 30,
|
|
});
|
|
gateway.server.listen(gatewayPort, '127.0.0.1');
|
|
await once(gateway.server, 'listening');
|
|
return {
|
|
publicOrigin,
|
|
publicKey,
|
|
seen,
|
|
gateway,
|
|
setRole: value => {
|
|
role = value;
|
|
},
|
|
setExpiry: value => {
|
|
expiryOverride = value;
|
|
},
|
|
revoke: () => {
|
|
authorized = false;
|
|
},
|
|
async launch() {
|
|
return fetch(`${requestOrigin}/_wishforge/session?code=${launch}`, { redirect: 'manual' });
|
|
},
|
|
cookie: `${gateway.cookieName}=${session}`,
|
|
async close() {
|
|
await gateway.close();
|
|
for (const socket of upgraded) socket.destroy();
|
|
await Promise.all([close(application), close(api)]);
|
|
},
|
|
};
|
|
}
|
|
test('anonymous denial is signed by the gateway and cannot be forged by an application 401', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
const denied = await fetch(f.publicOrigin + '/app-401', {
|
|
headers: { 'x-wishforge-preview-challenge': challenge },
|
|
});
|
|
const body = Buffer.from(await denied.arrayBuffer());
|
|
assert.equal(denied.status, 401);
|
|
assert.equal(f.seen.length, 0);
|
|
const signed = denied.headers.get('x-wishforge-preview-proof');
|
|
assert.ok(
|
|
verifyPreviewProof(f.publicKey, signed, {
|
|
decision: 'anonymous_denied',
|
|
status: 401,
|
|
path: '/app-401',
|
|
challenge,
|
|
publicOrigin: f.publicOrigin,
|
|
bodySha256: bodySha256(body),
|
|
releaseId: null,
|
|
}),
|
|
);
|
|
assert.equal(verifyPreviewProof(f.publicKey, signed, { challenge: 'different-challenge' }), undefined);
|
|
const response = await fetch(f.publicOrigin + '/app-401', {
|
|
headers: { 'x-wishforge-preview-capability': probe, 'x-wishforge-preview-challenge': challenge },
|
|
});
|
|
const appBody = Buffer.from(await response.arrayBuffer());
|
|
assert.equal(response.status, 401);
|
|
assert.ok(
|
|
verifyPreviewProof(f.publicKey, response.headers.get('x-wishforge-preview-proof'), {
|
|
decision: 'authorized',
|
|
releaseId: 'release-a',
|
|
status: 401,
|
|
bodySha256: bodySha256(appBody),
|
|
}),
|
|
);
|
|
assert.equal(
|
|
verifyPreviewProof(f.publicKey, response.headers.get('x-wishforge-preview-proof'), {
|
|
decision: 'anonymous_denied',
|
|
}),
|
|
undefined,
|
|
);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
test('launch is one-use, sets host-only HttpOnly cookie, strips credentials and hides upstream redirects', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
const response = await f.launch();
|
|
assert.equal(response.status, 303);
|
|
assert.equal(response.headers.get('location'), f.publicOrigin + '/');
|
|
const cookie = response.headers.get('set-cookie');
|
|
assert.match(cookie, /HttpOnly/);
|
|
assert.match(cookie, /SameSite=Lax/);
|
|
assert.match(cookie, /Path=\//);
|
|
assert.doesNotMatch(cookie, /Domain=/i);
|
|
assert.equal((await f.launch()).status, 403);
|
|
const app = await fetch(f.publicOrigin + '/actual', {
|
|
headers: {
|
|
cookie: f.cookie + '; app=allowed; WF_OTHER=not-forwarded',
|
|
authorization: 'Bearer user-must-not-reach-app',
|
|
'x-wishforge-service-token': serviceToken,
|
|
},
|
|
});
|
|
assert.equal(app.status, 200);
|
|
await app.text();
|
|
assert.equal(f.seen.at(-1).headers.authorization, undefined);
|
|
assert.equal(f.seen.at(-1).headers['x-wishforge-service-token'], undefined);
|
|
assert.equal(f.seen.at(-1).headers.cookie, 'app=allowed');
|
|
assert.doesNotMatch(app.headers.get('set-cookie'), /Domain|WF_PREVIEW_SESSION/i);
|
|
assert.equal(app.headers.get('x-wishforge-preview-proof'), null);
|
|
const redirect = await fetch(f.publicOrigin + '/redirect', { headers: { cookie: f.cookie }, redirect: 'manual' });
|
|
assert.equal(redirect.headers.get('location'), f.publicOrigin + '/actual');
|
|
assert.equal(
|
|
await new Promise((resolve, reject) => {
|
|
const request = http.get(
|
|
f.publicOrigin + '/',
|
|
{ headers: { host: 'other-preview.invalid', cookie: f.cookie } },
|
|
response => {
|
|
response.resume();
|
|
resolve(response.statusCode);
|
|
},
|
|
);
|
|
request.on('error', reject);
|
|
}),
|
|
421,
|
|
);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
test('Viewer reads are permitted but mutations and cross-origin requests are denied', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
f.setRole('viewer');
|
|
await f.launch();
|
|
assert.equal((await fetch(f.publicOrigin + '/', { headers: { cookie: f.cookie } })).status, 200);
|
|
assert.equal(
|
|
(
|
|
await fetch(f.publicOrigin + '/', {
|
|
method: 'POST',
|
|
headers: { cookie: f.cookie, origin: f.publicOrigin },
|
|
body: 'unsafe mutation',
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
assert.equal(
|
|
(await fetch(f.publicOrigin + '/', { headers: { cookie: f.cookie, origin: 'https://other.preview.invalid' } }))
|
|
.status,
|
|
403,
|
|
);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
test('release probes bind the body, path, challenge, scope and active release, without forwarding capabilities', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
const response = await fetch(f.publicOrigin + '/business?fixture=1', {
|
|
headers: {
|
|
'x-wishforge-preview-capability': probe,
|
|
'x-wishforge-preview-challenge': challenge,
|
|
authorization: 'Bearer ignored',
|
|
},
|
|
});
|
|
const body = Buffer.from(await response.arrayBuffer());
|
|
const signed = response.headers.get('x-wishforge-preview-proof');
|
|
assert.ok(
|
|
verifyPreviewProof(f.publicKey, signed, {
|
|
tenantId: 'tenant-a',
|
|
environmentId: 'environment-a',
|
|
releaseId: 'release-a',
|
|
bindingDigest: 'sha256:' + 'a'.repeat(64),
|
|
policyDigest: 'sha256:' + 'b'.repeat(64),
|
|
decision: 'authorized',
|
|
capabilitySha256: bodySha256(probe),
|
|
path: '/business?fixture=1',
|
|
challenge,
|
|
status: 200,
|
|
bodySha256: bodySha256(body),
|
|
}),
|
|
);
|
|
assert.equal(verifyPreviewProof(f.publicKey, signed, { bodySha256: bodySha256('different') }), undefined);
|
|
assert.equal(f.seen.at(-1).headers['x-wishforge-preview-capability'], undefined);
|
|
assert.equal(f.seen.at(-1).headers.authorization, undefined);
|
|
f.revoke();
|
|
assert.equal(
|
|
(
|
|
await fetch(f.publicOrigin + '/', {
|
|
headers: { 'x-wishforge-preview-capability': probe, 'x-wishforge-preview-challenge': challenge },
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
test('revocation closes an existing streamed response', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.launch();
|
|
const response = await fetch(f.publicOrigin + '/stream', { headers: { cookie: f.cookie } }),
|
|
reader = response.body.getReader();
|
|
assert.equal((await reader.read()).done, false);
|
|
f.revoke();
|
|
await assert.rejects(async () => {
|
|
for (;;) {
|
|
const value = await reader.read();
|
|
if (value.done) throw new Error('terminated');
|
|
}
|
|
}, /terminated/);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
test('WebSocket proxy requires session and origin, strips credentials, and closes on revocation', async () => {
|
|
const f = await fixture();
|
|
let socket;
|
|
try {
|
|
await f.launch();
|
|
const req = http.request(f.publicOrigin + '/socket', {
|
|
headers: {
|
|
connection: 'Upgrade',
|
|
upgrade: 'websocket',
|
|
'sec-websocket-version': '13',
|
|
'sec-websocket-key': Buffer.alloc(16).toString('base64'),
|
|
cookie: f.cookie,
|
|
origin: f.publicOrigin,
|
|
authorization: 'Bearer not-forwarded',
|
|
},
|
|
});
|
|
const upgraded = once(req, 'upgrade');
|
|
req.end();
|
|
const [response, peer] = await upgraded;
|
|
socket = peer;
|
|
assert.equal(response.statusCode, 101);
|
|
assert.equal(f.seen.at(-1).headers.cookie, undefined);
|
|
assert.equal(f.seen.at(-1).headers.authorization, undefined);
|
|
const ended = once(socket, 'close');
|
|
f.revoke();
|
|
await ended;
|
|
} finally {
|
|
socket?.destroy();
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('TLS-terminated preview uses the Secure host-prefix cookie', async () => {
|
|
const f = await fixture({ secure: true });
|
|
try {
|
|
const response = await f.launch();
|
|
assert.equal(response.status, 303);
|
|
const cookie = response.headers.get('set-cookie');
|
|
assert.match(cookie, /^__Host-WF_PREVIEW_SESSION=/);
|
|
assert.match(cookie, /; Secure/);
|
|
assert.match(cookie, /HttpOnly/);
|
|
assert.doesNotMatch(cookie, /Domain=/i);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('application cookie login survives the proxy without forwarding WishForge credentials', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.launch();
|
|
const before = await fetch(f.publicOrigin + '/account', { headers: { cookie: f.cookie } });
|
|
assert.equal(before.status, 401);
|
|
const login = await fetch(f.publicOrigin + '/login', {
|
|
method: 'POST',
|
|
headers: { cookie: f.cookie, origin: f.publicOrigin, 'content-type': 'application/json' },
|
|
body: JSON.stringify({ fixture: true }),
|
|
});
|
|
assert.equal(login.status, 200);
|
|
const cookie = login.headers.get('set-cookie');
|
|
assert.match(cookie, /application_session=logged-in/);
|
|
assert.doesNotMatch(cookie, /Domain=/i);
|
|
const account = await fetch(f.publicOrigin + '/account', {
|
|
headers: { cookie: f.cookie + '; ' + cookie.split(';')[0] },
|
|
});
|
|
assert.equal(account.status, 200);
|
|
assert.equal(await account.text(), 'private application account');
|
|
assert.equal(f.seen.at(-1).headers.cookie, 'application_session=logged-in');
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('launch redirects to the release-bound non-root application entry path', async () => {
|
|
const f = await fixture({ entryPath: '/catalog/start' });
|
|
try {
|
|
const response = await f.launch();
|
|
assert.equal(response.status, 303);
|
|
assert.equal(response.headers.get('location'), f.publicOrigin + '/catalog/start');
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('malformed authorization expiry is denied before application forwarding', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.launch();
|
|
f.setExpiry('not-a-date');
|
|
assert.equal((await fetch(f.publicOrigin + '/', { headers: { cookie: f.cookie } })).status, 403);
|
|
assert.equal(f.seen.length, 0);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('malicious upgrade response headers cannot crash the preview gateway', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.launch();
|
|
const status = await new Promise((resolve, reject) => {
|
|
const request = http.get(
|
|
f.publicOrigin + '/bad-socket-headers',
|
|
{
|
|
headers: {
|
|
connection: 'Upgrade',
|
|
upgrade: 'websocket',
|
|
'sec-websocket-version': '13',
|
|
'sec-websocket-key': Buffer.alloc(16).toString('base64'),
|
|
cookie: f.cookie,
|
|
origin: f.publicOrigin,
|
|
},
|
|
},
|
|
response => {
|
|
response.resume();
|
|
resolve(response.statusCode);
|
|
},
|
|
);
|
|
request.on('error', reject);
|
|
});
|
|
assert.equal(status, 502);
|
|
assert.equal((await fetch(f.publicOrigin + '/', { headers: { cookie: f.cookie } })).status, 200);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|