feat(sandbox): route host-shell surfaces into microVM via shell wrapper

This commit is contained in:
Chris Scott committed 2026-08-20 09:16:49 -04:00
1 parent ae117d6a78
commit f315dda3f3
11 files changed
+244 -11

No files matched your search

@@ -180,8 +180,9 @@ async function requireRealDirectory(dir: string, purpose: string): Promise<boole
throw new Error(`${purpose} ${dir} is not a directory; refusing to quarantine or restore through it`)
}
const resolved = path.resolve(dir)
const canonical = await realpath(dir)
if (canonical !== resolved) {
const canonicalParent = await realpath(path.dirname(resolved))
const canonical = await realpath(resolved)
if (canonical !== path.join(canonicalParent, path.basename(resolved))) {
throw new Error(`${purpose} ${dir} resolves to ${canonical} instead of ${resolved}; refusing to quarantine or restore through a redirected directory`)
}
return true
@@ -2,9 +2,12 @@ import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/comm
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
export const WRAPPED_COMMANDS_CAP = 256
export function buildSandboxPluginSource(): string {
return `var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
var WRAPPED_COMMANDS_CAP = ${WRAPPED_COMMANDS_CAP}
function guardCommand(reason) {
var safe = String(SANDBOX_UNAVAILABLE_PREFIX + reason).replace(/'/g, "'\\\\''")
@@ -50,6 +53,16 @@ function lockCommand(args, command) {
var wrappedCommands = new Map()
var bypassed = false
function rememberWrapped(callID, command) {
if (wrappedCommands.has(callID)) {
wrappedCommands.delete(callID)
}
wrappedCommands.set(callID, command)
while (wrappedCommands.size > WRAPPED_COMMANDS_CAP) {
wrappedCommands.delete(wrappedCommands.keys().next().value)
}
}
function replaceCommand(output, command, callID) {
if (!lockArgsReference(output, output.args)) {
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
@@ -57,7 +70,7 @@ function replaceCommand(output, command, callID) {
if (!lockCommand(output.args, command)) {
throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host')
}
wrappedCommands.set(callID, command)
rememberWrapped(callID, command)
}
export default async function ({ directory, worktree }) {
@@ -133,10 +146,10 @@ export default async function ({ directory, worktree }) {
},
'tool.execute.after': async (input, output) => {
if (input.tool !== 'bash') return
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
var wrapped = wrappedCommands.get(input.callID)
if (wrapped === undefined) return
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')
@@ -146,4 +159,3 @@ export default async function ({ directory, worktree }) {
}
`
}
@@ -17,7 +17,12 @@ function stripSandboxProxyApiPrefix(pathname: string): string {
return pathname
}
function isAmbiguousSandboxProxyPath(pathname: string): boolean {
return pathname !== '/' && (pathname.includes('//') || pathname.endsWith('/'))
}
function canonicalizeSandboxProxyPath(pathname: string): string | null {
if (isAmbiguousSandboxProxyPath(pathname)) return null
if (!pathname.includes('%')) return stripSandboxProxyApiPrefix(pathname)
if (ENCODED_PATH_HAZARD.test(pathname)) return null
try {
@@ -11,7 +11,7 @@ var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
var PLAN_TIMEOUT_MS = ${sandboxPlanTimeoutMs()}
function failClosed(reason) {
process.stdout.write(SANDBOX_UNAVAILABLE_PREFIX + reason + '\\n')
process.stderr.write(SANDBOX_UNAVAILABLE_PREFIX + reason + '\\n')
process.exit(1)
}
@@ -408,6 +408,52 @@ describe('opencode-proxy routes', () => {
expect(upstreamFetch).not.toHaveBeenCalled()
})
it('blocks duplicate-separator PTY creation with 403 when the OpenCode child is enforced', async () => {
isSandboxEnforcedMock.mockReturnValue(true)
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
globalThis.fetch = upstreamFetch as unknown as typeof fetch
const res = await app.request('/api/opencode-proxy//pty', {
method: 'POST',
headers: { Authorization: 'Bearer test-internal-token' },
})
expect(res.status).toBe(403)
expect(upstreamFetch).not.toHaveBeenCalled()
})
it('blocks trailing-separator PTY creation with 403 when the OpenCode child is enforced', async () => {
isSandboxEnforcedMock.mockReturnValue(true)
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
globalThis.fetch = upstreamFetch as unknown as typeof fetch
const res = await app.request('/api/opencode-proxy/pty/', {
method: 'POST',
headers: { Authorization: 'Bearer test-internal-token' },
})
expect(res.status).toBe(403)
expect(upstreamFetch).not.toHaveBeenCalled()
})
it('blocks duplicate-separator config mutation with 403 when the OpenCode child is enforced', async () => {
isSandboxEnforcedMock.mockReturnValue(true)
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
globalThis.fetch = upstreamFetch as unknown as typeof fetch
const res = await app.request('/api/opencode-proxy//config', {
method: 'PATCH',
headers: {
Authorization: 'Bearer test-internal-token',
'Content-Type': 'application/json',
},
body: JSON.stringify({ theme: 'dark' }),
})
expect(res.status).toBe(403)
expect(upstreamFetch).not.toHaveBeenCalled()
})
it('forwards custom slash command execution when the OpenCode child is enforced', async () => {
isSandboxEnforcedMock.mockReturnValue(true)
const upstreamFetch = vi.fn().mockResolvedValue(
+1 -1
View File
@@ -108,7 +108,7 @@ vi.mock('../../src/services/opencode-single-server', async (importOriginal) => {
restart: vi.fn(),
clearStartupError: vi.fn(),
getLastStartupError: vi.fn(),
checkHealth: vi.fn(() => true),
checkHealth: vi.fn().mockResolvedValue(true),
markRestartPending: vi.fn(),
isRestartPending: vi.fn(),
isSandboxEnforced: vi.fn(),
@@ -798,6 +798,32 @@ describe('opencode plugin quarantine', () => {
).toBe('v1')
})
it('quarantines and restores through a legitimate symlinked ancestor directory', async () => {
const realBase = path.join(root, 'real-base')
mkdirSync(path.join(realBase, '.config', 'opencode', 'plugin'), { recursive: true })
writeFileSync(path.join(realBase, '.config', 'opencode', 'plugin', 'user-plugin.js'), 'user code')
await fs.symlink(realBase, path.join(root, 'linked-base'))
const linkedConfigHome = path.join(root, 'linked-base', '.config')
const linkedConfigPath = path.join(linkedConfigHome, 'opencode', 'opencode.json')
await quarantineOpenCodePlugins(linkedConfigHome, linkedConfigPath)
expect(await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin'))).toEqual([])
expect(
await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin.ocm-quarantine')),
).toContain('user-plugin.js')
await restoreQuarantinedOpenCodePlugins(linkedConfigHome, linkedConfigPath)
expect(await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin'))).toContain('user-plugin.js')
expect(
await fs.readFile(path.join(realBase, '.config', 'opencode', 'plugin', 'user-plugin.js'), 'utf-8'),
).toBe('user code')
expect(
await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin.ocm-quarantine')),
).toEqual([])
})
it('round-trips a legitimate plugin file whose name ends in .ocm-conflict<digits>', async () => {
writeFileSync(path.join(configHome, 'opencode', 'plugin', 'audit.ocm-conflict1'), 'legit plugin')
writeConfig({})
@@ -7,7 +7,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import path from 'path'
import os from 'os'
import { pathToFileURL } from 'url'
import { SANDBOX_PLAN_TIMEOUT_MS } from '../../src/services/opencode-sandbox-plugin'
import { SANDBOX_PLAN_TIMEOUT_MS, WRAPPED_COMMANDS_CAP } from '../../src/services/opencode-sandbox-plugin'
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
import { quarantineOpenCodePlugins } from '../../src/services/opencode-plugin-quarantine'
@@ -568,6 +568,74 @@ describe('ocm-sandbox plugin', () => {
guardFor('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'),
)
})
it('evicts the oldest tracked call once the wrapped command map exceeds its cap', async () => {
process.env.OCM_SANDBOX_ENFORCED = 'true'
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ mode: 'sandbox', command: "msb exec 'echo wrapped'" }),
})
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory({ directory: '/repo' })
const callIDs = Array.from({ length: WRAPPED_COMMANDS_CAP + 1 }, (_, index) => `call-${index}`)
for (const callID of callIDs) {
await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID }, { args: { command: 'echo hi' } })
}
await hooks['tool.execute.after']?.(
{ tool: 'bash', sessionID: 's', callID: callIDs[0]!, args: { command: 'echo evil' } },
{ title: '', output: '', metadata: {} },
)
const afterEvicted = { args: { command: 'echo next' } }
await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'after-evicted' }, afterEvicted)
expect(afterEvicted.args.command).toBe("msb exec 'echo wrapped'")
await hooks['tool.execute.after']?.(
{ tool: 'bash', sessionID: 's', callID: callIDs[callIDs.length - 1]!, args: { command: 'echo evil' } },
{ title: '', output: '', metadata: {} },
)
const afterBypass = { args: { command: 'echo blocked' } }
await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'after-bypass' }, afterBypass)
expect(afterBypass.args.command).toBe(
guardFor('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'),
)
})
it('removes the tracked call entry before returning on an enforcement-state change', async () => {
process.env.OCM_SANDBOX_ENFORCED = 'true'
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ mode: 'sandbox', command: "msb exec 'echo hi'" }),
})
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory({ directory: '/repo' })
const output = { args: { command: 'echo hi' } }
await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'c' }, output)
expect(output.args.command).toBe("msb exec 'echo hi'")
delete process.env.OCM_SANDBOX_ENFORCED
await hooks['tool.execute.after']?.(
{ tool: 'bash', sessionID: 's', callID: 'c', args: { command: 'echo evil-unwrapped' } },
{ title: '', output: '', metadata: {} },
)
process.env.OCM_SANDBOX_ENFORCED = 'true'
await hooks['tool.execute.after']?.(
{ tool: 'bash', sessionID: 's', callID: 'c', args: { command: 'echo evil-unwrapped' } },
{ title: '', output: '', metadata: {} },
)
const next = { args: { command: 'echo should-still-be-planned' } }
await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'd' }, next)
expect(next.args.command).toBe("msb exec 'echo hi'")
})
})
function resolveOpencodeBinary(): string | null {
@@ -48,6 +48,56 @@ describe('sandbox proxy policy', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fpty/p1/connect').blocked).toBe(true)
})
it('fails closed on duplicate and trailing separators when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/pty/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '//pty').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api//pty').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api/pty/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1/connect/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/pty//p1/connect').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '//pty/p1/connect').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/%70ty/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/p%74y/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/session//ses_1/message').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/message/').blocked).toBe(true)
})
it('does not flag the bare root path as ambiguous when enforced', () => {
expect(decideSandboxProxyBlock(true, 'GET', '/')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'POST', '/api')).toEqual({ blocked: false })
})
it('fails closed on duplicate and trailing separators for config, mcp, and auth mutations when enforced', () => {
expect(decideSandboxProxyBlock(true, 'PATCH', '/config/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'PATCH', '//config').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'PATCH', '/api//config').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/mcp/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '//mcp').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api//mcp').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'PUT', '/auth/openai/').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'PUT', '//auth/openai').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'PUT', '/api//auth/openai').blocked).toBe(true)
})
it('never classifies ambiguous config, mcp, or auth mutation paths when enforced', () => {
expect(isSandboxConfigMutation(true, 'PATCH', '//config')).toBe(false)
expect(isSandboxConfigMutation(true, 'PATCH', '/api//config')).toBe(false)
expect(isSandboxMcpAdd(true, 'POST', '//mcp')).toBe(false)
expect(isSandboxMcpAdd(true, 'POST', '/api//mcp')).toBe(false)
expect(isSandboxAuthWrite(true, 'PUT', '//auth/openai')).toBe(false)
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai/')).toBe(false)
expect(isSandboxAuthWrite(true, 'PUT', '/api//auth/openai')).toBe(false)
})
it('passes mutation bodies through untouched on ambiguous paths since the block decision gates them when enforced', () => {
expect(decideSandboxMutationBody(true, 'PATCH', '//config', JSON.stringify({ theme: 'dark' }))).toEqual({ kind: 'passthrough' })
expect(decideSandboxMutationBody(true, 'POST', '/api//mcp', JSON.stringify({
name: 'remote-server',
config: { type: 'remote', url: 'https://example.com/mcp' },
}))).toEqual({ kind: 'passthrough' })
expect(decideSandboxMutationBody(true, 'PUT', '/auth/openai/', JSON.stringify({ type: 'api', key: 'k' }))).toEqual({ kind: 'passthrough' })
})
it('classifies /api-prefixed config, mcp, and auth writes identically when enforced', () => {
expect(isSandboxConfigMutation(true, 'PATCH', '/api/config')).toBe(true)
expect(isSandboxConfigMutation(true, 'PATCH', '/api/%63onfig')).toBe(true)
+15 -2
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Database } from 'bun:sqlite'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
@@ -33,6 +33,10 @@ vi.mock('../../../src/utils/logger', () => ({
const mockExecuteCommand = executeCommand as ReturnType<typeof vi.fn>
const mockDetectSandboxCapability = detectSandboxCapability as ReturnType<typeof vi.fn>
const originalWorkspacePath = process.env.WORKSPACE_PATH
const suiteWorkspaceParent = mkdtempSync(path.join(realpathSync(tmpdir()), 'ocm-runtime-test-'))
process.env.WORKSPACE_PATH = suiteWorkspaceParent
const reposRoot = getReposPath()
const worktreesRoot = getScheduleWorktreesPath()
const repoADir = path.join(reposRoot, 'repo-a')
@@ -63,6 +67,15 @@ describe('SandboxRuntimeService', () => {
rmSync(worktreeDir, { recursive: true, force: true })
})
afterAll(() => {
if (originalWorkspacePath === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = originalWorkspacePath
}
rmSync(suiteWorkspaceParent, { recursive: true, force: true })
})
function enableEnforcement(): void {
settingsService.updateSettings({ sandbox: { enabled: true } })
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.6.8' })
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { promises as fs } from 'fs'
import path from 'path'
import os from 'os'
import { spawnSync } from 'child_process'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import {
SANDBOX_SHELL_FILENAME,
@@ -62,4 +63,15 @@ describe('sandbox shell wrapper', () => {
expect(source).toContain('OCM_INTERNAL_TOKEN')
expect(source).toContain(SANDBOX_UNAVAILABLE_PREFIX)
})
it('fail-closes to stderr with exit 1 when the sandbox is unavailable', async () => {
await installSandboxShell(configHome)
const result = spawnSync(getSandboxShellPath(configHome), [], { encoding: 'utf8' })
expect(result.status).toBe(1)
expect(result.stdout).toBe('')
expect(result.stderr).toContain(SANDBOX_UNAVAILABLE_PREFIX)
expect(result.stderr).toContain('interactive shell sessions are not available while sandbox enforcement is on')
})
})