diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f55e8e..b2a6172 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,5 +44,8 @@ jobs: - name: Typecheck run: pnpm -r typecheck + - name: Install bubblewrap + run: sudo apt-get update && sudo apt-get install -y bubblewrap + - name: Test run: pnpm -r test diff --git a/README.md b/README.md index 07b4a8a..2699a46 100644 --- a/README.md +++ b/README.md @@ -90,19 +90,21 @@ ASIL can run against any HTTP server speaking the OpenAI-compatible `/v1/chat/co ### Running against untrusted repos — sandbox -ASIL executes target-repo code (`pnpm install`, build, tests) inside disposable worktrees. To keep that safe: +ASIL executes target-repo commands (`pnpm install`, build, tests, typecheck, and the scanner's search commands) inside a bubblewrap jail. The command can write only its working directory. It gets a private `/tmp` and `HOME`, not the operator's home directory. Network is off, except for `pnpm install` and `npm install`, which need a registry. Install still passes `--ignore-scripts` unless `ASIL_ALLOW_INSTALL_SCRIPTS=1`. -- **Secrets are stripped from the execution environment.** The runner that executes target-repo commands gets a scrubbed env — `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and git/GitHub tokens are never in scope, so a malicious `postinstall`/build/test script can't exfiltrate them. Git and `gh` use a separate allowlisted environment that keeps only path, locale, git identity, and the GitHub token those commands need. -- **Install lifecycle scripts are disabled by default** (`pnpm install --ignore-scripts`). Opt back in with `ASIL_ALLOW_INSTALL_SCRIPTS=1` only for repos you trust. +`bwrap` must be on `PATH`. If it is missing or cannot start, the command fails. Set `ASIL_SANDBOX=off` only when you accept unsandboxed execution; grind prints a warning and continues. -This is process-level hardening. It removes the credential-exfiltration vector for install, build, and test, and it adds the following limits: +Git and `gh` stay outside the jail. They use an allowlisted environment with path, locale, git identity, and the GitHub token. Commits set `core.hooksPath` to `/dev/null` and pass `--no-verify`. -- Git and `gh` do not inherit model API keys. Commits set `core.hooksPath` to `/dev/null` and pass `--no-verify`, so hooks in the target repository do not run. -- Worktrees live under the system temp directory and include a hash of the repository path, so two repositories cannot delete each other's worktrees. Cleanup refuses to delete anything else. -- Patch file reads stay inside the target repository. Relative paths configured for usage data, the queue, skills, and domain answers cannot climb out of the repository. An absolute path is used as given, unless it contains `..` and resolves outside the repository. -- `auto grind` does not commit, push, or open a pull request unless you pass `--apply`. Without that flag a task that passes the gates stays queued for a later run. +Other limits: -It does **not** sandbox the filesystem or network. A hostile repository's build or test can still read local files or make network calls. For an untrusted repository, run ASIL inside a container that does not share your home directory or network. +- `REPO_ROOT` is required for `auto grind`, including `--dry-run`. It does not default to the current directory. +- Worktrees live under the system temp directory and include a hash of the repository path. Cleanup refuses to delete anything else. +- Patch reads stay inside the target repository. Relative paths for usage data, the queue, skills, and domain answers cannot leave the repository. An absolute path is used as given unless it contains `..` and resolves outside the repository. +- `auto grind` does not commit, push, or open a pull request unless you pass `--apply`. `--apply` updates the loop's `auto/*` branches and opens pull requests. Without that flag a task that passes the gates stays queued. +- Before scanning, grind prints whether each scanned category loaded a skill file. A missing file uses the built-in instructions. `--require-skills` exits before scanning when any scanned category is missing its skill. + +`--dry-run` does not call a model or change git. It still runs the scanner's test, typecheck, and search commands, inside the jail. ### Languages — Python profile @@ -218,7 +220,8 @@ Every LLM call in B and A flows through a `CostCheckpoint`. Each checkpoint is b |---|---|---|---| | `ANTHROPIC_API_KEY` | env | required | Primary LLM | | `OPENAI_API_KEY` | env | required | Adversarial gate (different provider) | -| `REPO_ROOT` | env | current working directory | Absolute path to the target repo. Set this explicitly. | +| `REPO_ROOT` | env | required for `auto grind` | Absolute path of the target repository. `think` and `report` still default to the current directory. | +| `ASIL_SANDBOX` | env | on | Set to `off` to run target-repository commands without bubblewrap. | | `ASIL_USAGE_DATA_DIR` | env | `/.asil/usage-data` | Cost tracker state. Relative values must stay inside the repo. An absolute value is used as given unless `..` leaves the repo. | | `ASIL_QUEUE_PATH` | env | `/.asil/usage-data/queue.json` | Task queue. Same path rules as `ASIL_USAGE_DATA_DIR`. | | `ASIL_SKILLS_PATH` | env | `/.asil/skills` | Markdown skills. Files are `{name}.md` or `{name}/SKILL.md` directly under this directory. Same path rules as `ASIL_USAGE_DATA_DIR`. | diff --git a/examples/quickstart.md b/examples/quickstart.md index 4081948..5a1fbc5 100644 --- a/examples/quickstart.md +++ b/examples/quickstart.md @@ -25,7 +25,7 @@ packages: ## 2. Set up environment -Create `.env` next to `pnpm-workspace.yaml` in the ASIL checkout. The CLI loads that file and no other: +Create `.env` next to `pnpm-workspace.yaml` in the ASIL checkout. The CLI loads that file and no other. `auto grind` refuses to start unless `REPO_ROOT` is set. Target-repository commands run inside bubblewrap (`bwrap` on `PATH`). Set `ASIL_SANDBOX=off` only when you accept unsandboxed execution. ``` ANTHROPIC_API_KEY=sk-ant-… @@ -80,10 +80,11 @@ pnpm --filter asil-runners auto grind --max-tasks 3 --skip dependency-update,doc The runner will: -1. Scan and queue tasks -2. Pause on any unresolved `// DOMAIN_QUESTION:` markers and offer triage -3. For each task: isolate, execute, typecheck, test, self-review × 3, adversarial gate, domain guard. `--apply` then commits, pushes, and opens a pull request. Without `--apply` the task stays queued. -4. Print a summary with cost spent and PRs opened +1. Print whether each scanned category loaded a skill file. Pass `--require-skills` to stop before scanning when one is missing. +2. Scan and queue tasks. Scanner commands run inside the jail. +3. Pause on any unresolved `// DOMAIN_QUESTION:` markers and offer triage +4. For each task: isolate, execute, typecheck, test, self-review × 3, adversarial gate, domain guard. `--apply` then commits, pushes, and opens a pull request, including updates to the loop's `auto/*` branches. Without `--apply` the task stays queued. +5. Print a summary with cost spent and PRs opened ## 7. Inspect the spend diff --git a/packages/asil-improvement-loop/src/index.ts b/packages/asil-improvement-loop/src/index.ts index 3364cd9..9cbfa74 100644 --- a/packages/asil-improvement-loop/src/index.ts +++ b/packages/asil-improvement-loop/src/index.ts @@ -19,6 +19,7 @@ export { type CycleEvent, } from './cycle-detector.js'; export { + SCANNED_CATEGORIES, scanCodebase, scanTestFailures, scanTypeErrors, @@ -52,6 +53,7 @@ export { type FileFetcher, } from './executor.js'; export { + findSkillFile, loadSkillMarkdown, skillCandidatePaths, SKILL_NAME_ALIASES, diff --git a/packages/asil-improvement-loop/src/scanner.ts b/packages/asil-improvement-loop/src/scanner.ts index a5c347d..b457cc5 100644 --- a/packages/asil-improvement-loop/src/scanner.ts +++ b/packages/asil-improvement-loop/src/scanner.ts @@ -55,6 +55,15 @@ export interface ScannerDeps { * `profile` defaults to TypeScript for backwards compatibility with * callers built before the multi-language refactor. */ +/** Categories `scanCodebase` actually runs. */ +export const SCANNED_CATEGORIES = [ + 'test-failure', + 'type-error', + 'todo-resolution', + 'coverage-gap', + 'dead-code', +] as const; + export async function scanCodebase( repoRoot: string, deps: ScannerDeps, diff --git a/packages/asil-improvement-loop/src/skill-loader.ts b/packages/asil-improvement-loop/src/skill-loader.ts index f1ab50a..70d68e9 100644 --- a/packages/asil-improvement-loop/src/skill-loader.ts +++ b/packages/asil-improvement-loop/src/skill-loader.ts @@ -10,7 +10,7 @@ * 3. `skills/{name}.md` (older installs that nested a skills/ folder) * 4. `skills/{name}/SKILL.md` */ -import { readFileSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; /** @@ -48,6 +48,15 @@ export function skillCandidatePaths(skillName: string): string[] { return paths; } +/** Absolute path of the first matching skill file, or null when none exist. */ +export function findSkillFile(skillsPath: string, skillName: string): string | null { + for (const rel of skillCandidatePaths(skillName)) { + const abs = join(skillsPath, rel); + if (existsSync(abs)) return abs; + } + return null; +} + /** * Load skill Markdown from disk. Returns an empty string when nothing * matches so callers can fall back to inline defaults. diff --git a/packages/asil-runners/src/__tests__/run-a-flags.test.ts b/packages/asil-runners/src/__tests__/run-a-flags.test.ts index e8895ea..cd9b4d3 100644 --- a/packages/asil-runners/src/__tests__/run-a-flags.test.ts +++ b/packages/asil-runners/src/__tests__/run-a-flags.test.ts @@ -1,5 +1,8 @@ -import { describe, expect, it } from 'vitest'; -import { parseFlags } from '../run-a.js'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { afterEach, describe, expect, it } from 'vitest'; +import { formatSkillStatus, parseFlags, skillStatuses } from '../run-a.js'; describe('parseFlags', () => { it('does not publish unless --apply is set', () => { @@ -19,4 +22,29 @@ describe('parseFlags', () => { expect(flags?.dryRun).toBe(true); expect(flags?.apply).toBe(true); }); + + it('requires skills only when --require-skills is set', () => { + expect(parseFlags([])?.requireSkills).toBe(false); + expect(parseFlags(['--require-skills'])?.requireSkills).toBe(true); + }); +}); + +describe('skillStatuses', () => { + let dir: string; + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it('reports a loaded file and a missing skill', () => { + dir = mkdtempSync(join(tmpdir(), 'asil-skills-')); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'code-simplification.md'), '# skill\n'); + const rows = skillStatuses(dir, ['test-failure', 'todo-resolution', 'coverage-gap', 'dead-code']); + expect(rows).toHaveLength(1); + expect(rows[0]?.category).toBe('type-error'); + expect(rows[0]?.path).toBe(join(dir, 'code-simplification.md')); + expect(formatSkillStatus(rows[0]!)).toContain('code-simplification.md'); + + const missing = skillStatuses(dir, ['type-error', 'test-failure', 'coverage-gap', 'dead-code']); + expect(missing[0]?.path).toBeNull(); + expect(formatSkillStatus(missing[0]!)).toContain('missing, using built-in instructions'); + }); }); diff --git a/packages/asil-runners/src/__tests__/sandbox.test.ts b/packages/asil-runners/src/__tests__/sandbox.test.ts new file mode 100644 index 0000000..d8a7858 --- /dev/null +++ b/packages/asil-runners/src/__tests__/sandbox.test.ts @@ -0,0 +1,137 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + bubblewrapAvailable, + buildBwrapArgs, + commandAllowsNetwork, + createSandboxedCommandRunner, + toolchainRoot, +} from '../sandbox.js'; + +const noFs = { + exists: () => false, + resolveCommand: () => null, + pathEnv: '', +}; + +describe('commandAllowsNetwork', () => { + it('allows network only for pnpm and npm install', () => { + expect(commandAllowsNetwork('pnpm', ['install', '--frozen-lockfile'])).toBe(true); + expect(commandAllowsNetwork('npm', ['install'])).toBe(true); + expect(commandAllowsNetwork('pnpm', ['test'])).toBe(false); + expect(commandAllowsNetwork('pnpm', ['run', '-r', 'build'])).toBe(false); + expect(commandAllowsNetwork('grep', ['-n', 'TODO'])).toBe(false); + }); +}); + +describe('buildBwrapArgs', () => { + it('drops the network and binds only the working directory for a test command', () => { + const args = buildBwrapArgs('pnpm', ['test'], '/work/repo', noFs); + expect(args).toContain('--unshare-net'); + expect(args).toContain('--clearenv'); + const bindAt = args.indexOf('--bind'); + expect(args.slice(bindAt, bindAt + 3)).toEqual(['--bind', '/work/repo', '/work/repo']); + expect(args).toContain('--setenv'); + expect(args).toContain('HOME'); + expect(args).toContain('/tmp/home'); + if (process.env.HOME && process.env.HOME !== '/tmp/home') { + expect(args).not.toContain(process.env.HOME); + } + }); + + it('keeps the network for pnpm install', () => { + const args = buildBwrapArgs('pnpm', ['install', '--ignore-scripts'], '/work/repo', noFs); + expect(args).not.toContain('--unshare-net'); + }); + + it('read-only binds a toolchain that lives outside the system directories', () => { + const args = buildBwrapArgs('pnpm', ['test'], '/work/repo', { + exists: (path) => path === '/usr', + resolveCommand: (command) => + command === 'pnpm' ? '/opt/node/bin/pnpm' : null, + pathEnv: '/opt/node/bin', + }); + expect(args).toContain('/usr'); + expect(args).toContain('/opt/node'); + expect(args.filter((part) => part === '--ro-bind').length).toBe(2); + }); + + it('refuses to bind the filesystem root', () => { + expect(() => buildBwrapArgs('true', [], '/', noFs)).toThrow(/working directory is \//); + }); +}); + +describe('toolchainRoot', () => { + it('uses the parent of a bin directory', () => { + expect(toolchainRoot('/opt/node/bin/node')).toBe('/opt/node'); + expect(toolchainRoot('/usr/bin/grep')).toBe('/usr'); + }); +}); + +describe('createSandboxedCommandRunner', () => { + const prev = process.env.ASIL_SANDBOX; + afterEach(() => { + if (prev === undefined) delete process.env.ASIL_SANDBOX; + else process.env.ASIL_SANDBOX = prev; + }); + + it('reports a missing bubblewrap binary instead of running the command unsandboxed', async () => { + const runner = createSandboxedCommandRunner({ + ...process.env, + ASIL_SANDBOX: 'on', + PATH: '', + }); + const result = await runner.run('true', [], { cwd: tmpdir() }); + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toMatch(/bwrap|bubblewrap|ENOENT/i); + }); +}); + +describe('bubblewrap jail', () => { + const available = bubblewrapAvailable(); + let dir: string; + afterEach(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + it.skipIf(!available)( + 'cannot read a sibling directory or open an outbound socket', + async () => { + dir = mkdtempSync(join(tmpdir(), 'asil-jail-')); + const work = join(dir, 'work'); + const outside = join(dir, 'secret.txt'); + mkdirSync(work); + writeFileSync(outside, 'secret'); + writeFileSync( + join(work, 'probe.js'), + ` + const fs = require('fs'); + const net = require('net'); + let readOk = false; + try { fs.readFileSync(process.argv[2]); readOk = true; } catch {} + const sock = net.connect({ host: '1.1.1.1', port: 443 }); + const finish = (netOpen) => { + console.log(readOk ? 'READ_OK' : 'READ_BLOCKED'); + console.log(netOpen ? 'NET_OPEN' : 'NET_BLOCKED'); + process.exit(readOk || netOpen ? 2 : 0); + }; + sock.setTimeout(1500); + sock.on('connect', () => finish(true)); + sock.on('timeout', () => finish(true)); + sock.on('error', () => finish(false)); + `, + ); + const runner = createSandboxedCommandRunner(); + const result = await runner.run( + 'node', + [join(work, 'probe.js'), outside], + { cwd: work }, + ); + expect(result.stdout).toContain('READ_BLOCKED'); + expect(result.stdout).toContain('NET_BLOCKED'); + expect(result.exitCode).toBe(0); + }, + ); +}); diff --git a/packages/asil-runners/src/cli.ts b/packages/asil-runners/src/cli.ts index fd4f0a9..b621a56 100644 --- a/packages/asil-runners/src/cli.ts +++ b/packages/asil-runners/src/cli.ts @@ -62,8 +62,11 @@ const HELP = ` Set ANTHROPIC_API_KEY and OPENAI_API_KEY in the environment or in the repository root .env (next to pnpm-workspace.yaml). OPENAI_API_KEY is only needed for grind (adversarial gate). + REPO_ROOT is required for grind. It does not default to the + current directory. grind does not commit, push, or open a pull request unless you - pass --apply. + pass --apply. Target-repository commands run inside bubblewrap + unless ASIL_SANDBOX=off. `.trimStart(); export async function runCli( diff --git a/packages/asil-runners/src/run-a.ts b/packages/asil-runners/src/run-a.ts index 916dd73..7655d3f 100644 --- a/packages/asil-runners/src/run-a.ts +++ b/packages/asil-runners/src/run-a.ts @@ -18,11 +18,14 @@ import { writePerTaskTranscripts, } from 'asil-analyzer'; import { + CATEGORY_SKILL_MAP, createDomainAnswerStore, findDomainQuestions, + findSkillFile, pythonProfile, resolveConfiguredPath, runLoop, + SCANNED_CATEGORIES, scanCodebase, typescriptProfile, type ImprovementLoopConfig, @@ -31,12 +34,11 @@ import { type Severity, type TaskCategory, } from 'asil-improvement-loop'; +import { createSandboxedCommandRunner } from './sandbox.js'; import { createAnthropicCaller, createCodexCaller, - createCommandRunner, createCostInfra, - scrubbedEnv, createDiffApplier, createFileFetcher, createFileReader, @@ -64,6 +66,8 @@ interface Flags { minSeverity: Severity; /** Rotate through categories so one busy category can't starve the rest. */ roundRobin: boolean; + /** Exit before scanning when a scanned category has no skill file. */ + requireSkills: boolean; } const SEVERITIES: readonly Severity[] = ['critical', 'high', 'medium', 'low']; @@ -72,6 +76,30 @@ function resolveProfile(name: 'ts' | 'python'): LanguageProfile { return name === 'python' ? pythonProfile : typescriptProfile; } +export interface SkillStatus { + category: TaskCategory; + skill: string; + path: string | null; +} + +/** One status per category the scanner will run, after --skip. */ +export function skillStatuses( + skillsPath: string, + skip: readonly string[], +): SkillStatus[] { + return SCANNED_CATEGORIES.filter((category) => !skip.includes(category)).map( + (category) => { + const skill = CATEGORY_SKILL_MAP[category]; + return { category, skill, path: findSkillFile(skillsPath, skill) }; + }, + ); +} + +export function formatSkillStatus(status: SkillStatus): string { + if (status.path) return ` ${status.category} (${status.skill}): ${status.path}`; + return ` ${status.category} (${status.skill}): missing, using built-in instructions`; +} + export function parseFlags(argv: readonly string[]): Flags | null { const flags: Flags = { maxTasks: 5, @@ -83,6 +111,7 @@ export function parseFlags(argv: readonly string[]): Flags | null { profile: 'ts', minSeverity: 'low', roundRobin: false, + requireSkills: false, }; for (let i = 0; i < argv.length; i += 1) { const a = argv[i]; @@ -123,6 +152,8 @@ export function parseFlags(argv: readonly string[]): Flags | null { i += 1; } else if (a === '--round-robin') { flags.roundRobin = true; + } else if (a === '--require-skills') { + flags.requireSkills = true; } else if (a === '--help' || a === '-h') { return null; } @@ -153,7 +184,16 @@ Options: --round-robin Rotate through task categories instead of strict priority order, so one busy category can't starve the rest within a run. - --help, -h Show this help`; + --require-skills Exit before scanning when a scanned category has no + skill file. Without this flag a missing skill uses the + built-in instructions. + --help, -h Show this help + +Environment: + REPO_ROOT Required. Absolute path of the target repository. + grind does not default to the current directory. + ASIL_SANDBOX Set to off to run target-repository commands without + the bubblewrap jail. Default is on.` export async function main(): Promise { const flags = parseFlags(process.argv.slice(2)); @@ -162,6 +202,13 @@ export async function main(): Promise { process.exit(0); } + if (!process.env.REPO_ROOT) { + console.error( + 'REPO_ROOT is required for grind. Set it to the absolute path of the target repository.', + ); + process.exit(1); + } + const env = loadEnv(); if (flags.transcriptsDir) { flags.transcriptsDir = resolveConfiguredPath(env.REPO_ROOT, flags.transcriptsDir); @@ -185,14 +232,9 @@ export async function main(): Promise { process.exit(1); } - // The loop's runner executes untrusted target-repo code (pnpm - // install/build/test, tsc, grep) inside worktrees. Strip secrets from - // its environment so a malicious postinstall, build, or test script - // cannot exfiltrate ANTHROPIC_API_KEY, OPENAI_API_KEY, or git tokens. - // The LLM callers hold their keys in this process (read at - // construction), so they are unaffected. Git and gh use a separate - // allowlisted environment. - const runner = createCommandRunner({ env: scrubbedEnv() }); + // Target-repo commands run inside bubblewrap. Git and gh use a + // separate allowlisted runner and are not wrapped here. + const runner = createSandboxedCommandRunner(); const fileReader = createFileReader(); console.log('\n🔄 System A — Autonomous Improvement Loop'); @@ -204,9 +246,27 @@ export async function main(): Promise { console.log(` Order: ${flags.roundRobin ? 'round-robin' : 'priority'}`); console.log(` Dry run: ${flags.dryRun}`); console.log( - ` Publish: ${flags.apply ? 'push and open a pull request' : 'off (pass --apply to publish)'}\n`, + ` Publish: ${flags.apply ? 'push and open a pull request' : 'off (pass --apply to publish)'}`, + ); + console.log( + ` --apply updates the loop's auto/* branches and opens pull requests.\n`, ); + const skillsPath = resolveConfiguredPath( + env.REPO_ROOT, + process.env.ASIL_SKILLS_PATH ?? '.asil/skills', + ); + const skills = skillStatuses(skillsPath, flags.skipCategories); + console.log('Skills:'); + for (const status of skills) console.log(formatSkillStatus(status)); + console.log(''); + if (flags.requireSkills && skills.some((status) => status.path === null)) { + console.error( + 'Missing skills. Refusing to continue because --require-skills was set.', + ); + process.exit(1); + } + const profile = resolveProfile(flags.profile); if (flags.dryRun) { @@ -312,10 +372,7 @@ export async function main(): Promise { maxTasksPerRun: flags.maxTasks, maxAttempts: 2, taskCooldownMs: 5000, - markdownSkillsPath: resolveConfiguredPath( - env.REPO_ROOT, - process.env.ASIL_SKILLS_PATH ?? '.asil/skills', - ), + markdownSkillsPath: skillsPath, repoRoot: env.REPO_ROOT, queuePath: resolveConfiguredPath( env.REPO_ROOT, diff --git a/packages/asil-runners/src/sandbox.ts b/packages/asil-runners/src/sandbox.ts new file mode 100644 index 0000000..72ccf01 --- /dev/null +++ b/packages/asil-runners/src/sandbox.ts @@ -0,0 +1,275 @@ +/** + * Run a target-repository command inside bubblewrap. + * + * The child can write only its working directory. It gets a private + * home and tmp. Network is off except for package-manager installs. + * Git and gh do not use this runner. + */ +import { execFileSync } from 'node:child_process'; +import { + closeSync, + existsSync, + openSync, + readSync, + realpathSync, +} from 'node:fs'; +import { basename, dirname, join, resolve, sep } from 'node:path'; +import type { CommandRunner } from 'asil-improvement-loop'; +import { createCommandRunner, scrubbedEnv } from './wiring.js'; + +const SYSTEM_DIRS = ['/usr', '/lib', '/lib64', '/bin', '/sbin'] as const; + +const NETWORK_FILES = [ + '/etc/ssl', + '/etc/resolv.conf', + '/etc/hosts', + '/etc/nsswitch.conf', + '/etc/ca-certificates', +] as const; + +export interface SandboxDeps { + exists?: (path: string) => boolean; + resolveCommand?: (command: string, pathEnv: string) => string | null; + pathEnv?: string; +} + +export function commandAllowsNetwork( + command: string, + args: readonly string[], +): boolean { + const base = basename(command); + return (base === 'pnpm' || base === 'npm') && args.includes('install'); +} + +function inside(root: string, candidate: string): boolean { + const absRoot = resolve(root); + const abs = resolve(candidate); + return abs === absRoot || abs.startsWith(absRoot + sep); +} + +/** Directory that contains a toolchain `bin/` plus its libraries. */ +export function toolchainRoot(realBinary: string): string { + const dir = dirname(realBinary); + return basename(dir) === 'bin' ? dirname(dir) : dir; +} + +function readShebang(realBinary: string): string | null { + let fd: number | null = null; + try { + fd = openSync(realBinary, 'r'); + const buf = Buffer.alloc(128); + const n = readSync(fd, buf, 0, buf.length, 0); + const text = buf.subarray(0, n).toString('utf8'); + if (!text.startsWith('#!')) return null; + const line = text.split('\n', 1)[0]?.slice(2).trim() ?? ''; + const parts = line.split(/\s+/).filter(Boolean); + if (parts[0] === '/usr/bin/env' && parts[1]) return parts[1]; + return parts[0] ?? null; + } catch { + return null; + } finally { + if (fd !== null) closeSync(fd); + } +} + +export function resolveCommandOnPath( + command: string, + pathEnv: string, +): string | null { + const candidates = command.includes('/') + ? [command] + : pathEnv.split(sep === '\\' ? ';' : ':').filter(Boolean).map((dir) => join(dir, command)); + for (const candidate of candidates) { + try { + if (!existsSync(candidate)) continue; + return realpathSync(candidate); + } catch { + // try the next PATH entry + } + } + return null; +} + +function collectBinaries( + command: string, + pathEnv: string, + resolveCommand: (command: string, pathEnv: string) => string | null, +): string[] { + const found: string[] = []; + const seen = new Set(); + const visit = (name: string): void => { + const real = resolveCommand(name, pathEnv); + if (!real || seen.has(real)) return; + seen.add(real); + found.push(real); + const shebang = readShebang(real); + if (shebang) visit(shebang); + }; + visit(command); + return found; +} + +export function buildBwrapArgs( + command: string, + args: readonly string[], + cwd: string, + deps: SandboxDeps = {}, +): string[] { + const exists = deps.exists ?? existsSync; + const resolveCommand = deps.resolveCommand ?? resolveCommandOnPath; + const pathEnv = deps.pathEnv ?? process.env.PATH ?? ''; + const workDir = resolve(cwd); + if (workDir === resolve('/')) { + throw new Error('Refusing to jail a command whose working directory is /.'); + } + + const network = commandAllowsNetwork(command, args); + const roBinds: string[] = []; + for (const dir of SYSTEM_DIRS) { + if (exists(dir)) roBinds.push(dir); + } + + const binaries = collectBinaries(command, pathEnv, resolveCommand); + const extraPath: string[] = []; + for (const real of binaries) { + const root = toolchainRoot(real); + if (roBinds.some((bound) => inside(bound, root))) { + const binDir = dirname(real); + if (!['/usr/bin', '/usr/local/bin', '/bin', '/sbin'].includes(binDir)) { + extraPath.push(binDir); + } + continue; + } + if (!roBinds.includes(root)) roBinds.push(root); + extraPath.push(dirname(real)); + } + + if (network) { + for (const file of NETWORK_FILES) { + if (exists(file) && !roBinds.some((bound) => inside(bound, file))) { + roBinds.push(file); + } + } + } + + const pathValue = [ + ...extraPath, + '/usr/local/bin', + '/usr/bin', + '/bin', + ].join(':'); + + const bwrapArgs = [ + '--die-with-parent', + '--unshare-user', + '--unshare-pid', + '--unshare-uts', + '--hostname', + 'asil', + '--unshare-ipc', + ...(network ? [] : ['--unshare-net']), + '--clearenv', + '--setenv', + 'PATH', + pathValue, + '--setenv', + 'HOME', + '/tmp/home', + '--setenv', + 'TMPDIR', + '/tmp', + '--setenv', + 'LANG', + 'C.UTF-8', + '--setenv', + 'LC_ALL', + 'C.UTF-8', + '--setenv', + 'CI', + '1', + '--setenv', + 'npm_config_store_dir', + join(workDir, '.pnpm-store'), + ]; + + for (const dir of roBinds) { + bwrapArgs.push('--ro-bind', dir, dir); + } + bwrapArgs.push( + '--proc', + '/proc', + '--dev', + '/dev', + '--tmpfs', + '/tmp', + '--dir', + '/tmp/home', + '--bind', + workDir, + workDir, + '--chdir', + workDir, + '--', + command, + ...args, + ); + return bwrapArgs; +} + +let warnedSandboxOff = false; + +/** Target-repo command runner. Jailed unless `ASIL_SANDBOX=off`. */ +export function createSandboxedCommandRunner( + env: NodeJS.ProcessEnv = process.env, +): CommandRunner { + if (env.ASIL_SANDBOX === 'off') { + if (!warnedSandboxOff) { + warnedSandboxOff = true; + console.error( + 'ASIL_SANDBOX=off: target-repository commands are not jailed.', + ); + } + return createCommandRunner({ env: scrubbedEnv(env) }); + } + + const inner = createCommandRunner({ env: scrubbedEnv(env) }); + return { + async run(command, args, opts) { + let bwrapArgs: string[]; + try { + bwrapArgs = buildBwrapArgs(command, args, opts.cwd, { + pathEnv: env.PATH, + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return { stdout: '', stderr: message, exitCode: 1 }; + } + const result = await inner.run('bwrap', bwrapArgs, { cwd: opts.cwd }); + if (result.exitCode === 127) { + return { + stdout: result.stdout, + stderr: + 'bubblewrap (bwrap) is required to run target-repository commands. ' + + 'Install bubblewrap, or set ASIL_SANDBOX=off to run them without a jail. ' + + result.stderr, + exitCode: 127, + }; + } + return result; + }, + }; +} + +/** True when a trivial jailed command can start. */ +export function bubblewrapAvailable(): boolean { + try { + const cwd = existsSync('/tmp') ? '/tmp' : '.'; + execFileSync('bwrap', buildBwrapArgs('/usr/bin/true', [], cwd), { + stdio: 'ignore', + timeout: 10_000, + }); + return true; + } catch { + return false; + } +}