209 lines
9.5 KiB
TypeScript

import { it, expect, vi } from 'vitest';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, rm, writeFile, symlink, mkdir } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { GitWorkspace } from '@wishforge/runtime';
import { createGitService, issueGitToken, verifyGitToken } from '../src/service.js';
it('refuses the development HTTP override in production before creating storage', async () => {
vi.stubEnv('NODE_ENV', 'production');
try {
await expect(
createGitService({
root: '/unused-production-fixture',
publicBaseUrl: 'http://127.0.0.1:4504',
adminToken: 'admin-'.repeat(8),
tokenSecret: 'signing-'.repeat(8),
allowLocalHttp: true,
}),
).rejects.toMatchObject({ code: 'INSECURE_ENDPOINT' });
} finally {
vi.unstubAllEnvs();
}
});
it('enforces repository, permission and expiry scope on short-lived Git tokens', () => {
const secret = 's'.repeat(32);
const token = issueGitToken(
{ aud: 'wishforge-git', tenantId: 'tenant', projectId: 'project', permission: 'read', iat: 100, exp: 400 },
secret,
);
expect(
verifyGitToken(token, secret, { tenantId: 'tenant', projectId: 'project', write: false }, 200).permission,
).toBe('read');
expect(() => verifyGitToken(token, secret, { tenantId: 'other', projectId: 'project', write: false }, 200)).toThrow();
expect(() => verifyGitToken(token, secret, { tenantId: 'tenant', projectId: 'project', write: true }, 200)).toThrow();
expect(() =>
verifyGitToken(token, secret, { tenantId: 'tenant', projectId: 'project', write: false }, 500),
).toThrow();
});
it('provisions a real bare repository and serves authenticated clone/CAS push over smart HTTP', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'wishforge-git-service-'));
const admin = 'admin-'.repeat(8);
const server = await createGitService({
root: path.join(root, 'repos'),
publicBaseUrl: 'http://127.0.0.1:4504',
adminToken: admin,
tokenSecret: 'signing-'.repeat(8),
allowLocalHttp: true,
});
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
if (!address || typeof address === 'string') throw new Error('no port');
const base = `http://127.0.0.1:${address.port}`;
const post = async (route: string, body: unknown) => {
const response = await fetch(`${base}${route}`, {
method: 'POST',
headers: { authorization: `Bearer ${admin}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
});
expect(response.status).toBe(200);
return response.json() as Promise<Record<string, string>>;
};
const reject = async (route: string, body: unknown) => {
const response = await fetch(`${base}${route}`, {
method: 'POST',
headers: { authorization: `Bearer ${admin}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
});
expect(response.status).toBe(400);
return response.json() as Promise<{ error: string }>;
};
try {
const repo = await post('/repos', { tenantId: 'tenant', projectId: 'project', defaultBranch: 'release/v1' });
expect(repo.initialCommit).toMatch(/^[a-f0-9]{40}$/);
expect(repo.defaultBranch).toBe('release/v1');
const repeated = await post('/repos', { tenantId: 'tenant', projectId: 'project', defaultBranch: 'main' });
expect(repeated.defaultBranch).toBe('release/v1');
expect(repeated.initialCommit).toBe(repo.initialCommit);
expect((await post('/repos', { tenantId: 'tenant', projectId: 'default-main' })).defaultBranch).toBe('main');
const repositoryUrl = `${base}/git/tenant/project.git`;
const reader = await post('/tokens', { tenantId: 'tenant', projectId: 'project', permission: 'read' });
const writer = await post('/tokens', { tenantId: 'tenant', projectId: 'project', permission: 'write' });
const git = new GitWorkspace(undefined, {
allowLocalHttp: true,
credential: { token: reader.token!, repositoryUrl },
});
const checkout = await git.create({
root: path.join(root, 'clones'),
runId: 'run',
repository: repositoryUrl,
targetBranch: 'release/v1',
});
await writeFile(path.join(checkout.workspace, 'README.md'), 'A persistent project\n');
await mkdir(path.join(checkout.workspace, 'wiki', 'features'), { recursive: true });
await mkdir(path.join(checkout.workspace, 'wiki', 'modules'), { recursive: true });
await writeFile(path.join(checkout.workspace, 'wiki', 'index.md'), '# Project Wiki\n');
await writeFile(path.join(checkout.workspace, 'wiki', 'modules', 'api.md'), '# API module\nInternal map.\n');
await writeFile(
path.join(checkout.workspace, 'wiki', 'features', 'wish.md'),
'# Wish\nSee `apps/api/src/http.ts:416`.\n',
);
// A symbolic link inside the Wiki is not a page: reading it would leave the repository.
await symlink('../../../README.md', path.join(checkout.workspace, 'wiki', 'features', 'link.md'));
const checkpoint = await git.checkpoint(checkout.workspace, checkout.baseCommit, 'run', 'test');
const push = {
repository: checkout.workspace,
targetRef: 'refs/heads/release/v1',
expectedTargetCommit: checkout.baseCommit,
candidateCommit: checkpoint.sourceCommit,
verifiedCommit: checkpoint.sourceCommit,
};
await expect(git.pushVerifiedCandidate(push)).rejects.toThrow();
git.setCredential({ token: writer.token!, repositoryUrl });
await git.pushVerifiedCandidate(push);
const second = await git.create({
root: path.join(root, 'clones'),
runId: 'second',
repository: repositoryUrl,
targetBranch: 'release/v1',
});
expect(second.baseCommit).toBe(checkpoint.sourceCommit);
const wiki = await post('/wiki', { tenantId: 'tenant', projectId: 'project', branch: 'release/v1' });
expect(wiki.version).toBe(checkpoint.sourceCommit);
expect(wiki.files).toHaveLength(3);
expect(JSON.stringify(wiki.files)).not.toContain('link.md');
const source = await post('/wiki', {
tenantId: 'tenant',
projectId: 'project',
branch: 'release/v1',
path: 'wiki/features/wish.md',
});
expect(source.file).toMatchObject({
path: 'wiki/features/wish.md',
content: expect.stringContaining('apps/api/src/http.ts:416'),
});
// Only Markdown pages under wiki/ are readable, and never through a symbolic link.
for (const unsafe of ['wiki/features/link.md', 'wiki/../README.md', 'README.md', 'wiki/features/wish.txt'])
expect(
await reject('/wiki', { tenantId: 'tenant', projectId: 'project', branch: 'release/v1', path: unsafe }),
).toMatchObject({ error: 'INVALID_PATH' });
const afterPush = await post('/repos', { tenantId: 'tenant', projectId: 'project', defaultBranch: 'other' });
expect(afterPush.defaultBranch).toBe('release/v1');
expect(afterPush.initialCommit).toBe(checkpoint.sourceCommit);
// An IDE credential pushes ide/ branches only; a wish verifies and merges them.
const ide = await post('/tokens', {
tenantId: 'tenant',
projectId: 'project',
permission: 'write',
refPrefix: 'refs/heads/ide/',
});
const run = promisify(execFile);
const inClone = (...args: string[]) =>
run(
'git',
[
'-c',
`http.${repositoryUrl}.extraHeader=Authorization: Bearer ${ide.token!}`,
'-c',
'user.name=Fixture',
'-c',
'user.email=fixture@example.invalid',
...args,
],
{ cwd: second.workspace },
);
await writeFile(path.join(second.workspace, 'ide.txt'), 'from the IDE\n');
await inClone('add', 'ide.txt');
await inClone('commit', '-m', 'Edit in the IDE');
await expect(inClone('push', repositoryUrl, 'HEAD:refs/heads/release/v1')).rejects.toThrow(/ide\//);
await inClone('push', repositoryUrl, 'HEAD:refs/heads/ide/work');
const branches = await post('/refs', { tenantId: 'tenant', projectId: 'project', prefix: 'refs/heads/ide/' });
expect(branches.branches).toEqual([
{ name: 'ide/work', commit: (await inClone('rev-parse', 'HEAD')).stdout.trim(), updatedAt: expect.any(String) },
]);
expect((await post('/repos', { tenantId: 'tenant', projectId: 'project' })).initialCommit).toBe(
checkpoint.sourceCommit,
);
const unsafe = await fetch(`${base}/repos`, {
method: 'POST',
headers: { authorization: `Bearer ${admin}`, 'content-type': 'application/json' },
body: JSON.stringify({ tenantId: 'tenant', projectId: 'invalid-branch', defaultBranch: 'main:other' }),
});
expect(unsafe.status).toBe(400);
const cross = await fetch(`${base}/git/other/project.git/info/refs?service=git-upload-pack`, {
headers: { authorization: `Bearer ${reader.token!}` },
});
expect(cross.status).toBe(401);
await mkdir(path.join(root, 'outside.git'));
await symlink(path.join(root, 'outside.git'), path.join(root, 'repos', 'tenant', 'escape.git'));
const escaped = await fetch(`${base}/repos`, {
method: 'POST',
headers: { authorization: `Bearer ${admin}`, 'content-type': 'application/json' },
body: JSON.stringify({ tenantId: 'tenant', projectId: 'escape' }),
});
expect(escaped.status).toBe(400);
expect((await escaped.json()).error).toBe('REPOSITORY_SCOPE');
} finally {
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
await rm(root, { recursive: true, force: true });
}
}, 15000);