refactor(sandbox): remove OpenCode version allowlist gating under enforcement

This commit is contained in:
Chris Scott committed 2026-08-22 13:03:07 -04:00
1 parent 0215de9d92
commit aab80f9d65
17 files changed
+98 -524

No files matched your search

+2 -6
View File
@@ -16,19 +16,16 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve tool versions (opencode and microsandbox are intentionally pinned)
- name: Resolve tool versions (bundled OpenCode and microsandbox for reproducibility)
id: versions
run: |
# OPENCODE_VERSION is pinned, not detected: sandbox enforcement depends on the
# bash-tool hook contract, which is verified per build. It must stay in sync with
# SANDBOX_VERIFIED_OPENCODE_VERSIONS in backend/src/services/opencode-single-server.ts.
UV_VERSION=$(git ls-remote --tags --sort=-v:refname https://github.com/astral-sh/uv.git 'refs/tags/[0-9]*' | head -1 | sed 's/.*refs\/tags\///')
OPENCODE_VERSION=1.18.16
MICROSANDBOX_VERSION=0.6.8
echo "uv=${UV_VERSION}" >> $GITHUB_OUTPUT
echo "opencode=${OPENCODE_VERSION}" >> $GITHUB_OUTPUT
echo "microsandbox=${MICROSANDBOX_VERSION}" >> $GITHUB_OUTPUT
echo "Versions: uv=${UV_VERSION} (latest), opencode=${OPENCODE_VERSION} (pinned), microsandbox=${MICROSANDBOX_VERSION} (pinned)"
echo "Versions: uv=${UV_VERSION} (latest), opencode=${OPENCODE_VERSION} (bundled default), microsandbox=${MICROSANDBOX_VERSION} (pinned)"
- name: Docker meta
id: meta
@@ -70,4 +67,3 @@ jobs:
cache-to: type=gha,mode=max
target: runner
+1 -29
View File
@@ -28,9 +28,8 @@ import { logger } from '../utils/logger'
import {
discoverModelsCached,
} from '../utils/discovery-cache'
import { opencodeServerManager, ConfigReloadError, isSandboxVerifiedOpenCodeVersion, getSandboxVerifiedOpenCodeVersions } from '../services/opencode-single-server'
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
import { sanitizeConfigForEnforcementResult, type EnforcementRemovedSections } from '../services/opencode/enforcement-config'
import { isSandboxEnforcementActive } from '../services/sandbox/enforcement'
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
import { sseAggregator } from '../services/sse-aggregator'
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
@@ -989,19 +988,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
logger.info(`Current OpenCode version: ${oldVersion}`)
try {
if (isSandboxEnforcementActive(db)) {
const verified = getSandboxVerifiedOpenCodeVersions()
logger.warn('OpenCode upgrade blocked while sandbox enforcement is active')
return c.json({
success: false,
error: 'OpenCode upgrade is disabled while sandbox enforcement is active',
details: `Sandbox enforcement only accepts verified OpenCode builds (${verified.join(', ')}). Disable Agent Sandboxing in Settings and restart the OpenCode server before upgrading.`,
oldVersion,
newVersion: oldVersion,
upgraded: false,
}, 409)
}
const installMethod = getOpenCodeInstallMethod()
logger.info(`Running opencode upgrade --method ${installMethod} with 90s timeout...`)
const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade --method ${installMethod} 2>&1`, 90000)
@@ -1110,7 +1096,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
prerelease: boolean
}>
const enforcementActive = isSandboxEnforcementActive(db)
const versions = releases
.filter(r => !r.prerelease)
.map(r => {
@@ -1120,7 +1105,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
tag: r.tag_name,
name: r.name,
publishedAt: r.published_at,
installable: !enforcementActive || isSandboxVerifiedOpenCodeVersion(version),
}
})
@@ -1152,18 +1136,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
throw new Error('Invalid version format. Must be in MAJOR.MINOR.PATCH format (e.g., 1.2.27)')
}
if (isSandboxEnforcementActive(db) && !isSandboxVerifiedOpenCodeVersion(versionWithoutPrefix)) {
const verified = getSandboxVerifiedOpenCodeVersions()
logger.warn(`OpenCode v${versionWithoutPrefix} install blocked while sandbox enforcement is active`)
return c.json({
success: false,
error: `OpenCode v${versionWithoutPrefix} is not verified for sandbox enforcement`,
details: `Sandbox enforcement only accepts verified OpenCode builds (${verified.join(', ')}).`,
oldVersion,
newVersion: oldVersion,
}, 409)
}
logger.info(`Installing OpenCode version: ${version}`)
const versionArg = version.startsWith('v') ? version : `v${version}`
const installMethod = getOpenCodeInstallMethod()
@@ -39,7 +39,6 @@ export { sanitizeConfigForEnforcement }
const MIN_OPENCODE_VERSION = '1.0.137'
const SANDBOX_VERIFIED_OPENCODE_VERSIONS = ['1.18.16']
const MAX_STDERR_SIZE = 10240
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
const PROCESS_EXIT_GRACE_MS = 2000
@@ -47,14 +46,6 @@ const PROCESS_EXIT_POLL_MS = 50
const CHILD_STATE_MARKER_REFRESH_MS = 60000
const DEPRECATED_PLUGIN_PACKAGES = ['opencode-openai-codex-auth', 'opencode-copilot-auth']
export function getSandboxVerifiedOpenCodeVersions(): readonly string[] {
return SANDBOX_VERIFIED_OPENCODE_VERSIONS
}
export function isSandboxVerifiedOpenCodeVersion(version: string): boolean {
return (SANDBOX_VERIFIED_OPENCODE_VERSIONS as readonly string[]).includes(version)
}
type StartupValidationIssue = {
path: string
message: string
@@ -513,14 +504,6 @@ class OpenCodeServerManager {
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
replacingExistingServer = true
}
const enforcedVersion = await this.fetchVersion()
if (enforcedVersion === null || !this.isSandboxVersionSupported()) {
const message =
enforcedVersion === null
? `OpenCode version could not be determined; refusing to run an enforced server (verified builds: ${SANDBOX_VERIFIED_OPENCODE_VERSIONS.join(', ')})`
: `OpenCode version ${enforcedVersion} does not support sandboxed bash tool rewriting; refusing to run an enforced server (verified builds: ${SANDBOX_VERIFIED_OPENCODE_VERSIONS.join(', ')})`
this.failNonRecoverable(message)
}
} else if (existingProcesses.length > 0) {
logger.info(`OpenCode server already running on port ${openCodeServerPort}`)
const healthy = await this.checkHealth()
@@ -815,14 +798,6 @@ class OpenCodeServerManager {
logger.warn('Some features like MCP management may not work correctly')
}
}
if (sandboxEnforced && (this.version === null || !this.isSandboxVersionSupported())) {
const message =
this.version === null
? `OpenCode version could not be determined; refusing to run an enforced server (verified builds: ${SANDBOX_VERIFIED_OPENCODE_VERSIONS.join(', ')})`
: `OpenCode version ${this.version} does not support sandboxed bash tool rewriting; refusing to run an enforced server (verified builds: ${SANDBOX_VERIFIED_OPENCODE_VERSIONS.join(', ')})`
await this.stop(true)
this.failNonRecoverable(message)
}
} finally {
this.releaseOp(acquired)
}
@@ -1121,14 +1096,6 @@ class OpenCodeServerManager {
return compareVersions(this.version, MIN_OPENCODE_VERSION) >= 0
}
getSandboxVerifiedVersions(): readonly string[] {
return SANDBOX_VERIFIED_OPENCODE_VERSIONS
}
isSandboxVersionSupported(): boolean {
return this.version !== null && isSandboxVerifiedOpenCodeVersion(this.version)
}
getLastStartupError(): string | null {
return this.lastStartupError
}
@@ -1,15 +0,0 @@
import type { Database } from 'bun:sqlite'
import { logger } from '../../utils/logger'
import { SandboxRuntimeService } from './runtime'
import { opencodeServerManager } from '../opencode-single-server'
export function isSandboxEnforcementActive(db: Database): boolean {
let preferenceEnabled = false
try {
preferenceEnabled = new SandboxRuntimeService(db).isEnabled()
} catch (error) {
logger.warn('Failed to read the sandbox preference; treating sandbox enforcement as active:', error)
return true
}
return preferenceEnabled || opencodeServerManager.isSandboxEnforced()
}
@@ -12,8 +12,6 @@ const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: { isSandboxEnforced: isSandboxEnforcedMock, isLifecycleInitialized: isLifecycleInitializedMock },
OpenCodeServerManager: class {},
getSandboxVerifiedOpenCodeVersions: () => [],
isSandboxVerifiedOpenCodeVersion: () => false,
sanitizeConfigForEnforcement: (config: Record<string, unknown>) => config,
ConfigReloadError: class extends Error {},
NonRecoverableStartupError: class extends Error {},
@@ -19,8 +19,6 @@ const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: { isSandboxEnforced: isSandboxEnforcedMock, isLifecycleInitialized: isLifecycleInitializedMock },
OpenCodeServerManager: class {},
getSandboxVerifiedOpenCodeVersions: () => [],
isSandboxVerifiedOpenCodeVersion: () => false,
sanitizeConfigForEnforcement: (config: Record<string, unknown>) => config,
ConfigReloadError: class extends Error {},
NonRecoverableStartupError: class extends Error {},
+33 -152
View File
@@ -1256,6 +1256,19 @@ describe('Settings Routes - OpenCode Upgrade', () => {
expect(mockRestart).toHaveBeenCalledTimes(1)
expect(mockReloadConfig).not.toHaveBeenCalled()
})
it('allows upgrading while sandbox enforcement is active', async () => {
mockIsSandboxEnforced.mockReturnValue(true)
mockGetVersion.mockReturnValueOnce('1.18.16')
mockFetchVersion.mockResolvedValueOnce('1.19.0')
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
const res = await settingsApp.fetch(new Request('http://localhost/opencode-upgrade', { method: 'POST' }))
expect(res.status).toBe(200)
expect(mockExecSync).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
})
})
describe('timeout and recovery scenarios', () => {
@@ -1363,44 +1376,6 @@ describe('Settings Routes - OpenCode Upgrade', () => {
expect(json.upgraded).toBe(false)
})
})
describe('sandbox enforcement gating', () => {
it('blocks the upgrade while the persisted sandbox preference is enabled', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
mockGetVersion.mockReturnValue('1.18.16')
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(409)
expect(json.error).toContain('sandbox enforcement')
expect(json.details).toContain('1.18.16')
expect(mockExecSync).not.toHaveBeenCalled()
expect(mockRestart).not.toHaveBeenCalled()
expect(mockClearStartupError).not.toHaveBeenCalled()
})
it('blocks the upgrade while the running OpenCode child is enforced', async () => {
mockIsSandboxEnforced.mockReturnValue(true)
mockGetVersion.mockReturnValue('1.18.16')
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(409)
expect(json.error).toContain('sandbox enforcement')
expect(mockExecSync).not.toHaveBeenCalled()
expect(mockRestart).not.toHaveBeenCalled()
})
})
})
describe('POST /opencode-install-version', () => {
@@ -1423,6 +1398,26 @@ describe('Settings Routes - OpenCode Upgrade', () => {
expect(json.newVersion).toBe('1.0.5')
})
it('allows installing any version while sandbox enforcement is active', async () => {
mockIsSandboxEnforced.mockReturnValue(true)
mockGetVersion.mockReturnValueOnce('1.18.16')
mockFetchVersion.mockResolvedValueOnce('1.20.0')
mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.20.0\n', stderr: '', signal: null, error: undefined })
const res = await settingsApp.fetch(new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.20.0' }),
headers: { 'Content-Type': 'application/json' }
}))
expect(res.status).toBe(200)
expect(mockSpawnSync).toHaveBeenCalledWith(
'opencode',
['upgrade', 'v1.20.0', '--method', 'curl'],
expect.any(Object)
)
})
it('should prepend v to version if missing', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.5')
@@ -1533,120 +1528,6 @@ describe('Settings Routes - OpenCode Upgrade', () => {
expect(res.status).toBe(400)
})
})
describe('sandbox enforcement gating', () => {
it('allows installing a verified version while the sandbox preference is enabled', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
mockGetVersion.mockReturnValueOnce('1.18.16')
mockFetchVersion.mockResolvedValueOnce('1.18.16')
mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.18.16\n', stderr: '', signal: null, error: undefined })
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.18.16' }),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.success).toBe(true)
expect(mockSpawnSync).toHaveBeenCalledWith(
'opencode',
['upgrade', 'v1.18.16', '--method', 'curl'],
expect.any(Object)
)
})
it('rejects an unverified version install while the sandbox preference is enabled', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
mockGetVersion.mockReturnValue('1.18.16')
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.19.0' }),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(409)
expect(json.error).toContain('not verified')
expect(json.details).toContain('1.18.16')
expect(mockSpawnSync).not.toHaveBeenCalled()
expect(mockRestart).not.toHaveBeenCalled()
})
it('rejects an unverified version install while the running child is enforced', async () => {
mockIsSandboxEnforced.mockReturnValue(true)
mockGetVersion.mockReturnValue('1.18.16')
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.20.0' }),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(409)
expect(json.error).toContain('not verified')
expect(mockSpawnSync).not.toHaveBeenCalled()
})
})
})
describe('GET /opencode-versions - installable flags', () => {
let originalFetch: typeof globalThis.fetch
function mockReleasesResponse() {
const releases = [
{ tag_name: 'v1.20.0', name: '', published_at: '2026-02-01T00:00:00Z', prerelease: false },
{ tag_name: 'v1.19.0', name: '', published_at: '2026-01-01T00:00:00Z', prerelease: false },
{ tag_name: 'v1.18.16', name: '', published_at: '2025-12-01T00:00:00Z', prerelease: false },
]
globalThis.fetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify(releases), { status: 200, headers: { 'content-type': 'application/json' } }),
) as unknown as typeof fetch
}
beforeEach(() => {
originalFetch = globalThis.fetch
})
afterEach(() => {
globalThis.fetch = originalFetch
})
it('marks every release installable when enforcement is inactive', async () => {
mockReleasesResponse()
const res = await settingsApp.fetch(new Request('http://localhost/opencode-versions'))
const json = await res.json() as { versions: Array<{ version: string; installable: boolean }> }
expect(res.status).toBe(200)
expect(json.versions.every((release) => release.installable === true)).toBe(true)
})
it('marks only verified releases installable while sandbox enforcement is active', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
mockReleasesResponse()
const res = await settingsApp.fetch(new Request('http://localhost/opencode-versions'))
const json = await res.json() as { versions: Array<{ version: string; installable: boolean }> }
expect(res.status).toBe(200)
const byVersion = new Map(json.versions.map((release) => [release.version, release.installable]))
expect(byVersion.get('1.18.16')).toBe(true)
expect(byVersion.get('1.19.0')).toBe(false)
expect(byVersion.get('1.20.0')).toBe(false)
})
})
describe('error scenarios - server stability', () => {
@@ -2636,43 +2636,7 @@ describe('OpenCodeServerManager - server auth', () => {
expect(spawnMock).toHaveBeenCalled()
})
it('refuses to start an enforced server on an OpenCode build that predates hook argument rewriting', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
execSyncMock.mockImplementation((cmd: string) => {
if (cmd.includes('lsof')) return ''
if (cmd.includes('opencode --version')) return '1.18.15\n'
throw new Error('not found')
})
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await expect(manager.start()).rejects.toThrow('does not support sandboxed bash tool rewriting')
expect(manager.getLastStartupError()).toContain('1.18.15')
expect(manager.getLastStartupError()).toContain('1.18.16')
expect(spawnMock).not.toHaveBeenCalled()
})
it('refuses to start an enforced server when the OpenCode version cannot be determined', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
execSyncMock.mockImplementation((cmd: string) => {
if (cmd.includes('lsof')) return ''
throw new Error('not found')
})
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await expect(manager.start()).rejects.toThrow('OpenCode version could not be determined')
expect(manager.getLastStartupError()).toContain('1.18.16')
expect(spawnMock).not.toHaveBeenCalled()
})
it('starts an enforced server on a sandbox-compatible OpenCode build', async () => {
it('starts an enforced server on any OpenCode build', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
@@ -2715,95 +2679,6 @@ describe('OpenCodeServerManager - server auth', () => {
expect(spawnMock).toHaveBeenCalled()
})
it('refuses to start an enforced server on a newer unverified OpenCode build', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
execSyncMock.mockImplementation((cmd: string) => {
if (cmd.includes('lsof')) return ''
if (cmd.includes('opencode --version')) return '1.19.0\n'
throw new Error('not found')
})
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await expect(manager.start()).rejects.toThrow('does not support sandboxed bash tool rewriting')
expect(manager.getLastStartupError()).toContain('1.19.0')
expect(manager.getLastStartupError()).toContain('verified builds: 1.18.16')
expect(spawnMock).not.toHaveBeenCalled()
})
it('terminates an existing port owner before rejecting an unsupported enforced version', async () => {
const originalNodeEnv = ENV.SERVER.NODE_ENV
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: 'production', configurable: true, writable: true })
const killSpy = vi.spyOn(process, 'kill')
try {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
execSyncMock.mockImplementation((cmd: string) => {
if (cmd.includes('lsof')) return '9996\n'
if (cmd.includes('opencode --version')) return '1.19.0\n'
throw new Error('not found')
})
killSpy.mockImplementation(((pid: number, signal?: number | string) => {
if (pid === 9996 && signal === 0) {
const error = new Error('No such process') as NodeJS.ErrnoException
error.code = 'ESRCH'
throw error
}
return true
}) as typeof process.kill)
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await expect(manager.start()).rejects.toThrow('does not support sandboxed bash tool rewriting')
expect(killSpy).toHaveBeenCalledWith(9996, 'SIGKILL')
expect(manager.getLastStartupError()).toContain('1.19.0')
expect(spawnMock).not.toHaveBeenCalled()
expect((manager as any).isHealthy).toBe(false)
} finally {
killSpy.mockRestore()
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: originalNodeEnv, configurable: true, writable: true })
}
}, 15000)
it('terminates an existing port owner before rejecting an undeterminable enforced version', async () => {
const originalNodeEnv = ENV.SERVER.NODE_ENV
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: 'production', configurable: true, writable: true })
const killSpy = vi.spyOn(process, 'kill')
try {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => true,
}))
execSyncMock.mockImplementation((cmd: string) => {
if (cmd.includes('lsof')) return '9995\n'
throw new Error('not found')
})
killSpy.mockImplementation(((pid: number, signal?: number | string) => {
if (pid === 9995 && signal === 0) {
const error = new Error('No such process') as NodeJS.ErrnoException
error.code = 'ESRCH'
throw error
}
return true
}) as typeof process.kill)
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
const manager = OpenCodeServerManager.getInstance()
manager.setDatabase(createPasswordDb(null))
await expect(manager.start()).rejects.toThrow('OpenCode version could not be determined')
expect(killSpy).toHaveBeenCalledWith(9995, 'SIGKILL')
expect(spawnMock).not.toHaveBeenCalled()
expect((manager as any).isHealthy).toBe(false)
} finally {
killSpy.mockRestore()
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: originalNodeEnv, configurable: true, writable: true })
}
}, 15000)
it('keeps a restart request pending when it is marked during startup', async () => {
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
isEnabled: () => false,
@@ -2847,13 +2722,6 @@ describe('OpenCodeServerManager - server auth', () => {
expect(manager.isRestartPending()).toBe(false)
})
it('exposes the sandbox-verified OpenCode versions as the single version gate', async () => {
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
expect(opencodeServerManager.getSandboxVerifiedVersions()).toEqual(['1.18.16'])
expect(opencodeServerManager.isSandboxVersionSupported()).toBe(false)
})
function setOpenCodeEnv(values: { host: string; password: string }) {
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: values.host, configurable: true, writable: true })
Object.defineProperty(ENV.OPENCODE, 'SERVER_PASSWORD', { value: values.password, configurable: true, writable: true })
+1 -1
View File
@@ -105,7 +105,7 @@ Enforcement follows this chain:
1. **Toggle** — Enable **Sandbox** in Settings. If `/dev/kvm` is unavailable the toggle cannot be turned on and the capability reason is shown; if the runtime later becomes unavailable while the preference stays enabled, the toggle remains turned on and every sandboxed command fails closed with the reason instead of running on the host.
2. **Restart** — Changing the preference marks the OpenCode server restart as pending. The new enforcement value is only applied to newly spawned OpenCode processes, so a restart is required. When an enforced server starts, the Manager terminates the previous server's process group — the detached OpenCode child plus every host-process descendant it spawned, including a shell command or MCP process started while enforcement was off — waits for all members to exit, escalates to `SIGKILL` on the group if needed, and refuses to start the enforced server if any member survives, so no unenforced host-executed process can outlive the transition. Non-detached development children are terminated by PID only, preserving the existing hot-reload behavior.
3. **Stamp** — On startup the Manager resolves the preference (not the runtime probe) and stamps every spawned OpenCode child environment with `OCM_SANDBOX_ENFORCED=true` whenever the preference is enabled. A missing or broken sandbox runtime therefore keeps enforcement active and blocks commands with the capability reason rather than silently running them on the host. If the preference itself cannot be read, the Manager fails closed the same way: it treats enforcement as active, terminates any attested predecessor and port-owning server so no unenforced child stays reachable, and aborts startup as non-recoverable with the settings error. User-defined environment variables cannot override this value.
4. **OpenCode build** — Sandbox enforcement rewrites `bash` tool arguments through the plugin `tool.execute.before` hook, a behavior that depends on the OpenCode build. The container image ships a pinned OpenCode build (`1.18.16`), and the Manager refuses to start an enforced server unless the installed build is one of the versions verified by the black-box hook contract test (currently `1.18.16`), failing closed with a clear error instead of trusting an unverified build to run agent commands on the host. While enforcement is active (the persisted preference or a running enforced child), the Settings UI disables the Update action and the unverified rows in the Versions dialog, and the Manager rejects `POST /opencode-upgrade` and any unverified `POST /opencode-install-version` request, so the installed build can never be replaced with an unverified release; installing a verified version remains allowed. The container entrypoint also repairs a missing or below-minimum `opencode` by reinstalling the bundled build rather than the latest release.
4. **OpenCode build** — Sandbox enforcement rewrites `bash` tool arguments through the plugin `tool.execute.before` hook, a behavior that depends on the OpenCode build. The container image bundles a fixed OpenCode build (`1.18.16`) as the reproducible default and fallback, but that build is not an allowlist: users may install, upgrade, or roll back OpenCode versions while sandbox enforcement is active, and the Settings Update action, the Versions dialog, `POST /opencode-upgrade`, and `POST /opencode-install-version` all keep working under enforcement. The container entrypoint also repairs a missing or below-minimum `opencode` by reinstalling the bundled build as the fallback.
5. **Fail closed** — The installed OpenCode plugin rewrites every `bash` tool command through the internal sandbox planning endpoint. If the sandbox cannot be prepared, the command is replaced with an error and exits non-zero instead of running on the host. A session outside the project roots fails with:
```text
Sandbox enforcement is on but the sandbox is unavailable: working directory is outside the sandboxed project roots (/workspace/repos, /workspace/schedule-worktrees)
-1
View File
@@ -198,7 +198,6 @@ export const settingsApi = {
tag: string
name: string
publishedAt: string
installable: boolean
}>
currentVersion: string | null
}> => {
@@ -11,11 +11,9 @@ vi.mock('@/components/settings/RestartServerDialog', () => ({
RestartServerDialog: () => null,
}))
const BLOCKED_REASON = 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
function mockHealth() {
vi.mocked(useServerHealth).mockReturnValue({
data: { opencode: 'healthy', opencodeVersion: '1.18.16', sandbox },
data: { opencode: 'healthy', opencodeVersion: '1.18.16' },
isLoading: false,
error: null,
refetch: vi.fn(),
@@ -41,57 +39,32 @@ function mockActions(overrides: Partial<ReturnType<typeof useOpenCodeServerActio
describe('ServerHealthStatus', () => {
beforeEach(() => {
vi.clearAllMocks()
mockHealth()
mockActions()
})
it('keeps Update and Versions enabled when sandboxing is off', () => {
mockHealth({ available: true, enforced: false })
it('keeps Update and Versions enabled', () => {
render(<ServerHealthStatus />)
expect(screen.getByRole('button', { name: /Update/i })).toBeEnabled()
expect(screen.getByRole('button', { name: /Versions/i })).toBeEnabled()
})
it('disables Update but keeps Versions accessible when sandbox enforcement is on', () => {
mockHealth({ available: true, enforced: true })
render(<ServerHealthStatus />)
const update = screen.getByRole('button', { name: /Update/i })
const versions = screen.getByRole('button', { name: /Versions/i })
expect(update).toBeDisabled()
expect(update).toHaveAttribute('title', BLOCKED_REASON)
expect(versions).toBeEnabled()
expect(screen.getByText(/Agent sandboxing is on; Update is disabled and only verified versions can be installed\./)).toBeInTheDocument()
})
it('keeps Update and Versions enabled while enforcement is pending but not active', () => {
mockHealth({ available: false, enforced: false, reason: 'KVM unavailable' })
render(<ServerHealthStatus />)
expect(screen.getByRole('button', { name: /Update/i })).toBeEnabled()
expect(screen.getByRole('button', { name: /Versions/i })).toBeEnabled()
})
it('does not invoke an upgrade while the Update button is disabled', async () => {
it('invokes an upgrade when Update is clicked', async () => {
const user = userEvent.setup()
const performUpgrade = vi.fn()
mockActions({ performUpgrade })
mockHealth({ available: true, enforced: true })
render(<ServerHealthStatus />)
await user.click(screen.getByRole('button', { name: /Update/i }))
expect(performUpgrade).not.toHaveBeenCalled()
expect(performUpgrade).toHaveBeenCalled()
})
it('opens the version dialog when Versions is clicked under enforcement', async () => {
it('opens the version dialog when Versions is clicked', async () => {
const user = userEvent.setup()
const onOpenVersionDialog = vi.fn()
mockHealth({ available: true, enforced: true })
render(<ServerHealthStatus onOpenVersionDialog={onOpenVersionDialog} />)
@@ -37,10 +37,6 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
}
const isUnhealthy = health.opencode !== 'healthy'
const sandboxEnforced = health.sandbox?.enforced === true
const updateBlockedReason = sandboxEnforced
? 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
: undefined
return (
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
@@ -66,19 +62,13 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
Manager v{health.opencodeManagerVersion}
</p>
)}
{sandboxEnforced && (
<p className="text-xs text-muted-foreground">
Agent sandboxing is on; Update is disabled and only verified versions can be installed.
</p>
)}
</div>
<div className="flex flex-wrap gap-2 justify-center sm:justify-end">
<Button
variant="outline"
size="sm"
onClick={performUpgrade}
disabled={upgradeOpenCodeMutation.isPending || sandboxEnforced}
title={updateBlockedReason}
disabled={upgradeOpenCodeMutation.isPending}
>
{upgradeOpenCodeMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
@@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { VersionSelectDialog } from './VersionSelectDialog'
import { settingsApi } from '@/api/settings'
import { useServerHealth } from '@/hooks/useServerHealth'
import { refreshOpenCodeServerCaches } from '@/lib/queryInvalidation'
vi.mock('@/api/settings', () => ({
settingsApi: {
@@ -13,13 +13,11 @@ vi.mock('@/api/settings', () => ({
},
}))
vi.mock('@/hooks/useServerHealth')
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), loading: vi.fn(), dismiss: vi.fn() },
}))
vi.mock('@/lib/queryInvalidation', () => ({
invalidateConfigCaches: vi.fn(),
updateOpenCodeVersionCaches: vi.fn(),
refreshOpenCodeServerCaches: vi.fn(),
}))
const mockGetOpenCodeVersions = settingsApi.getOpenCodeVersions as ReturnType<typeof vi.fn>
@@ -34,32 +32,20 @@ function renderDialog(open = true) {
)
}
function mockHealth(enforced: boolean) {
vi.mocked(useServerHealth).mockReturnValue({
data: { sandbox: { available: true, enforced } },
isLoading: false,
error: null,
refetch: vi.fn(),
restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false },
} as ReturnType<typeof useServerHealth>)
}
describe('VersionSelectDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetOpenCodeVersions.mockResolvedValue({
versions: [
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: true },
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z', installable: true },
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z' },
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z' },
],
currentVersion: '1.18.16',
})
mockInstallOpenCodeVersion.mockResolvedValue({ success: true, message: 'ok', oldVersion: null, newVersion: '1.19.0' })
mockHealth(false)
})
it('lists versions and allows selection when sandboxing is off', async () => {
it('lists versions and allows selection', async () => {
const user = userEvent.setup()
renderDialog()
@@ -73,38 +59,11 @@ describe('VersionSelectDialog', () => {
expect(screen.getByRole('button', { name: /^Install$/i })).toBeEnabled()
})
it('keeps verified versions installable and disables unverified versions when sandbox enforcement is on', async () => {
mockHealth(true)
it('installs the selected version', async () => {
mockGetOpenCodeVersions.mockResolvedValue({
versions: [
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: false },
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z', installable: true },
],
currentVersion: '1.17.0',
})
renderDialog()
expect(
await screen.findByText(/only verified OpenCode versions can be installed/),
).toBeInTheDocument()
const unverifiedRow = screen.getByRole('button', { name: /v1\.19\.0/ })
const verifiedRow = screen.getByRole('button', { name: /v1\.18\.16/ })
expect(unverifiedRow).toBeDisabled()
expect(verifiedRow).toBeEnabled()
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
const user = userEvent.setup()
await user.click(verifiedRow)
expect(screen.getByRole('button', { name: /^Install$/i })).toBeEnabled()
})
it('keeps the install button disabled when the only available row is unverified under enforcement', async () => {
mockHealth(true)
mockGetOpenCodeVersions.mockResolvedValue({
versions: [
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: false },
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z' },
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z' },
],
currentVersion: '1.17.0',
})
@@ -113,10 +72,12 @@ describe('VersionSelectDialog', () => {
renderDialog()
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
const unverifiedRow = screen.getByRole('button', { name: /v1\.19\.0/ })
expect(unverifiedRow).toBeDisabled()
await user.click(unverifiedRow)
const versionRow = screen.getByRole('button', { name: /v1\.19\.0/ })
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
await user.click(versionRow)
await user.click(screen.getByRole('button', { name: /^Install$/i }))
expect(mockInstallOpenCodeVersion).toHaveBeenCalledWith('1.19.0')
expect(refreshOpenCodeServerCaches).toHaveBeenCalledWith(expect.any(QueryClient), '1.19.0')
})
})
@@ -5,8 +5,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } f
import { Button } from '@/components/ui/button'
import { settingsApi } from '@/api/settings'
import { showToast } from '@/lib/toast'
import { invalidateConfigCaches, updateOpenCodeVersionCaches } from '@/lib/queryInvalidation'
import { useServerHealth } from '@/hooks/useServerHealth'
import { refreshOpenCodeServerCaches } from '@/lib/queryInvalidation'
interface VersionSelectDialogProps {
open: boolean
@@ -15,8 +14,6 @@ interface VersionSelectDialogProps {
export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogProps) {
const queryClient = useQueryClient()
const { data: health } = useServerHealth()
const sandboxEnforced = health?.sandbox?.enforced === true
const [selectedVersion, setSelectedVersion] = useState<string | null>(null)
const { data, isLoading, error } = useQuery({
@@ -26,34 +23,27 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
staleTime: 60000,
})
const selectedRelease = data?.versions.find((release) => release.version === selectedVersion)
const selectedInstallable = selectedRelease?.installable === true
const installMutation = useMutation({
mutationFn: (version: string) => settingsApi.installOpenCodeVersion(version),
onSuccess: (result) => {
if (result.newVersion) {
updateOpenCodeVersionCaches(queryClient, result.newVersion)
}
invalidateConfigCaches(queryClient)
refreshOpenCodeServerCaches(queryClient, result.newVersion ?? undefined)
showToast.success(result.message)
onOpenChange(false)
},
onError: (error) => {
queryClient.invalidateQueries({ queryKey: ['opencode-versions'] })
invalidateConfigCaches(queryClient)
if (error && typeof error === 'object' && 'response' in error) {
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
const data = response?.data
if (data?.recovered && data.newVersion) {
updateOpenCodeVersionCaches(queryClient, data.newVersion)
refreshOpenCodeServerCaches(queryClient, data.newVersion)
showToast.success(`Install failed but server recovered at v${data.newVersion}`)
} else {
refreshOpenCodeServerCaches(queryClient)
showToast.error(data?.recoveryMessage || 'Failed to install version')
}
} else {
refreshOpenCodeServerCaches(queryClient)
showToast.error('Failed to install version')
}
},
@@ -101,13 +91,6 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
{data && (
<>
{sandboxEnforced && (
<div className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-600 dark:text-amber-400 mb-3">
While agent sandboxing is enabled, only verified OpenCode versions can be installed. Unverified
versions are disabled. Disable Agent Sandboxing in Settings and restart the OpenCode server to
install other versions.
</div>
)}
<div className="h-[300px] overflow-y-auto pr-2">
<div className="space-y-2">
{data.versions.map((release) => {
@@ -118,15 +101,13 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
<button
key={release.version}
onClick={() => setSelectedVersion(isCurrent ? null : release.version)}
disabled={isCurrent || installMutation.isPending || !release.installable}
disabled={isCurrent || installMutation.isPending}
className={`w-full text-left p-3 rounded-lg border transition-colors ${
isSelected
? 'border-primary bg-primary/10'
: isCurrent
? 'border-green-500/50 bg-green-500/10 cursor-default'
: !release.installable
? 'border-border opacity-50 cursor-not-allowed'
: 'border-border hover:border-primary/50 hover:bg-muted/50'
: 'border-border hover:border-primary/50 hover:bg-muted/50'
}`}
>
<div className="flex items-center justify-between">
@@ -138,11 +119,6 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
Current
</span>
)}
{!release.installable && (
<span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
Unverified
</span>
)}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{formatDate(release.publishedAt)}
@@ -166,7 +142,7 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
</Button>
<Button
onClick={handleInstall}
disabled={!selectedVersion || installMutation.isPending || !selectedInstallable}
disabled={!selectedVersion || installMutation.isPending}
className="min-w-[120px]"
>
{installMutation.isPending ? (
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { settingsApi } from '@/api/settings'
import { showToast } from '@/lib/toast'
import { invalidateConfigCaches, updateOpenCodeVersionCaches } from '@/lib/queryInvalidation'
import { refreshOpenCodeServerCaches } from '@/lib/queryInvalidation'
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
const RESTART_TOAST_ID = 'opencode-restart'
@@ -22,17 +22,14 @@ export function useOpenCodeServerActions() {
const restartServerMutation = useMutation({
mutationFn: async () => settingsApi.restartOpenCodeServer(),
onSuccess: () => {
invalidateConfigCaches(queryClient)
refreshOpenCodeServerCaches(queryClient)
},
})
const upgradeOpenCodeMutation = useMutation({
mutationFn: async () => settingsApi.upgradeOpenCode(),
onSuccess: (data) => {
if (data.upgraded && data.newVersion) {
updateOpenCodeVersionCaches(queryClient, data.newVersion)
}
invalidateConfigCaches(queryClient)
refreshOpenCodeServerCaches(queryClient, data.upgraded ? data.newVersion ?? undefined : undefined)
if (data.upgraded) {
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: UPGRADE_TOAST_ID })
} else {
@@ -47,15 +44,16 @@ export function useOpenCodeServerActions() {
const data = response?.data
if (data?.recovered && data.newVersion) {
updateOpenCodeVersionCaches(queryClient, data.newVersion)
refreshOpenCodeServerCaches(queryClient, data.newVersion)
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: UPGRADE_TOAST_ID })
} else {
refreshOpenCodeServerCaches(queryClient)
showToast.error(data?.recoveryMessage || defaultMessage, { id: UPGRADE_TOAST_ID })
}
} else {
refreshOpenCodeServerCaches(queryClient)
showToast.error(defaultMessage, { id: UPGRADE_TOAST_ID })
}
invalidateConfigCaches(queryClient)
},
})
+14 -4
View File
@@ -1,15 +1,25 @@
import { QueryClient } from '@tanstack/react-query'
import { describe, expect, it, vi } from 'vitest'
import { updateOpenCodeVersionCaches } from './queryInvalidation'
import { refreshOpenCodeServerCaches } from './queryInvalidation'
describe('updateOpenCodeVersionCaches', () => {
it('updates and invalidates both OpenCode version caches', () => {
describe('refreshOpenCodeServerCaches', () => {
it('invalidates every cache that displays the installed OpenCode version', () => {
const queryClient = new QueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
refreshOpenCodeServerCaches(queryClient)
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['health'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-versions'] })
})
it('updates both OpenCode version caches when the new version is known', () => {
const queryClient = new QueryClient()
queryClient.setQueryData(['health'], { opencodeVersion: '1.0.0', status: 'healthy' })
queryClient.setQueryData(['opencode-versions'], { currentVersion: '1.0.0', versions: [] })
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
updateOpenCodeVersionCaches(queryClient, '1.0.1')
refreshOpenCodeServerCaches(queryClient, '1.0.1')
expect(queryClient.getQueryData(['health'])).toEqual({ opencodeVersion: '1.0.1', status: 'healthy' })
expect(queryClient.getQueryData(['opencode-versions'])).toEqual({ currentVersion: '1.0.1', versions: [] })
+10 -8
View File
@@ -31,14 +31,16 @@ export function invalidateConfigCaches(queryClient: QueryClient) {
invalidateProviderCaches(queryClient)
}
export function updateOpenCodeVersionCaches(queryClient: QueryClient, version: string) {
queryClient.setQueryData<Record<string, unknown>>(['health'], (oldData) => (
oldData ? { ...oldData, opencodeVersion: version } : oldData
))
queryClient.setQueryData<Record<string, unknown>>(['opencode-versions'], (oldData) => (
oldData ? { ...oldData, currentVersion: version } : oldData
))
queryClient.invalidateQueries({ queryKey: ['health'] })
export function refreshOpenCodeServerCaches(queryClient: QueryClient, version?: string) {
if (version) {
queryClient.setQueryData<Record<string, unknown>>(['health'], (oldData) => (
oldData ? { ...oldData, opencodeVersion: version } : oldData
))
queryClient.setQueryData<Record<string, unknown>>(['opencode-versions'], (oldData) => (
oldData ? { ...oldData, currentVersion: version } : oldData
))
}
invalidateConfigCaches(queryClient)
queryClient.invalidateQueries({ queryKey: ['opencode-versions'] })
}