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>
317 lines
13 KiB
JavaScript
317 lines
13 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import http from 'node:http';
|
|
import { once } from 'node:events';
|
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
import { createGateway } from '../server.mjs';
|
|
import { generateKeyPairSync } from 'node:crypto';
|
|
import assertions from '../../security/assertions.cjs';
|
|
|
|
async function listen(server) {
|
|
server.listen(0, '127.0.0.1');
|
|
await once(server, 'listening');
|
|
return `http://127.0.0.1:${server.address().port}`;
|
|
}
|
|
async function fixture(t, options = {}) {
|
|
const state = { revoked: false, role: 'developer', calls: [], receivedHeaders: undefined };
|
|
const upstream = http.createServer((req, res) => {
|
|
state.receivedHeaders = req.headers;
|
|
if (state.connectionToken) {
|
|
res.setHeader('set-cookie', `theia-connection-token=${state.connectionToken}; HttpOnly; SameSite=Strict; Path=/`);
|
|
if (req.url === '/protected' && req.headers.cookie !== `theia-connection-token=${state.connectionToken}`) {
|
|
res.writeHead(403);
|
|
res.end();
|
|
return;
|
|
}
|
|
}
|
|
res.writeHead(200, { 'content-type': 'application/json' });
|
|
res.end(JSON.stringify({ path: req.url }));
|
|
});
|
|
const websocket = new WebSocketServer({ server: upstream });
|
|
websocket.on('connection', socket => socket.on('message', (data, binary) => socket.send(data, { binary })));
|
|
const upstreamUrl = await listen(upstream);
|
|
state.upstreamUrl = upstreamUrl;
|
|
state.collaborationUpstreamUrl = upstreamUrl;
|
|
const auth = http.createServer(async (req, res) => {
|
|
let raw = '';
|
|
for await (const part of req) raw += part;
|
|
const body = JSON.parse(raw);
|
|
state.calls.push({ path: req.url, headers: req.headers, body });
|
|
if (
|
|
state.revoked ||
|
|
(req.url.endsWith('/lifecycle-authorize')
|
|
? false
|
|
: req.url.endsWith('/integration-authorize')
|
|
? body.runId !== 'run-1'
|
|
: body.userToken !== 'user-token')
|
|
) {
|
|
res.writeHead(403);
|
|
res.end();
|
|
return;
|
|
}
|
|
res.writeHead(200, { 'content-type': 'application/json' });
|
|
res.end(
|
|
JSON.stringify({
|
|
data: {
|
|
tenantId: 'tenant-a',
|
|
projectId: 'p1',
|
|
workspaceId: 'w1',
|
|
userId: 'authenticated-user',
|
|
role: state.role,
|
|
purpose: req.url.endsWith('/lifecycle-authorize')
|
|
? 'workspace-lifecycle'
|
|
: req.url.endsWith('/integration-authorize')
|
|
? 'integration-state'
|
|
: undefined,
|
|
upstreamUrl: state.upstreamUrl,
|
|
collaborationUpstreamUrl: state.collaborationUpstreamUrl,
|
|
},
|
|
}),
|
|
);
|
|
});
|
|
const apiOrigin = await listen(auth);
|
|
// Reserve a local port, then bind the gateway with its actual public origin.
|
|
const reservation = http.createServer();
|
|
const publicUrl = await listen(reservation);
|
|
await new Promise(r => reservation.close(r));
|
|
const gateway = createGateway({
|
|
publicUrl,
|
|
apiOrigin,
|
|
tenantId: 'tenant-a',
|
|
serviceToken: 'gateway-secret',
|
|
allowedUpstreamOrigins: [upstreamUrl],
|
|
allowedCollaborationOrigins: [upstreamUrl],
|
|
assertionPrivateKey: options.privateKey,
|
|
reauthorizeMs: 50,
|
|
});
|
|
gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1');
|
|
await once(gateway.server, 'listening');
|
|
t.after(async () => {
|
|
await gateway.close();
|
|
for (const socket of websocket.clients) socket.terminate();
|
|
websocket.close();
|
|
await Promise.all([new Promise(r => upstream.close(r)), new Promise(r => auth.close(r))]);
|
|
});
|
|
const requestLaunch = () =>
|
|
fetch(`${publicUrl}/launch`, {
|
|
method: 'POST',
|
|
headers: { authorization: 'Bearer user-token', 'content-type': 'application/json' },
|
|
body: JSON.stringify({ workspaceId: 'w1' }),
|
|
});
|
|
async function session() {
|
|
const response = await requestLaunch();
|
|
assert.equal(response.status, 200);
|
|
const { launchUrl } = await response.json();
|
|
assert.ok(!launchUrl.includes('user-token'));
|
|
const exchanged = await fetch(launchUrl, { redirect: 'manual' });
|
|
assert.equal(exchanged.status, 303);
|
|
return { launchUrl, exchanged, cookie: exchanged.headers.get('set-cookie').split(';')[0] };
|
|
}
|
|
return { state, publicUrl, requestLaunch, session };
|
|
}
|
|
|
|
test('requires authentication, exchanges a one-time code, and never forwards bearer/cookie', async t => {
|
|
const f = await fixture(t);
|
|
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`)).status, 401);
|
|
const s = await f.session();
|
|
assert.match(s.exchanged.headers.get('set-cookie'), /HttpOnly/);
|
|
assert.match(s.exchanged.headers.get('set-cookie'), /SameSite=Strict/);
|
|
assert.equal(s.exchanged.headers.get('referrer-policy'), 'no-referrer');
|
|
assert.equal((await fetch(s.launchUrl, { redirect: 'manual' })).status, 401);
|
|
const response = await fetch(`${f.publicUrl}/workspaces/w1/file?name=test`, { headers: { cookie: s.cookie } });
|
|
assert.equal(response.status, 200);
|
|
assert.deepEqual(await response.json(), { path: '/file?name=test' });
|
|
assert.equal(f.state.receivedHeaders.authorization, undefined);
|
|
assert.equal(f.state.receivedHeaders.cookie, undefined);
|
|
assert.equal(f.state.receivedHeaders['x-wishforge-tenant'], 'tenant-a');
|
|
assert.ok(
|
|
f.state.calls.every(
|
|
c => c.headers.authorization === 'Bearer gateway-secret' && c.headers['x-wishforge-tenant'] === 'tenant-a',
|
|
),
|
|
);
|
|
assert.equal((await fetch(`${f.publicUrl}/workspaces/w2/`, { headers: { cookie: s.cookie } })).status, 401);
|
|
});
|
|
|
|
test('viewer cannot obtain edit access and caller cannot choose an upstream or downgrade operation', async t => {
|
|
const f = await fixture(t);
|
|
f.state.role = 'viewer';
|
|
assert.equal((await f.requestLaunch()).status, 403);
|
|
f.state.role = 'developer';
|
|
f.state.upstreamUrl = 'http://169.254.169.254/';
|
|
assert.equal((await f.requestLaunch()).status, 502);
|
|
const malformed = await fetch(`${f.publicUrl}/launch`, {
|
|
method: 'POST',
|
|
headers: { authorization: 'Bearer user-token', 'content-type': 'application/json' },
|
|
body: JSON.stringify({ workspaceId: 'w1', upstreamUrl: 'http://evil.invalid' }),
|
|
});
|
|
assert.equal(malformed.status, 400);
|
|
await fetch(`${f.publicUrl}/workspaces/w1/?operation=preview`, { headers: { authorization: 'Bearer user-token' } });
|
|
assert.equal(f.state.calls.at(-1).body.operation, 'edit');
|
|
});
|
|
|
|
test('HTTP rechecks revocation and rejects cross-origin cookie requests', async t => {
|
|
const f = await fixture(t);
|
|
const s = await f.session();
|
|
assert.equal(
|
|
(
|
|
await fetch(`${f.publicUrl}/workspaces/w1/`, {
|
|
headers: { cookie: s.cookie, origin: 'https://attacker.invalid' },
|
|
})
|
|
).status,
|
|
403,
|
|
);
|
|
f.state.revoked = true;
|
|
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: s.cookie } })).status, 403);
|
|
});
|
|
|
|
test('preserves the upstream Theia process token server-side without forwarding client cookies', async t => {
|
|
const f = await fixture(t);
|
|
f.state.connectionToken = 'server-only-process-token';
|
|
const s = await f.session();
|
|
const first = await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: `${s.cookie}; unrelated=secret` } });
|
|
assert.equal(first.status, 200);
|
|
assert.equal(first.headers.get('set-cookie'), null);
|
|
const protectedResponse = await fetch(`${f.publicUrl}/workspaces/w1/protected`, {
|
|
headers: { cookie: `${s.cookie}; theia-connection-token=attacker-value` },
|
|
});
|
|
assert.equal(protectedResponse.status, 200);
|
|
assert.equal(f.state.receivedHeaders.cookie, 'theia-connection-token=server-only-process-token');
|
|
});
|
|
|
|
test('gateway signs the API-authorized actor and strips forged workspace identity headers', async t => {
|
|
const pair = generateKeyPairSync('ed25519');
|
|
const f = await fixture(t, { privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }) });
|
|
const s = await f.session();
|
|
const response = await fetch(`${f.publicUrl}/workspaces/w1/`, {
|
|
headers: { cookie: s.cookie, 'x-wishforge-actor-assertion': 'forged', 'x-wishforge-user': 'attacker' },
|
|
});
|
|
assert.equal(response.status, 200);
|
|
const who = assertions.verifyAssertion(
|
|
pair.publicKey.export({ type: 'spki', format: 'pem' }),
|
|
f.state.receivedHeaders['x-wishforge-actor-assertion'],
|
|
{ tenantId: 'tenant-a', workspaceId: 'w1' },
|
|
);
|
|
assert.equal(who.actorId, 'authenticated-user');
|
|
assert.equal(f.state.receivedHeaders['x-wishforge-user'], undefined);
|
|
});
|
|
|
|
test('WebSocket traffic is authenticated and a revoked member is disconnected', { timeout: 5000 }, async t => {
|
|
const f = await fixture(t);
|
|
const s = await f.session();
|
|
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/services`, {
|
|
origin: f.publicUrl,
|
|
headers: { cookie: s.cookie },
|
|
});
|
|
await once(ws, 'open');
|
|
ws.send('editor-frame');
|
|
const [frame] = await once(ws, 'message');
|
|
assert.equal(frame.toString(), 'editor-frame');
|
|
const closed = once(ws, 'close');
|
|
f.state.revoked = true;
|
|
await closed;
|
|
assert.ok(f.state.calls.length >= 4);
|
|
});
|
|
|
|
test(
|
|
'collaboration HTTP/WS stays behind workspace edit authorization and cannot select another upstream',
|
|
{ timeout: 5000 },
|
|
async t => {
|
|
const f = await fixture(t);
|
|
const s = await f.session();
|
|
const reply = await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/meta`, {
|
|
headers: { cookie: s.cookie, 'x-oct-client': 'test' },
|
|
});
|
|
assert.equal(reply.status, 200);
|
|
assert.deepEqual(await reply.json(), { path: '/api/meta' });
|
|
assert.equal(f.state.calls.at(-1).body.operation, 'edit');
|
|
assert.equal(f.state.receivedHeaders['x-oct-client'], 'test');
|
|
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/collaboration/socket.io/`, {
|
|
origin: f.publicUrl,
|
|
headers: { cookie: s.cookie },
|
|
});
|
|
await once(ws, 'open');
|
|
ws.send('room-frame');
|
|
const [frame] = await once(ws, 'message');
|
|
assert.equal(frame.toString(), 'room-frame');
|
|
const closed = once(ws, 'close');
|
|
f.state.revoked = true;
|
|
await closed;
|
|
f.state.revoked = false;
|
|
f.state.collaborationUpstreamUrl = 'http://169.254.169.254/';
|
|
assert.equal(
|
|
(await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/meta`, { headers: { cookie: s.cookie } })).status,
|
|
502,
|
|
);
|
|
},
|
|
);
|
|
|
|
test('integration state relay is service authenticated, scope checked and purpose restricted', async t => {
|
|
const pair = generateKeyPairSync('ed25519');
|
|
const f = await fixture(t, { privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }) });
|
|
const request = (token, extra = {}) =>
|
|
fetch(`${f.publicUrl}/internal/integration-state`, {
|
|
method: 'POST',
|
|
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
body: JSON.stringify({
|
|
tenantId: 'tenant-a',
|
|
workspaceId: 'w1',
|
|
runId: 'run-1',
|
|
revision: 1,
|
|
generation: 'generation-one',
|
|
...extra,
|
|
}),
|
|
});
|
|
assert.equal((await request('user-token')).status, 401);
|
|
assert.equal((await request('gateway-secret', { tenantId: 'tenant-b' })).status, 400);
|
|
assert.equal((await request('gateway-secret', { runId: 'other-run' })).status, 403);
|
|
const response = await request('gateway-secret');
|
|
assert.equal(response.status, 200);
|
|
assert.deepEqual(await response.json(), { path: '/_wishforge/integration/state' });
|
|
const token = f.state.receivedHeaders['x-wishforge-actor-assertion'];
|
|
const key = pair.publicKey.export({ type: 'spki', format: 'pem' });
|
|
assert.equal(
|
|
assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1', purpose: 'integration-state' })
|
|
.purpose,
|
|
'integration-state',
|
|
);
|
|
assert.throws(() => assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1' }), /PURPOSE/);
|
|
f.state.upstreamUrl = 'http://169.254.169.254/';
|
|
assert.equal((await request('gateway-secret')).status, 502);
|
|
f.state.revoked = true;
|
|
assert.equal((await request('gateway-secret')).status, 403);
|
|
});
|
|
|
|
test('lifecycle inspection is read-only scoped and accounts for every live workspace socket', async t => {
|
|
const pair = generateKeyPairSync('ed25519');
|
|
const f = await fixture(t, { privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }) });
|
|
const inspect = () =>
|
|
fetch(`${f.publicUrl}/internal/lifecycle-state`, {
|
|
method: 'POST',
|
|
headers: { authorization: 'Bearer gateway-secret', 'content-type': 'application/json' },
|
|
body: JSON.stringify({ tenantId: 'tenant-a', workspaceId: 'w1' }),
|
|
});
|
|
let response = await inspect();
|
|
assert.equal(response.status, 200);
|
|
assert.deepEqual(await response.json(), { path: '/_wishforge/lifecycle/state', gatewayConnections: 0 });
|
|
const key = pair.publicKey.export({ type: 'spki', format: 'pem' });
|
|
const token = f.state.receivedHeaders['x-wishforge-actor-assertion'];
|
|
assert.equal(
|
|
assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1', purpose: 'workspace-lifecycle' })
|
|
.purpose,
|
|
'workspace-lifecycle',
|
|
);
|
|
assert.throws(() => assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1' }), /PURPOSE/);
|
|
const session = await f.session();
|
|
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/services`, {
|
|
origin: f.publicUrl,
|
|
headers: { cookie: session.cookie },
|
|
});
|
|
await once(ws, 'open');
|
|
response = await inspect();
|
|
assert.equal((await response.json()).gatewayConnections, 1);
|
|
ws.close();
|
|
await once(ws, 'close');
|
|
response = await inspect();
|
|
assert.equal((await response.json()).gatewayConnections, 0);
|
|
});
|