gitza-mcp/tests/core.test.ts

265 lines
9.9 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest';
import { config, origin, repositoryName } from '../src/config.js';
import { Vault, equal, randomSecret } from '../src/crypto.js';
import { authorize, GitzaApi, ToolError } from '../src/api.js';
import { executeTool, lines, tools } from '../src/tools.js';
import { escape } from '../src/views.js';
const repository = {
id: 1,
full_name: 'alice/project',
name: 'project',
html_url: 'https://git.example/alice/project',
default_branch: 'main',
private: true,
};
function fixture(reply: unknown = []) {
const requests: { path: string; init?: RequestInit }[] = [];
const fetcher = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
const path = String(input);
requests.push({ path, init });
return new Response(JSON.stringify(path.endsWith('/repos/alice/project') ? repository : reply));
});
const ctx = {
api: new GitzaApi('https://git.example', 'secret', fetcher),
repositories: [{ id: 1, name: 'alice/project' }],
write: false,
};
return { ctx, requests, fetcher };
}
describe('configuration boundary', () => {
it('defaults to read-only and the Gitza origin', () => {
expect(config({}).write).toBe(false);
expect(config({}).upstream).toBe('https://git.gitza.co.za');
});
it.each([
'http://example.com',
'https://user:secret@example.com',
'https://example.com/path',
'https://example.com?token=secret',
'ftp://example.com',
])('rejects unsafe origin %s', (value) => {
expect(() => origin(value, true)).toThrow();
});
it('allows HTTP only on explicit development loopback', () => {
expect(() => origin('http://127.0.0.1:1234')).toThrow();
expect(origin('http://127.0.0.1:1234', true)).toBe('http://127.0.0.1:1234');
});
it.each(['../a', 'a/..', 'a/b/c', 'https://a/b', 'a/evil?'])(
'rejects invalid repository %s',
(value) => {
expect(repositoryName.safeParse(value).success).toBe(false);
},
);
it('does not leak invalid environment values', () => {
expect(() => config({ GITZA_WRITE: 'sensitive-value' })).toThrow('GITZA_WRITE');
try {
config({ GITZA_WRITE: 'sensitive-value' });
} catch (e) {
expect(String(e)).not.toContain('sensitive-value');
}
});
});
describe('credential encryption', () => {
it('authenticates ciphertext and binds it to its account', () => {
const vault = new Vault(JSON.stringify({ v1: randomSecret() }));
const sealed = vault.seal({ token: 'top-secret' }, 'alice');
expect(sealed).not.toContain('top-secret');
expect(vault.open(sealed, 'alice')).toEqual({ token: 'top-secret' });
expect(() => vault.open(sealed, 'bob')).toThrow();
expect(() => vault.open(sealed.slice(0, -5) + 'aaaaa', 'alice')).toThrow();
});
it('reads old keys and writes with the new active key', () => {
const old = randomSecret();
const sealed = new Vault(JSON.stringify({ old })).seal('value', 'row');
const next = new Vault(JSON.stringify({ next: randomSecret(), old }));
expect(next.open(sealed, 'row')).toBe('value');
expect(next.seal('value', 'row')).toMatch(/^next\./);
});
it('rejects invalid keys and handles unequal CSRF byte lengths', () => {
expect(() => new Vault('{"v1":"short"}')).toThrow();
expect(equal('abc', 'a')).toBe(false);
expect(equal('a', 'é')).toBe(false);
});
});
describe('API isolation and error handling', () => {
it('checks the allowlist before contacting the upstream', async () => {
const { ctx, fetcher } = fixture();
await expect(authorize(ctx, 'bob/private')).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
expect(fetcher).not.toHaveBeenCalled();
});
it('detects repository replacement under the same name', async () => {
const { ctx } = fixture();
ctx.repositories[0]!.id = 2;
await expect(authorize(ctx, 'alice/project')).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
});
it('does not follow redirects or return upstream error bodies', async () => {
const f = vi.fn(async () => new Response('secret details', { status: 403 }));
const api = new GitzaApi('https://git.example', 'token', f);
await expect(api.request('/repos/a/b')).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
expect(f.mock.calls[0]).toBeDefined();
});
it('uses header credentials and redirect rejection', async () => {
const { ctx, requests } = fixture();
await authorize(ctx, 'alice/project');
expect(requests[0]!.init!.redirect).toBe('error');
expect(requests[0]!.path).not.toContain('secret');
});
it('never retries a failed write', async () => {
const f = vi.fn(async () => {
throw new Error('secret');
});
const api = new GitzaApi('https://git.example', 'token', f);
await expect(api.request('/repos/a/b/issues', { method: 'POST', body: {} })).rejects.toThrow(
'outcome is unknown',
);
expect(f).toHaveBeenCalledTimes(1);
});
it('honours rate-limit retry hints', async () => {
const api = new GitzaApi(
'https://git.example',
'token',
async () => new Response('', { status: 429, headers: { 'Retry-After': '12' } }),
);
await expect(api.request('/x')).rejects.toMatchObject({ code: 'RATE_LIMITED', retryAfter: 12 });
});
it('bounds upstream bodies', async () => {
const api = new GitzaApi(
'https://git.example',
'token',
async () => new Response('x'.repeat(4 * 1024 * 1024 + 1)),
);
await expect(api.request('/x')).rejects.toMatchObject({ code: 'TOO_LARGE' });
});
it('maps cancelled calls without exposing transport details', async () => {
const abort = new AbortController();
abort.abort();
const api = new GitzaApi('https://git.example', 'token', async () => {
throw new Error('secret URL');
});
await expect(api.request('/x', { signal: abort.signal })).rejects.toMatchObject({
code: 'CANCELLED',
});
});
});
describe('tool behaviour', () => {
it.each(['create_issue', 'add_comment', 'create_pull_request'])(
'denies %s on a read-only connection',
async (name) => {
const { ctx, fetcher } = fixture();
const args =
name === 'create_issue'
? { title: 'hello' }
: name === 'add_comment'
? { index: 1, body: 'hi' }
: { title: 'hello', base: 'main', head: 'feature' };
await expect(
executeTool(name, { repository: 'alice/project', ...args }, ctx),
).rejects.toMatchObject({ code: 'ACCESS_DENIED' });
expect(fetcher).not.toHaveBeenCalled();
},
);
it('validates extra fields, pagination and traversal', async () => {
const { ctx } = fixture();
await expect(
executeTool('list_issues', { repository: 'alice/project', limit: 101 }, ctx),
).rejects.toMatchObject({ code: 'INVALID_INPUT' });
await expect(
executeTool('get_file', { repository: 'alice/project', path: '../secret' }, ctx),
).rejects.toMatchObject({ code: 'INVALID_INPUT' });
await expect(
executeTool('get_repository', { repository: 'alice/project', token: 'evil' }, ctx),
).rejects.toMatchObject({ code: 'INVALID_INPUT' });
});
it('reads text windows and never fetches download URLs', async () => {
const { ctx, requests } = fixture({
type: 'file',
content: Buffer.from('one\ntwo\nthree').toString('base64'),
encoding: 'base64',
sha: 'abc',
size: 13,
download_url: 'http://169.254.169.254/secret',
});
const result = await executeTool(
'get_file',
{
repository: 'alice/project',
path: 'src/file.ts',
ref: 'feature/topic',
start_line: 2,
max_lines: 1,
},
ctx,
);
expect(result.content).toBe('two');
expect(result.next_line).toBe(3);
expect(result.truncated).toBe(true);
expect(requests).toHaveLength(2);
expect(requests[1]!.path).toContain('ref=feature%2Ftopic');
});
it.each(['symlink', 'submodule', 'dir'])('does not follow %s', async (type) => {
const { ctx } = fixture({ type });
await expect(
executeTool('get_file', { repository: 'alice/project', path: 'file' }, ctx),
).rejects.toBeInstanceOf(ToolError);
});
it('rejects binary files', async () => {
const { ctx } = fixture({
type: 'file',
encoding: 'base64',
content: Buffer.from([0, 1, 2]).toString('base64'),
});
await expect(
executeTool('get_file', { repository: 'alice/project', path: 'file' }, ctx),
).rejects.toMatchObject({ code: 'BINARY_FILE' });
});
it('writes once and returns useful metadata', async () => {
const { ctx, requests } = fixture({
id: 7,
html_url: 'https://git.example/issue/7',
title: 'hello',
internal_secret: 'hidden',
});
ctx.write = true;
const result = await executeTool(
'create_issue',
{ repository: 'alice/project', title: 'hello' },
ctx,
);
expect(result.data).toEqual({ id: 7, html_url: 'https://git.example/issue/7', title: 'hello' });
expect(requests.filter((r) => r.init?.method === 'POST')).toHaveLength(1);
});
it('bounds giant single lines and escapes malicious HTML in screens', () => {
expect(() => lines('x'.repeat(70000), {})).toThrow();
expect(escape('<script>"&')).toBe('&lt;script&gt;&quot;&amp;');
});
it('contains exactly the supported capability surface', () => {
expect(tools).toHaveLength(15);
expect(tools.filter((t) => t.write).map((t) => t.name)).toEqual([
'create_issue',
'add_comment',
'create_pull_request',
]);
});
it('cannot open a PR from an unselected fork through a qualified head', async () => {
const { ctx, fetcher } = fixture();
ctx.write = true;
await expect(
executeTool(
'create_pull_request',
{
repository: 'alice/project',
title: 'Copy private fork',
base: 'main',
head: 'bob:secret',
},
ctx,
),
).rejects.toMatchObject({ code: 'INVALID_INPUT' });
expect(fetcher).not.toHaveBeenCalled();
});
});