wishforge-ide/packages/runtime/test/build-integration.test.ts
eust-w 223f497624 feat: give Kubernetes sandboxes an egress proxy for installs and a remote image builder
In Kubernetes mode the per-run network policy allowed only DNS, the API,
Temporal and Git, so dependency installs could not reach a registry and image
builds had no builder.

- WF_RUN_INSTALL_PROXY_URL points both sandboxes at an operator's egress proxy
  (pods labelled egress-proxy); the per-run policy admits it and installation
  commands get HTTP(S)_PROXY, also inside bubblewrap, while checks still have
  no network.
- WF_VERIFIER_DOCKER_HOST with a TLS client certificate points the verifier at
  a remote builder daemon (pods labelled image-builder); a separate policy
  lets only the verifier pod reach it, and release deletes that policy too.
  Builds pass DOCKER_HOST, DOCKER_TLS_VERIFY and DOCKER_CERT_PATH, and refuse
  a Docker context and a remote builder together.
- The control namespace's baseline admits sandbox traffic to both components.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 20:05:30 +08:00

202 lines
8.5 KiB
TypeScript

import { it, expect, afterEach } from 'vitest';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { buildDockerImage, executeCommand, GitWorkspace, type Command } from '../src/index.js';
const directories: string[] = [];
async function temp() {
const value = await mkdtemp(path.join(os.tmpdir(), 'wishforge-integration-'));
directories.push(value);
return value;
}
afterEach(async () => {
await Promise.all(directories.splice(0).map(value => rm(value, { recursive: true, force: true })));
});
it('creates an actual Git integration candidate and atomically rejects stale promotion', async () => {
const root = await temp();
const git = new GitWorkspace();
const source = await git.create({ root, runId: 'source' });
await writeFile(path.join(source.workspace, 'hello.txt'), 'candidate\n');
const checkpoint = await git.checkpoint(source.workspace, source.baseCommit, 'source', 'test');
const repository = path.join(root, 'integration.git');
await git.initializeIntegration({
repository,
workspace: source.workspace,
sourceCommit: checkpoint.sourceCommit,
baseCommit: source.baseCommit,
targetRef: 'refs/heads/main',
});
const candidate = await git.createCandidate({
repository,
path: path.join(root, 'candidate'),
targetRef: 'refs/heads/main',
expectedTargetCommit: source.baseCommit,
sourceCommit: checkpoint.sourceCommit,
});
await git.promoteVerifiedCandidate({
repository,
targetRef: 'refs/heads/main',
expectedTargetCommit: source.baseCommit,
candidateCommit: candidate.commit,
verifiedCommit: candidate.commit,
});
expect(await git.head(repository, 'refs/heads/main')).toBe(candidate.commit);
await expect(
git.promoteVerifiedCandidate({
repository,
targetRef: 'refs/heads/main',
expectedTargetCommit: source.baseCommit,
candidateCommit: candidate.commit,
verifiedCommit: candidate.commit,
}),
).rejects.toThrow('exited');
const restore = await git.create({
repository: source.workspace,
allowLocalRepository: true,
baseCommit: source.baseCommit,
root,
runId: 'restore',
});
const applied = await executeCommand({
executable: 'git',
args: ['apply', '--check', '-'],
cwd: restore.workspace,
input: checkpoint.patch,
});
expect(applied.exitCode).toBe(0);
});
it('builds from an exact Git archive and uses BuildKit metadata digest, never a tag', async () => {
const root = await temp();
const git = new GitWorkspace();
const source = await git.create({ root, runId: 'source' });
await writeFile(path.join(source.workspace, 'Dockerfile'), 'FROM scratch\nCOPY app /app\n');
await writeFile(path.join(source.workspace, 'app'), 'safe');
await writeFile(path.join(source.workspace, '.gitignore'), 'secret.txt\n');
const checkpoint = await git.checkpoint(source.workspace, source.baseCommit, 'source', 'test');
await writeFile(path.join(source.workspace, 'secret.txt'), 'never send ignored local secrets to BuildKit');
let sawBuild = false;
const execute = async (command: Command) => {
if (command.executable !== 'docker') return executeCommand(command);
sawBuild = true;
const context = command.args.at(-1)!;
expect(await readFile(path.join(context, 'app'), 'utf8')).toBe('safe');
await expect(readFile(path.join(context, 'secret.txt'))).rejects.toThrow();
const metadataPath = command.args[command.args.indexOf('--metadata-file') + 1]!;
await writeFile(metadataPath, JSON.stringify({ 'containerimage.digest': `sha256:${'c'.repeat(64)}` }));
return { exitCode: 0, stdout: '', stderr: '' };
};
const built = await buildDockerImage(
{
workspace: source.workspace,
sourceCommit: checkpoint.sourceCommit,
imageRepository: 'registry.example/team/web',
architecture: 'linux/amd64',
},
execute,
);
expect(sawBuild).toBe(true);
expect(built.imageDigest).toBe(`registry.example/team/web@sha256:${'c'.repeat(64)}`);
expect(built.imageDigest).not.toContain(':wf-');
});
it('restores the exact checkpoint into a separate verifier volume and rejects bundle tampering', async () => {
const root = await temp();
const git = new GitWorkspace();
const seed = await git.create({ root: path.join(root, 'seed'), runId: 'seed' });
const remote = path.join(root, 'remote.git');
await executeCommand({ executable: 'git', args: ['clone', '--bare', seed.workspace, remote], cwd: root });
const repository = { repository: remote, allowLocalRepository: true };
const source = await git.create({ ...repository, root: path.join(root, 'executor'), runId: 'run' });
await writeFile(path.join(source.workspace, 'binary.bin'), Buffer.from([0, 1, 2, 255, 3]));
await writeFile(path.join(source.workspace, 'app.txt'), 'saved\n\n');
const checkpoint = await git.checkpoint(source.workspace, source.baseCommit, 'run', 'test');
const restored = await git.restore({
...repository,
checkpoint,
root: path.join(root, 'verifier'),
runId: 'restored',
});
expect(await git.head(restored.workspace)).toBe(checkpoint.sourceCommit);
expect(await readFile(path.join(restored.workspace, 'binary.bin'))).toEqual(Buffer.from([0, 1, 2, 255, 3]));
await writeFile(path.join(source.workspace, 'app.txt'), 'executor tampered after export');
expect(await readFile(path.join(restored.workspace, 'app.txt'), 'utf8')).toBe('saved\n\n');
await expect(
git.restore({
...repository,
checkpoint: { ...checkpoint, gitBundleSha256: 'f'.repeat(64) },
root: path.join(root, 'verifier'),
runId: 'tampered',
}),
).rejects.toThrow('digest');
});
it('limits a selected source context to the immutable archive rather than the Docker endpoint', async () => {
const root = await temp();
const git = new GitWorkspace();
const source = await git.create({ root, runId: 'context-source' });
await mkdir(path.join(source.workspace, 'web'));
await writeFile(path.join(source.workspace, 'web', 'Dockerfile'), 'FROM scratch\nCOPY app /app\n');
await writeFile(path.join(source.workspace, 'web', 'app'), 'nested');
const checkpoint = await git.checkpoint(source.workspace, source.baseCommit, 'context-source', 'test');
let builds = 0;
const execute = async (command: Command) => {
if (command.executable !== 'docker') return executeCommand(command);
builds++;
expect(path.basename(command.args.at(-1)!)).toBe('web');
expect(await readFile(path.join(command.args.at(-1)!, 'app'), 'utf8')).toBe('nested');
expect(command.args.slice(0, 2)).toEqual(['--context', 'operator-builder']);
await writeFile(
command.args[command.args.indexOf('--metadata-file') + 1]!,
JSON.stringify({ 'containerimage.digest': `sha256:${'d'.repeat(64)}` }),
);
return { exitCode: 0, stdout: '', stderr: '' };
};
const input = {
workspace: source.workspace,
sourceCommit: checkpoint.sourceCommit,
dockerfile: 'web/Dockerfile',
sourceContext: 'web',
dockerContext: 'operator-builder',
imageRepository: 'registry.example/team/web',
architecture: 'linux/amd64' as const,
};
expect((await buildDockerImage(input, execute)).imageDigest).toContain('@sha256:');
await expect(buildDockerImage({ ...input, sourceContext: '..' }, execute)).rejects.toMatchObject({
code: 'BUILD_CONTEXT_SCOPE',
});
expect(builds).toBe(1);
// A sandbox without a local Docker builds on the operator's remote builder, over TLS.
const remote = {
...input,
dockerContext: undefined,
dockerHost: 'tcp://builder.svc:2376',
dockerTlsDirectory: '/tls',
};
const remoteExecute = async (command: Command) => {
if (command.executable !== 'docker') return executeCommand(command);
expect(command.args[0]).toBe('buildx');
expect(command.env).toMatchObject({
DOCKER_HOST: 'tcp://builder.svc:2376',
DOCKER_TLS_VERIFY: '1',
DOCKER_CERT_PATH: '/tls',
});
await writeFile(
command.args[command.args.indexOf('--metadata-file') + 1]!,
JSON.stringify({ 'containerimage.digest': `sha256:${'e'.repeat(64)}` }),
);
return { exitCode: 0, stdout: '', stderr: '' };
};
expect((await buildDockerImage(remote, remoteExecute)).imageDigest).toContain('@sha256:');
await expect(buildDockerImage({ ...remote, dockerContext: 'operator-builder' }, remoteExecute)).rejects.toMatchObject(
{
code: 'INVALID_BUILDER',
},
);
await expect(
buildDockerImage({ ...remote, dockerHost: 'unix:///var/run/docker.sock' }, remoteExecute),
).rejects.toMatchObject({ code: 'INVALID_BUILDER' });
});