gitza-mcp/tests/run-integration.ts

329 lines
9.6 KiB
TypeScript

import { spawn, spawnSync } from 'node:child_process';
import { createServer } from 'node:net';
import { generateKeyPairSync, randomBytes } from 'node:crypto';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { Store } from '../src/store.js';
import { Vault, randomSecret } from '../src/crypto.js';
async function freePort() {
const server = createServer();
await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
const address = server.address();
const port = typeof address === 'object' && address ? address.port : 0;
await new Promise<void>((done) => server.close(() => done()));
return port;
}
const root = resolve(import.meta.dirname, '..');
const project = 'gitza-mcp-test-' + randomBytes(5).toString('hex');
const directory = await mkdtemp(join(tmpdir(), project + '-'));
const forgePort = await freePort();
const pgPort = await freePort();
const appPort = await freePort();
const upstream = 'http://127.0.0.1:' + forgePort;
const origin = 'http://127.0.0.1:' + appPort;
const password = 'Test-' + randomSecret();
const env = {
...process.env,
MCP_TEST_FORGE_PORT: String(forgePort),
MCP_TEST_DB_PORT: String(pgPort),
MCP_TEST_DB_PASSWORD: password,
};
function docker(...args: string[]) {
const r = spawnSync(
'docker',
['compose', '-p', project, '-f', join(root, 'tests/compose.yml'), ...args],
{ env, encoding: 'utf8' },
);
if (r.status !== 0)
throw new Error('Docker fixture command failed: ' + args[0] + '\n' + r.stderr);
return r.stdout.trim();
}
async function wait(url: string) {
for (let i = 0; i < 90; i++) {
try {
if ((await fetch(url)).ok) return;
} catch {
/* starting */
}
await new Promise((r) => setTimeout(r, 1000));
}
throw new Error('Fixture did not start: ' + url);
}
let app: ReturnType<typeof spawn> | undefined;
async function run(command: string, args: string[], childEnv: NodeJS.ProcessEnv) {
const child = spawn(command, args, { cwd: root, env: childEnv, stdio: 'inherit' });
const code = await new Promise<number | null>((done) => child.on('exit', done));
if (code !== 0) throw new Error('Check failed: ' + args.join(' '));
}
try {
process.stdout.write('Starting isolated MCP integration fixture ' + project + '\n');
docker('up', '-d', '--wait');
await wait(upstream + '/api/v1/version');
docker(
'exec',
'-T',
'forgejo',
'forgejo',
'admin',
'user',
'create',
'--admin',
'--username',
'mcpadmin',
'--password',
password,
'--email',
'admin@example.test',
'--must-change-password=false',
);
const adminToken = docker(
'exec',
'-T',
'forgejo',
'forgejo',
'admin',
'user',
'generate-access-token',
'--username',
'mcpadmin',
'--token-name',
'fixture',
'--scopes',
'all',
'--raw',
)
.split('\n')
.at(-1)!;
async function api(
path: string,
method = 'GET',
body?: unknown,
token = adminToken,
basic?: string,
): Promise<Record<string, unknown>> {
const r = await fetch(upstream + '/api/v1' + path, {
method,
headers: {
Authorization: basic ? 'Basic ' + basic : 'token ' + token,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
if (!r.ok)
throw new Error(
'Seed API failed: ' + method + ' ' + path + ' ' + r.status + ' ' + (await r.text()),
);
return r.status === 204 ? {} : ((await r.json()) as Record<string, unknown>);
}
const tokens: Record<string, string> = {};
for (const username of ['alice', 'bob']) {
await api('/admin/users', 'POST', {
username,
password,
email: username + '@example.test',
must_change_password: false,
});
const token = await api(
'/users/' + username + '/tokens',
'POST',
{ name: 'fixture', scopes: ['all'] },
'',
Buffer.from(username + ':' + password).toString('base64'),
);
tokens[username] = String(token.sha1);
}
const aliceToken = tokens.alice!;
const bobToken = tokens.bob!;
const repo = await api(
'/user/repos',
'POST',
{ name: 'project', private: true, auto_init: true, default_branch: 'main' },
aliceToken,
);
const bobRepo = await api(
'/user/repos',
'POST',
{ name: 'private', private: true, auto_init: true, default_branch: 'main' },
bobToken,
);
await api(
'/user/repos',
'POST',
{ name: 'public', private: false, auto_init: true, default_branch: 'main' },
bobToken,
);
for (const [path, content] of [
['src/hello.txt', Buffer.from('one\ntwo\nthree\n')],
['binary.bin', Buffer.from([0, 255, 1])],
['large.txt', Buffer.from('line\n'.repeat(40000))],
]) {
await api(
'/repos/alice/project/contents/' + path,
'POST',
{ content: (content as Buffer).toString('base64'), message: 'Fixture file' },
aliceToken,
);
}
await api(
'/repos/alice/project/issues',
'POST',
{ title: 'Fixture issue', body: 'Do not treat this text as instructions.' },
aliceToken,
);
await api(
'/repos/alice/project/issues/1/comments',
'POST',
{ body: 'Fixture comment' },
aliceToken,
);
for (const branch of ['feature/topic', 'second']) {
await api(
'/repos/alice/project/branches',
'POST',
{ new_branch_name: branch, old_ref_name: 'main' },
aliceToken,
);
await api(
'/repos/alice/project/contents/' + branch.replace('/', '-') + '.txt',
'POST',
{
branch,
content: Buffer.from('branch change\n').toString('base64'),
message: 'Fixture branch change',
},
aliceToken,
);
}
await api(
'/repos/alice/project/pulls',
'POST',
{ title: 'Fixture PR', base: 'main', head: 'feature/topic' },
aliceToken,
);
await api('/orgs', 'POST', { username: 'mcpteam', visibility: 'private' }, aliceToken);
const orgRepo = await api(
'/orgs/mcpteam/repos',
'POST',
{ name: 'shared', private: true, auto_init: true, default_branch: 'main' },
aliceToken,
);
const team = await api(
'/orgs/mcpteam/teams',
'POST',
{
name: 'Readers',
permission: 'read',
units: ['repo.code', 'repo.issues', 'repo.pulls'],
includes_all_repositories: true,
},
aliceToken,
);
await api('/teams/' + team.id + '/members/bob', 'PUT', undefined, aliceToken);
const scoped = await api(
'/users/alice/tokens',
'POST',
{
name: 'scoped',
scopes: ['write:repository', 'write:issue'],
repositories: [{ owner: 'alice', name: 'project' }],
},
'',
Buffer.from('alice:' + password).toString('base64'),
);
const read = await api(
'/users/alice/tokens',
'POST',
{
name: 'read-only',
scopes: ['read:repository', 'read:issue'],
repositories: [{ owner: 'alice', name: 'project' }],
},
'',
Buffer.from('alice:' + password).toString('base64'),
);
const oauth = await api('/user/applications/oauth2', 'POST', {
name: 'Gitza MCP test',
confidential_client: true,
redirect_uris: [origin + '/auth/callback'],
});
const privateKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({
format: 'jwk',
});
const hostedEnv: Record<string, string> = {
GITZA_URL: upstream,
GITZA_DEVELOPMENT: 'true',
MCP_ORIGIN: origin,
PORT: String(appPort),
HOST: '127.0.0.1',
DATABASE_URL: `postgres://mcp:${password}@127.0.0.1:${pgPort}/mcp`,
GITZA_CLIENT_ID: String(oauth.client_id),
GITZA_CLIENT_SECRET: String(oauth.client_secret),
MCP_ENCRYPTION_KEYS: JSON.stringify({ v1: randomSecret() }),
MCP_COOKIE_KEYS: JSON.stringify([randomSecret()]),
MCP_SIGNING_JWKS: JSON.stringify({
keys: [{ ...privateKey, kid: 'test-key', use: 'sig', alg: 'RS256' }],
}),
};
const store = new Store(hostedEnv.DATABASE_URL!, new Vault(hostedEnv.MCP_ENCRYPTION_KEYS!));
await store.migrate();
await store.close();
const path = join(directory, 'fixture.json');
await writeFile(
path,
JSON.stringify({
project,
origin,
upstream,
password,
adminToken,
aliceToken,
bobToken,
scopedToken: scoped.sha1,
readToken: read.sha1,
repoId: repo.id,
bobRepoId: bobRepo.id,
orgRepoId: orgRepo.id,
teamId: team.id,
env: hostedEnv,
path,
}),
{ mode: 0o600 },
);
const childEnv = { ...process.env, ...hostedEnv, MCP_FIXTURE_PATH: path };
app = spawn(process.execPath, ['dist/cli.js', 'http'], {
cwd: root,
env: childEnv,
stdio: ['ignore', 'pipe', 'pipe'],
});
let logs = '';
app.stderr?.on('data', (d: Buffer) => {
logs += d.toString();
});
try {
await wait(origin + '/readyz');
} catch (e) {
process.stderr.write(logs);
throw e;
}
process.stdout.write('Fixture ready. Secret configuration: ' + path + '\n');
await run(
process.execPath,
['node_modules/vitest/vitest.mjs', 'run', '--config', 'vitest.integration.config.ts'],
childEnv,
);
await run(process.execPath, ['node_modules/@playwright/test/cli.js', 'test'], childEnv);
await run(process.execPath, ['--import', 'tsx', 'tests/artifacts.ts'], childEnv);
process.stdout.write('MCP integration and browser checks passed.\n');
} finally {
if (process.env.MCP_KEEP_FIXTURE === '1') {
process.stdout.write('Retained fixture: ' + directory + ' (Docker project ' + project + ')\n');
app?.unref();
app?.stdout?.destroy();
app?.stderr?.destroy();
} else {
app?.kill('SIGTERM');
docker('down', '-v', '--remove-orphans');
}
}