The gateway refused new launches once 1000 codes or sessions existed in total, so one member could crowd everyone else out for as long as the sessions lived. Each person now holds at most 20 of each; beyond that their own oldest ends, and its open connections close at their next check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
216 lines
8.5 KiB
JavaScript
216 lines
8.5 KiB
JavaScript
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import { Readable } from 'node:stream';
|
||
import { createGateway } from '../server.mjs';
|
||
|
||
// These drive the gateway's request handler directly with a fake fetch, so they also run where
|
||
// opening sockets is not permitted. gateway.test.mjs covers proxying over real connections.
|
||
const publicUrl = 'http://gateway.test:4400';
|
||
const apiOrigin = 'http://api.test:4000';
|
||
const upstreamUrl = 'http://theia.test:3000/';
|
||
|
||
function fakeFetch(options = {}) {
|
||
const state = { calls: [], deliveries: [], connectionToken: 'connection-token-1', rejectDelivery: 0 };
|
||
const json = (value, status = 200) =>
|
||
new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } });
|
||
state.fetch = async (input, init = {}) => {
|
||
const url = String(input);
|
||
const body = init.body ? JSON.parse(init.body) : undefined;
|
||
state.calls.push({ url, method: init.method ?? 'GET', headers: init.headers ?? {}, body });
|
||
if (url === `${apiOrigin}/internal/workspaces/w1/authorize`)
|
||
return json({
|
||
data: {
|
||
tenantId: 'tenant-a',
|
||
projectId: 'p1',
|
||
workspaceId: 'w1',
|
||
// The launch presents a person's token; later checks name the person it was granted to.
|
||
userId: body.userToken ? (options.userFor?.(body.userToken) ?? 'authenticated-user') : body.userId,
|
||
role: 'developer',
|
||
upstreamUrl,
|
||
...(body.userToken ? { author: { name: 'Ada Lovelace', email: 'ada@example.com' } } : {}),
|
||
},
|
||
});
|
||
if (url === `${apiOrigin}/internal/workspaces/w1/git-credential`) {
|
||
if (options.unsupported) return json({ error: 'WORKSPACE_REPOSITORY_UNSUPPORTED' }, 409);
|
||
return json({
|
||
data: {
|
||
projectId: 'p1',
|
||
projectName: 'Todo App',
|
||
repositoryUrl: 'https://git.test/git/tenant-a/p1.git',
|
||
branch: 'main',
|
||
token: 'payload.signature',
|
||
expiresAt: new Date(Date.now() + 900_000).toISOString(),
|
||
},
|
||
});
|
||
}
|
||
if (url === upstreamUrl)
|
||
return new Response('<html></html>', {
|
||
headers: { 'set-cookie': `theia-connection-token=${state.connectionToken}; HttpOnly; SameSite=Strict; Path=/` },
|
||
});
|
||
if (url === `${upstreamUrl}wishforge-internal/git-credential`) {
|
||
if (state.rejectDelivery > 0 || init.headers.cookie !== `theia-connection-token=${state.connectionToken}`) {
|
||
state.rejectDelivery -= 1;
|
||
return new Response('', { status: 403 });
|
||
}
|
||
state.deliveries.push({ cookie: init.headers.cookie, body });
|
||
return json({ status: 'cloning' });
|
||
}
|
||
throw new Error(`Unexpected fetch ${url}`);
|
||
};
|
||
return state;
|
||
}
|
||
|
||
function send(gateway, { method = 'GET', url, headers = {}, body }) {
|
||
const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]);
|
||
Object.assign(req, { method, url, headers: { host: 'gateway.test:4400', ...headers } });
|
||
return new Promise(resolve => {
|
||
const res = {
|
||
headersSent: false,
|
||
writeHead(status, responseHeaders = {}) {
|
||
this.status = status;
|
||
this.headers = responseHeaders;
|
||
this.headersSent = true;
|
||
return this;
|
||
},
|
||
end(chunk) {
|
||
resolve({ status: this.status, headers: this.headers, body: chunk ? String(chunk) : '' });
|
||
},
|
||
destroy() {
|
||
resolve({ status: 0, headers: {}, body: '' });
|
||
},
|
||
on() {
|
||
return this;
|
||
},
|
||
};
|
||
gateway.server.emit('request', req, res);
|
||
});
|
||
}
|
||
|
||
async function eventually(check) {
|
||
for (let i = 0; i < 100; i++) {
|
||
if (check()) return;
|
||
await new Promise(resolve => setTimeout(resolve, 5));
|
||
}
|
||
assert.fail('condition was not reached');
|
||
}
|
||
|
||
function setup(t, options) {
|
||
const state = fakeFetch(options);
|
||
const gateway = createGateway({
|
||
publicUrl,
|
||
apiOrigin,
|
||
tenantId: 'tenant-a',
|
||
serviceToken: 'gateway-secret',
|
||
allowedUpstreamOrigins: [new URL(upstreamUrl).origin],
|
||
fetchImpl: state.fetch,
|
||
});
|
||
t.after(() => gateway.close());
|
||
return { gateway, state };
|
||
}
|
||
|
||
async function launch(gateway, token = 'user-token') {
|
||
const response = await send(gateway, {
|
||
method: 'POST',
|
||
url: '/launch',
|
||
headers: { origin: publicUrl, authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||
body: { workspaceId: 'w1' },
|
||
});
|
||
assert.equal(response.status, 200, response.body);
|
||
return new URL(JSON.parse(response.body).launchUrl).searchParams.get('code');
|
||
}
|
||
const redeem = (gateway, code) => send(gateway, { url: `/session?code=${encodeURIComponent(code)}` });
|
||
|
||
async function openSession(gateway, token) {
|
||
const session = await redeem(gateway, await launch(gateway, token));
|
||
assert.equal(session.status, 303, session.body);
|
||
return session.headers['set-cookie'].split(';')[0];
|
||
}
|
||
|
||
test('launching presents the person’s token, and the session keeps only who it was granted to', async t => {
|
||
const { gateway, state } = setup(t);
|
||
await openSession(gateway);
|
||
const checks = state.calls.filter(call => call.url.endsWith('/authorize'));
|
||
assert.deepEqual(
|
||
checks.map(call => call.body),
|
||
[
|
||
{ userToken: 'user-token', operation: 'edit' },
|
||
{ userToken: 'user-token', operation: 'edit' },
|
||
],
|
||
);
|
||
assert.equal(checks[0].headers.authorization, 'Bearer gateway-secret');
|
||
});
|
||
|
||
test('a new session delivers a fresh repository credential and its author to the workspace', async t => {
|
||
const { gateway, state } = setup(t);
|
||
await openSession(gateway);
|
||
await eventually(() => state.deliveries.length === 1);
|
||
const minted = state.calls.find(call => call.url.endsWith('/git-credential'));
|
||
assert.deepEqual(minted.body, { userId: 'authenticated-user' });
|
||
assert.equal(minted.headers['X-WishForge-Tenant'], 'tenant-a');
|
||
const [delivery] = state.deliveries;
|
||
assert.equal(delivery.cookie, 'theia-connection-token=connection-token-1');
|
||
assert.deepEqual(delivery.body, {
|
||
projectId: 'p1',
|
||
projectName: 'Todo App',
|
||
repositoryUrl: 'https://git.test/git/tenant-a/p1.git',
|
||
branch: 'main',
|
||
token: 'payload.signature',
|
||
expiresAt: delivery.body.expiresAt,
|
||
author: { name: 'Ada Lovelace', email: 'ada@example.com' },
|
||
});
|
||
});
|
||
|
||
test('a restarted workspace gets the delivery after the gateway fetches its new connection token', async t => {
|
||
const { gateway, state } = setup(t);
|
||
state.rejectDelivery = 1;
|
||
await openSession(gateway);
|
||
await eventually(() => state.deliveries.length === 1);
|
||
assert.equal(state.calls.filter(call => call.url === upstreamUrl).length, 2);
|
||
});
|
||
|
||
test('people cannot reach the credential endpoint of the workspace through the gateway', async t => {
|
||
const { gateway, state } = setup(t);
|
||
const cookie = await openSession(gateway);
|
||
await eventually(() => state.deliveries.length === 1);
|
||
const before = state.calls.length;
|
||
for (const path of [
|
||
'/workspaces/w1/wishforge-internal/git-credential',
|
||
'/workspaces/w1/wishforge-internal/other',
|
||
'/workspaces/w1/wishforge-internal',
|
||
// Theia's Express routes match regardless of case.
|
||
'/workspaces/w1/Wishforge-Internal/git-credential',
|
||
'/workspaces/w1/WISHFORGE-INTERNAL/GIT-CREDENTIAL',
|
||
]) {
|
||
const response = await send(gateway, { method: 'POST', url: path, headers: { origin: publicUrl, cookie } });
|
||
assert.equal(response.status, 404);
|
||
}
|
||
assert.equal(state.calls.length, before);
|
||
});
|
||
|
||
test('a project without a platform repository is not delivered anything', async t => {
|
||
const { gateway, state } = setup(t, { unsupported: true });
|
||
await openSession(gateway);
|
||
await eventually(() => state.calls.some(call => call.url.endsWith('/git-credential')));
|
||
await new Promise(resolve => setTimeout(resolve, 20));
|
||
assert.equal(state.deliveries.length, 0);
|
||
assert.equal(
|
||
state.calls.some(call => call.url.startsWith(upstreamUrl)),
|
||
false,
|
||
);
|
||
});
|
||
|
||
test('one person cannot use up the capacity everyone shares; their own oldest codes and sessions end', async t => {
|
||
const { gateway } = setup(t, { userFor: token => (token === 'other-token' ? 'other-user' : 'authenticated-user') });
|
||
const codes = [];
|
||
for (let i = 0; i < 21; i++) codes.push(await launch(gateway));
|
||
assert.equal((await redeem(gateway, codes[0])).status, 401);
|
||
const cookies = [];
|
||
for (let i = 0; i < 21; i++) cookies.push(await openSession(gateway));
|
||
assert.equal(gateway.sessionCount(), 20);
|
||
const page = cookie => send(gateway, { url: '/workspaces/w1/', headers: { origin: publicUrl, cookie } });
|
||
assert.equal((await page(cookies[0])).status, 401);
|
||
// Someone else still gets in.
|
||
await openSession(gateway, 'other-token');
|
||
assert.equal(gateway.sessionCount(), 21);
|
||
});
|