diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index 1bfe393f..b761fecd 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -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 - diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 81f015ea..b373b425 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -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() diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 03679e94..56b71950 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -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 } diff --git a/backend/src/services/sandbox/enforcement.ts b/backend/src/services/sandbox/enforcement.ts deleted file mode 100644 index 89ea6252..00000000 --- a/backend/src/services/sandbox/enforcement.ts +++ /dev/null @@ -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() -} diff --git a/backend/test/routes/opencode-auth-proxy.test.ts b/backend/test/routes/opencode-auth-proxy.test.ts index 4c71509f..094a5e3a 100644 --- a/backend/test/routes/opencode-auth-proxy.test.ts +++ b/backend/test/routes/opencode-auth-proxy.test.ts @@ -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) => config, ConfigReloadError: class extends Error {}, NonRecoverableStartupError: class extends Error {}, diff --git a/backend/test/routes/opencode-proxy.test.ts b/backend/test/routes/opencode-proxy.test.ts index 763d008b..7c580d21 100644 --- a/backend/test/routes/opencode-proxy.test.ts +++ b/backend/test/routes/opencode-proxy.test.ts @@ -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) => config, ConfigReloadError: class extends Error {}, NonRecoverableStartupError: class extends Error {}, diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index ff8c0f21..9cc16475 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -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 - - 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 - - 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 - - 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 - - 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 - - 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', () => { diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index 9b685b80..0fe995c4 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -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 }) diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index 5b89c419..4c6188ac 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -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) diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 77e1eda3..6781ed04 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -198,7 +198,6 @@ export const settingsApi = { tag: string name: string publishedAt: string - installable: boolean }> currentVersion: string | null }> => { diff --git a/frontend/src/components/settings/ServerHealthStatus.test.tsx b/frontend/src/components/settings/ServerHealthStatus.test.tsx index ff8aa101..c1419f8e 100644 --- a/frontend/src/components/settings/ServerHealthStatus.test.tsx +++ b/frontend/src/components/settings/ServerHealthStatus.test.tsx @@ -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 { 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() 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() - - 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() - - 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() 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() diff --git a/frontend/src/components/settings/ServerHealthStatus.tsx b/frontend/src/components/settings/ServerHealthStatus.tsx index f87fc0ef..1b1618a1 100644 --- a/frontend/src/components/settings/ServerHealthStatus.tsx +++ b/frontend/src/components/settings/ServerHealthStatus.tsx @@ -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 ( @@ -66,19 +62,13 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr Manager v{health.opencodeManagerVersion}

)} - {sandboxEnforced && ( -

- Agent sandboxing is on; Update is disabled and only verified versions can be installed. -

- )}