wishforge-ide/apps/ide/gateway/test/gateway.test.mjs
eust-w ed20bf640e fix: keep IDE collaboration sign-in alive, and label branch-run diffs
- OCT holds each login poll open for 30 seconds before answering. The
  gateway gave every upstream 30 seconds of silence, so creating a
  collaboration session failed with "Workspace upstream unavailable" once
  sign-in took that long, and raced at best.
- Collaboration requests now get at least 65 seconds; other upstreams
  keep 30 (upstreamTimeoutMs).
- A run that starts from a branch shows its checkpoint relative to that
  branch, so the branch's own commits, which merge too, are not in the
  diff. The run page now says so instead of "relative to the target
  branch".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:24:04 +08:00

308 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';
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: [], credentialRequests: [], receivedHeaders: undefined };
const upstream = http.createServer(async (req, res) => {
state.receivedHeaders = req.headers;
// Like OCT's login poll, which answers only after holding the request open.
if (state.delayMs && (req.url === '/slow' || req.url.startsWith('/api/login/poll/')))
await new Promise(resolve => setTimeout(resolve, state.delayMs));
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);
// Repository credentials are covered by gateway-handler.test.mjs; this project has none,
// so the gateway never contacts Theia on its own here.
if (req.url.endsWith('/git-credential')) {
state.credentialRequests.push(body);
res.writeHead(409);
res.end();
return;
}
state.calls.push({ path: req.url, headers: req.headers, body });
// A new session presents the user's token; an established one names the granted user.
if (state.revoked || (body.userToken !== 'user-token' && body.userId !== 'authenticated-user')) {
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,
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],
reauthorizeMs: 50,
...options,
});
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('gives up on a silent Theia upstream but waits out an OCT login poll', async t => {
const f = await fixture(t, { upstreamTimeoutMs: 100 });
const s = await f.session();
f.state.delayMs = 400;
const headers = { cookie: s.cookie, origin: f.publicUrl };
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/slow`, { headers })).status, 502);
const poll = await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/login/poll/token-1`, {
method: 'POST',
headers,
});
assert.equal(poll.status, 200);
assert.deepEqual(await poll.json(), { path: '/api/login/poll/token-1' });
});
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('strips caller-supplied workspace identity headers before reaching Theia', async t => {
const f = await fixture(t);
const s = await f.session();
const response = await fetch(`${f.publicUrl}/workspaces/w1/`, {
headers: { cookie: s.cookie, 'x-wishforge-tenant': 'tenant-b', 'x-wishforge-user': 'attacker' },
});
assert.equal(response.status, 200);
assert.equal(f.state.receivedHeaders['x-wishforge-tenant'], 'tenant-a');
assert.equal(f.state.receivedHeaders['x-wishforge-workspace'], 'w1');
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(
'an IDE in use outlives the idle timeout, rechecking the granted user rather than their token',
{ timeout: 5000 },
async t => {
const f = await fixture(t, { sessionTtlMs: 300 });
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');
// Longer than the idle timeout: the open socket's periodic checks keep renewing the session.
await new Promise(resolve => setTimeout(resolve, 800));
ws.send('still-working');
const [frame] = await once(ws, 'message');
assert.equal(frame.toString(), 'still-working');
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: s.cookie } })).status, 200);
const last = f.state.calls.at(-1).body;
assert.equal(last.userId, 'authenticated-user');
assert.equal(last.userToken, undefined);
// Revocation still ends the session.
const closed = once(ws, 'close');
f.state.revoked = true;
await closed;
},
);
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('lifecycle inspection is service authenticated, scoped, and counts every live workspace socket', async t => {
const f = await fixture(t);
const inspect = (token = 'gateway-secret', tenantId = 'tenant-a') =>
fetch(`${f.publicUrl}/internal/lifecycle-state`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ tenantId, workspaceId: 'w1' }),
});
assert.equal((await inspect('user-token')).status, 401);
assert.equal((await inspect('gateway-secret', 'tenant-b')).status, 400);
let response = await inspect();
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { workspaceId: 'w1', known: true, gatewayConnections: 0 });
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);
});