From 0215de9d92e63d67edfce9ad99a52a76adb4b9af Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 22 Aug 2026 00:14:19 -0400 Subject: [PATCH] fix(sandbox): bound lifecycle queue and harden install/backup paths Bound the OpenCode supervisor lifecycle queue to one running plus one pending operation so repeated restarts cannot stack unbounded HTTP requests, while exempting stop() so shutdown is never dropped. Reject enforcement backups that carry no recoverable removed sections, matching the existing fail-closed handling of unparseable backups. Install OpenCode through a private mktemp staging directory instead of the predictable /tmp/opencode path. Use named path/os imports in the files added by this branch. --- .../services/opencode-plugin-quarantine.ts | 6 ++-- backend/src/services/opencode-supervisor.ts | 30 ++++++++++++++----- .../src/services/opencode/plugin-registry.ts | 6 ++-- backend/src/services/sandbox/shell-wrapper.ts | 8 ++--- .../test/scripts/docker-entrypoint.test.ts | 9 ++++-- .../opencode-plugin-quarantine.test.ts | 25 ++++++++++++++++ .../test/services/opencode-supervisor.test.ts | 30 +++++++++++++++++++ .../services/sandbox/shell-wrapper.test.ts | 12 ++++---- scripts/docker-entrypoint.sh | 10 ++++--- 9 files changed, 108 insertions(+), 28 deletions(-) diff --git a/backend/src/services/opencode-plugin-quarantine.ts b/backend/src/services/opencode-plugin-quarantine.ts index 69a4f48d..92ded980 100644 --- a/backend/src/services/opencode-plugin-quarantine.ts +++ b/backend/src/services/opencode-plugin-quarantine.ts @@ -367,8 +367,10 @@ async function restorePluginEntries(dir: string): Promise { async function readPluginConfigBackup(backupPath: string): Promise { try { const parsed = parseJsonc(await fs.readFile(backupPath, 'utf-8')) as unknown - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { - return parsed as PluginConfigBackup + if (!isRecord(parsed)) return null + const backup = parsed as PluginConfigBackup + if (isRecord(backup.removedSections) || Array.isArray(backup.originalPlugins) || Array.isArray(backup.plugin)) { + return backup } } catch { return null diff --git a/backend/src/services/opencode-supervisor.ts b/backend/src/services/opencode-supervisor.ts index 838d8d4b..a301eb36 100644 --- a/backend/src/services/opencode-supervisor.ts +++ b/backend/src/services/opencode-supervisor.ts @@ -27,6 +27,8 @@ export const OPENCODE_RECOVERY_ACTIONS = [ export type OpenCodeRecoveryAction = (typeof OPENCODE_RECOVERY_ACTIONS)[number] +const MAX_QUEUED_LIFECYCLE_OPERATIONS = 2 + export type OpenCodeOperationReason = | 'backend_startup' | 'health_poll' @@ -66,6 +68,7 @@ export class OpenCodeSupervisor { private consecutiveFailures = 0 private operationInProgress = false private operationTail: Promise = Promise.resolve() + private queuedOperations = 0 private updatedAt = new Date().toISOString() constructor( @@ -167,7 +170,7 @@ export class OpenCodeSupervisor { await this.openCodeServerManager.stop() this.setState('stopped') return this.getStatus() - }) + }, { droppable: false }) logger.info('Stopped OpenCode supervisor') } @@ -194,20 +197,33 @@ export class OpenCodeSupervisor { } } - private async runLifecycleOperation(operation: () => Promise): Promise { + private async runLifecycleOperation( + operation: () => Promise, + options: { droppable?: boolean } = {}, + ): Promise { + if ((options.droppable ?? true) && this.queuedOperations >= MAX_QUEUED_LIFECYCLE_OPERATIONS) { + logger.warn('Dropped an OpenCode lifecycle request: one operation is running and another is already queued') + return this.getStatus() + } + + this.queuedOperations += 1 const previousTail = this.operationTail let releaseTail!: () => void this.operationTail = new Promise((resolve) => { releaseTail = resolve }) - await previousTail - this.operationInProgress = true try { - return await operation() + await previousTail + this.operationInProgress = true + try { + return await operation() + } finally { + this.operationInProgress = false + this.touch() + } } finally { - this.operationInProgress = false - this.touch() + this.queuedOperations -= 1 releaseTail() } } diff --git a/backend/src/services/opencode/plugin-registry.ts b/backend/src/services/opencode/plugin-registry.ts index 4940105b..bbbc687e 100644 --- a/backend/src/services/opencode/plugin-registry.ts +++ b/backend/src/services/opencode/plugin-registry.ts @@ -1,4 +1,4 @@ -import path from 'path' +import { join } from 'path' import { writeFileAtomic } from '../../utils/fs-safe' import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin' import { buildSandboxPluginSource } from '../opencode-sandbox-plugin' @@ -16,12 +16,12 @@ export const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [ export const TRUSTED_OPENCODE_PLUGIN_FILENAMES: readonly string[] = MANAGED_OPENCODE_PLUGINS.map((plugin) => plugin.filename) export function getOpenCodePluginDir(configHome: string): string { - return path.join(configHome, 'opencode', 'plugin') + return join(configHome, 'opencode', 'plugin') } export async function installManagedPlugins(configHome: string): Promise { const dir = getOpenCodePluginDir(configHome) for (const plugin of MANAGED_OPENCODE_PLUGINS) { - await writeFileAtomic(path.join(dir, plugin.filename), plugin.buildSource()) + await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource()) } } diff --git a/backend/src/services/sandbox/shell-wrapper.ts b/backend/src/services/sandbox/shell-wrapper.ts index 40d4091c..d2f47204 100644 --- a/backend/src/services/sandbox/shell-wrapper.ts +++ b/backend/src/services/sandbox/shell-wrapper.ts @@ -1,4 +1,4 @@ -import path from 'path' +import { join } from 'path' import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './command' import { writeFileAtomic } from '../../utils/fs-safe' @@ -85,15 +85,15 @@ main() ` export function getSandboxShellDir(configHome: string): string { - return path.join(configHome, 'ocm') + return join(configHome, 'ocm') } export function getSandboxShellPath(configHome: string): string { - return path.join(getSandboxShellDir(configHome), SANDBOX_SHELL_FILENAME) + return join(getSandboxShellDir(configHome), SANDBOX_SHELL_FILENAME) } export function getEnforcedSandboxShellPath(): string { - return getSandboxShellPath(path.join(getWorkspacePath(), '.config')) + return getSandboxShellPath(join(getWorkspacePath(), '.config')) } export async function installSandboxShell(configHome: string): Promise { diff --git a/backend/test/scripts/docker-entrypoint.test.ts b/backend/test/scripts/docker-entrypoint.test.ts index 55133091..42452b89 100644 --- a/backend/test/scripts/docker-entrypoint.test.ts +++ b/backend/test/scripts/docker-entrypoint.test.ts @@ -190,11 +190,15 @@ const runOpenCodeSection = (snippet: string, env: Record = {}) = const stubInstallTools = () => { writeStub('curl', `echo "curl $*" >> "$OCM_STUB_LOG" -rm -rf /tmp/opencode /tmp/opencode.tar.gz +out="" +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then out="$2"; fi + shift +done mkdir -p "$HOME/.opencode/bin" printf '#!/bin/bash\\necho 1.18.16\\n' > "$HOME/.opencode/bin/opencode" chmod +x "$HOME/.opencode/bin/opencode" -printf 'fake binary\\n' > /tmp/opencode`) +printf 'fake binary\\n' > "$(dirname "$out")/opencode"`) writeStub('tar', `echo "tar $*" >> "$OCM_STUB_LOG"`) } @@ -208,6 +212,7 @@ describe('install_opencode', () => { const urls = curlLog().join(' ') expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//) expect(urls).not.toContain('/releases/latest/download/') + expect(urls).not.toContain('/tmp/opencode.tar.gz') }) it('refuses to guess the pinned build when OPENCODE_BUNDLED_VERSION is unset', () => { diff --git a/backend/test/services/opencode-plugin-quarantine.test.ts b/backend/test/services/opencode-plugin-quarantine.test.ts index 20a96d38..a2769f8f 100644 --- a/backend/test/services/opencode-plugin-quarantine.test.ts +++ b/backend/test/services/opencode-plugin-quarantine.test.ts @@ -531,6 +531,31 @@ describe('opencode plugin quarantine', () => { expect(await fs.readFile(backupPath, 'utf-8')).toBe(corrupt) }) + it('refuses to overwrite a backup that holds no recoverable removed sections', 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` + writeFileSync(backupPath, '{}') + + await expect(quarantineOpenCodePlugins(configHome, configPath)).rejects.toThrow(/refusing to overwrite it/) + expect(await fs.readFile(backupPath, 'utf-8')).toBe('{}') + }) + + it('accepts a legacy backup that recorded an empty plugin list', async () => { + writeConfig({ plugin: ['my-plugin'], model: 'x' }) + await quarantineOpenCodePlugins(configHome, configPath) + + const backupPath = `${configPath}.ocm-sandbox-backup` + writeFileSync(backupPath, JSON.stringify({ originalPlugins: [] })) + + await expect(quarantineOpenCodePlugins(configHome, configPath)).resolves.toBeUndefined() + }) + 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'] } }, diff --git a/backend/test/services/opencode-supervisor.test.ts b/backend/test/services/opencode-supervisor.test.ts index 39c0b79b..987859f4 100644 --- a/backend/test/services/opencode-supervisor.test.ts +++ b/backend/test/services/opencode-supervisor.test.ts @@ -570,4 +570,34 @@ describe('OpenCodeSupervisor', () => { expect(manager.restart).toHaveBeenCalledTimes(1) expect(manager.stop).toHaveBeenCalledTimes(1) }) + + it('drops a restart stacked behind an already queued restart but never drops a stop', async () => { + const manager = createManager() + const settings = createSettings() + const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, { + failureThreshold: 1, + watchEnabled: false, + }) + + let releaseRestart!: () => void + manager.restart.mockImplementationOnce( + () => new Promise((resolve) => { releaseRestart = resolve }), + ) + manager.checkHealth.mockResolvedValue(true) + + const running = supervisor.restart('manual') + await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1)) + + const queued = supervisor.restart('manual') + const dropped = supervisor.restart('manual') + const stopPromise = supervisor.stop() + + await expect(dropped).resolves.toMatchObject({ state: 'starting' }) + + releaseRestart() + await Promise.all([running, queued, stopPromise]) + + expect(manager.restart).toHaveBeenCalledTimes(2) + expect(manager.stop).toHaveBeenCalledTimes(1) + }) }) diff --git a/backend/test/services/sandbox/shell-wrapper.test.ts b/backend/test/services/sandbox/shell-wrapper.test.ts index ee5ddd7b..12856371 100644 --- a/backend/test/services/sandbox/shell-wrapper.test.ts +++ b/backend/test/services/sandbox/shell-wrapper.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { promises as fs } from 'fs' -import path from 'path' -import os from 'os' +import { join } from 'path' +import { tmpdir } from 'os' import { spawnSync } from 'child_process' import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { @@ -19,7 +19,7 @@ describe('sandbox shell wrapper', () => { let configHome: string beforeEach(async () => { - configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-shell-wrapper-')) + configHome = await fs.mkdtemp(join(tmpdir(), 'ocm-shell-wrapper-')) }) afterEach(async () => { @@ -27,15 +27,15 @@ describe('sandbox shell wrapper', () => { }) it('derives the sandbox shell directory from the config home', () => { - expect(getSandboxShellDir(configHome)).toBe(path.join(configHome, 'ocm')) + expect(getSandboxShellDir(configHome)).toBe(join(configHome, 'ocm')) }) it('derives the sandbox shell path from the config home', () => { - expect(getSandboxShellPath(configHome)).toBe(path.join(configHome, 'ocm', SANDBOX_SHELL_FILENAME)) + expect(getSandboxShellPath(configHome)).toBe(join(configHome, 'ocm', SANDBOX_SHELL_FILENAME)) }) it('derives the enforced sandbox shell path from the workspace config home', () => { - expect(getEnforcedSandboxShellPath()).toBe(path.join(getWorkspacePath(), '.config', 'ocm', SANDBOX_SHELL_FILENAME)) + expect(getEnforcedSandboxShellPath()).toBe(join(getWorkspacePath(), '.config', 'ocm', SANDBOX_SHELL_FILENAME)) }) it('uses a sandbox shell basename outside the rc-file sourcing basenames so OpenCode never injects shell config', () => { diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.sh index 5ef41151..112f6be4 100644 --- a/scripts/docker-entrypoint.sh +++ b/scripts/docker-entrypoint.sh @@ -63,13 +63,15 @@ install_opencode() { return 1 fi echo "Installing OpenCode ${opencode_version}..." + local staging + staging="$(mktemp -d)" 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 - tar -xzf /tmp/opencode.tar.gz -C /tmp + -o "$staging/opencode.tar.gz" + tar -xzf "$staging/opencode.tar.gz" -C "$staging" mkdir -p "$HOME/.opencode/bin" - mv /tmp/opencode "$HOME/.opencode/bin/opencode" + mv "$staging/opencode" "$HOME/.opencode/bin/opencode" chmod 755 "$HOME/.opencode/bin/opencode" - rm -f /tmp/opencode.tar.gz + rm -rf "$staging" } echo "Checking Bun installation..."