refactor(sandbox): pin shell shim to sandbox agent bash without rewriting commands

This commit is contained in:
Chris Scott committed 2026-08-23 14:02:31 -04:00
1 parent 681181ef4c
commit 098816f7cc
14 files changed
+1041 -1357

No files matched your search

+5 -6
View File
@@ -4,16 +4,15 @@ import type { Database } from 'bun:sqlite'
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
import { logger } from '../../utils/logger'
const SandboxCommandRequestSchema = z.object({
const SandboxShellRequestSchema = z.object({
directory: z.string().min(1),
command: z.string().min(1),
enforced: z.boolean().optional(),
})
export function createInternalSandboxRoutes(db: Database) {
const app = new Hono()
app.post('/command', async (c) => {
app.post('/shell', async (c) => {
let body: unknown
try {
body = await c.req.json()
@@ -21,17 +20,17 @@ export function createInternalSandboxRoutes(db: Database) {
return c.json({ error: 'Invalid request' }, 400)
}
const parsed = SandboxCommandRequestSchema.safeParse(body)
const parsed = SandboxShellRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid request' }, 400)
}
try {
return c.json(
await new SandboxRuntimeService(db).planCommand(parsed.data.directory, parsed.data.command, parsed.data.enforced === true),
await new SandboxRuntimeService(db).planShell(parsed.data.directory, parsed.data.enforced === true),
)
} catch (error) {
logger.error('Failed to plan sandbox command', error)
logger.error('Failed to plan the sandbox shell', error)
return c.json({ mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }, 500)
}
})
+74 -95
View File
@@ -1,17 +1,23 @@
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
import { SANDBOX_SHELL_ENV_HOST_SHELL, SANDBOX_SHELL_ENV_WORKDIR } from './sandbox/shell-shim'
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
export const WRAPPED_COMMANDS_CAP = 256
export function buildSandboxPluginSource(shellShimPath: string): string {
return `import { existsSync } from 'fs'
export function buildSandboxPluginSource(): string {
return `var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
var WRAPPED_COMMANDS_CAP = ${WRAPPED_COMMANDS_CAP}
var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)}
var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)}
var ENV_HOST_SHELL = ${JSON.stringify(SANDBOX_SHELL_ENV_HOST_SHELL)}
function guardCommand(reason) {
var safe = String(SANDBOX_UNAVAILABLE_PREFIX + reason).replace(/'/g, "'\\\\''")
return "printf '%s\\\\n' '" + safe + "' >&2; exit 1"
function isEnforced() {
return process.env.OCM_SANDBOX_ENFORCED === 'true'
}
function unavailable(reason) {
return new Error(SANDBOX_UNAVAILABLE_PREFIX + reason)
}
function lockAccessor(target, key, value) {
@@ -32,107 +38,80 @@ function lockAccessor(target, key, value) {
&& target[key] === value
}
var wrappedCommands = new Map()
var bypassed = false
function rememberWrapped(callID, command) {
if (wrappedCommands.has(callID)) {
wrappedCommands.delete(callID)
async function planSandboxShell(cwd) {
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) {
throw unavailable('sandbox plan lookup unavailable: internal API is not configured')
}
wrappedCommands.set(callID, command)
while (wrappedCommands.size > WRAPPED_COMMANDS_CAP) {
wrappedCommands.delete(wrappedCommands.keys().next().value)
var controller = new AbortController()
var planTimedOut = false
var planTimer = setTimeout(function () {
planTimedOut = true
controller.abort()
}, PLAN_TIMEOUT_MS)
var plan = null
var failure = null
try {
var res = await fetch(baseUrl + '/sandbox/shell', {
method: 'POST',
headers: {
'content-type': 'application/json',
Authorization: 'Bearer ' + token,
},
body: JSON.stringify({ directory: cwd, enforced: true }),
signal: controller.signal,
})
if (!res.ok) {
failure = 'sandbox plan request failed with status ' + res.status
} else {
plan = await res.json()
}
} catch (error) {
failure = planTimedOut ? 'sandbox plan lookup timed out' : (error instanceof Error ? error.message : String(error))
} finally {
clearTimeout(planTimer)
}
if (failure !== null) {
throw unavailable(failure)
}
if (plan === null || typeof plan !== 'object' || plan.mode !== 'sandbox' || typeof plan.workdir !== 'string' || plan.workdir.length === 0) {
throw unavailable(plan !== null && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response')
}
return plan.workdir
}
function replaceCommand(output, command, callID) {
if (!lockAccessor(output, 'args', output.args)) {
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
}
if (!lockAccessor(output.args, 'command', command)) {
throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host')
}
rememberWrapped(callID, command)
}
export default async function () {
var hostShell
export default async function ({ directory }) {
return {
'tool.execute.before': async (input, output) => {
if (input.tool !== 'bash') return
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
if (typeof output.args?.command !== 'string') {
replaceCommand(output, guardCommand('sandbox enforcement blocked a malformed bash invocation: command is missing or not a string'), input.callID)
return
config: async (cfg) => {
if (!isEnforced()) return
var configured = cfg.shell
if (typeof configured === 'string' && configured.length > 0 && configured !== SHELL_SHIM_PATH) {
hostShell = configured
}
if (bypassed) {
replaceCommand(output, guardCommand('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'), input.callID)
return
}
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) {
replaceCommand(output, guardCommand('sandbox plan lookup unavailable: internal API is not configured'), input.callID)
return
}
var replacement = null
var effectiveDirectory = directory
var requestedWorkdir = output.args.workdir
if (typeof requestedWorkdir === 'string' && requestedWorkdir.length > 0) {
if (requestedWorkdir.charAt(0) === '/') {
effectiveDirectory = requestedWorkdir
} else {
effectiveDirectory = directory.replace(/\\/+$/, '') + '/' + requestedWorkdir
lockAccessor(cfg, 'shell', SHELL_SHIM_PATH)
},
'shell.env': async (input, output) => {
if (!isEnforced() || typeof input.callID !== 'string' || input.callID.length === 0) {
if (hostShell !== undefined) {
output.env[ENV_HOST_SHELL] = hostShell
}
return
}
var controller = new AbortController()
var planTimedOut = false
var planTimer = setTimeout(function () {
planTimedOut = true
controller.abort()
}, PLAN_TIMEOUT_MS)
try {
var res = await fetch(baseUrl + '/sandbox/command', {
method: 'POST',
headers: {
'content-type': 'application/json',
Authorization: 'Bearer ' + token,
},
body: JSON.stringify({
directory: effectiveDirectory,
command: output.args.command,
enforced: true,
}),
signal: controller.signal,
})
if (!res.ok) {
replacement = guardCommand('sandbox plan request failed with status ' + res.status)
} else {
var plan = await res.json()
if (plan && typeof plan === 'object' && plan.mode === 'sandbox' && typeof plan.command === 'string' && plan.command.length > 0) {
replacement = plan.command
} else {
replacement = guardCommand(plan && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response')
}
}
} catch (error) {
replacement = guardCommand(planTimedOut ? 'sandbox plan lookup timed out' : (error instanceof Error ? error.message : String(error)))
} finally {
clearTimeout(planTimer)
if (!existsSync(SHELL_SHIM_PATH)) {
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
}
if (replacement !== null) {
replaceCommand(output, replacement, input.callID)
var workdir = await planSandboxShell(input.cwd)
if (!lockAccessor(output.env, ENV_WORKDIR, workdir)) {
throw unavailable('sandbox enforcement could not pin the sandbox working directory; aborting before the command runs on the host')
}
},
'tool.execute.after': async (input, output) => {
if (input.tool !== 'bash') return
var wrapped = wrappedCommands.get(input.callID)
wrappedCommands.delete(input.callID)
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
if (wrapped === undefined) return
if (!bypassed && input.args && input.args.command !== wrapped) {
bypassed = true
console.error('OpenCode Manager: sandbox enforcement bypass detected for bash call ' + input.callID + '; blocking all further sandboxed commands')
}
if (!isEnforced() || input.tool !== 'bash') return
if (output.metadata === null || typeof output.metadata !== 'object') return
output.metadata.sandbox = true
},
}
}
@@ -2,15 +2,16 @@ import { join } from 'path'
import { writeFileAtomic } from '../../utils/fs-safe'
import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin'
import { buildSandboxPluginSource } from '../opencode-sandbox-plugin'
import { ensureSandboxShellShim } from '../sandbox/shell-shim'
type ManagedOpenCodePlugin = {
filename: string
buildSource: () => string
buildSource: (context: { shellShimPath: string }) => string
}
const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [
{ filename: 'ocm-gh-env.js', buildSource: buildGhEnvPluginSource },
{ filename: 'ocm-sandbox.js', buildSource: buildSandboxPluginSource },
{ filename: 'ocm-gh-env.js', buildSource: () => buildGhEnvPluginSource() },
{ filename: 'ocm-sandbox.js', buildSource: ({ shellShimPath }) => buildSandboxPluginSource(shellShimPath) },
]
export function getOpenCodePluginDir(configHome: string): string {
@@ -18,8 +19,9 @@ export function getOpenCodePluginDir(configHome: string): string {
}
export async function installManagedPlugins(configHome: string): Promise<void> {
const shellShimPath = await ensureSandboxShellShim(configHome)
const dir = getOpenCodePluginDir(configHome)
for (const plugin of MANAGED_OPENCODE_PLUGINS) {
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource())
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource({ shellShimPath }))
}
}
+1 -10
View File
@@ -23,7 +23,7 @@ export function overrideSandboxExecutableTrustValidator(validator: ((candidate:
resetSandboxExecutableCache()
}
function isPathWithinRoot(root: string, target: string): boolean {
export function isPathWithinRoot(root: string, target: string): boolean {
const relative = path.relative(path.resolve(root), path.resolve(target))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
@@ -469,12 +469,3 @@ export function resolveSandboxExecUserUid(): number | null {
return Number(uid)
}
export function buildSandboxExecCommandString(directory: string, command: string): string {
const timeoutSeconds = Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)
return `${quoteForShell(sandboxExecutablePath())} exec ${WORKSPACE_SANDBOX_NAME} --no-tty -q -u ${quoteForShell(resolveSandboxExecUser())} -w ${quoteForShell(directory)} --timeout ${timeoutSeconds}s -- sh -c ${quoteForShell(command)}`
}
export function buildBlockedCommand(reason: string): string {
const message = `${SANDBOX_UNAVAILABLE_PREFIX}${reason}`
return `printf '%s\n' ${quoteForShell(message)} >&2; exit 1`
}
+4 -5
View File
@@ -11,7 +11,6 @@ import {
WORKSPACE_SANDBOX_NAME,
buildCanonicalSandboxSpec,
buildSandboxCreateArgs,
buildSandboxExecCommandString,
buildSandboxInspectArgs,
buildSandboxListArgs,
buildSandboxRemoveArgs,
@@ -30,9 +29,9 @@ const SANDBOX_LS_TIMEOUT_MS = 15000
const SANDBOX_STOP_TIMEOUT_MS = 30000
const SANDBOX_RUNTIME_TMPFS_GUEST = path.resolve('/tmp')
export type SandboxPlan =
export type SandboxShellPlan =
| { mode: 'host' }
| { mode: 'sandbox'; command: string }
| { mode: 'sandbox'; workdir: string }
| { mode: 'blocked'; reason: string }
export type SandboxStatus = {
@@ -648,7 +647,7 @@ export class SandboxRuntimeService {
}
}
async planCommand(directory: string, command: string, enforced = false): Promise<SandboxPlan> {
async planShell(directory: string, enforced = false): Promise<SandboxShellPlan> {
if (!enforced && !this.isEnabled()) {
return { mode: 'host' }
}
@@ -665,7 +664,7 @@ export class SandboxRuntimeService {
}
try {
await ensureWorkspaceSandbox()
return { mode: 'sandbox', command: buildSandboxExecCommandString(workDirectory, command) }
return { mode: 'sandbox', workdir: workDirectory }
} catch (error) {
logger.error('Failed to prepare the workspace sandbox', error)
return { mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }
@@ -0,0 +1,76 @@
import path from 'path'
import { existsSync } from 'fs'
import { ENV } from '@opencode-manager/shared/config/env'
import { writeFileAtomic } from '../../utils/fs-safe'
import {
isPathWithinRoot,
quoteForShell,
resolveSandboxExecUser,
sandboxExecutablePath,
sandboxMountRoots,
WORKSPACE_SANDBOX_NAME,
} from './command'
export const SANDBOX_SHELL_FILENAME = 'ocm-sandbox-shell'
export const SANDBOX_SHELL_ENV_WORKDIR = 'OCM_SANDBOX_WORKDIR'
export const SANDBOX_SHELL_ENV_HOST_SHELL = 'OCM_SANDBOX_HOST_SHELL'
export function sandboxShellShimPath(configHome: string): string {
return path.join(configHome, 'ocm', SANDBOX_SHELL_FILENAME)
}
export function resolveShimHostShell(): string {
const configured = process.env.SHELL?.trim()
if (
configured !== undefined &&
configured !== '' &&
path.isAbsolute(configured) &&
path.basename(configured) !== SANDBOX_SHELL_FILENAME &&
existsSync(configured)
) {
return configured
}
if (existsSync('/bin/bash')) return '/bin/bash'
return '/bin/sh'
}
export function buildSandboxShellShimScript(): string {
const timeoutSeconds = Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)
const execPrefix = [
quoteForShell(sandboxExecutablePath()),
'exec',
WORKSPACE_SANDBOX_NAME,
'--no-tty',
'-q',
'-u',
quoteForShell(resolveSandboxExecUser()),
'-w',
`"$${SANDBOX_SHELL_ENV_WORKDIR}"`,
'--timeout',
`${timeoutSeconds}s`,
'--',
'sh',
'"$@"',
].join(' ')
return `#!/bin/sh
if [ -n "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then
exec ${execPrefix}
fi
OCM_SANDBOX_DEFAULT_SHELL=${quoteForShell(resolveShimHostShell())}
exec "\${${SANDBOX_SHELL_ENV_HOST_SHELL}:-$OCM_SANDBOX_DEFAULT_SHELL}" "$@"
`
}
export async function ensureSandboxShellShim(configHome: string): Promise<string> {
const shimPath = sandboxShellShimPath(configHome)
const mountRoot = sandboxMountRoots().find((root) => isPathWithinRoot(root, shimPath))
if (mountRoot !== undefined) {
throw new Error(
`refusing to install the sandbox shell shim at ${shimPath}: the path is inside the sandboxed project root ${mountRoot} and would be writable by agent commands`,
)
}
await writeFileAtomic(shimPath, buildSandboxShellShimScript(), { mode: 0o700 })
return shimPath
}
+19 -19
View File
@@ -11,7 +11,7 @@ import { createOpenCodeClient } from '../../src/services/opencode/client'
import { allMigrations } from '../../src/db/migrations'
import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { migrate } from '../../src/db/migration-runner'
import { buildSandboxExecCommandString, resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../src/services/sandbox/command'
import { resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../src/services/sandbox/command'
import { executeCommand } from '../../src/utils/process'
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
import { getReposPath, getScheduleWorktreesPath, ENV } from '@opencode-manager/shared/config/env'
@@ -140,8 +140,8 @@ describe('internal sandbox routes', () => {
rmSync(repoDir, { recursive: true, force: true })
})
function postCommand(body: unknown, auth = true) {
return app.request('/api/internal/sandbox/command', {
function postShell(body: unknown, auth = true) {
return app.request('/api/internal/sandbox/shell', {
method: 'POST',
body: JSON.stringify(body),
headers: {
@@ -151,62 +151,62 @@ describe('internal sandbox routes', () => {
})
}
it('POST /command returns 401 without bearer token', async () => {
const res = await postCommand({ directory: repoDir, command: 'echo hi' }, false)
it('POST /shell returns 401 without bearer token', async () => {
const res = await postShell({ directory: repoDir }, false)
expect(res.status).toBe(401)
})
it('POST /command returns host mode when the sandbox preference is off', async () => {
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
it('POST /shell returns host mode when the sandbox preference is off', async () => {
const res = await postShell({ directory: repoDir })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ mode: 'host' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
})
it('POST /command returns a wrapped sandbox command when enforcement is on', async () => {
it('POST /shell returns the mapped sandbox working directory when enforcement is on', async () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
const res = await postShell({ directory: repoDir })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
mode: 'sandbox',
command: buildSandboxExecCommandString(repoDir, 'echo hi'),
workdir: repoDir,
})
})
it('POST /command returns 400 for a malformed body', async () => {
const res = await postCommand({ directory: '', command: 'echo hi' })
it('POST /shell returns 400 for a malformed body', async () => {
const res = await postShell({ directory: '' })
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Invalid request' })
})
it('POST /command blocks an enabled request when the capability is unavailable instead of running on the host', async () => {
it('POST /shell blocks an enabled request when the capability is unavailable instead of running on the host', async () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
const res = await postShell({ directory: repoDir })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
})
it('POST /command never returns host mode for an enforced request even when the preference is off', async () => {
const res = await postCommand({ directory: repoDir, command: 'echo hi', enforced: true })
it('POST /shell never returns host mode for an enforced request even when the preference is off', async () => {
const res = await postShell({ directory: repoDir, enforced: true })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
mode: 'sandbox',
command: buildSandboxExecCommandString(repoDir, 'echo hi'),
workdir: repoDir,
})
})
it('POST /command blocks an enforced request for a directory outside the project roots', async () => {
const res = await postCommand({ directory: '/etc', command: 'echo hi', enforced: true })
it('POST /shell blocks an enforced request for a directory outside the project roots', async () => {
const res = await postShell({ directory: '/etc', enforced: true })
expect(res.status).toBe(200)
const body = (await res.json()) as { mode: string; reason?: string }
File diff suppressed because it is too large. Load diff
+10 -121
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { spawnSync } from 'child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
@@ -8,10 +8,8 @@ import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
import {
WORKSPACE_SANDBOX_NAME,
SANDBOX_UNAVAILABLE_PREFIX,
buildBlockedCommand,
buildCanonicalSandboxSpec,
buildSandboxCreateArgs,
buildSandboxExecCommandString,
buildSandboxInspectArgs,
buildSandboxListArgs,
buildSandboxRemoveArgs,
@@ -243,108 +241,6 @@ describe('sandbox command builders', () => {
}
})
it('targets the shared sandbox with a per-command working directory and a verbatim guest payload', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-'))
const msbPath = path.join(fakeBin, 'msb')
const captureFile = path.join(fakeBin, 'payload.txt')
writeFileSync(
msbPath,
[
'#!/bin/sh',
'payload=""',
'prev=""',
'for arg in "$@"; do',
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
' prev="$arg"',
'done',
`printf '%s' "$payload" > "${captureFile}"`,
'sh -c "$payload"',
].join('\n'),
{ mode: 0o755 },
)
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const mod = await import('../../../src/services/sandbox/command')
mod.overrideSandboxExecutableTrustValidator(() => true)
const { buildSandboxExecCommandString, resolveSandboxExecUser } = mod
const directory = path.join(getReposPath(), 'foo')
const command = 'echo "it\'s a test" && echo line2 | tr a-z A-Z\necho after-newline'
const exec = buildSandboxExecCommandString(directory, command)
expect(exec).toBe(
`${quoteForShell(msbPath)} exec ${WORKSPACE_SANDBOX_NAME} --no-tty -q -u ${quoteForShell(resolveSandboxExecUser())} -w ${quoteForShell(directory)} --timeout ${Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)}s -- sh -c ${quoteForShell(command)}`,
)
const result = spawnSync('sh', ['-c', exec], {
encoding: 'utf8',
})
expect(result.status).toBe(0)
expect(result.stdout).toBe("it's a test\nLINE2\nafter-newline\n")
expect(readFileSync(captureFile, 'utf8')).toBe(command)
} finally {
delete process.env.MSB_PATH
rmSync(fakeBin, { recursive: true, force: true })
}
})
it('passes MSB_PATH and the resolved exec identity to msb as single literal arguments', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-hostile-'))
const captureFile = path.join(fakeBin, 'argv.txt')
const msbPath = path.join(fakeBin, 'my msb')
const hostileUser = 'node; echo hacked'
writeFileSync(
msbPath,
[
'#!/bin/sh',
`printf '%s\\n' "$0" "$@" > "${captureFile}"`,
'payload=""',
'prev=""',
'for arg in "$@"; do',
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
' prev="$arg"',
'done',
'sh -c "$payload"',
].join('\n'),
{ mode: 0o755 },
)
try {
process.env.MSB_PATH = msbPath
process.env.SANDBOX_EXEC_USER = hostileUser
vi.resetModules()
const mod = await import('../../../src/services/sandbox/command')
mod.overrideSandboxExecutableTrustValidator(() => true)
const { buildSandboxExecCommandString, resolveSandboxExecUser } = mod
const directory = path.join(getReposPath(), 'foo')
const command = 'echo hostile-ok'
const exec = buildSandboxExecCommandString(directory, command)
const result = spawnSync('sh', ['-c', exec], {
encoding: 'utf8',
env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH ?? ''}` },
})
expect(result.status).toBe(0)
expect(result.stdout).toBe('hostile-ok\n')
const resolvedUser = resolveSandboxExecUser()
expect(resolvedUser).toMatch(/^\d+:\d+$/)
const argv = readFileSync(captureFile, 'utf8').split('\n')
expect(argv[0]).toBe(msbPath)
expect(argv[argv.indexOf('-u') + 1]).toBe(resolvedUser)
expect(argv[argv.indexOf('-w') + 1]).toBe(directory)
expect(argv[argv.indexOf('-c') + 1]).toBe(command)
expect(argv.join(' ')).not.toContain(hostileUser)
} finally {
delete process.env.MSB_PATH
delete process.env.SANDBOX_EXEC_USER
rmSync(fakeBin, { recursive: true, force: true })
}
})
it('resolves the named exec user default to the manager uid:gid', () => {
const proc = process as unknown as { getuid: () => number; getgid: () => number }
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
@@ -379,18 +275,8 @@ describe('sandbox command builders', () => {
}
})
it('builds a blocked command that exits non-zero and writes the reason to stderr', () => {
const reason = "KVM is unavailable (it's not a hypervisor host)"
const command = buildBlockedCommand(reason)
const message = `${SANDBOX_UNAVAILABLE_PREFIX}${reason}`
it('exposes the sandbox-unavailable message prefix', () => {
expect(SANDBOX_UNAVAILABLE_PREFIX).toBe('Sandbox enforcement is on but the sandbox is unavailable: ')
expect(command).toBe(`printf '%s\n' ${quoteForShell(message)} >&2; exit 1`)
const result = spawnSync('sh', ['-c', command], { encoding: 'utf8' })
expect(result.status).toBe(1)
expect(result.stderr).toBe(`${message}\n`)
expect(result.stdout).toBe('')
})
it('resolves a relative MSB_PATH to one absolute executable found on PATH', async () => {
@@ -520,8 +406,11 @@ describe('sandbox command builders', () => {
})
})
describe('unwrapSandboxExecCommand round-trips against the real builder', () => {
it('recovers the original command from a real sandbox exec wrapper', () => {
describe('unwrapSandboxExecCommand recovers commands from the legacy recorded wrapper format', () => {
const legacyWrapped = (directory: string, command: string) =>
`${quoteForShell('/usr/local/bin/msb')} exec ocm-workspace --no-tty -q -u '1001:1001' -w ${quoteForShell(directory)} --timeout 600s -- sh -c ${quoteForShell(command)}`
it('recovers the original command from a legacy sandbox exec wrapper', () => {
const directory = '/workspace/repos/ai-test'
for (const command of [
'git status',
@@ -529,13 +418,13 @@ describe('unwrapSandboxExecCommand round-trips against the real builder', () =>
"echo 'x' -- sh -c 'y'",
'git status\ngit diff\necho done',
]) {
expect(unwrapSandboxExecCommand(buildSandboxExecCommandString(directory, command))).toBe(command)
expect(unwrapSandboxExecCommand(legacyWrapped(directory, command))).toBe(command)
}
})
it('passes through plain, blocked, empty, and near-miss commands unchanged', () => {
const blocked = buildBlockedCommand('KVM is unavailable')
const nearMiss = buildSandboxExecCommandString('/workspace/repos/ai-test', 'git status').replace(' --no-tty -q ', ' --no-tty ')
const blocked = "printf '%s\n' 'Sandbox enforcement is on but the sandbox is unavailable: KVM is unavailable' >&2; exit 1"
const nearMiss = legacyWrapped('/workspace/repos/ai-test', 'git status').replace(' --no-tty -q ', ' --no-tty ')
expect(unwrapSandboxExecCommand('git status')).toBe('git status')
expect(unwrapSandboxExecCommand(blocked)).toBe(blocked)
+143 -143
View File
@@ -7,7 +7,7 @@ import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/s
import { migrate } from '../../../src/db/migration-runner'
import { allMigrations } from '../../../src/db/migrations'
import { SettingsService } from '../../../src/services/settings'
import { buildSandboxExecCommandString, buildSandboxInspectArgs, resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, sandboxExecutablePath, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../../src/services/sandbox/command'
import { buildSandboxInspectArgs, resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, sandboxExecutablePath, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../../src/services/sandbox/command'
import { SandboxRuntimeService, resetSandboxRuntimeState, stopWorkspaceSandboxOnShutdown } from '../../../src/services/sandbox/runtime'
import { executeCommand } from '../../../src/utils/process'
import { detectSandboxCapability } from '../../../src/services/sandbox/capability'
@@ -212,7 +212,7 @@ describe('SandboxRuntimeService', () => {
it('returns host mode when the preference is off', async () => {
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.3.1' })
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'host' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
@@ -222,7 +222,7 @@ describe('SandboxRuntimeService', () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
@@ -236,9 +236,9 @@ describe('SandboxRuntimeService', () => {
})
const directory = repoADir
const plan = await service.planCommand(directory, 'echo hi')
const plan = await service.planShell(directory)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(directory, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: directory })
expect(mockExecuteCommand).toHaveBeenCalledWith(
[sandboxExecutablePath(), ...buildSandboxInspectArgs()],
expect.objectContaining({ ignoreExitCode: true, silent: true }),
@@ -257,12 +257,12 @@ describe('SandboxRuntimeService', () => {
const dirA = repoADir
const dirB = repoBDir
const [planA, planB] = await Promise.all([
service.planCommand(dirA, 'echo a'),
service.planCommand(dirB, 'echo b'),
service.planShell(dirA),
service.planShell(dirB),
])
expect(planA).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(dirA, 'echo a') })
expect(planB).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(dirB, 'echo b') })
expect(planA).toEqual({ mode: 'sandbox', workdir: dirA })
expect(planB).toEqual({ mode: 'sandbox', workdir: dirB })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
@@ -276,9 +276,9 @@ describe('SandboxRuntimeService', () => {
})
const directory = worktreeDir
const plan = await service.planCommand(directory, 'echo hi')
const plan = await service.planShell(directory)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(directory, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: directory })
})
it('starts an existing stopped sandbox instead of recreating it', async () => {
@@ -298,9 +298,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand).toHaveBeenCalledWith(
[sandboxExecutablePath(), 'start', WORKSPACE_SANDBOX_NAME],
expect.objectContaining({ ignoreExitCode: true }),
@@ -322,7 +322,7 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 1, stdout: '', stderr: 'vm kernel failed to boot: no memory' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -345,9 +345,9 @@ describe('SandboxRuntimeService', () => {
.mockResolvedValueOnce(inspectedRunningSandbox())
const directory = repoADir
const plan = await service.planCommand(directory, 'echo hi')
const plan = await service.planShell(directory)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(directory, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: directory })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
@@ -386,9 +386,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
@@ -405,7 +405,7 @@ describe('SandboxRuntimeService', () => {
.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'Command terminated by signal SIGKILL' })
.mockResolvedValueOnce({ exitCode: 0, stdout: stoppedListingOutput(), stderr: '' })
const first = await service.planCommand(repoADir, 'echo hi')
const first = await service.planShell(repoADir)
expect(first).toEqual({
mode: 'blocked',
@@ -415,7 +415,7 @@ describe('SandboxRuntimeService', () => {
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
const retried = await service.planCommand(repoADir, 'echo hi')
const retried = await service.planShell(repoADir)
expect(retried).toEqual({
mode: 'blocked',
@@ -445,9 +445,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand).toHaveBeenCalledWith(
[sandboxExecutablePath(), 'rm', '--force', WORKSPACE_SANDBOX_NAME],
expect.objectContaining({ ignoreExitCode: true }),
@@ -490,9 +490,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -526,9 +526,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -570,9 +570,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -613,9 +613,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -651,9 +651,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network.secrets is malformed'))
@@ -683,9 +683,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -719,9 +719,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('unexpected tmpfs mount'))
@@ -752,9 +752,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('assistant .opencode mask'))
@@ -792,9 +792,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -826,9 +826,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(1)
@@ -860,9 +860,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('unexpected config shape'))
@@ -900,9 +900,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -925,9 +925,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -955,9 +955,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
@@ -990,9 +990,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -1014,9 +1014,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
})
@@ -1047,9 +1047,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
@@ -1077,9 +1077,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('host disk image'))
@@ -1113,9 +1113,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('unrestricted egress'))
@@ -1156,9 +1156,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network policy'))
@@ -1200,9 +1200,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network policy'))
@@ -1242,9 +1242,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network policy'))
@@ -1285,9 +1285,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('default_ingress'))
@@ -1315,9 +1315,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network policy'))
@@ -1346,7 +1346,7 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -1379,9 +1379,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('does not match'))
@@ -1407,9 +1407,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('networking is disabled'))
@@ -1435,9 +1435,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network profile'))
@@ -1463,9 +1463,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network profile'))
@@ -1489,13 +1489,13 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const first = await service.planCommand(repoADir, 'echo a')
expect(first).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo a') })
const first = await service.planShell(repoADir)
expect(first).toEqual({ mode: 'sandbox', workdir: repoADir })
vi.advanceTimersByTime(6000)
const second = await service.planCommand(repoBDir, 'echo b')
expect(second).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoBDir, 'echo b') })
const second = await service.planShell(repoBDir)
expect(second).toEqual({ mode: 'sandbox', workdir: repoBDir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
@@ -1523,9 +1523,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('malformed JSON'))
@@ -1547,9 +1547,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('msb inspect failed with code 1'))
@@ -1559,7 +1559,7 @@ describe('SandboxRuntimeService', () => {
enableEnforcement()
mockExecuteCommand.mockResolvedValue({ exitCode: 1, stdout: '', stderr: 'failed to connect to supervisor' })
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -1572,7 +1572,7 @@ describe('SandboxRuntimeService', () => {
enableEnforcement()
mockExecuteCommand.mockResolvedValue({ exitCode: 0, stdout: '{"error":"truncated', stderr: '' })
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -1585,7 +1585,7 @@ describe('SandboxRuntimeService', () => {
enableEnforcement()
mockExecuteCommand.mockResolvedValue({ exitCode: 0, stdout: '{"name":"ocm-workspace"}', stderr: '' })
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -1603,7 +1603,7 @@ describe('SandboxRuntimeService', () => {
throw new Error('Command failed with code 1: no KVM acceleration available')
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'blocked', reason: 'Command failed with code 1: no KVM acceleration available' })
expect(logger.error).toHaveBeenCalled()
@@ -1612,7 +1612,7 @@ describe('SandboxRuntimeService', () => {
it('returns blocked for a directory outside the mounted project roots', async () => {
enableEnforcement()
const plan = await service.planCommand('/etc', 'echo hi')
const plan = await service.planShell('/etc')
expect(plan).toEqual({
mode: 'blocked',
@@ -1642,9 +1642,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('sandbox user null does not match'))
@@ -1678,9 +1678,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('does not match the canonical specification'))
@@ -1707,9 +1707,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('runtime.cmd'))
@@ -1736,9 +1736,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('runtime.entrypoint'))
@@ -1764,9 +1764,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('patches'))
@@ -1792,9 +1792,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('network.ports'))
@@ -1822,9 +1822,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('lifecycle.ephemeral'))
@@ -1846,9 +1846,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
@@ -1875,9 +1875,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('security_profile'))
@@ -1903,9 +1903,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('manifest digest'))
@@ -1931,15 +1931,15 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '[]', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi', true)
const plan = await service.planShell(repoADir, true)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
})
it('blocks an enforced request when the capability is unavailable instead of falling back to host', async () => {
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
const plan = await service.planCommand(repoADir, 'echo hi', true)
const plan = await service.planShell(repoADir, true)
expect(plan).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
@@ -1952,14 +1952,14 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '[]', stderr: '' }
})
await service.planCommand(repoADir, 'echo a')
await service.planShell(repoADir)
const lateDir = path.join(getScheduleWorktreesPath(), 'job-9-run-9')
mkdirSync(lateDir, { recursive: true })
try {
const plan = await service.planCommand(lateDir, 'echo b')
const plan = await service.planShell(lateDir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(lateDir, 'echo b') })
expect(plan).toEqual({ mode: 'sandbox', workdir: lateDir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
@@ -1990,12 +1990,12 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '[]', stderr: '' }
})
const first = await service.planCommand(repoADir, 'echo a')
expect(first).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo a') })
const first = await service.planShell(repoADir)
expect(first).toEqual({ mode: 'sandbox', workdir: repoADir })
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available or not writable' })
const second = await service.planCommand(repoADir, 'echo b')
const second = await service.planShell(repoADir)
expect(second).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available or not writable' })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
@@ -2038,7 +2038,7 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const planning = service.planCommand(repoADir, 'echo a')
const planning = service.planShell(repoADir)
await vi.waitFor(() => {
expect(mockExecuteCommand.mock.calls.some((call) => call[0].includes('inspect'))).toBe(true)
})
@@ -2048,7 +2048,7 @@ describe('SandboxRuntimeService', () => {
const plan = await planning
await stopping
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo a') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
const calls = mockExecuteCommand.mock.calls
const inspectIndex = calls.findIndex((call) => call[0].includes('inspect'))
const stopIndex = calls.findIndex((call) => call[0].includes('stop'))
@@ -2075,7 +2075,7 @@ describe('SandboxRuntimeService', () => {
expect(mockExecuteCommand.mock.calls.some((call) => call[0].includes('stop'))).toBe(true)
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'blocked', reason: expect.stringContaining('shutdown is in progress') })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
@@ -2090,7 +2090,7 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const planning = service.planCommand(repoADir, 'echo a')
const planning = service.planShell(repoADir)
const stopping = service.stopWorkspaceSandbox()
const plan = await planning
@@ -2145,9 +2145,9 @@ describe('SandboxRuntimeService', () => {
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('stop'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
})
@@ -2193,7 +2193,7 @@ describe('SandboxRuntimeService', () => {
try {
symlinkSync(target, reposRoot)
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -2233,9 +2233,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('missing one of the project bind mounts'))
@@ -2252,11 +2252,11 @@ describe('SandboxRuntimeService', () => {
.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' })
.mockResolvedValueOnce(inspectedRunningSandbox())
const failed = await service.planCommand(repoADir, 'echo a')
const failed = await service.planShell(repoADir)
expect(failed).toEqual({ mode: 'blocked', reason: 'Command failed with code 1: no KVM acceleration available' })
const retried = await service.planCommand(repoADir, 'echo b')
expect(retried).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo b') })
const retried = await service.planShell(repoADir)
expect(retried).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(2)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(2)
})
@@ -2284,7 +2284,7 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({
mode: 'blocked',
@@ -2295,7 +2295,7 @@ describe('SandboxRuntimeService', () => {
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Recreating unverifiable sandbox'))
const retried = await service.planCommand(repoADir, 'echo again')
const retried = await service.planShell(repoADir)
expect(retried).toEqual({
mode: 'blocked',
reason: 'msb rm failed with code 1: failed to kill vm: operation not permitted',
@@ -2329,9 +2329,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
@@ -2353,13 +2353,13 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'blocked', reason: expect.stringContaining('failed attestation') })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
const retried = await service.planCommand(repoADir, 'echo again')
const retried = await service.planShell(repoADir)
expect(retried).toEqual({ mode: 'blocked', reason: expect.stringContaining('failed attestation') })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(2)
})
@@ -2386,9 +2386,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
})
@@ -2417,9 +2417,9 @@ describe('SandboxRuntimeService', () => {
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planCommand(repoADir, 'echo hi')
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(expectedReasonPart))
@@ -0,0 +1,271 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { spawnSync } from 'child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { WORKSPACE_SANDBOX_NAME } from '../../../src/services/sandbox/command'
import {
SANDBOX_SHELL_ENV_HOST_SHELL,
SANDBOX_SHELL_ENV_WORKDIR,
} from '../../../src/services/sandbox/shell-shim'
afterEach(() => {
vi.restoreAllMocks()
})
function writeArgvCapturingFakeMsb(msbPath: string, captureFile: string): void {
writeFileSync(
msbPath,
[
'#!/bin/sh',
`printf '%s\\0' "$0" "$@" > "${captureFile}"`,
'payload=""',
'prev=""',
'for arg in "$@"; do',
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
' prev="$arg"',
'done',
'sh -c "$payload"',
].join('\n'),
{ mode: 0o755 },
)
}
describe('sandbox shell shim', () => {
it('execs msb through the shim with the working directory and a byte-for-byte guest payload', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-msb-'))
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
const msbPath = path.join(fakeBin, 'msb')
const captureFile = path.join(fakeBin, 'argv.txt')
writeArgvCapturingFakeMsb(msbPath, captureFile)
const originalMsbPath = process.env.MSB_PATH
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const commandMod = await import('../../../src/services/sandbox/command')
commandMod.overrideSandboxExecutableTrustValidator(() => true)
const { ENV } = await import('@opencode-manager/shared/config/env')
const shimPath = await shimMod.ensureSandboxShellShim(configHome)
const directory = path.join(getReposPath(), 'foo')
const command = 'echo "it\'s a test" && echo line2 | tr a-z A-Z\necho after-newline'
const result = spawnSync(shimPath, ['-c', command], {
encoding: 'utf8',
env: { ...process.env, [SANDBOX_SHELL_ENV_WORKDIR]: directory },
})
expect(result.status).toBe(0)
expect(result.stdout).toBe("it's a test\nLINE2\nafter-newline\n")
const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '')
expect(argv).toEqual([
msbPath,
'exec',
WORKSPACE_SANDBOX_NAME,
'--no-tty',
'-q',
'-u',
commandMod.resolveSandboxExecUser(),
'-w',
directory,
'--timeout',
`${Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)}s`,
'--',
'sh',
'-c',
command,
])
} finally {
if (originalMsbPath === undefined) {
delete process.env.MSB_PATH
} else {
process.env.MSB_PATH = originalMsbPath
}
rmSync(fakeBin, { recursive: true, force: true })
rmSync(configHome, { recursive: true, force: true })
}
})
it('passes MSB_PATH and the resolved exec identity to msb as single literal arguments', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-hostile-'))
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
const captureFile = path.join(fakeBin, 'argv.txt')
const msbPath = path.join(fakeBin, 'my msb')
const hostileUser = 'node; echo hacked'
writeArgvCapturingFakeMsb(msbPath, captureFile)
const originalMsbPath = process.env.MSB_PATH
const originalExecUser = process.env.SANDBOX_EXEC_USER
process.env.MSB_PATH = msbPath
process.env.SANDBOX_EXEC_USER = hostileUser
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const commandMod = await import('../../../src/services/sandbox/command')
commandMod.overrideSandboxExecutableTrustValidator(() => true)
const shimPath = await shimMod.ensureSandboxShellShim(configHome)
const directory = path.join(getReposPath(), 'foo')
const command = 'echo hostile-ok'
const result = spawnSync(shimPath, ['-c', command], {
encoding: 'utf8',
env: { ...process.env, [SANDBOX_SHELL_ENV_WORKDIR]: directory },
})
expect(result.status).toBe(0)
expect(result.stdout).toBe('hostile-ok\n')
const resolvedUser = commandMod.resolveSandboxExecUser()
expect(resolvedUser).toMatch(/^\d+:\d+$/)
const argv = readFileSync(captureFile, 'utf8').split('\0').filter((element) => element !== '')
expect(argv[0]).toBe(msbPath)
expect(argv[argv.indexOf('-u') + 1]).toBe(resolvedUser)
expect(argv[argv.indexOf('-w') + 1]).toBe(directory)
expect(argv[argv.indexOf('-c') + 1]).toBe(command)
expect(argv.join(' ')).not.toContain(hostileUser)
} finally {
if (originalMsbPath === undefined) {
delete process.env.MSB_PATH
} else {
process.env.MSB_PATH = originalMsbPath
}
if (originalExecUser === undefined) {
delete process.env.SANDBOX_EXEC_USER
} else {
process.env.SANDBOX_EXEC_USER = originalExecUser
}
rmSync(fakeBin, { recursive: true, force: true })
rmSync(configHome, { recursive: true, force: true })
}
})
it('passes through to the host shell when the workdir env is unset and never invokes msb', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-passthrough-'))
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
const msbCaptureFile = path.join(fakeBin, 'msb-invoked.txt')
const msbPath = path.join(fakeBin, 'msb')
writeFileSync(msbPath, ['#!/bin/sh', `printf 'invoked' > "${msbCaptureFile}"`].join('\n'), { mode: 0o755 })
const originalMsbPath = process.env.MSB_PATH
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const commandMod = await import('../../../src/services/sandbox/command')
commandMod.overrideSandboxExecutableTrustValidator(() => true)
const shimPath = await shimMod.ensureSandboxShellShim(configHome)
const env: Record<string, string | undefined> = { ...process.env }
delete env[SANDBOX_SHELL_ENV_WORKDIR]
delete env[SANDBOX_SHELL_ENV_HOST_SHELL]
const result = spawnSync(shimPath, ['-c', 'echo passthrough-ok'], { encoding: 'utf8', env })
expect(result.status).toBe(0)
expect(result.stdout).toBe('passthrough-ok\n')
expect(existsSync(msbCaptureFile)).toBe(false)
} finally {
if (originalMsbPath === undefined) {
delete process.env.MSB_PATH
} else {
process.env.MSB_PATH = originalMsbPath
}
rmSync(fakeBin, { recursive: true, force: true })
rmSync(configHome, { recursive: true, force: true })
}
})
it('lets OCM_SANDBOX_HOST_SHELL override the baked default host shell in the passthrough branch', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-shim-hostshell-'))
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
const msbCaptureFile = path.join(fakeBin, 'msb-invoked.txt')
const msbPath = path.join(fakeBin, 'msb')
writeFileSync(msbPath, ['#!/bin/sh', `printf 'invoked' > "${msbCaptureFile}"`].join('\n'), { mode: 0o755 })
const fakeShellPath = path.join(fakeBin, 'custom-host-shell')
const shellCaptureFile = path.join(fakeBin, 'shell-argv.txt')
writeFileSync(
fakeShellPath,
[
'#!/bin/sh',
`printf '%s\\0' "$0" "$@" > "${shellCaptureFile}"`,
'sh "$@"',
].join('\n'),
{ mode: 0o755 },
)
const originalMsbPath = process.env.MSB_PATH
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const commandMod = await import('../../../src/services/sandbox/command')
commandMod.overrideSandboxExecutableTrustValidator(() => true)
const shimPath = await shimMod.ensureSandboxShellShim(configHome)
const env: Record<string, string | undefined> = { ...process.env, [SANDBOX_SHELL_ENV_HOST_SHELL]: fakeShellPath }
delete env[SANDBOX_SHELL_ENV_WORKDIR]
const command = 'echo custom-shell-ok'
const result = spawnSync(shimPath, ['-c', command], { encoding: 'utf8', env })
expect(result.status).toBe(0)
expect(result.stdout).toBe('custom-shell-ok\n')
expect(existsSync(msbCaptureFile)).toBe(false)
const shellArgv = readFileSync(shellCaptureFile, 'utf8').split('\0').filter((element) => element !== '')
expect(shellArgv[0]).toBe(fakeShellPath)
expect(shellArgv[shellArgv.indexOf('-c') + 1]).toBe(command)
} finally {
if (originalMsbPath === undefined) {
delete process.env.MSB_PATH
} else {
process.env.MSB_PATH = originalMsbPath
}
rmSync(fakeBin, { recursive: true, force: true })
rmSync(configHome, { recursive: true, force: true })
}
})
it('writes an executable regular shim at sandboxShellShimPath and is idempotent', async () => {
const configHome = mkdtempSync(path.join(tmpdir(), 'ocm-shim-config-'))
try {
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const expected = shimMod.sandboxShellShimPath(configHome)
const first = await shimMod.ensureSandboxShellShim(configHome)
expect(first).toBe(expected)
const stat = statSync(expected)
expect(stat.isFile()).toBe(true)
expect(stat.mode & 0o100).not.toBe(0)
const content = readFileSync(expected, 'utf8')
expect(content).toContain('#!/bin/sh')
const second = await shimMod.ensureSandboxShellShim(configHome)
expect(second).toBe(expected)
expect(readFileSync(expected, 'utf8')).toBe(content)
} finally {
rmSync(configHome, { recursive: true, force: true })
}
})
it('refuses to install the shim when its path falls inside a sandbox mount root', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-shim-guard-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'workspace', 'repos')
mkdirSync(repos, { recursive: true })
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
vi.resetModules()
const shimMod = await import('../../../src/services/sandbox/shell-shim')
const configHome = path.join(repos, 'config')
await expect(shimMod.ensureSandboxShellShim(configHome)).rejects.toThrow(
'refusing to install the sandbox shell shim',
)
expect(existsSync(shimMod.sandboxShellShimPath(configHome))).toBe(false)
} finally {
if (originalWorkspacePath === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = originalWorkspacePath
}
rmSync(tmp, { recursive: true, force: true })
}
})
})
+16 -6
View File
@@ -24,13 +24,19 @@ The microVM sees repositories through bind mounts at the same paths used by the
| Local MCP servers | No; normal OpenCode behavior |
| Formatters, LSP servers, and hooks | No; normal OpenCode behavior |
| Custom provider modules | No; normal OpenCode behavior |
| Explicit OpenCode `shell` configuration | No; normal OpenCode behavior |
| Explicit OpenCode `shell` configuration | Overridden while enforcement is on |
The Manager-owned `ocm-sandbox.js` plugin intercepts the OpenCode `bash` tool before execution, asks the Manager for a sandbox execution plan, and replaces the command with `msb exec`. The replacement is locked and verified so a later plugin cannot silently restore the original host command. If the sandbox cannot be prepared, the tool call fails instead of running on the host.
The Manager generates a POSIX shell shim and points OpenCode's `shell` setting at it, so the agent `bash` tool spawns the shim instead of a host shell. The Manager-owned `ocm-sandbox.js` plugin pins that setting and, before each `bash` spawn, asks the Manager for the sandbox working directory and injects it as `OCM_SANDBOX_WORKDIR`. The shim routes the command into the microVM through `msb exec` whenever that variable is set. Both the pinned setting and the injected directory are locked and verified so a later plugin cannot silently restore host execution. If the sandbox cannot be prepared, the tool call fails instead of running on the host.
The command the agent wrote is never rewritten. It reaches `msb exec` as a single argument, so the recorded tool call, the permission rules, and the model's own context all keep the original command.
Each sandboxed `bash` call is marked `sandbox` in its tool metadata, which the WebUI shows as a green badge on the tool call. Metadata is not sent to the model.
## OpenCode Configuration
Sandbox enforcement does not sanitize, rewrite, filter, or replace OpenCode configuration. Global and project configuration loads normally, configured plugins are installed normally, and config, MCP, and authentication API requests are forwarded unchanged.
Sandbox enforcement does not sanitize, rewrite, filter, or replace OpenCode configuration files. Global and project configuration loads normally, configured plugins are installed normally, and config, MCP, and authentication API requests are forwarded unchanged.
The single exception is the in-memory `shell` setting: while enforcement is on, the sandbox plugin pins it to the generated shim. No configuration file is modified. A shell the user configured is remembered and handed back to the shim for the surfaces that are not the agent `bash` tool.
Existing `.ocm-sandbox-backup` and `.ocm-quarantine` artifacts created by older releases are restored during startup and are no longer created.
@@ -40,6 +46,8 @@ Configured extensions execute with OpenCode's normal host-process privileges. Th
WebUI `!command` shell mode, slash-command shell templates, and PTY terminals follow OpenCode's normal host-process behavior during enforcement. Only the OpenCode `bash` tool is routed into the microVM; these surfaces are not sandboxed.
They also spawn the shim, because it is the configured shell, but no working directory is injected for them, so the shim passes the command straight through to the host shell. PTY terminals receive the user's configured shell; `!command` shell mode and slash-command shell templates fall back to the shell the Manager resolved at startup rather than a login shell.
The OpenCode server binds to the configured `OPENCODE_HOST` regardless of enforcement, so the password guard for non-loopback hosts applies in both modes.
## Host Requirements
@@ -99,8 +107,9 @@ OpenCode's host process still reads these paths normally. They are omitted only
1. Enable **Sandbox** in Settings.
2. Restart the OpenCode server when prompted.
3. The Manager starts the new child with `OCM_SANDBOX_ENFORCED=true`.
4. The sandbox plugin rewrites each `bash` tool command through the internal planner.
5. If capability detection, planning, boot, attestation, or command replacement fails, the command exits non-zero instead of running on the host.
4. The Manager writes the shell shim next to the generated plugins and refuses to start an enforced server if it cannot.
5. The sandbox plugin resolves each `bash` tool working directory through the internal planner and pins it for the shim.
6. If capability detection, planning, boot, attestation, or working-directory pinning fails, the tool call fails instead of running on the host.
A directory outside the mounted roots fails with:
@@ -121,6 +130,7 @@ The enforcement stamp remains authoritative for the lifetime of the OpenCode chi
- The first command pays image pull and microVM boot latency, bounded by `SANDBOX_START_TIMEOUT_MS`.
- `SANDBOX_IMAGE` must contain every tool the agent expects to run.
- `SANDBOX_EXEC_USER` must match the workspace owner so commands can write mounted files.
- OpenCode permission rules see the rewritten `msb exec` command rather than the original command.
- A `shell` the user configured does not apply to `!command` shell mode or slash-command shell templates while enforcement is on.
- Credentials injected into OpenCode's host shell environment are not forwarded into the microVM.
- Message parts recorded by older releases still hold the old `msb exec` wrapper; the WebUI unwraps them for display and still badges them.
- Plugins and other configured host-process extensions are trusted and are not isolated by agent `bash` sandboxing.
@@ -283,7 +283,7 @@ describe('MessagePart', () => {
})
describe('sandbox indicator', () => {
const createBashPart = (command: string): MessagePartType => ({
const createBashPart = (command: string, metadata?: Record<string, unknown>): MessagePartType => ({
type: 'tool',
tool: 'bash',
sessionID: 'test-session',
@@ -291,13 +291,21 @@ describe('MessagePart', () => {
status: 'completed',
input: { command },
output: 'ok',
...(metadata === undefined ? {} : { metadata }),
time: { start: Date.now(), end: Date.now() + 100 },
},
})
const wrapped = "'/usr/local/bin/msb' exec ocm-workspace --no-tty -q -u '1001:1001' -w '/workspace/repos/ai-test' --timeout 600s -- sh -c 'git status'"
it('shows the sandbox badge and the unwrapped command for a sandboxed bash call', () => {
it('shows the sandbox badge for a bash call the sandbox plugin marked', () => {
render(<MessagePart part={createBashPart('git status', { sandbox: true })} />)
expect(screen.getByText('sandbox')).toBeInTheDocument()
expect(screen.getByText('git status')).toBeInTheDocument()
})
it('shows the sandbox badge and the unwrapped command for a legacy recorded sandbox call', () => {
render(<MessagePart part={createBashPart(wrapped)} />)
expect(screen.getByText('sandbox')).toBeInTheDocument()
@@ -80,7 +80,10 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
? part.state.input.command
: undefined
const displayCommand = rawCommand === undefined ? undefined : unwrapSandboxExecCommand(rawCommand)
const isSandboxedCommand = rawCommand !== undefined && displayCommand !== rawCommand
const isSandboxedCommand = rawCommand !== undefined && (
displayCommand !== rawCommand ||
(part.state.status === 'completed' && (part.state.metadata as Record<string, unknown> | undefined)?.sandbox === true)
)
const isUserBashCommand = part.state.status === 'completed' &&
typeof displayCommand === 'string' &&
userBashCommands.has(displayCommand)
@@ -160,7 +163,11 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
const sandboxIndicator = isSandboxedCommand ? (
<Badge variant="secondary" className="shrink-0 gap-1" title="Executed inside the sandbox microVM">
<Badge
variant="outline"
className="shrink-0 gap-1 border-green-600/40 bg-green-500/15 text-green-700 dark:text-green-400"
title="Executed inside the sandbox microVM"
>
<Shield className="w-3 h-3" />
sandbox
</Badge>