app: pin nested repositories and refuse unprotected worktrees in the Linux sandbox

A writable workspace pinned only its own .git, so a nested repository or
submodule could have its config and hooks changed from inside the sandbox,
and a worktree pointer could name a gitdir the profile never mounted. Pin
every .git under the workspace with the same read-only control entries,
and refuse a worktree whose gitdir or shared directory is outside the
workspace. A workspace with no repository keeps commands refused, because
bwrap cannot deny creating .git by name.
This commit is contained in:
eXsoR65
2026-11-21 04:38:33 +00:00
committed by Ash
parent 3f4426a600
commit 1b3b491485
7 changed files with 496 additions and 10 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
## Status
The bubblewrap backend is **not part of this change**: it was written, reviewed below, and then scoped out
The bubblewrap backend is **implemented on this branch** and stays opt-in; it was written, reviewed below, and scoped out
until the gaps in items 1 and 2 close (git metadata for absent, nested and worktree repositories; minimal
runtime roots). This review and the plan that carried the backend are the record; the branch keeps Linux
commands on the existing fail-closed behaviour. No product default was weakened.
+6 -6
View File
@@ -55,13 +55,13 @@ clean-machine install.
read the workspace on any platform. Attachments are the supported way to give a bot file content;
workspace work belongs to a task or project chat.
## Linux command sandbox — separate work, not in this change
## Linux command sandbox — follow-up branch
Per the maintainer's review, the bubblewrap backend is not part of this client portability change:
commands stay refused on Linux until the git and worktree gaps are closed. The implementation and its
conformance test are preserved on the `sandbox-followup` branch for a separate PR. It remains
**opt-in** (`TENSORFOLD_LINUX_SANDBOX=1`) because three deviations from the macOS sandbox profile
remain:
The bubblewrap backend is implemented on this branch with the git and worktree gaps closed, and
remains **opt-in** (`TENSORFOLD_LINUX_SANDBOX=1`) until a maintainer decides otherwise. Nested
repositories are pinned like the workspace root; a worktree whose gitdir or shared directory lies
outside the workspace is refused, as is a workspace with no repository, so commands stay fail-closed
where the profile cannot protect metadata. One deviation from the macOS sandbox profile remains:
1. Creating a brand-new `.git` where none exists cannot be denied; existing repositories pin `.git`
against rename and pin `config`, `config.worktree`, `hooks` and `info` read-only.
@@ -0,0 +1,97 @@
// Run: TENSORFOLD_LINUX_SANDBOX=1 node .../jiti-cli.mjs electron/agent/linux-sandbox.conformance.test.ts
// Real confinement evidence for the bubblewrap backend. Skips cleanly on hosts where bwrap cannot
// create a namespace (nested containers), so it never claims confinement it did not observe.
import assert from 'node:assert/strict'
import { createServer } from 'node:net'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import path from 'node:path'
import { runSandboxedCommand } from './sandbox'
process.env.TENSORFOLD_LINUX_SANDBOX = '1'
const { canUseLinuxSandbox, probeLinuxSandbox } = await import('./linux-sandbox')
if (process.platform !== 'linux') {
console.log('CONFORMANCE: skipped (not Linux)')
} else if (!probeLinuxSandbox(process.cwd())) {
console.log('CONFORMANCE: skipped (bubblewrap cannot create a namespace on this host)')
} else {
assert.equal(canUseLinuxSandbox(), true, 'the opt-in enables the backend once the probe passes')
const root = realpathSync(mkdtempSync(path.join(realpathSync(tmpdir()), 'tf-bwrap-conformance-')))
const cwd = path.join(root, 'ws')
mkdirSync(path.join(cwd, '.git', 'hooks'), { recursive: true })
writeFileSync(path.join(cwd, '.git', 'config'), '[core]\n')
const server = createServer((socket) => socket.end('ok'))
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const port = (server.address() as { port: number }).port
try {
const hello = await runSandboxedCommand('printf confined', { cwd })
assert.equal(hello.stdout, 'confined')
assert.equal(hello.implementation, 'linux-bwrap', 'the Linux backend reported the run')
const inside = await runSandboxedCommand('printf data > inside.txt', { cwd, profile: 'build-test' })
assert.equal(inside.code, 0, inside.stderr)
assert.equal(readFileSync(path.join(cwd, 'inside.txt'), 'utf8'), 'data')
// The home directory is not a mounted root, so it does not exist in the namespace at all.
const outsideTarget = path.join(realpathSync(homedir()), 'tf-bwrap-escape.txt')
const outside = await runSandboxedCommand(`printf escape > ${JSON.stringify(outsideTarget)}`, { cwd, profile: 'build-test' })
assert.notEqual(outside.code, 0, 'writes outside the mounted roots fail')
assert.equal(existsSync(outsideTarget), false, 'nothing appeared outside the workspace')
const readOnly = await runSandboxedCommand('printf blocked > ro.txt', { cwd, profile: 'read-only' })
assert.notEqual(readOnly.code, 0, 'read-only profiles cannot write the workspace')
assert.equal(existsSync(path.join(cwd, 'ro.txt')), false)
const gitTamper = await runSandboxedCommand('printf pwned > .git/hooks/evil', { cwd, profile: 'build-test' })
assert.notEqual(gitTamper.code, 0, 'git hooks stay read-only under a writable profile')
assert.equal(existsSync(path.join(cwd, '.git', 'hooks', 'evil')), false)
const gitConfig = await runSandboxedCommand('printf pwned >> .git/config', { cwd, profile: 'build-test' })
assert.notEqual(gitConfig.code, 0, 'git config stays read-only under a writable profile')
assert.equal(readFileSync(path.join(cwd, '.git', 'config'), 'utf8'), '[core]\n')
// A nested repository is pinned like the root: its hooks and config stay read-only.
const nested = path.join(cwd, 'vendor', 'sub')
mkdirSync(path.join(nested, '.git', 'hooks'), { recursive: true })
writeFileSync(path.join(nested, '.git', 'config'), '[core]\n')
const nestedHook = await runSandboxedCommand('printf pwned > vendor/sub/.git/hooks/evil', { cwd, profile: 'build-test' })
assert.notEqual(nestedHook.code, 0, 'a nested repository\'s hooks stay read-only')
assert.equal(existsSync(path.join(nested, '.git', 'hooks', 'evil')), false)
const nestedConfig = await runSandboxedCommand('printf pwned >> vendor/sub/.git/config', { cwd, profile: 'build-test' })
assert.notEqual(nestedConfig.code, 0, 'a nested repository\'s config stays read-only')
assert.equal(readFileSync(path.join(nested, '.git', 'config'), 'utf8'), '[core]\n')
// A worktree outside the workspace is refused before the command runs.
const outsideWorktree = path.join(root, 'outside-worktree')
mkdirSync(path.join(root, 'elsewhere', '.git', 'worktrees', 'outside'), { recursive: true })
mkdirSync(outsideWorktree)
writeFileSync(path.join(outsideWorktree, '.git'), 'gitdir: ../elsewhere/.git/worktrees/outside\n')
const refusedWorktree = await runSandboxedCommand('printf should-not-run', { cwd: outsideWorktree, profile: 'build-test' })
assert.equal(refusedWorktree.code, 126, 'a worktree outside the workspace is refused')
assert.equal(refusedWorktree.sandboxed, false)
assert.match(refusedWorktree.stderr, /outside the workspace/)
// No network in build-test: a bash /dev/tcp connect to a live loopback listener must fail.
const denied = await runSandboxedCommand(`timeout 3 bash -c 'exec 3<>/dev/tcp/127.0.0.1/${port}'`, { cwd, profile: 'build-test' })
assert.notEqual(denied.code, 0, 'build-test cannot reach a loopback listener')
const allowed = await runSandboxedCommand(`timeout 3 bash -c 'exec 3<>/dev/tcp/127.0.0.1/${port}'`, { cwd, profile: 'network-fetch' })
assert.equal(allowed.code, 0, `network-fetch reaches the same listener: ${allowed.stderr}`)
// Cancellation must stop the sandboxed process group promptly.
const controller = new AbortController()
const started = Date.now()
const pending = runSandboxedCommand('sleep 30', { cwd, profile: 'build-test', signal: controller.signal })
setTimeout(() => controller.abort(), 300)
const cancelled = await pending
assert.notEqual(cancelled.code, 0, 'cancelled command did not report success')
assert.ok(Date.now() - started < 10_000, 'cancellation stops the sandboxed command promptly')
console.log('CONFORMANCE: passed (filesystem, git controls, nested repositories, worktree refusal, network and cancellation enforced)')
} finally {
server.close()
rmSync(root, { recursive: true, force: true })
}
}
+127
View File
@@ -0,0 +1,127 @@
// Run: node electron/agent/linux-sandbox.test.ts
import assert from 'node:assert/strict'
import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { canUseLinuxSandbox, linuxSandboxArgv, linuxSandboxBinary, planLinuxMounts } from './linux-sandbox'
import { runSandboxedCommand } from './sandbox'
let passed = 0
const ok = (name: string) => { passed++; console.log(` ✓ ${name}`) }
const root = mkdtempSync(path.join(realpathSync(tmpdir()), 'vontra-linux-sandbox-'))
try {
const cwd = path.join(root, 'ws')
mkdirSync(path.join(cwd, '.git', 'hooks'), { recursive: true })
mkdirSync(path.join(cwd, '.git', 'info'), { recursive: true })
writeFileSync(path.join(cwd, '.git', 'config'), '[core]\n')
// build-test: cwd writable, network denied, git control pinned.
const buildTest = linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false })
assert.ok(buildTest.includes('--unshare-all'), 'namespaces unshared')
assert.ok(!buildTest.includes('--share-net'), 'network stays unshared')
assert.ok(buildTest.includes('--die-with-parent'))
const bind = (argv: string[], flag: string, target: string) =>
argv.some((arg, i) => arg === flag && argv[i + 2] === target)
assert.ok(bind(buildTest, '--bind', cwd), 'cwd bound writable')
assert.ok(bind(buildTest, '--ro-bind', path.join(cwd, '.git', 'config')), 'git config pinned read-only')
assert.ok(bind(buildTest, '--ro-bind', path.join(cwd, '.git', 'hooks')), 'git hooks pinned read-only')
assert.ok(bind(buildTest, '--bind', path.join(cwd, '.git')), 'git dir pinned against rename')
assert.equal(buildTest.at(-1), '--', 'argv ends before the command')
// A nested repository is pinned like the root: writable bind, control entries read-only.
const nested = path.join(cwd, 'vendor', 'sub')
mkdirSync(path.join(nested, '.git', 'hooks'), { recursive: true })
writeFileSync(path.join(nested, '.git', 'config'), '[core]\n')
const nestedArgv = linuxSandboxArgv(cwd, { allowCwdWrite: true, allowNetwork: false })
assert.ok(bind(nestedArgv, '--bind', path.join(nested, '.git')), 'nested .git pinned against rename')
assert.ok(bind(nestedArgv, '--ro-bind', path.join(nested, '.git', 'config')), 'nested git config read-only')
assert.ok(bind(nestedArgv, '--ro-bind', path.join(nested, '.git', 'hooks')), 'nested git hooks read-only')
ok('nested repositories are pinned like the workspace root')
process.env.TENSORFOLD_LINUX_SANDBOX = '1'
// A worktree whose gitdir lives outside the workspace is refused, and refusal fails closed.
const outsideWorktree = path.join(root, 'outside-worktree')
mkdirSync(path.join(root, 'elsewhere', '.git', 'worktrees', 'outside'), { recursive: true })
mkdirSync(outsideWorktree)
writeFileSync(path.join(outsideWorktree, '.git'), 'gitdir: ../elsewhere/.git/worktrees/outside\n')
assert.throws(() => linuxSandboxArgv(outsideWorktree, { allowCwdWrite: true, allowNetwork: false }), /outside the workspace/)
if (canUseLinuxSandbox()) {
const refused = await runSandboxedCommand('printf should-not-run', { cwd: outsideWorktree })
assert.equal(refused.code, 126)
assert.equal(refused.sandboxed, false)
assert.match(refused.stderr, /outside the workspace/)
ok('a worktree pointing outside the workspace is refused before the command runs')
} else {
console.log(' (worktree refusal runtime check skipped: bubblewrap unavailable)')
}
// A workspace without a repository cannot be protected; commands stay refused.
const plain = path.join(root, 'plain-workspace')
mkdirSync(plain)
assert.throws(() => linuxSandboxArgv(plain, { allowCwdWrite: true, allowNetwork: false }), /needs a git workspace/)
if (canUseLinuxSandbox()) {
const plainRun = await runSandboxedCommand('printf should-not-run', { cwd: plain })
assert.equal(plainRun.code, 126)
assert.match(plainRun.stderr, /needs a git workspace/)
ok('a workspace without a repository keeps commands refused')
} else {
console.log(' (non-repository refusal runtime check skipped: bubblewrap unavailable)')
}
// read-only: cwd read-only; network-fetch: network shared.
const readOnly = linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: false })
assert.ok(bind(readOnly, '--ro-bind', cwd), 'cwd bound read-only')
assert.ok(!bind(readOnly, '--bind', cwd), 'cwd not writable')
assert.ok(!readOnly.some((arg, i) => arg === '--ro-bind' && readOnly[i + 2] === path.join(cwd, '.git')), 'no git pinning without cwd writes')
const network = linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: true })
assert.ok(network.includes('--share-net'), 'network-fetch shares the network namespace')
ok('draft profile contains requested mount and network arguments (not confinement proof)')
// A workspace inside the temporary root must end read-only, after the writable parent mount.
const tmpCwd = path.join(realpathSync(tmpdir()), 'vontra-tmp-workspace')
mkdirSync(tmpCwd, { recursive: true })
const tmpMounts = planLinuxMounts(tmpCwd, { allowCwdWrite: false, allowNetwork: false })
assert.deepEqual(tmpMounts.filter((mount) => mount.path === tmpCwd).map((mount) => mount.mode), ['ro'], 'read-only workspace stays read-only')
const tmpIndex = tmpMounts.findIndex((mount) => mount.path === realpathSync(tmpdir()))
const cwdIndex = tmpMounts.findIndex((mount) => mount.path === tmpCwd)
assert.ok(tmpIndex >= 0 && cwdIndex > tmpIndex, 'the read-only workspace mount follows its writable temporary parent')
assert.equal(tmpMounts[cwdIndex].mode, 'ro')
const writeMounts = planLinuxMounts(tmpCwd, { allowCwdWrite: true, allowNetwork: false })
assert.equal(writeMounts.find((mount) => mount.path === tmpCwd)?.mode, 'rw')
const ordered = planLinuxMounts(cwd, { allowCwdWrite: true, allowNetwork: false })
for (let i = 1; i < ordered.length; i++) assert.ok(ordered[i - 1].path.length <= ordered[i].path.length, 'mounts are parent-first')
ok('mount plan keeps a read-only workspace decisive under a writable temporary parent')
// usrmerge-style symlinked roots get a compatibility symlink, not a broken path.
const real = path.join(root, 'real-usr-bin')
const link = path.join(root, 'bin')
mkdirSync(real)
symlinkSync(real, link)
const withLink = linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: false, extraReadRoots: [link] })
assert.ok(withLink.some((arg, i) => arg === '--symlink' && withLink[i + 1] === real && withLink[i + 2] === link), 'symlinked root gets a compat symlink')
assert.ok(bind(withLink, '--ro-bind', real), 'the resolved root is bound')
ok('symlinked read roots resolve and keep their original path visible')
// Draft integration cases; the backend remains disabled pending adversarial qualification.
if (canUseLinuxSandbox()) {
const hello = await runSandboxedCommand('printf hello', { cwd })
assert.equal(hello.stdout, 'hello')
assert.equal(hello.implementation, 'linux-bwrap')
const escape = await runSandboxedCommand('touch /usr/bin/vontra-escape-attempt', { cwd, profile: 'read-only' })
assert.notEqual(escape.code, 0, 'writes outside the profile fail')
assert.equal(escape.sandboxed, true)
const planted = await runSandboxedCommand('printf pwned > .git/hooks/evil', { cwd, profile: 'build-test' })
assert.notEqual(planted.code, 0, 'git hooks stay read-only under build-test')
const net = await runSandboxedCommand('curl -sI --max-time 3 https://example.com', { cwd, profile: 'build-test' })
assert.notEqual(net.code, 0, 'build-test has no network')
ok('bwrap confinement: fs, git-control and network rules enforced')
} else {
console.log(' (draft Linux backend disabled pending qualification; confinement NOT verified)')
}
} finally {
rmSync(root, { recursive: true, force: true })
}
console.log(`\n${passed} passed`)
+232
View File
@@ -0,0 +1,232 @@
import { spawnSync } from 'node:child_process'
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs'
import type { Dirent } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { commandShell } from './cli-path'
// Linux command sandbox on bubblewrap: macOS sandbox-exec profiles, mirrored as bwrap argv only.
export const LINUX_SANDBOX_IMPLEMENTATION = 'linux-bwrap'
export function linuxSandboxBinary(): string | null {
for (const candidate of ['/usr/bin/bwrap', '/bin/bwrap']) if (existsSync(candidate)) return candidate
return null
}
let linuxSandboxAvailable: boolean | undefined
/** Probe the real production argv with a read-only fixture, so loader and mount rules are exercised. */
export function probeLinuxSandbox(cwd: string, run = spawnSync): boolean {
const binary = linuxSandboxBinary()
if (!binary) return false
const probe = run(binary, [...linuxSandboxArgv(cwd, { allowCwdWrite: false, allowNetwork: false, production: false }), commandShell(), '-c', 'exit 0'], {
stdio: 'ignore',
timeout: 4_000,
})
return probe.status === 0
}
export function canUseLinuxSandbox(): boolean {
// Opt-in only until conformance is qualified; never enabled by default on an unverified host.
const qualified = process.env.TENSORFOLD_LINUX_SANDBOX === '1'
if (!qualified || process.platform !== 'linux') return false
const binary = linuxSandboxBinary()
if (!binary) return false
if (linuxSandboxAvailable !== undefined) return linuxSandboxAvailable
linuxSandboxAvailable = probeLinuxSandbox(process.cwd())
return linuxSandboxAvailable
}
interface ResolvedRoot {
requested: string
resolved: string
}
/** Existing roots, realpath'd (usrmerge collapses /bin into /usr/bin), parents before children. */
function resolveRoots(requested: Array<string | null | undefined>): ResolvedRoot[] {
const seen = new Set<string>()
const out: ResolvedRoot[] = []
for (const item of requested) {
if (!item) continue
let resolved: string
try {
resolved = realpathSync(path.resolve(item))
} catch { continue }
if (seen.has(resolved)) continue
seen.add(resolved)
out.push({ requested: path.resolve(item), resolved })
}
return out.sort((a, b) => a.resolved.length - b.resolved.length || a.resolved.localeCompare(b.resolved))
}
/** usrmerge compatibility links: /bin -> usr/bin etc. so absolute interpreter paths still resolve. */
function compatSymlinks(roots: ResolvedRoot[]): string[] {
const args: string[] = []
for (const root of roots) {
if (root.requested === root.resolved) continue
try {
if (!lstatSync(root.requested).isSymbolicLink()) continue
} catch { continue }
args.push('--symlink', root.resolved, root.requested)
}
return args
}
/** A workspace the sandbox cannot protect: git metadata the profile would not mount. */
export class LinuxSandboxError extends Error {}
// Git control files stay read-only under a writable workspace; refs and objects stay writable.
const GIT_CONTROL_ENTRIES = ['config', 'config.worktree', 'hooks', 'info']
const NESTED_ENTRY_LIMIT = 2_048
const NESTED_DEPTH_LIMIT = 8
const insideWorkspace = (cwd: string, target: string) => target === cwd || target.startsWith(`${cwd}${path.sep}`)
/** Real path under the workspace, or null when the entry does not exist. */
function workspacePath(cwd: string, target: string): string | null {
let resolved: string
try { resolved = realpathSync(target) } catch { return null }
if (!insideWorkspace(cwd, resolved)) throw new LinuxSandboxError(`The sandbox will not mount git metadata outside the workspace: ${target}`)
return resolved
}
function gitdirPointer(pointer: string): string | null {
try {
const match = /^gitdir:[ \t]*(.+)$/m.exec(readFileSync(pointer, 'utf8'))
return match ? match[1].trim() : null
} catch { return null }
}
/** A git directory the profile pins: writable itself, its control entries read-only. */
function pinGitDirectory(cwd: string, gitDir: string, args: string[]): void {
const resolved = workspacePath(cwd, gitDir)
if (!resolved) return
args.push('--bind', resolved, gitDir)
for (const entry of GIT_CONTROL_ENTRIES) {
const resolvedEntry = workspacePath(cwd, path.join(gitDir, entry))
if (resolvedEntry) args.push('--ro-bind', resolvedEntry, path.join(gitDir, entry))
}
}
/** A worktree's real gitdir, refusing one that lives outside the workspace. */
function pinWorktree(cwd: string, pointer: string, args: string[]): void {
const target = gitdirPointer(pointer)
if (!target) throw new LinuxSandboxError(`The sandbox cannot read the worktree pointer at ${pointer}.`)
let gitdir: string
try { gitdir = realpathSync(path.resolve(path.dirname(pointer), target)) } catch { throw new LinuxSandboxError(`The sandbox cannot resolve the worktree gitdir in ${pointer}.`) }
if (!insideWorkspace(cwd, gitdir)) throw new LinuxSandboxError(`The sandbox refuses a worktree whose gitdir is outside the workspace: ${gitdir}`)
pinGitDirectory(cwd, gitdir, args)
const common = workspacePath(cwd, path.join(gitdir, 'commondir'))
if (!common) return
let commonDir: string
try { commonDir = realpathSync(path.resolve(path.dirname(common), readFileSync(common, 'utf8').trim())) } catch { throw new LinuxSandboxError(`The sandbox cannot resolve the shared git directory in ${common}.`) }
if (!insideWorkspace(cwd, commonDir)) throw new LinuxSandboxError(`The sandbox refuses a worktree whose shared git directory is outside the workspace: ${commonDir}`)
for (const entry of GIT_CONTROL_ENTRIES) {
const resolvedEntry = workspacePath(cwd, path.join(commonDir, entry))
if (resolvedEntry) args.push('--ro-bind', resolvedEntry, path.join(commonDir, entry))
}
}
/** Every .git under the workspace, bounded: an unbounded walk would silently pin a subset. */
function nestedGitPaths(cwd: string): string[] {
const found: string[] = []
let visited = 0
const walk = (dir: string, depth: number): void => {
if (depth > NESTED_DEPTH_LIMIT) return
let entries: Dirent[]
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
for (const entry of entries) {
if (++visited > NESTED_ENTRY_LIMIT) throw new LinuxSandboxError(`The sandbox will not walk more than ${NESTED_ENTRY_LIMIT} workspace entries to find nested repositories.`)
if (entry.name === '.git' || entry.name === 'node_modules' || !entry.isDirectory()) continue
const child = path.join(dir, entry.name)
if (existsSync(path.join(child, '.git'))) found.push(path.join(child, '.git'))
walk(child, depth + 1)
}
}
walk(cwd, 0)
return found
}
/** Root git metadata plus every nested repository, all pinned the same way. */
export function gitMetadataArgs(cwd: string): string[] {
const args: string[] = []
const rootGit = path.join(cwd, '.git')
let rootKind: 'dir' | 'file' | null = null
try { rootKind = lstatSync(rootGit).isDirectory() ? 'dir' : 'file' } catch { rootKind = null }
// A workspace without a repository keeps commands refused: bwrap cannot deny creating .git by name.
if (!rootKind) throw new LinuxSandboxError('The sandbox needs a git workspace; commands stay refused here.')
if (rootKind === 'file') pinWorktree(cwd, rootGit, args)
else pinGitDirectory(cwd, rootGit, args)
for (const nested of nestedGitPaths(cwd)) {
let kind: 'dir' | 'file'
try { kind = lstatSync(nested).isDirectory() ? 'dir' : 'file' } catch { continue }
if (kind === 'file') pinWorktree(cwd, nested, args)
else pinGitDirectory(cwd, nested, args)
}
return args
}
export interface LinuxSandboxProfileOptions {
allowCwdWrite: boolean
allowNetwork: boolean
extraReadRoots?: Array<string | null | undefined>
/** False for the capability probe, which must not inspect or depend on the caller's workspace. */
production?: boolean
}
/** Every requested read root, kept with its unresolved name so usrmerge links stay visible. */
export function linuxReadRoots(cwd: string, options: LinuxSandboxProfileOptions): ResolvedRoot[] {
return resolveRoots([
cwd,
'/bin',
'/sbin',
'/lib',
'/lib64',
'/usr/bin',
'/usr/sbin',
'/usr/lib',
'/usr/libexec',
'/usr/share',
'/usr/local',
'/etc',
'/opt',
os.tmpdir(),
process.env.TMPDIR,
...(options.extraReadRoots ?? []),
])
}
/** One final decision per resolved path; later mounts win, so children must follow their parents. */
export function planLinuxMounts(cwd: string, options: LinuxSandboxProfileOptions): Array<{ mode: 'ro' | 'rw'; path: string }> {
const readRoots = linuxReadRoots(cwd, options)
const writeRoots = resolveRoots([
...(options.allowCwdWrite ? [cwd] : []),
os.tmpdir(),
process.env.TMPDIR,
])
const writable = new Set(writeRoots.map((root) => root.resolved))
const byPath = new Map<string, 'ro' | 'rw'>()
for (const root of readRoots) byPath.set(root.resolved, writable.has(root.resolved) ? 'rw' : 'ro')
for (const root of writeRoots) byPath.set(root.resolved, 'rw')
// A read-only workspace always wins, even when it sits inside a writable temporary parent.
const canonicalCwd = (() => { try { return realpathSync(cwd) } catch { return path.resolve(cwd) } })()
if (!options.allowCwdWrite) byPath.set(canonicalCwd, 'ro')
return [...byPath.entries()]
.map(([mountPath, mode]) => ({ mode, path: mountPath }))
.sort((a, b) => a.path.length - b.path.length || a.path.localeCompare(b.path))
}
/** bwrap argv (without the binary) implementing the same contract as macSandboxProfile. */
export function linuxSandboxArgv(cwd: string, options: LinuxSandboxProfileOptions): string[] {
const mounts = planLinuxMounts(cwd, options)
const args: string[] = ['--unshare-all', '--die-with-parent']
if (options.allowNetwork) args.push('--share-net')
args.push('--proc', '/proc', '--dev', '/dev')
// Parent-first order is what makes a read-only child decisive.
for (const mount of mounts) args.push(mount.mode === 'rw' ? '--bind' : '--ro-bind', mount.path, mount.path)
if (options.allowCwdWrite) args.push(...gitMetadataArgs(realpathSync(cwd)))
args.push(...compatSymlinks(linuxReadRoots(cwd, options)))
args.push('--chdir', cwd, '--')
return args
}
+31 -2
View File
@@ -6,6 +6,7 @@ import path from 'node:path'
import { StringDecoder } from 'node:string_decoder'
import { approvalPolicyScope, isReadOnlyShellCommand } from './approval-policy'
import { commandShell, commandShellArgs } from './cli-path'
import { LinuxSandboxError, canUseLinuxSandbox, linuxSandboxArgv, linuxSandboxBinary } from './linux-sandbox'
import { commandApprovalReason } from './command-policy'
import { hostGitEnv } from './host-git-env'
import { redactCommandStreams } from './command-output-redaction'
@@ -59,7 +60,7 @@ export interface SandboxArtifactBundle {
command: string
cwd: string
profile: SandboxProfileId | 'unsandboxed'
implementation: 'macos-sandbox-exec' | 'unsandboxed'
implementation: 'macos-sandbox-exec' | 'linux-bwrap' | 'unsandboxed'
inputSnapshot: SandboxFileArtifact[]
outputFiles: SandboxFileArtifact[]
screenshots: SandboxFileArtifact[]
@@ -75,7 +76,7 @@ export interface SandboxedCommandResult {
stderr: string
sandboxed: boolean
profile: SandboxProfileId | 'unsandboxed'
implementation: 'macos-sandbox-exec' | 'unsandboxed'
implementation: 'macos-sandbox-exec' | 'linux-bwrap' | 'unsandboxed'
/** Number of value-level secrets removed from stdout/stderr before this result left the sandbox. */
redactionCount?: number
artifacts?: SandboxArtifactBundle
@@ -239,6 +240,34 @@ export async function runSandboxedCommand(command: string, options: SandboxedCom
})
return attachSandboxArtifacts(command, cwd, result, baseline)
}
if (canUseLinuxSandbox()) {
const definition = SANDBOX_PROFILES[profile]
let bwrapArgv: string[]
try {
bwrapArgv = linuxSandboxArgv(cwd, { allowCwdWrite: definition.allowCwdWrite, allowNetwork })
} catch (error) {
// A workspace whose git metadata the profile cannot protect keeps commands refused.
if (!(error instanceof LinuxSandboxError)) throw error
return attachSandboxArtifacts(command, cwd, {
code: 126,
stdout: '',
stderr: `${error.message}\n`,
sandboxed: false,
profile,
implementation: 'unsandboxed',
}, baseline)
}
const result = await runShell([linuxSandboxBinary()!, ...bwrapArgv, commandShell(), ...commandShellArgs(), command], {
cwd,
timeoutMs: options.timeoutMs,
maxBuffer: options.maxBuffer,
sandboxed: true,
profile,
implementation: 'linux-bwrap',
signal: options.signal,
})
return attachSandboxArtifacts(command, cwd, result, baseline)
}
if (!allowUnsandboxedCommands()) {
return attachSandboxArtifacts(command, cwd, {
code: 126,
+2 -1
View File
@@ -1,3 +1,4 @@
import { canUseLinuxSandbox } from '../../agent/linux-sandbox'
import { canUseMacSandbox } from '../../agent/sandbox'
import type { SecurityControlSnapshot } from '../../agent/types'
import { store } from '../state'
@@ -33,7 +34,7 @@ export function securityControlSnapshot(): SecurityControlSnapshot {
return {
actor: auditActor(),
role: currentSecurityRole(),
commandSandboxAvailable: canUseMacSandbox(),
commandSandboxAvailable: canUseMacSandbox() || canUseLinuxSandbox(),
mcpSandboxAvailable: canUseMacSandbox(),
signedUpdatesRequired: signedUpdatesRequired(),
updatePublicKeyConfigured: !!updateSignaturePublicKey(),