feat(sandbox): add KVM-backed agent sandboxing via microsandbox

This commit is contained in:
Chris Scott committed 2026-08-13 16:14:16 -04:00
1 parent 1d477bdee4
commit aa3fb48a62
80 files changed
+17304 -204

No files matched your search

@@ -724,3 +724,31 @@ describe('installAssistantWorkspace', () => {
expect(result.defaultAgent?.created).toBe(false)
})
})
describe('assistant mode directory contract', () => {
it('resolves the assistant directory from the shared sandbox mount owner', async () => {
const ws = await createTempAssistantWorkspace()
try {
const { getAssistantModePath, getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
const { getAssistantModeDirectory } = await import('../../src/services/assistant-mode')
const { sandboxSecretMaskPath } = await import('../../src/services/sandbox/command')
expect(getAssistantModeDirectory()).toBe(getAssistantModePath())
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
expect(getAssistantOpenCodeDir()).toBe(path.join(ws.assistantDir, '.opencode'))
} finally {
await ws.cleanup()
}
})
it('keeps the internal token underneath the sandboxed assistant .opencode directory', async () => {
const ws = await createTempAssistantWorkspace()
try {
const { getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
const tokenPath = path.join(ws.assistantDir, '.opencode/internal-token')
expect(tokenPath).toContain(getAssistantOpenCodeDir())
} finally {
await ws.cleanup()
}
})
})
@@ -39,6 +39,32 @@ describe('ocm-gh-env plugin', () => {
await expect(fs.access(file)).resolves.toBeUndefined()
})
it('atomically replaces a symlink at the plugin path with a regular file', async () => {
const pluginDir = getGhEnvPluginDir(configHome)
const pluginPath = path.join(pluginDir, 'ocm-gh-env.js')
const symlinkTarget = path.join(pluginDir, 'attacker-hook.js')
await fs.mkdir(pluginDir, { recursive: true })
await fs.rm(pluginPath, { force: true })
await fs.writeFile(symlinkTarget, 'export default async function () {}')
await fs.symlink(symlinkTarget, pluginPath)
await installGhEnvPlugin(configHome)
const stat = await fs.lstat(pluginPath)
expect(stat.isFile()).toBe(true)
expect(stat.isSymbolicLink()).toBe(false)
expect(await fs.readFile(pluginPath, 'utf-8')).toContain('shell.env')
expect(await fs.readFile(symlinkTarget, 'utf-8')).toBe('export default async function () {}')
})
it('throws when the plugin file cannot be written instead of swallowing the failure', async () => {
const blockedHome = path.join(configHome, 'blocked')
await fs.mkdir(blockedHome, { recursive: true })
await fs.writeFile(path.join(blockedHome, 'opencode'), 'not a directory')
await expect(installGhEnvPlugin(blockedHome)).rejects.toThrow()
})
it('injects fetched GH env into output.env', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,93 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const managerMock = vi.hoisted(() => ({
getLastStartupError: vi.fn<() => string | null>(() => null),
clearStartupError: vi.fn<() => void>(),
restart: vi.fn<() => Promise<void>>(),
checkHealth: vi.fn<() => boolean>(() => true),
}))
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: managerMock,
}))
import {
restartOpenCode,
setOpenCodeRestartCoordinator,
} from '../../src/services/opencode-restart'
import type { OpenCodeRestartCoordinator } from '../../src/services/opencode-restart-coordinator'
import type { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
function createSupervisor(healthy: boolean): OpenCodeSupervisor {
return {
restart: vi.fn().mockResolvedValue({ healthy }),
reloadConfig: vi.fn(),
} as unknown as OpenCodeSupervisor
}
function createCoordinator(healthy: boolean, resumedSessionIDs: string[] = []): OpenCodeRestartCoordinator {
return {
runWithResume: vi.fn(async (restart: () => Promise<boolean>) => ({
healthy: healthy ?? (await restart()),
resumedSessionIDs,
})),
} as unknown as OpenCodeRestartCoordinator
}
describe('restartOpenCode', () => {
beforeEach(() => {
vi.clearAllMocks()
setOpenCodeRestartCoordinator(null)
})
afterEach(() => {
setOpenCodeRestartCoordinator(null)
})
it('throws with the startup failure reason when the coordinator reports an unhealthy restart', async () => {
managerMock.getLastStartupError.mockReturnValue('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting')
setOpenCodeRestartCoordinator(createCoordinator(false))
await expect(restartOpenCode(createSupervisor(true))).rejects.toThrow(
'OpenCode version 1.18.15 does not support sandboxed bash tool rewriting',
)
})
it('preserves resumed session IDs only when the coordinator reports a healthy restart', async () => {
setOpenCodeRestartCoordinator(createCoordinator(true, ['session-1', 'session-2']))
const result = await restartOpenCode(createSupervisor(true))
expect(result).toEqual({ resumedSessionIDs: ['session-1', 'session-2'] })
})
it('throws with the startup failure reason when the supervisor restart is unhealthy without a coordinator', async () => {
managerMock.getLastStartupError.mockReturnValue('OpenCode server failed to become healthy')
await expect(restartOpenCode(createSupervisor(false))).rejects.toThrow('OpenCode server failed to become healthy')
})
it('returns without resumed sessions when the supervisor restart is healthy without a coordinator', async () => {
const supervisor = createSupervisor(true)
const result = await restartOpenCode(supervisor)
expect(result).toEqual({ resumedSessionIDs: [] })
expect(supervisor.restart).toHaveBeenCalledWith('settings_restart')
})
it('uses a generic failure message when no startup error is recorded', async () => {
managerMock.getLastStartupError.mockReturnValue(null)
await expect(restartOpenCode(createSupervisor(false))).rejects.toThrow(
'OpenCode server restart did not complete successfully',
)
})
it('propagates a manager restart failure when no supervisor is provided', async () => {
managerMock.restart.mockRejectedValue(new Error('server failed to become healthy'))
await expect(restartOpenCode()).rejects.toThrow('server failed to become healthy')
expect(managerMock.clearStartupError).toHaveBeenCalled()
})
})
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ensureDirectoryExists, writeFileContent } from '../../src/services/file-operations'
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
@@ -36,6 +36,8 @@ interface FakeManager {
reloadConfig: ReturnType<typeof vi.fn>
clearStartupError: ReturnType<typeof vi.fn>
getLastStartupError: ReturnType<typeof vi.fn>
isLastStartupErrorNonRecoverable: ReturnType<typeof vi.fn>
setLifecycleInitialized: ReturnType<typeof vi.fn>
getPort: ReturnType<typeof vi.fn>
getVersion: ReturnType<typeof vi.fn>
getMinVersion: ReturnType<typeof vi.fn>
@@ -51,6 +53,10 @@ interface FakeSettingsService {
}
describe('OpenCodeSupervisor', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const createManager = (): FakeManager => ({
start: vi.fn().mockResolvedValue(undefined),
stop: vi.fn().mockResolvedValue(undefined),
@@ -60,6 +66,8 @@ describe('OpenCodeSupervisor', () => {
reloadConfig: vi.fn().mockResolvedValue(undefined),
clearStartupError: vi.fn(),
getLastStartupError: vi.fn(() => null),
isLastStartupErrorNonRecoverable: vi.fn(() => false),
setLifecycleInitialized: vi.fn(),
getPort: vi.fn(() => 5551),
getVersion: vi.fn(() => '1.0.137'),
getMinVersion: vi.fn(() => '1.0.137'),
@@ -122,6 +130,65 @@ describe('OpenCodeSupervisor', () => {
await supervisor.stop()
})
it('opens the proxy lifecycle gate when the managed child is attested healthy', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('keeps the proxy lifecycle gate closed when startup fails non-recoverably', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
userId: 'default',
})
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
const status = await supervisor.start()
expect(status.healthy).toBe(false)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
})
it('closes the proxy lifecycle gate when recovery is exhausted and reopens it once health returns', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
userId: 'default',
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const failed = await supervisor.start()
expect(failed.healthy).toBe(false)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
const recovered = await supervisor.checkNow('manual')
expect(recovered.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
await supervisor.stop()
})
it('does not recover polling failures until the threshold is reached', async () => {
const manager = createManager()
const settings = createSettings()
@@ -137,6 +204,35 @@ describe('OpenCodeSupervisor', () => {
expect(status.state).toBe('unhealthy')
expect(status.failureCount).toBe(1)
expect(manager.restart).not.toHaveBeenCalled()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
})
it('closes the proxy lifecycle gate on a below-threshold health failure and reopens it once health returns', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 2,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
manager.checkHealth.mockResolvedValueOnce(false)
const unhealthy = await supervisor.checkNow('manual')
expect(unhealthy.state).toBe('unhealthy')
expect(unhealthy.failureCount).toBe(1)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
expect(manager.restart).not.toHaveBeenCalled()
manager.checkHealth.mockResolvedValueOnce(true)
const recovered = await supervisor.checkNow('manual')
expect(recovered.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('captures debug state before debug recovery', async () => {
@@ -171,4 +267,306 @@ describe('OpenCodeSupervisor', () => {
expect(manager.checkHealth).not.toHaveBeenCalled()
})
it('does not run configuration recovery for a non-recoverable startup failure', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
userId: 'default',
})
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
const status = await supervisor.start()
expect(status.state).toBe('failed')
expect(status.healthy).toBe(false)
expect(status.lastError).toContain('does not support sandboxed bash tool rewriting')
expect(manager.restart).not.toHaveBeenCalled()
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
expect(writeFileContent).not.toHaveBeenCalled()
await supervisor.stop()
})
it('does not run configuration recovery when a manual restart fails non-recoverably', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
userId: 'default',
})
manager.restart.mockRejectedValueOnce(new Error('Failed to quarantine untrusted OpenCode plugins'))
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
const status = await supervisor.restart('settings_restart')
expect(status.state).toBe('failed')
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
expect(writeFileContent).not.toHaveBeenCalled()
await supervisor.stop()
})
it('stops the recovery ladder when a recovery restart fails non-recoverably', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
userId: 'default',
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth.mockResolvedValue(false)
manager.restart.mockImplementation(async () => {
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
throw new Error('Failed to install the sandbox OpenCode plugin')
})
const status = await supervisor.start()
expect(status.state).toBe('failed')
expect(status.lastError).toContain('Failed to install the sandbox OpenCode plugin')
expect(manager.restart).toHaveBeenCalledTimes(1)
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
expect(writeFileContent).not.toHaveBeenCalled()
await supervisor.stop()
})
it('still follows the normal recovery ladder for a recoverable startup failure', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
userId: 'default',
})
manager.start.mockRejectedValueOnce(new Error('OpenCode config validation failed: command.review: Invalid'))
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const status = await supervisor.start()
expect(status.state).toBe('healthy')
expect(settings.archiveBrokenConfig).toHaveBeenCalledWith('default')
expect(settings.restoreToLastKnownGoodConfig).toHaveBeenCalledWith('default')
expect(settings.updateOpenCodeConfig).toHaveBeenCalled()
expect(writeFileContent).toHaveBeenCalled()
await supervisor.stop()
})
it('executes a restart requested during an active restart after the active restart completes', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const first = supervisor.restart('settings_restart')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
const second = supervisor.restart('manual')
await new Promise((resolve) => setTimeout(resolve, 20))
expect(manager.restart).toHaveBeenCalledTimes(1)
releaseRestart()
const [firstStatus, secondStatus] = await Promise.all([first, second])
expect(manager.restart).toHaveBeenCalledTimes(2)
expect(firstStatus.healthy).toBe(true)
expect(secondStatus.healthy).toBe(true)
})
it('executes a reload requested during an active reload after the active reload completes', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
let releaseReload!: () => void
manager.reloadConfig.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseReload = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const first = supervisor.reloadConfig('settings_reload')
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
const second = supervisor.reloadConfig('manual')
await new Promise((resolve) => setTimeout(resolve, 20))
expect(manager.reloadConfig).toHaveBeenCalledTimes(1)
releaseReload()
const [firstStatus, secondStatus] = await Promise.all([first, second])
expect(manager.reloadConfig).toHaveBeenCalledTimes(2)
expect(firstStatus.healthy).toBe(true)
expect(secondStatus.healthy).toBe(true)
})
it('closes the proxy lifecycle gate for the whole restart transition and reopens once healthy', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const restart = supervisor.restart('settings_restart')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseRestart()
const status = await restart
expect(status.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('closes the proxy lifecycle gate for the whole reload transition and reopens once healthy', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseReload!: () => void
manager.reloadConfig.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseReload = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const reload = supervisor.reloadConfig('settings_reload')
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseReload()
const status = await reload
expect(status.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('closes the proxy lifecycle gate while stopping and never reopens it', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseStop!: () => void
manager.stop.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseStop = resolve }),
)
const stopPromise = supervisor.stop()
await vi.waitFor(() => expect(manager.stop).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseStop()
await stopPromise
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
})
it('closes the proxy lifecycle gate while recovering a polling failure until health returns', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
userId: 'default',
})
await supervisor.start()
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValueOnce(false)
const recovering = supervisor.checkNow('manual')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
releaseRestart()
const status = await recovering
expect(status.healthy).toBe(true)
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
})
it('executes a stop requested during an active restart after the restart completes', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
watchEnabled: false,
})
let releaseRestart!: () => void
manager.restart.mockImplementationOnce(
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
)
manager.checkHealth.mockResolvedValue(true)
const restart = supervisor.restart('manual')
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
const stopPromise = supervisor.stop()
await new Promise((resolve) => setTimeout(resolve, 20))
expect(manager.stop).not.toHaveBeenCalled()
releaseRestart()
await Promise.all([restart, stopPromise])
expect(manager.restart).toHaveBeenCalledTimes(1)
expect(manager.stop).toHaveBeenCalledTimes(1)
})
})
@@ -203,6 +203,68 @@ describe('OpenCodeClient', () => {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
it('honours an explicit host override instead of OPENCODE_HOST', async () => {
const originalFetch = globalThis.fetch
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '192.168.1.10', configurable: true, writable: true })
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', '127.0.0.1')
await client.forward({ method: 'GET', path: '/doc' })
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
} finally {
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '127.0.0.1', configurable: true, writable: true })
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
it('brackets an IPv6 loopback host in the request URL', async () => {
const originalFetch = globalThis.fetch
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', '::1')
await client.forward({ method: 'GET', path: '/doc' })
expect(capturedUrl?.origin).toBe('http://[::1]:5551')
} finally {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
it('resolves a lazy host override on every request', async () => {
const originalFetch = globalThis.fetch
const hosts: string[] = []
let currentHost = '192.168.1.10'
const fetchFn = async (input: URL | Request | string) => {
hosts.push(input instanceof URL ? input.hostname : new URL(input.toString()).hostname)
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', () => currentHost)
await client.forward({ method: 'GET', path: '/doc' })
currentHost = '127.0.0.1'
await client.forward({ method: 'GET', path: '/doc' })
expect(hosts).toEqual(['192.168.1.10', '127.0.0.1'])
} finally {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
})
describe('forwardRaw', () => {
@@ -0,0 +1,378 @@
import { describe, it, expect } from 'vitest'
import {
decideSandboxProxyBlock,
decideSandboxConfigBody,
decideSandboxMcpAddBody,
decideSandboxAuthBody,
decideSandboxMutationBody,
isSandboxConfigMutation,
isSandboxMcpAdd,
isSandboxAuthWrite,
SANDBOX_BLOCKED_REASON_PREFIX,
SANDBOX_CONFIG_MUTATION_REASON_PREFIX,
} from '../../../src/services/opencode/proxy-policy'
describe('sandbox proxy policy', () => {
it('passes every route through when enforcement is off', () => {
expect(decideSandboxProxyBlock(false, 'POST', '/session/s1/shell')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(false, 'POST', '/pty')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(false, 'POST', '/session/s1/command')).toEqual({ blocked: false })
})
it('blocks the session shell endpoint when enforced', () => {
const decision = decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell')
expect(decision.blocked).toBe(true)
if (decision.blocked) {
expect(decision.reason).toContain(SANDBOX_BLOCKED_REASON_PREFIX)
expect(decision.reason).toContain('host process')
}
})
it('blocks custom slash command execution when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/command').blocked).toBe(true)
})
it('blocks PTY creation and connection when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/pty').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1/connect').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/pty/p1/connect').blocked).toBe(true)
})
it('treats /api-prefixed execution routes identically to unprefixed routes when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/api/pty').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1/connect').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/shell').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/command').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api/p%74y').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/api/session')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/api/session/ses_1/message')).toEqual({ blocked: false })
})
it('fails closed on encoded separators inside the /api prefix when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fpty').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fsession/ses_1/shell').blocked).toBe(true)
})
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)
expect(isSandboxConfigMutation(true, 'PATCH', '/api/config/')).toBe(false)
expect(isSandboxMcpAdd(true, 'POST', '/api/mcp')).toBe(true)
expect(isSandboxMcpAdd(true, 'POST', '/api/mcp/')).toBe(false)
expect(isSandboxAuthWrite(true, 'PUT', '/api/auth/openai')).toBe(true)
expect(isSandboxAuthWrite(true, 'PUT', '/api/auth/openai/extra')).toBe(false)
})
it('leaves non-execution routes reachable when enforced', () => {
expect(decideSandboxProxyBlock(true, 'GET', '/session')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/message')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'DELETE', '/pty/p1')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/config')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/prompt_async')).toEqual({ blocked: false })
})
it('ignores methods that do not match a blocked route', () => {
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/shell')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/pty')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/command')).toEqual({ blocked: false })
})
it('blocks percent-encoded spellings of blocked routes when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%73hell').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%73%68%65%6c%6c').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%63ommand').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/p%74y').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'GET', '/p%74y/ses_1/connect').blocked).toBe(true)
})
it('fails closed on encoded separators, double-encoded, control, and malformed paths when enforced', () => {
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%2F..').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1%2Fshell').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%5Cx').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%2573hell').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%00').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%zz').blocked).toBe(true)
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%c0%ae').blocked).toBe(true)
})
it('passes safely encoded non-execution paths through when enforced', () => {
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/%6dessage')).toEqual({ blocked: false })
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/prompt%5Fasync')).toEqual({ blocked: false })
})
it('classifies only enforced PATCH /config as a config mutation', () => {
expect(isSandboxConfigMutation(true, 'PATCH', '/config')).toBe(true)
expect(isSandboxConfigMutation(true, 'PATCH', '/%63onfig')).toBe(true)
expect(isSandboxConfigMutation(true, 'PATCH', '/config/')).toBe(false)
expect(isSandboxConfigMutation(true, 'PATCH', '/project')).toBe(false)
expect(isSandboxConfigMutation(true, 'POST', '/config')).toBe(false)
expect(isSandboxConfigMutation(true, 'GET', '/config')).toBe(false)
expect(isSandboxConfigMutation(false, 'PATCH', '/config')).toBe(false)
})
it('passes non-config mutation bodies through untouched', () => {
expect(decideSandboxConfigBody(true, 'GET', '/config', '')).toEqual({ kind: 'passthrough' })
expect(decideSandboxConfigBody(true, 'POST', '/config', '{}')).toEqual({ kind: 'passthrough' })
expect(decideSandboxConfigBody(true, 'PATCH', '/session/s1/message', '{}')).toEqual({ kind: 'passthrough' })
expect(decideSandboxConfigBody(false, 'PATCH', '/config', '{}')).toEqual({ kind: 'passthrough' })
})
it('strips configured plugins from an enforced config mutation', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
theme: 'dark',
plugin: ['opencode-plugin-npm'],
mcp: { remote: { type: 'remote', url: 'https://example.com' } },
}))
expect(decision.kind).toBe('sanitized')
if (decision.kind === 'sanitized') {
const body = JSON.parse(decision.body) as Record<string, unknown>
expect(body.theme).toBe('dark')
expect(body.plugin).toBeUndefined()
expect(body.mcp).toEqual({ remote: { type: 'remote', url: 'https://example.com' } })
}
})
it('strips local MCP servers and formatter config from an enforced config mutation', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
formatter: { command: 'prettier' },
mcp: { local: { type: 'local', command: ['node', 'server.js'] }, remote: { type: 'remote', url: 'https://example.com' } },
}))
expect(decision.kind).toBe('sanitized')
if (decision.kind === 'sanitized') {
const body = JSON.parse(decision.body) as Record<string, unknown>
expect(body.formatter).toBeUndefined()
expect(body.mcp).toEqual({ remote: { type: 'remote', url: 'https://example.com' } })
}
})
it('leaves a config mutation with no host-execution sections unchanged when enforced', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ theme: 'dark' }))
expect(decision).toEqual({ kind: 'sanitized', body: JSON.stringify({ theme: 'dark' }) })
})
it('fails closed on malformed or non-object config mutation bodies when enforced', () => {
const invalidJson = decideSandboxConfigBody(true, 'PATCH', '/config', '{not json')
expect(invalidJson.kind).toBe('reject')
if (invalidJson.kind === 'reject') {
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
}
const emptyBody = decideSandboxConfigBody(true, 'PATCH', '/config', '')
expect(emptyBody.kind).toBe('reject')
const arrayBody = decideSandboxConfigBody(true, 'PATCH', '/config', '[]')
expect(arrayBody.kind).toBe('reject')
})
it('strips LSP servers and experimental hook commands from an enforced config mutation', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
lsp: { typescript: { command: ['typescript-language-server', '--stdio'] } },
experimental: {
hook: { file_edited: [{ command: ['chmod', '+x', 'script.sh'] }] },
chatMaxRetries: 4,
},
model: 'x',
}))
expect(decision.kind).toBe('sanitized')
if (decision.kind === 'sanitized') {
const body = JSON.parse(decision.body) as Record<string, unknown>
expect(body.lsp).toBeUndefined()
expect(body.experimental).toEqual({ chatMaxRetries: 4 })
expect(body.model).toBe('x')
}
})
it('strips the shell configuration from an enforced config mutation', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
shell: { command: '/repo/bin/evil-shell', args: [] },
model: 'x',
}))
expect(decision.kind).toBe('sanitized')
if (decision.kind === 'sanitized') {
const body = JSON.parse(decision.body) as Record<string, unknown>
expect(body.shell).toBeUndefined()
expect(body.model).toBe('x')
}
})
it('strips an enabling lsp boolean from an enforced config mutation while keeping an explicit false', () => {
const enabled = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ lsp: true, model: 'x' }))
expect(enabled.kind).toBe('sanitized')
if (enabled.kind === 'sanitized') {
expect(JSON.parse(enabled.body)).toEqual({ model: 'x' })
}
const disabled = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ lsp: false, model: 'x' }))
expect(disabled).toEqual({ kind: 'sanitized', body: JSON.stringify({ lsp: false, model: 'x' }) })
})
it('drops the experimental section entirely when only its hook carries commands', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
experimental: { hook: { session_completed: [{ command: ['echo', 'done'] }] } },
}))
expect(decision.kind).toBe('sanitized')
if (decision.kind === 'sanitized') {
const body = JSON.parse(decision.body) as Record<string, unknown>
expect(body.experimental).toBeUndefined()
}
})
it('classifies only enforced POST /mcp as an MCP add', () => {
expect(isSandboxMcpAdd(true, 'POST', '/mcp')).toBe(true)
expect(isSandboxMcpAdd(true, 'POST', '/%6dcp')).toBe(true)
expect(isSandboxMcpAdd(true, 'POST', '/mcp/')).toBe(false)
expect(isSandboxMcpAdd(true, 'POST', '/mcp/my-server/connect')).toBe(false)
expect(isSandboxMcpAdd(true, 'GET', '/mcp')).toBe(false)
expect(isSandboxMcpAdd(true, 'DELETE', '/mcp')).toBe(false)
expect(isSandboxMcpAdd(false, 'POST', '/mcp')).toBe(false)
})
it('passes non-MCP-add bodies through untouched', () => {
expect(decideSandboxMcpAddBody(true, 'GET', '/mcp', '')).toEqual({ kind: 'passthrough' })
expect(decideSandboxMcpAddBody(true, 'POST', '/mcp/my-server/connect', '{}')).toEqual({ kind: 'passthrough' })
expect(decideSandboxMcpAddBody(false, 'POST', '/mcp', '{}')).toEqual({ kind: 'passthrough' })
})
it('rejects a local MCP server add while enforced', () => {
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
name: 'evil',
config: { type: 'local', command: ['node', 'server.js'], environment: { TOKEN: 'secret' } },
}))
expect(decision.kind).toBe('reject')
if (decision.kind === 'reject') {
expect(decision.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
expect(decision.reason).toContain('only remote MCP servers')
}
})
it('rejects a command-bearing MCP add even without an explicit local type while enforced', () => {
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
name: 'evil',
config: { command: ['npx', 'evil-server'] },
}))
expect(decision.kind).toBe('reject')
})
it('passes a provably remote MCP server add through while enforced', () => {
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
name: 'remote-server',
config: { type: 'remote', url: 'https://example.com/mcp' },
}))
expect(decision).toEqual({ kind: 'passthrough' })
})
it('rejects malformed or non-object MCP add bodies while enforced', () => {
const invalidJson = decideSandboxMcpAddBody(true, 'POST', '/mcp', '{not json')
expect(invalidJson.kind).toBe('reject')
if (invalidJson.kind === 'reject') {
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
}
const arrayBody = decideSandboxMcpAddBody(true, 'POST', '/mcp', '[]')
expect(arrayBody.kind).toBe('reject')
})
it('dispatches MCP adds before config mutations and leaves other bodies untouched', () => {
expect(decideSandboxMutationBody(true, 'POST', '/mcp', JSON.stringify({
name: 'evil',
config: { type: 'local', command: ['node', 'server.js'] },
})).kind).toBe('reject')
expect(decideSandboxMutationBody(true, 'POST', '/mcp', JSON.stringify({
name: 'remote-server',
config: { type: 'remote', url: 'https://example.com/mcp' },
}))).toEqual({ kind: 'passthrough' })
expect(decideSandboxMutationBody(true, 'PATCH', '/config', JSON.stringify({ theme: 'dark' }))).toEqual({
kind: 'sanitized',
body: JSON.stringify({ theme: 'dark' }),
})
expect(decideSandboxMutationBody(true, 'POST', '/session/s1/message', '{}')).toEqual({ kind: 'passthrough' })
})
it('strips custom provider npm selectors from an enforced config mutation while keeping built-in providers', () => {
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
model: 'x',
provider: {
'openai-native': { options: { apiKey: 'k' } },
evil: { npm: 'file:///repo/evil-provider.js', options: { token: 't' } },
remote: { npm: '@scope/remote-provider', models: { 'm-1': { name: 'M1' } } },
},
}))
expect(decision.kind).toBe('sanitized')
if (decision.kind === 'sanitized') {
const body = JSON.parse(decision.body) as Record<string, unknown>
expect(body.model).toBe('x')
expect(body.provider).toEqual({ 'openai-native': { options: { apiKey: 'k' } } })
}
})
it('classifies only enforced PUT /auth/{provider} as an auth write', () => {
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai')).toBe(true)
expect(isSandboxAuthWrite(true, 'PUT', '/auth/%6fpenai')).toBe(true)
expect(isSandboxAuthWrite(true, 'POST', '/auth/openai')).toBe(false)
expect(isSandboxAuthWrite(true, 'DELETE', '/auth/openai')).toBe(false)
expect(isSandboxAuthWrite(true, 'GET', '/auth/openai')).toBe(false)
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai/extra')).toBe(false)
expect(isSandboxAuthWrite(false, 'PUT', '/auth/openai')).toBe(false)
})
it('passes non-auth-write bodies through untouched', () => {
expect(decideSandboxAuthBody(true, 'GET', '/auth/openai', '')).toEqual({ kind: 'passthrough' })
expect(decideSandboxAuthBody(true, 'DELETE', '/auth/openai', '{}')).toEqual({ kind: 'passthrough' })
expect(decideSandboxAuthBody(true, 'PUT', '/config', '{}')).toEqual({ kind: 'passthrough' })
expect(decideSandboxAuthBody(false, 'PUT', '/auth/openai', '{}')).toEqual({ kind: 'passthrough' })
})
it('rejects a well-known auth write while enforced', () => {
const decision = decideSandboxAuthBody(true, 'PUT', '/auth/sso.example.com', JSON.stringify({
type: 'wellknown',
key: 'SSO_TOKEN',
token: 't',
}))
expect(decision.kind).toBe('reject')
if (decision.kind === 'reject') {
expect(decision.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
expect(decision.reason).toContain('well-known')
}
})
it('rejects a malformed or non-object auth write body while enforced', () => {
const invalidJson = decideSandboxAuthBody(true, 'PUT', '/auth/openai', '{not json')
expect(invalidJson.kind).toBe('reject')
if (invalidJson.kind === 'reject') {
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
}
const arrayBody = decideSandboxAuthBody(true, 'PUT', '/auth/openai', '[]')
expect(arrayBody.kind).toBe('reject')
})
it('passes api and oauth auth writes through while enforced', () => {
const api = decideSandboxAuthBody(true, 'PUT', '/auth/anthropic', JSON.stringify({
type: 'api',
key: 'sk-test',
}))
expect(api).toEqual({ kind: 'passthrough' })
const oauth = decideSandboxAuthBody(true, 'PUT', '/auth/github', JSON.stringify({
type: 'oauth',
access: 'a',
refresh: 'r',
expires: 1,
}))
expect(oauth).toEqual({ kind: 'passthrough' })
})
it('dispatches auth writes before config mutations in the combined body decision', () => {
expect(decideSandboxMutationBody(true, 'PUT', '/auth/evil', JSON.stringify({
type: 'wellknown',
key: 'K',
token: 't',
})).kind).toBe('reject')
expect(decideSandboxMutationBody(true, 'PUT', '/auth/openai', JSON.stringify({
type: 'api',
key: 'k',
}))).toEqual({ kind: 'passthrough' })
})
})
@@ -0,0 +1,196 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { accessSync, realpathSync, statSync } from 'fs'
import { spawnSync } from 'child_process'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { detectSandboxCapability, resetSandboxCapabilityCache } from '../../../src/services/sandbox/capability'
import { logger } from '../../../src/utils/logger'
vi.mock('fs', () => ({
accessSync: vi.fn(),
realpathSync: vi.fn((candidate: string) => candidate),
statSync: vi.fn(() => ({ uid: 0, gid: 0, mode: 0o755 })),
constants: {
R_OK: 4,
W_OK: 2,
X_OK: 1,
},
}))
vi.mock('child_process', () => ({
spawnSync: vi.fn(),
}))
vi.mock('../../../src/utils/logger', () => ({
logger: {
info: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}))
const mockAccessSync = accessSync as unknown as ReturnType<typeof vi.fn>
const mockSpawnSync = spawnSync as unknown as ReturnType<typeof vi.fn>
const mockRealpathSync = realpathSync as unknown as ReturnType<typeof vi.fn>
const mockStatSync = statSync as unknown as ReturnType<typeof vi.fn>
describe('detectSandboxCapability', () => {
beforeEach(() => {
vi.resetAllMocks()
mockRealpathSync.mockImplementation((candidate: string) => candidate)
mockStatSync.mockReturnValue({ uid: 0, gid: 0, mode: 0o755 })
resetSandboxCapabilityCache()
})
afterEach(() => {
resetSandboxCapabilityCache()
})
it('reports unavailable when /dev/kvm is not accessible or writable', () => {
mockAccessSync.mockImplementation(() => {
throw new Error('ENOENT')
})
const result = detectSandboxCapability()
expect(result.available).toBe(false)
expect(result.reason).toContain('/dev/kvm')
expect(mockSpawnSync).not.toHaveBeenCalled()
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('/dev/kvm'))
})
it('reports unavailable when msb --version exits with a non-zero status', () => {
mockAccessSync.mockImplementation(() => {})
mockSpawnSync.mockReturnValue({ status: 1, stdout: '', stderr: 'msb: not found' })
const result = detectSandboxCapability()
expect(result.available).toBe(false)
expect(result.reason).toBe('msb CLI not found or not executable')
})
it('reports unavailable when msb --version fails to spawn', () => {
mockAccessSync.mockImplementation(() => {})
mockSpawnSync.mockReturnValue({ status: null, stdout: '', stderr: '', error: new Error('spawn ENOENT') })
const result = detectSandboxCapability()
expect(result.available).toBe(false)
expect(result.reason).toBe('msb CLI not found or not executable')
})
it('reports available with the trimmed msb version when both probes succeed', () => {
mockAccessSync.mockImplementation(() => {})
mockSpawnSync.mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
const result = detectSandboxCapability()
expect(result).toEqual({ available: true, msbVersion: 'msb 0.3.1' })
})
it('reports unavailable when an explicit exec user uid does not match the manager uid', async () => {
process.env.SANDBOX_EXEC_USER = '2000'
try {
vi.resetModules()
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
'../../../src/services/sandbox/capability'
)
const { logger } = await import('../../../src/utils/logger')
const { spawnSync } = await import('child_process')
const { accessSync } = await import('fs')
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation(() => {})
const proc = process as unknown as { getuid: () => number; getgid: () => number }
const getuid = vi.spyOn(proc, 'getuid').mockReturnValue(1000)
const getgid = vi.spyOn(proc, 'getgid').mockReturnValue(1000)
resetSandboxCapabilityCache()
const result = detectSandboxCapability()
expect(result.available).toBe(false)
expect(result.reason).toContain('SANDBOX_EXEC_USER')
expect(result.reason).toContain('1000')
expect(spawnSync).not.toHaveBeenCalled()
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('SANDBOX_EXEC_USER'))
expect(getuid).toHaveBeenCalled()
expect(getgid).toHaveBeenCalled()
} finally {
delete process.env.SANDBOX_EXEC_USER
vi.restoreAllMocks()
}
})
it('memoizes the probe result until the cache is reset', () => {
mockAccessSync.mockImplementation(() => {})
mockSpawnSync.mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
const first = detectSandboxCapability()
const second = detectSandboxCapability()
expect(mockSpawnSync).toHaveBeenCalledTimes(1)
expect(second).toBe(first)
resetSandboxCapabilityCache()
const third = detectSandboxCapability()
expect(mockSpawnSync).toHaveBeenCalledTimes(2)
expect(third).toEqual(first)
})
it('resolves a relative MSB_PATH against PATH to one absolute executable before probing the version', async () => {
const { mkdtempSync, writeFileSync, rmSync } = await vi.importActual<typeof import('fs')>('fs')
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-bin-'))
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
const originalPath = process.env.PATH
process.env.PATH = fakeBin
try {
vi.resetModules()
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
'../../../src/services/sandbox/capability'
)
const { spawnSync } = await import('child_process')
const { accessSync } = await import('fs')
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation(() => {})
;(spawnSync as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
resetSandboxCapabilityCache()
const result = detectSandboxCapability()
expect(result.available).toBe(true)
expect(spawnSync).toHaveBeenCalledWith(
path.join(fakeBin, 'msb'),
['--version'],
expect.objectContaining({ encoding: 'utf8' }),
)
} finally {
process.env.PATH = originalPath
rmSync(fakeBin, { recursive: true, force: true })
}
})
it('reports unavailable when a relative MSB_PATH cannot be resolved on PATH', async () => {
const originalPath = process.env.PATH
process.env.PATH = '/nonexistent-ocm-bin'
try {
vi.resetModules()
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
'../../../src/services/sandbox/capability'
)
const { spawnSync } = await import('child_process')
const { accessSync } = await import('fs')
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation((target: string) => {
if (target === '/dev/kvm') return
throw new Error('ENOENT')
})
;(spawnSync as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
resetSandboxCapabilityCache()
const result = detectSandboxCapability()
expect(result.available).toBe(false)
expect(result.reason).toBe('msb CLI not found or not executable')
expect(spawnSync).not.toHaveBeenCalled()
} finally {
process.env.PATH = originalPath
}
})
})
@@ -0,0 +1,616 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { spawnSync } from 'child_process'
import { mkdirSync, mkdtempSync, readFileSync, 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'
import {
WORKSPACE_SANDBOX_NAME,
SANDBOX_UNAVAILABLE_PREFIX,
buildBlockedCommand,
buildCanonicalSandboxSpec,
buildSandboxCreateArgs,
buildSandboxInspectArgs,
buildSandboxListArgs,
buildSandboxRemoveArgs,
buildSandboxStartArgs,
buildSandboxStopManagedArgs,
buildSandboxVersionArgs,
quoteForShell,
resolveExpectedSandboxNetworkPolicy,
resolveSandboxExecUser,
resolveSandboxExecUserUid,
sandboxMountRoots,
sandboxNetworkPolicyMismatch,
sandboxSecretMaskPath,
} from '../../../src/services/sandbox/command'
afterEach(() => {
vi.restoreAllMocks()
})
describe('sandbox command builders', () => {
it('builds the version probe as exactly --version', () => {
expect(buildSandboxVersionArgs()).toEqual(['--version'])
})
it('builds inspect args targeting the shared workspace sandbox with JSON output', () => {
expect(buildSandboxInspectArgs()).toEqual(['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json'])
})
it('builds remove args that force-remove the shared workspace sandbox', () => {
expect(buildSandboxRemoveArgs()).toEqual(['rm', '--force', WORKSPACE_SANDBOX_NAME])
})
it('builds list args that emit machine-readable JSON for all sandboxes', () => {
expect(buildSandboxListArgs()).toEqual(['ls', '--format', 'json'])
})
it('builds start args targeting the shared workspace sandbox', () => {
expect(buildSandboxStartArgs()).toEqual(['start', WORKSPACE_SANDBOX_NAME])
})
it('builds managed-stop args that filter by the ocm.managed label', () => {
expect(buildSandboxStopManagedArgs()).toEqual(['stop', '--label', 'ocm.managed=true'])
})
it('escapes embedded single quotes so values survive a shell round-trip', () => {
const value = "echo 'a'b'"
expect(quoteForShell(value)).toBe(`'echo '\\''a'\\''b'\\'''`)
const result = spawnSync('sh', ['-c', `printf '%s' ${quoteForShell(value)}`], { encoding: 'utf8' })
expect(result.status).toBe(0)
expect(result.stdout).toBe(value)
})
it('builds create args with exactly two identical-path bind mounts and the detached flag', () => {
const args = buildSandboxCreateArgs()
expect(args[0]).toBe('run')
expect(args).toContain('-d')
expect(args).toContain('--name')
expect(args[args.indexOf('--name') + 1]).toBe(WORKSPACE_SANDBOX_NAME)
expect(args[args.indexOf('-w') + 1]).toBe(getReposPath())
expect(args[args.indexOf('-u') + 1]).toBe(resolveSandboxExecUser())
const labelArgs: string[] = []
for (let i = 0; i < args.length; i++) {
const value = args[i + 1]
if (args[i] === '--label' && value !== undefined) {
labelArgs.push(value)
}
}
expect(labelArgs).toContain('ocm.managed=true')
expect(labelArgs).toContain(`ocm.net=${ENV.SANDBOX.NET}`)
const mountArgs: string[] = []
for (let i = 0; i < args.length; i++) {
const value = args[i + 1]
if (args[i] === '--mount-dir' && value !== undefined) {
mountArgs.push(value)
}
}
expect(mountArgs).toEqual(sandboxMountRoots().map((root) => `${root}:${root}`))
expect(mountArgs[0]).toBe(`${getReposPath()}:${getReposPath()}`)
expect(mountArgs[1]).toBe(`${getScheduleWorktreesPath()}:${getScheduleWorktreesPath()}`)
})
it('masks the assistant .opencode directory with a tmpfs overlay', () => {
const args = buildSandboxCreateArgs()
expect(args[args.indexOf('--tmpfs') + 1]).toBe(getAssistantOpenCodeDir())
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
})
it('never mounts the SSH/config/state workspace directories', () => {
const joined = buildSandboxCreateArgs().join(' ')
const workspacePath = path.dirname(getReposPath())
expect(joined).not.toContain(`${workspacePath}/.config`)
expect(joined).not.toContain(`${workspacePath}/config`)
expect(joined).not.toContain('auth.json')
expect(joined).not.toContain(`${workspacePath}/.opencode`)
expect(joined).not.toContain('/.opencode/state')
})
it('derives a canonical spec from the create args matching the security configuration', () => {
const spec = buildCanonicalSandboxSpec()
const labels = spec.labels as Record<string, string>
const resources = spec.resources as Record<string, number>
const runtime = spec.runtime as Record<string, unknown>
const mounts = spec.mounts as Array<Record<string, unknown>>
const network = spec.network as Record<string, unknown>
const lifecycle = spec.lifecycle as Record<string, unknown>
expect(spec.name).toBe(WORKSPACE_SANDBOX_NAME)
const canonicalImage = spec.image as Record<string, { reference: string } | undefined>
expect(canonicalImage.Oci?.reference).toBe(ENV.SANDBOX.IMAGE)
expect(labels['ocm.managed']).toBe('true')
expect(labels['ocm.net']).toBe(ENV.SANDBOX.NET)
expect(resources.cpus).toBe(ENV.SANDBOX.CPUS)
expect(typeof resources.memory_mib).toBe('number')
expect(runtime.workdir).toBe(getReposPath())
expect(runtime.user).toBe(resolveSandboxExecUser())
expect(runtime.cmd).toEqual(['sleep', 'infinity'])
expect(runtime.entrypoint).toBeNull()
expect(spec.patches).toEqual([])
expect(network.enabled).toBe(true)
expect(network.ports).toEqual([])
expect(lifecycle.ephemeral).toBe(false)
expect(lifecycle.max_duration_secs).toBeNull()
expect(lifecycle.idle_timeout_secs).toBeNull()
const binds = mounts.filter((mount) => mount.type === 'Bind')
expect(binds).toHaveLength(2)
expect(binds.map((mount) => mount.host)).toEqual([getReposPath(), getScheduleWorktreesPath()])
for (const mount of binds) {
expect(mount.guest).toBe(mount.host)
const options = mount.options as Record<string, boolean>
expect(options.readonly).toBe(false)
expect(options.noexec).toBe(false)
expect(options.nosuid).toBe(false)
expect(options.nodev).toBe(false)
expect(mount.stat_virtualization).toBe('strict')
expect(mount.host_permissions).toBe('private')
expect(mount.follow_root_symlinks).toBe(false)
expect(mount.quota_mib).toBeNull()
}
const tmpfs = mounts.find((mount) => mount.type === 'Tmpfs')
expect(tmpfs?.guest).toBe(getAssistantOpenCodeDir())
expect((tmpfs as Record<string, unknown>).size_mib).toBeNull()
})
it('accepts real repo dirs and schedule worktrees while rejecting config, missing, and unrelated paths', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-roots-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const schedules = path.join(tmp, 'schedule-worktrees')
mkdirSync(path.join(repos, 'org', 'repo', 'subdir'), { recursive: true })
mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true })
mkdirSync(path.join(tmp, '.config', 'opencode'), { recursive: true })
process.env.WORKSPACE_PATH = tmp
const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command')
await expect(resolveSandboxWorkDirectory(repos)).resolves.toBe(repos)
await expect(resolveSandboxWorkDirectory(path.join(repos, 'org', 'repo', 'subdir'))).resolves.toBe(
path.join(repos, 'org', 'repo', 'subdir'),
)
await expect(resolveSandboxWorkDirectory(path.join(schedules, 'job-1-run-2'))).resolves.toBe(
path.join(schedules, 'job-1-run-2'),
)
await expect(resolveSandboxWorkDirectory(path.join(repos, '..', '.config', 'opencode'))).resolves.toBeNull()
await expect(resolveSandboxWorkDirectory(`${repos}-extra`)).resolves.toBeNull()
await expect(resolveSandboxWorkDirectory(path.join(repos, 'missing'))).resolves.toBeNull()
await expect(resolveSandboxWorkDirectory('/etc')).resolves.toBeNull()
} finally {
if (originalWorkspacePath === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = originalWorkspacePath
}
rmSync(tmp, { recursive: true, force: true })
}
})
it('returns canonical guest paths for symlinks inside the roots and null for escapes', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-escape-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
try {
const repos = path.join(tmp, 'repos')
const schedules = path.join(tmp, 'schedule-worktrees')
mkdirSync(path.join(tmp, 'outside'), { recursive: true })
mkdirSync(path.join(repos, 'repo'), { recursive: true })
mkdirSync(path.join(repos, 'other-repo'), { recursive: true })
mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true })
symlinkSync(path.join(tmp, 'outside'), path.join(repos, 'repo', 'escape'))
symlinkSync(path.join(repos, 'other-repo'), path.join(repos, 'repo', 'inside-link'))
symlinkSync(path.join(schedules, 'job-1-run-2'), path.join(repos, 'repo', 'cross-root-link'))
process.env.WORKSPACE_PATH = tmp
const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command')
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo'))).resolves.toBe(path.join(repos, 'repo'))
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape'))).resolves.toBeNull()
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape', 'nested'))).resolves.toBeNull()
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'inside-link'))).resolves.toBe(
path.join(repos, 'other-repo'),
)
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'cross-root-link'))).resolves.toBe(
path.join(schedules, 'job-1-run-2'),
)
} finally {
if (originalWorkspacePath === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = originalWorkspacePath
}
rmSync(tmp, { recursive: true, force: true })
}
})
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)
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
expect(resolveSandboxExecUser()).toBe('1001:1002')
expect(resolveSandboxExecUserUid()).toBe(1001)
})
it('aligns a numeric exec user with the manager gid', async () => {
const proc = process as unknown as { getuid: () => number; getgid: () => number }
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
process.env.SANDBOX_EXEC_USER = '1001'
try {
vi.resetModules()
const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command')
expect(resolveSandboxExecUser()).toBe('1001:1002')
} finally {
delete process.env.SANDBOX_EXEC_USER
}
})
it('keeps an explicit uid:gid exec user verbatim', async () => {
process.env.SANDBOX_EXEC_USER = '1000:1000'
try {
vi.resetModules()
const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command')
expect(resolveSandboxExecUser()).toBe('1000:1000')
} finally {
delete process.env.SANDBOX_EXEC_USER
}
})
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}`
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 () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-resolve-'))
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
const originalPath = process.env.PATH
process.env.PATH = fakeBin
try {
vi.resetModules()
const mod = await import('../../../src/services/sandbox/command')
mod.overrideSandboxExecutableTrustValidator(() => true)
const { resolveSandboxExecutable, sandboxExecutablePath } = mod
expect(resolveSandboxExecutable()).toBe(path.join(fakeBin, 'msb'))
expect(sandboxExecutablePath()).toBe(path.join(fakeBin, 'msb'))
} finally {
process.env.PATH = originalPath
rmSync(fakeBin, { recursive: true, force: true })
}
})
it('returns null when a relative MSB_PATH has no executable candidate on PATH', async () => {
const originalPath = process.env.PATH
process.env.PATH = '/nonexistent-ocm-bin'
try {
vi.resetModules()
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
expect(resolveSandboxExecutable()).toBeNull()
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
} finally {
process.env.PATH = originalPath
}
})
it('returns an absolute MSB_PATH verbatim without consulting PATH', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-abs-'))
const msbPath = path.join(fakeBin, 'my msb')
writeFileSync(msbPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
process.env.MSB_PATH = msbPath
try {
vi.resetModules()
const mod = await import('../../../src/services/sandbox/command')
mod.overrideSandboxExecutableTrustValidator(() => true)
const { resolveSandboxExecutable, sandboxExecutablePath } = mod
expect(resolveSandboxExecutable()).toBe(msbPath)
expect(sandboxExecutablePath()).toBe(msbPath)
} finally {
delete process.env.MSB_PATH
rmSync(fakeBin, { recursive: true, force: true })
}
})
it('rejects an msb executable located inside a mounted project root', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-mount-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
const originalPath = process.env.PATH
try {
const repos = path.join(tmp, 'workspace', 'repos')
mkdirSync(path.join(repos, 'bin'), { recursive: true })
writeFileSync(path.join(repos, 'bin', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
process.env.PATH = path.join(repos, 'bin')
vi.resetModules()
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
expect(resolveSandboxExecutable()).toBeNull()
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
} finally {
if (originalWorkspacePath === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = originalWorkspacePath
}
process.env.PATH = originalPath
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects an msb executable whose symlink resolves into a mounted project root', async () => {
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-symlink-'))
const originalWorkspacePath = process.env.WORKSPACE_PATH
const originalPath = process.env.PATH
try {
const repos = path.join(tmp, 'workspace', 'repos')
const bin = path.join(tmp, 'bin')
mkdirSync(path.join(repos, 'evil'), { recursive: true })
mkdirSync(bin)
writeFileSync(path.join(repos, 'evil', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
symlinkSync(path.join(repos, 'evil', 'msb'), path.join(bin, 'msb'))
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
process.env.PATH = bin
vi.resetModules()
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
expect(resolveSandboxExecutable()).toBeNull()
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
} finally {
if (originalWorkspacePath === undefined) {
delete process.env.WORKSPACE_PATH
} else {
process.env.WORKSPACE_PATH = originalWorkspacePath
}
process.env.PATH = originalPath
rmSync(tmp, { recursive: true, force: true })
}
})
it('rejects an msb executable writable by the manager user or a parent directory', async () => {
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-writable-'))
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
const originalPath = process.env.PATH
process.env.PATH = fakeBin
try {
vi.resetModules()
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
expect(resolveSandboxExecutable()).toBeNull()
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
} finally {
process.env.PATH = originalPath
rmSync(fakeBin, { recursive: true, force: true })
}
})
})
describe('sandbox network policy attestation helpers', () => {
const publicPolicy = {
default_egress: 'deny',
default_ingress: 'allow',
rules: [
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
],
}
it('resolves the public profile to the deny-by-default fixture policy', () => {
expect(resolveExpectedSandboxNetworkPolicy('public')).toEqual(publicPolicy)
})
it('composes comma-separated profiles with a single DNS rule in profile order', () => {
expect(resolveExpectedSandboxNetworkPolicy('public,private,host')).toEqual({
default_egress: 'deny',
default_ingress: 'allow',
rules: [
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
{ direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' },
{ direction: 'egress', destination: { group: 'host' }, protocols: [], ports: [], action: 'allow' },
],
})
})
it('deduplicates repeated profiles', () => {
expect(resolveExpectedSandboxNetworkPolicy('public, public')).toEqual(publicPolicy)
})
it('returns null for terminal, unknown, or empty profiles', () => {
expect(resolveExpectedSandboxNetworkPolicy('all')).toBeNull()
expect(resolveExpectedSandboxNetworkPolicy('none')).toBeNull()
expect(resolveExpectedSandboxNetworkPolicy('public,unknown')).toBeNull()
expect(resolveExpectedSandboxNetworkPolicy('')).toBeNull()
expect(resolveExpectedSandboxNetworkPolicy(' ')).toBeNull()
})
it('accepts the source-faithful public policy fixture', () => {
expect(sandboxNetworkPolicyMismatch(publicPolicy, resolveExpectedSandboxNetworkPolicy('public')!)).toBeNull()
})
it('rejects a policy with an allow-all wildcard rule', () => {
const inspected = {
...publicPolicy,
rules: [
publicPolicy.rules[0],
{ direction: 'egress', destination: { any: true }, protocols: [], ports: [], action: 'allow' },
],
}
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
})
it('rejects a policy whose profile rule is broadened to specific protocols and ports', () => {
const inspected = {
...publicPolicy,
rules: [
publicPolicy.rules[0],
{ direction: 'egress', destination: { group: 'public' }, protocols: ['tcp'], ports: [443], action: 'allow' },
],
}
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
})
it('rejects a policy carrying stale rules from another profile', () => {
const inspected = {
...publicPolicy,
rules: [
...publicPolicy.rules,
{ direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' },
],
}
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
})
it('rejects a policy missing a required rule', () => {
const inspected = {
...publicPolicy,
rules: [publicPolicy.rules[0]],
}
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
})
it('rejects an allow egress default with an unrestricted-egress reason', () => {
const inspected = { default_egress: 'allow', default_ingress: 'allow', rules: [] }
const mismatch = sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)
expect(mismatch).toContain('unrestricted egress')
})
it('rejects an altered ingress default', () => {
const inspected = { ...publicPolicy, default_ingress: 'deny' }
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('default_ingress')
})
it('rejects a missing or malformed policy', () => {
const expected = resolveExpectedSandboxNetworkPolicy('public')!
expect(sandboxNetworkPolicyMismatch(undefined, expected)).toContain('missing or malformed')
expect(sandboxNetworkPolicyMismatch({ default_egress: 'deny' }, expected)).toContain('missing or malformed')
expect(sandboxNetworkPolicyMismatch({ ...publicPolicy, rules: 'not-an-array' }, expected)).toContain('missing or malformed')
expect(sandboxNetworkPolicyMismatch(
{ ...publicPolicy, rules: [{ direction: 'egress', destination: { group: 'dns' }, action: 'allow' }] },
expected,
)).toContain('network policy')
})
})
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DEFAULT_USER_PREFERENCES, UserPreferencesSchema } from '@opencode-manager/shared/schemas'
describe('sandbox config', () => {
afterEach(() => {
delete process.env.SANDBOX_IMAGE
})
it('defaults sandbox.enabled to false in the persisted preference contract', () => {
const prefs = UserPreferencesSchema.parse(DEFAULT_USER_PREFERENCES)
expect(prefs.sandbox?.enabled).toBe(false)
})
it('round-trips sandbox.enabled when set to true', () => {
const prefs = UserPreferencesSchema.parse({
...DEFAULT_USER_PREFERENCES,
sandbox: { enabled: true },
})
expect(prefs.sandbox).toEqual({ enabled: true })
})
it('falls back ENV.SANDBOX.IMAGE to the default when SANDBOX_IMAGE is unset', async () => {
delete process.env.SANDBOX_IMAGE
vi.resetModules()
const { ENV } = await import('@opencode-manager/shared/config/env')
const { DEFAULTS } = await import('@opencode-manager/shared/config/defaults')
expect(ENV.SANDBOX.IMAGE).toBe(DEFAULTS.SANDBOX.IMAGE)
})
it('honors SANDBOX_IMAGE when set before module import', async () => {
process.env.SANDBOX_IMAGE = 'node:22-alpine'
vi.resetModules()
const { ENV } = await import('@opencode-manager/shared/config/env')
expect(ENV.SANDBOX.IMAGE).toBe('node:22-alpine')
})
})
File diff suppressed because it is too large. Load diff
+125 -2
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'
import { execSync } from 'child_process'
import { mkdtempSync, existsSync, mkdirSync, writeFileSync } from 'fs'
import { mkdtempSync, existsSync, mkdirSync, writeFileSync, symlinkSync, unlinkSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import path from 'path'
import { rm } from 'fs/promises'
@@ -20,6 +20,14 @@ vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
}
})
const opencodeServerManagerMock = vi.hoisted(() => ({
isSandboxEnforced: vi.fn(),
}))
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: opencodeServerManagerMock,
}))
describe('buildRepoEnvForRepo', () => {
it('includes OCM_GIT_REPO_ID and OCM_GIT_REPO_CWD when id is provided', async () => {
const { buildRepoEnvForRepo } = await import('../../src/services/schedule-worktree')
@@ -85,6 +93,10 @@ describe('ScheduleWorktreeManager', () => {
authenticateMcp: vi.fn(),
}
beforeEach(() => {
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(false)
})
beforeAll(() => {
tmpDir = mkdtempSync(path.join(tmpdir(), 'schedule-worktree-test-'))
tmpRoot = tmpDir
@@ -335,6 +347,7 @@ describe('ScheduleWorktreeManager', () => {
branch: null,
})
mockOpenCodeClient.postJson = mockPost
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
const manager = await createManager()
const repo = testRepo()
@@ -366,6 +379,116 @@ describe('ScheduleWorktreeManager', () => {
await cleanup()
})
it('prepare falls back to raw git when the workspace directory is outside the sandboxed project roots', async () => {
const workspaceId = 'ws-outside-456'
const outsideDirectory = path.join(path.dirname(tmpDir), 'ocm-outside-workspace')
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
id: workspaceId,
directory: outsideDirectory,
branch: null,
})
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
mockOpenCodeClient.forward = deleteMock
const manager = await createManager()
const repo = testRepo()
const job = { id: 31, branch: null }
const runId = 6
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBeNull()
expect(ctx!.worktreePath).toBe(path.join(scheduleWorktreesRoot, 'job-31-run-6'))
expect(existsSync(ctx!.worktreePath)).toBe(true)
expect(deleteMock).toHaveBeenCalledWith(
expect.objectContaining({
method: 'DELETE',
path: `/experimental/workspace/${workspaceId}`,
}),
)
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, ctx!.worktreePath)
})
it('uses an OpenCode workspace outside the mount roots as-is when sandboxing is not enforced', async () => {
const outsideDirectory = path.join(path.dirname(tmpDir), 'ocm-off-workspace')
const workspaceId = 'ws-off-123'
execSync(`git -C "${baseRepoPath}" worktree add --detach "${outsideDirectory}" origin/main`, { env })
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
id: workspaceId,
directory: outsideDirectory,
branch: null,
})
const manager = await createManager()
const repo = testRepo()
const job = { id: 32, branch: null }
const runId = 1
try {
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBe(workspaceId)
expect(ctx!.directory).toBe(outsideDirectory)
const branch = execSync(`git -C "${outsideDirectory}" rev-parse --abbrev-ref HEAD`, {
encoding: 'utf-8',
}).trim()
expect(branch).toBe('schedule/32/run-1')
} finally {
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, outsideDirectory).catch(() => {})
}
})
it('falls back to raw git when an enforced workspace directory is a symlink escaping the project roots', async () => {
const escapeTarget = path.join(path.dirname(tmpDir), 'ocm-escape-target')
const escapeLink = path.join(tmpDir, 'ocm-escape-link')
mkdirSync(escapeTarget, { recursive: true })
symlinkSync(escapeTarget, escapeLink)
const workspaceId = 'ws-escape-999'
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
id: workspaceId,
directory: escapeLink,
branch: null,
})
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
mockOpenCodeClient.forward = deleteMock
const manager = await createManager()
const repo = testRepo()
const job = { id: 33, branch: null }
const runId = 1
try {
const ctx = await manager.prepare(repo, job, runId)
expect(ctx).not.toBeNull()
expect(ctx!.workspaceId).toBeNull()
expect(ctx!.worktreePath).toBe(path.join(scheduleWorktreesRoot, 'job-33-run-1'))
expect(existsSync(ctx!.worktreePath)).toBe(true)
expect(deleteMock).toHaveBeenCalledWith(
expect.objectContaining({
method: 'DELETE',
path: `/experimental/workspace/${workspaceId}`,
}),
)
} finally {
unlinkSync(escapeLink)
rmSync(escapeTarget, { recursive: true, force: true })
const { removeWorktree } = await import('../../src/services/repo')
await removeWorktree(baseRepoPath, path.join(scheduleWorktreesRoot, 'job-33-run-1')).catch(() => {})
}
})
it('prepare falls back to raw git when postJson rejects', async () => {
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('API unavailable'))