fix(sandbox): harden enforcement validation and backup handling

This commit is contained in:
Chris Scott committed 2026-08-20 11:10:59 -04:00
1 parent f315dda3f3
commit 0481160f5e
13 files changed
+180 -101

No files matched your search

+20 -16
View File
@@ -323,23 +323,27 @@ app.get('/', async (c) => {
return c.json({ error: 'Failed to create workspace' }, 500)
}
const workspaceRecord = workspace as { id?: unknown; directory?: unknown } | null
if (
workspaceRecord &&
typeof workspaceRecord.directory === 'string' &&
opencodeServerManager.isSandboxEnforced() &&
(await resolveSandboxWorkDirectory(workspaceRecord.directory)) === null
) {
if (typeof workspaceRecord.id === 'string' && workspaceRecord.id.length > 0) {
await openCodeClient.forward({
method: 'DELETE',
path: `/experimental/workspace/${encodeURIComponent(workspaceRecord.id)}`,
directory: repo.fullPath,
}).catch(() => {})
const workspaceRecord = workspace && typeof workspace === 'object'
? workspace as { id?: unknown; directory?: unknown }
: null
if (opencodeServerManager.isSandboxEnforced()) {
const directoryAllowed =
typeof workspaceRecord?.directory === 'string' &&
(await resolveSandboxWorkDirectory(workspaceRecord.directory)) !== null
if (!directoryAllowed) {
if (typeof workspaceRecord?.id === 'string' && workspaceRecord.id.length > 0) {
await openCodeClient.forward({
method: 'DELETE',
path: `/experimental/workspace/${encodeURIComponent(workspaceRecord.id)}`,
directory: repo.fullPath,
}).catch(() => {})
} else {
logger.warn(`Rejected an OpenCode workspace for repo ${id} that could not be validated against the sandbox roots; it reported no usable id, so it may need manual cleanup`)
}
return c.json({
error: 'OpenCode worktrees are not available while sandboxing is enabled because they are created outside the sandboxed project roots',
}, 400)
}
return c.json({
error: 'OpenCode worktrees are not available while sandboxing is enabled because they are created outside the sandboxed project roots',
}, 400)
}
return c.json(workspace)
@@ -376,13 +376,11 @@ async function readPluginConfigBackup(backupPath: string): Promise<PluginConfigB
return null
}
function backupRemovedSections(backup: PluginConfigBackup | null): EnforcementRemovedSections {
if (backup !== null && backup.removedSections !== undefined && isRecord(backup.removedSections)) {
function backupRemovedSections(backup: PluginConfigBackup): EnforcementRemovedSections {
if (isRecord(backup.removedSections)) {
return backup.removedSections as EnforcementRemovedSections
}
const legacyPlugins = backup !== null && Array.isArray(backup.originalPlugins)
? backup.originalPlugins
: backup?.plugin
const legacyPlugins = Array.isArray(backup.originalPlugins) ? backup.originalPlugins : backup.plugin
return Array.isArray(legacyPlugins) ? { plugin: legacyPlugins } : {}
}
@@ -509,13 +507,14 @@ async function sanitizeEnforcementConfigSections(configPath: string): Promise<vo
let effectiveRemoved = removed
if (hasBackup) {
const backup = await readPluginConfigBackup(backupPath)
if (backup !== null) {
const priorRemoved = backupRemovedSections(backup)
if (backup.sanitizedConfig !== undefined && deepEqual(backup.sanitizedConfig, config)) {
effectiveRemoved = priorRemoved
} else {
effectiveRemoved = reconcileRemovedSections(priorRemoved, removed)
}
if (backup === null) {
throw new Error(`cannot read OpenCode enforcement backup ${backupPath}; refusing to overwrite it because the config sections it holds would be lost`)
}
const priorRemoved = backupRemovedSections(backup)
if (backup.sanitizedConfig !== undefined && deepEqual(backup.sanitizedConfig, config)) {
effectiveRemoved = priorRemoved
} else {
effectiveRemoved = reconcileRemovedSections(priorRemoved, removed)
}
}
-7
View File
@@ -68,13 +68,6 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
return { resumedSessionIDs: [] }
}
/**
* Restarts OpenCode for callers that have already persisted their change. A
* failed restart must not be reported as a failed write, so the failure is
* logged and returned as a flag instead of thrown; the caller returns the
* persisted entity so the client can distinguish "saved but needs a restart"
* from "nothing was saved".
*/
export async function restartOpenCodeAfterCommit(
supervisor?: OpenCodeSupervisor,
): Promise<{ restartFailed: boolean; restartError?: string }> {
+11 -29
View File
@@ -14,10 +14,10 @@ function guardCommand(reason) {
return "printf '%s\\\\n' '" + safe + "' >&2; exit 1"
}
function lockArgsReference(output, args) {
function lockAccessor(target, key, value) {
try {
Object.defineProperty(output, 'args', {
get: function () { return args },
Object.defineProperty(target, key, {
get: function () { return value },
set: function () {},
configurable: false,
enumerable: true,
@@ -25,29 +25,11 @@ function lockArgsReference(output, args) {
} catch (error) {
return false
}
var descriptor = Object.getOwnPropertyDescriptor(output, 'args')
return !!descriptor && descriptor.configurable === false && typeof descriptor.get === 'function'
}
function lockCommand(args, command) {
var current = null
try {
Object.defineProperty(args, 'command', {
get: function () { return command },
set: function () {},
configurable: false,
enumerable: true,
})
current = args.command
} catch (error) {
try {
args.command = command
current = args.command
} catch (ignored) {
current = null
}
}
return current === command
var descriptor = Object.getOwnPropertyDescriptor(target, key)
return !!descriptor
&& descriptor.configurable === false
&& typeof descriptor.get === 'function'
&& target[key] === value
}
var wrappedCommands = new Map()
@@ -64,10 +46,10 @@ function rememberWrapped(callID, command) {
}
function replaceCommand(output, command, callID) {
if (!lockArgsReference(output, output.args)) {
if (!lockAccessor(output, 'args', output.args)) {
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
}
if (!lockCommand(output.args, command)) {
if (!lockAccessor(output.args, 'command', command)) {
throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host')
}
rememberWrapped(callID, command)
@@ -79,7 +61,7 @@ export default async function ({ directory, worktree }) {
if (input.tool !== 'bash') return
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
if (typeof output.args?.command !== 'string') {
if (!lockArgsReference(output, output.args)) {
if (!lockAccessor(output, 'args', output.args)) {
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
}
return
@@ -1195,8 +1195,8 @@ class OpenCodeServerManager {
async fetchVersion(): Promise<string | null> {
try {
const executable = resolveOpenCodeExecutable() ?? 'opencode'
const result = execSync(`${executable} --version 2>&1`, { encoding: 'utf8' })
const match = result.match(/(\d+\.\d+\.\d+)/)
const result = spawnSync(executable, ['--version'], { encoding: 'utf8' })
const match = `${result.stdout ?? ''}${result.stderr ?? ''}`.match(/(\d+\.\d+\.\d+)/)
if (match && match[1]) {
this.version = match[1]
return this.version
@@ -48,9 +48,16 @@ export function sanitizeConfigForEnforcementResult(
return { sanitized, removed }
}
export function isProvablyRemoteMcpEntry(entry: unknown): boolean {
return isRecord(entry)
&& entry.type === 'remote'
&& typeof entry.url === 'string'
&& entry.command === undefined
&& entry.environment === undefined
}
export function isLocalMcpServerEntry(entry: unknown): boolean {
if (!isRecord(entry)) return false
return entry.type === 'local' || Array.isArray(entry.command)
return !isProvablyRemoteMcpEntry(entry)
}
export function isCustomProviderEntry(entry: unknown): boolean {
@@ -1,4 +1,4 @@
import { isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
import { isProvablyRemoteMcpEntry, isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
export type SandboxProxyDecision = { blocked: true; reason: string } | { blocked: false }
@@ -158,14 +158,7 @@ export function decideSandboxMcpAddBody(
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body must be a JSON object`,
}
}
const config = parsed.config
if (
!isRecord(config) ||
config.type !== 'remote' ||
typeof config.url !== 'string' ||
config.command !== undefined ||
config.environment !== undefined
) {
if (!isProvablyRemoteMcpEntry(parsed.config)) {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}only remote MCP servers can be added while enforcement is active`,
+14
View File
@@ -361,6 +361,20 @@ describe('Repo Routes', () => {
)
})
it('refuses a workspace whose directory cannot be validated while sandboxing is enforced', async () => {
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(true)
const forward = vi.fn(async () => new Response('', { status: 200 }))
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
const res = await app.request('/1/workspaces', { method: 'POST' })
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toContain('not available while sandboxing is enabled')
expect(forward).not.toHaveBeenCalledWith(expect.objectContaining({ method: 'DELETE' }))
})
it('allows workspace creation when sandboxing is not enforced', async () => {
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(false)
+41 -16
View File
@@ -16,13 +16,25 @@ const writeStub = (name: string, body: string) => {
chmodSync(file, 0o755)
}
const extractGrantKvmAccess = () => {
const extractShellFunction = (name: string) => {
const entrypoint = readFileSync(entrypointPath, 'utf-8')
const match = entrypoint.match(/^grant_kvm_access\(\) \{\n[\s\S]*?\n\}/m)
if (!match) throw new Error('grant_kvm_access() not found in docker-entrypoint.sh')
const match = entrypoint.match(new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?\\n\\}`, 'm'))
if (!match) throw new Error(`${name}() not found in docker-entrypoint.sh`)
return match[0]
}
const extractMinOpenCodeVersion = () => {
const match = readFileSync(entrypointPath, 'utf-8').match(/^MIN_OPENCODE_VERSION="[^"]+"$/m)
if (!match) throw new Error('MIN_OPENCODE_VERSION not found in docker-entrypoint.sh')
return match[0]
}
const installPrelude = () => [
extractMinOpenCodeVersion(),
extractShellFunction('version_gte'),
extractShellFunction('install_opencode'),
].join('\n')
beforeEach(() => {
stubDir = join(tmpdir(), `ocm-entrypoint-${Date.now()}-${Math.random().toString(36).slice(2)}`)
mkdirSync(stubDir, { recursive: true })
@@ -47,7 +59,7 @@ afterEach(() => {
const runScript = (snippet: string, env: Record<string, string> = {}) => {
const scriptPath = join(stubDir, 'test.sh')
writeFileSync(scriptPath, `set -e\n${extractGrantKvmAccess()}\n${snippet}\n`)
writeFileSync(scriptPath, `set -e\n${extractShellFunction('grant_kvm_access')}\n${snippet}\n`)
return spawnSync('bash', [scriptPath], {
encoding: 'utf-8',
env: {
@@ -147,13 +159,6 @@ describe('grant_kvm_access', () => {
})
})
const extractInstallOpencode = () => {
const entrypoint = readFileSync(entrypointPath, 'utf-8')
const match = entrypoint.match(/^install_opencode\(\) \{\n[\s\S]*?\n\}/m)
if (!match) throw new Error('install_opencode() not found in docker-entrypoint.sh')
return match[0]
}
const extractOpenCodeInstallSection = () => {
const entrypoint = readFileSync(entrypointPath, 'utf-8')
const startMarker = 'echo "Checking OpenCode installation..."'
@@ -198,7 +203,7 @@ const curlLog = () => stubCalls().filter((c) => c.startsWith('curl '))
describe('install_opencode', () => {
it('installs the bundled verified version, never latest', () => {
stubInstallTools()
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`)
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`)
expect(res.status).toBe(0)
const urls = curlLog().join(' ')
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
@@ -207,7 +212,7 @@ describe('install_opencode', () => {
it('refuses to guess the pinned build when OPENCODE_BUNDLED_VERSION is unset', () => {
stubInstallTools()
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`, {
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
OPENCODE_BUNDLED_VERSION: '',
})
expect(res.status).not.toBe(0)
@@ -215,9 +220,29 @@ describe('install_opencode', () => {
expect(curlLog()).toHaveLength(0)
})
it('refuses to download an OPENCODE_BUNDLED_VERSION below the supported minimum', () => {
stubInstallTools()
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
OPENCODE_BUNDLED_VERSION: '1.0.136',
})
expect(res.status).not.toBe(0)
expect(res.stderr).toContain('below the minimum supported')
expect(curlLog()).toHaveLength(0)
})
it('refuses to download a malformed OPENCODE_BUNDLED_VERSION', () => {
stubInstallTools()
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
OPENCODE_BUNDLED_VERSION: '1.18',
})
expect(res.status).not.toBe(0)
expect(res.stderr).toContain('is not an X.Y.Z version')
expect(curlLog()).toHaveLength(0)
})
it('honors an OPENCODE_BUNDLED_VERSION override for the download URL', () => {
stubInstallTools()
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`, {
const res = runOpenCodeSection(`${installPrelude()}\ninstall_opencode`, {
OPENCODE_BUNDLED_VERSION: '1.22.0',
})
expect(res.status).toBe(0)
@@ -228,7 +253,7 @@ describe('install_opencode', () => {
it('reinstalls the bundled verified version when opencode is missing', () => {
stubInstallTools()
const res = runOpenCodeSection(`${extractInstallOpencode()}\n${extractOpenCodeInstallSection()}`)
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
expect(res.status).toBe(0)
expect(res.stdout).toContain('OpenCode not found. Installing...')
const urls = curlLog().join(' ')
@@ -239,7 +264,7 @@ describe('install_opencode', () => {
it('repairs a below-minimum opencode with the bundled verified version, not latest', () => {
stubInstallTools()
writeStub('opencode', `echo "opencode version 1.0.0"`)
const res = runOpenCodeSection(`${extractInstallOpencode()}\n${extractOpenCodeInstallSection()}`)
const res = runOpenCodeSection(`${installPrelude()}\n${extractOpenCodeInstallSection()}`)
expect(res.status).toBe(0)
expect(res.stdout).toContain('below minimum required version')
const urls = curlLog().join(' ')
@@ -416,11 +416,12 @@ describe('opencode plugin quarantine', () => {
expect(backup.sanitizedConfig).toEqual({ model: 'x' })
})
it('strips local MCP servers and the formatter while keeping remote MCP servers', async () => {
it('strips every MCP server that is not provably remote along with the formatter', async () => {
writeConfig({
mcp: {
local: { type: 'local', command: ['npx', 'evil-server'] },
shorthand: { command: ['node', 'server.js'] },
stringCommand: { command: 'node server.js' },
remote: { type: 'remote', url: 'https://example.com/mcp' },
toggled: { enabled: false },
},
@@ -433,7 +434,6 @@ describe('opencode plugin quarantine', () => {
const sanitized = JSON.parse(await fs.readFile(configPath, 'utf-8')) as Record<string, unknown>
expect(sanitized.mcp).toEqual({
remote: { type: 'remote', url: 'https://example.com/mcp' },
toggled: { enabled: false },
})
expect(sanitized.formatter).toBeUndefined()
expect(sanitized.model).toBe('x')
@@ -444,6 +444,8 @@ describe('opencode plugin quarantine', () => {
mcp: {
local: { type: 'local', command: ['npx', 'evil-server'] },
shorthand: { command: ['node', 'server.js'] },
stringCommand: { command: 'node server.js' },
toggled: { enabled: false },
},
formatter: { typescript: { command: ['prettier', '--write'] } },
})
@@ -513,6 +515,22 @@ describe('opencode plugin quarantine', () => {
await expect(fs.access(`${configPath}.ocm-sandbox-backup`)).rejects.toThrow()
})
it('refuses to overwrite a corrupt backup so the sections it holds are never lost', async () => {
writeConfig({
mcp: { local: { type: 'local', command: ['npx', 'evil-server'] } },
formatter: { typescript: { command: ['prettier'] } },
model: 'x',
})
await quarantineOpenCodePlugins(configHome, configPath)
const backupPath = `${configPath}.ocm-sandbox-backup`
const corrupt = '{ "removedSections": '
writeFileSync(backupPath, corrupt)
await expect(quarantineOpenCodePlugins(configHome, configPath)).rejects.toThrow(/refusing to overwrite it/)
expect(await fs.readFile(backupPath, 'utf-8')).toBe(corrupt)
})
it('replaces a quarantined section with a newly supplied prohibited value while preserving other backed-up sections', async () => {
writeConfig({
mcp: { local: { type: 'local', command: ['npx', 'old-server'] } },
@@ -527,6 +527,31 @@ describe('ocm-sandbox plugin', () => {
expect(output.args.command).toBe('echo hi')
})
it('rejects an enforced bash call when the command property is non-configurable but writable', 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 args = {} as { command?: string }
Object.defineProperty(args, 'command', {
value: 'echo hi',
writable: true,
configurable: false,
enumerable: true,
})
const output = { args }
await expect(
hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'c' }, output),
).rejects.toThrow(/could not replace the bash command/)
expect(output.args.command).toBe('echo hi')
})
it('leaves the args reference replaceable when enforcement is off', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
@@ -138,6 +138,17 @@ const execSyncMock = execSync as any
const childSpawnSyncMock = spawnSync as any
const readdirSyncMock = readdirSync as any
const routeVersionProbeThroughExecSyncStub = () => {
childSpawnSyncMock.mockImplementation((file: string, args?: readonly string[]) => {
if (Array.isArray(args) && args[0] === '--version') {
return { status: 0, stdout: String(execSyncMock(`${file} --version`) ?? ''), stderr: '' }
}
return { status: 0, stdout: '', stderr: '' }
})
}
beforeEach(routeVersionProbeThroughExecSyncStub)
// Reset singleton before any tests run to clear any polluted state from previous test files
beforeAll(async () => {
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
+14 -6
View File
@@ -42,12 +42,26 @@ grant_kvm_access() {
echo "Granted node access to $dev (group '$group_name', gid $dev_gid)"
}
MIN_OPENCODE_VERSION="1.0.137"
version_gte() {
printf '%s\n%s\n' "$2" "$1" | sort -V -C
}
install_opencode() {
local opencode_version="${OPENCODE_BUNDLED_VERSION:-}"
if [ -z "$opencode_version" ]; then
echo "ERROR: OPENCODE_BUNDLED_VERSION is not set; refusing to guess the pinned OpenCode build" >&2
return 1
fi
if [[ ! "$opencode_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "ERROR: OPENCODE_BUNDLED_VERSION='$opencode_version' is not an X.Y.Z version; refusing to download it" >&2
return 1
fi
if ! version_gte "$opencode_version" "$MIN_OPENCODE_VERSION"; then
echo "ERROR: OPENCODE_BUNDLED_VERSION=$opencode_version is below the minimum supported $MIN_OPENCODE_VERSION; refusing to download it" >&2
return 1
fi
echo "Installing OpenCode ${opencode_version}..."
curl -fsSL "https://github.com/anomalyco/opencode/releases/download/v${opencode_version}/opencode-linux-$(uname -m | sed 's/x86_64/x64/; s/aarch64/arm64/').tar.gz" \
-o /tmp/opencode.tar.gz
@@ -77,12 +91,6 @@ fi
echo "Checking OpenCode installation..."
MIN_OPENCODE_VERSION="1.0.137"
version_gte() {
printf '%s\n%s\n' "$2" "$1" | sort -V -C
}
if ! command -v opencode >/dev/null 2>&1; then
echo "OpenCode not found. Installing..."
install_opencode