235 lines
9.2 KiB
TypeScript
235 lines
9.2 KiB
TypeScript
import { afterAll, describe, expect, it } from 'vitest';
|
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
import { GitzaApi } from '../../src/api.js';
|
|
import { executeTool, tools } from '../../src/tools.js';
|
|
import { Store } from '../../src/store.js';
|
|
import { Vault, randomSecret } from '../../src/crypto.js';
|
|
import { readFixture } from '../fixture.js';
|
|
|
|
const f = readFixture();
|
|
const ctx = {
|
|
api: new GitzaApi(f.upstream, f.scopedToken),
|
|
repositories: [{ id: f.repoId, name: 'alice/project' }],
|
|
write: true,
|
|
};
|
|
const store = new Store(f.env.DATABASE_URL!, new Vault(f.env.MCP_ENCRYPTION_KEYS!));
|
|
afterAll(async () => {
|
|
await store.close();
|
|
});
|
|
|
|
describe('real Gitza API', () => {
|
|
const readArgs: Record<string, Record<string, unknown>> = {
|
|
list_repositories: {},
|
|
get_repository: {},
|
|
list_directory: {},
|
|
get_file: { path: 'src/hello.txt', ref: 'feature/topic' },
|
|
list_branches: {},
|
|
list_commits: { sha: 'feature/topic' },
|
|
list_issues: {},
|
|
get_issue: { index: 1 },
|
|
list_comments: { index: 1 },
|
|
list_pull_requests: {},
|
|
get_pull_request: { index: 2 },
|
|
get_pull_request_diff: { index: 2 },
|
|
};
|
|
for (const tool of tools.filter((t) => !t.write)) {
|
|
it('executes ' + tool.name + ' with a repository-scoped token', async () => {
|
|
const args =
|
|
tool.name === 'list_repositories'
|
|
? {}
|
|
: { repository: 'alice/project', ...readArgs[tool.name] };
|
|
const result = await executeTool(tool.name, args, ctx);
|
|
expect(result).toBeTypeOf('object');
|
|
expect(JSON.stringify(result)).not.toContain(f.scopedToken);
|
|
});
|
|
}
|
|
it('paginates lists and large file windows', async () => {
|
|
const list = await executeTool('list_commits', { repository: 'alice/project', limit: 1 }, ctx);
|
|
expect(list.next_page).toBe(2);
|
|
const result = await executeTool(
|
|
'get_file',
|
|
{ repository: 'alice/project', path: 'large.txt', start_line: 100, max_lines: 5 },
|
|
ctx,
|
|
);
|
|
expect(result.next_line).toBe(105);
|
|
expect(result.truncated).toBe(true);
|
|
});
|
|
it('rejects binary files and missing objects', async () => {
|
|
await expect(
|
|
executeTool('get_file', { repository: 'alice/project', path: 'binary.bin' }, ctx),
|
|
).rejects.toMatchObject({ code: 'BINARY_FILE' });
|
|
await expect(
|
|
executeTool('get_file', { repository: 'alice/project', path: 'absent' }, ctx),
|
|
).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
|
|
});
|
|
it('creates an issue, comment and PR exactly once', async () => {
|
|
const issue = await executeTool(
|
|
'create_issue',
|
|
{ repository: 'alice/project', title: 'Integration issue' },
|
|
ctx,
|
|
);
|
|
const data = issue.data as { number: number; html_url: string };
|
|
expect(data.html_url).toContain('alice/project/issues/');
|
|
const comment = await executeTool(
|
|
'add_comment',
|
|
{ repository: 'alice/project', index: data.number, body: 'Integration comment' },
|
|
ctx,
|
|
);
|
|
expect((comment.data as { id: number }).id).toBeGreaterThan(0);
|
|
const pr = await executeTool(
|
|
'create_pull_request',
|
|
{ repository: 'alice/project', title: 'Integration PR', head: 'second', base: 'main' },
|
|
ctx,
|
|
);
|
|
expect((pr.data as { html_url: string }).html_url).toContain('/pulls/');
|
|
});
|
|
it('upstream read-only tokens cannot write even when local writes are enabled', async () => {
|
|
const read = { ...ctx, api: new GitzaApi(f.upstream, f.readToken) };
|
|
await expect(
|
|
executeTool('create_issue', { repository: 'alice/project', title: 'Denied' }, read),
|
|
).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
|
|
});
|
|
it('prevents cross-account access and reading unselected public repositories', async () => {
|
|
await expect(
|
|
executeTool('get_repository', { repository: 'bob/public' }, ctx),
|
|
).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
|
|
const bob = { ...ctx, api: new GitzaApi(f.upstream, f.bobToken) };
|
|
await expect(
|
|
executeTool('get_repository', { repository: 'alice/project' }, bob),
|
|
).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
|
|
});
|
|
it('honours organisation membership removal on the next call', async () => {
|
|
const org = {
|
|
api: new GitzaApi(f.upstream, f.bobToken),
|
|
repositories: [{ id: f.orgRepoId, name: 'mcpteam/shared' }],
|
|
write: false,
|
|
};
|
|
await expect(
|
|
executeTool('get_repository', { repository: 'mcpteam/shared' }, org),
|
|
).resolves.toHaveProperty('data');
|
|
const r = await fetch(f.upstream + '/api/v1/teams/' + f.teamId + '/members/bob', {
|
|
method: 'DELETE',
|
|
headers: { Authorization: 'token ' + f.aliceToken },
|
|
});
|
|
expect(r.status).toBe(204);
|
|
await expect(
|
|
executeTool('get_repository', { repository: 'mcpteam/shared' }, org),
|
|
).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
|
|
});
|
|
it('runs the built stdio executable as a real MCP subprocess', async () => {
|
|
const transport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: ['dist/cli.js', 'stdio'],
|
|
env: {
|
|
PATH: process.env.PATH!,
|
|
GITZA_URL: f.upstream,
|
|
GITZA_DEVELOPMENT: 'true',
|
|
GITZA_TOKEN: f.readToken,
|
|
GITZA_REPOSITORIES: 'alice/project',
|
|
},
|
|
stderr: 'pipe',
|
|
});
|
|
let stderr = '';
|
|
transport.stderr?.on('data', (d) => {
|
|
stderr += String(d);
|
|
});
|
|
const client = new Client({ name: 'release-test', version: '1' });
|
|
await client.connect(transport);
|
|
try {
|
|
expect((await client.listTools()).tools).toHaveLength(15);
|
|
const result = await client.callTool({
|
|
name: 'get_file',
|
|
arguments: { repository: 'alice/project', path: 'src/hello.txt' },
|
|
});
|
|
expect(result.isError).not.toBe(true);
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
expect(stderr).not.toContain(f.readToken);
|
|
});
|
|
});
|
|
|
|
describe('persistent state', () => {
|
|
it('migrations are idempotent and encrypted state survives reconnect', async () => {
|
|
await store.migrate();
|
|
const id = randomSecret();
|
|
await store.save('Test', id, { value: 'sensitive' }, 60);
|
|
const other = new Store(f.env.DATABASE_URL!, new Vault(f.env.MCP_ENCRYPTION_KEYS!));
|
|
try {
|
|
expect(await other.get('Test', id)).toEqual({ value: 'sensitive' });
|
|
const rows = await other.sql`SELECT payload FROM oauth_entities WHERE model = 'Test'`;
|
|
expect(JSON.stringify(rows)).not.toContain('sensitive');
|
|
} finally {
|
|
await other.close();
|
|
}
|
|
await store.remove('Test', id);
|
|
});
|
|
it('consumes authorization artifacts atomically', async () => {
|
|
const id = randomSecret();
|
|
const adapter = store.adapter('AuthorizationCode');
|
|
await adapter.upsert(id, { grantId: 'test' }, 60);
|
|
const results = await Promise.allSettled([adapter.consume(id), adapter.consume(id)]);
|
|
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
|
await adapter.destroy(id);
|
|
});
|
|
it('serializes concurrent account refreshes', async () => {
|
|
await store.account('refresh-test', 'refresh-test', { access_token: 'old', expires_at: 0 });
|
|
let refreshes = 0;
|
|
const refresh = async () => {
|
|
refreshes++;
|
|
await new Promise((r) => setTimeout(r, 50));
|
|
return { access_token: 'new', expires_at: Date.now() + 3600000 };
|
|
};
|
|
const results = await Promise.all([
|
|
store.credential('refresh-test', refresh),
|
|
store.credential('refresh-test', refresh),
|
|
]);
|
|
expect(refreshes).toBe(1);
|
|
expect(results.map((r) => r.access_token)).toEqual(['new', 'new']);
|
|
await store.disconnect('refresh-test');
|
|
});
|
|
it('enforces rate limits and cleanup retention', async () => {
|
|
const key = randomSecret();
|
|
expect(await store.allow(key, 2)).toBe(true);
|
|
expect(await store.allow(key, 2)).toBe(true);
|
|
expect(await store.allow(key, 2)).toBe(false);
|
|
await store.sql`INSERT INTO audit_events (at, tool, outcome) VALUES (now() - interval '31 days', 'expired-test', 'ok')`;
|
|
await store.cleanup();
|
|
expect(await store.sql`SELECT * FROM audit_events WHERE tool = 'expired-test'`).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe('HTTP boundary', () => {
|
|
it('advertises protected-resource discovery', async () => {
|
|
const r = await fetch(f.origin + '/mcp', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
});
|
|
expect(r.status).toBe(401);
|
|
expect(r.headers.get('www-authenticate')).toContain('resource_metadata');
|
|
const metadata = await (
|
|
await fetch(f.origin + '/.well-known/oauth-protected-resource/mcp')
|
|
).json();
|
|
expect(metadata.resource).toBe(f.origin + '/mcp');
|
|
});
|
|
it('rejects cross-origin browser requests and unsafe registration metadata', async () => {
|
|
const cross = await fetch(f.origin + '/mcp', {
|
|
method: 'POST',
|
|
headers: { Origin: 'https://evil.example' },
|
|
});
|
|
expect(cross.status).toBe(403);
|
|
const r = await fetch(f.origin + '/oauth/register', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
redirect_uris: ['http://evil.example/cb'],
|
|
token_endpoint_auth_method: 'none',
|
|
grant_types: ['authorization_code'],
|
|
response_types: ['code'],
|
|
}),
|
|
});
|
|
expect(r.status).toBe(400);
|
|
});
|
|
});
|