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.
This commit is contained in:
Chris Scott committed 2026-08-22 00:14:19 -04:00
1 parent 0481160f5e
commit 0215de9d92
9 files changed
+108 -28

No files matched your search

@@ -367,8 +367,10 @@ async function restorePluginEntries(dir: string): Promise<void> {
async function readPluginConfigBackup(backupPath: string): Promise<PluginConfigBackup | null> {
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
+23 -7
View File
@@ -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<void> = 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<OpenCodeLifecycleStatus>): Promise<OpenCodeLifecycleStatus> {
private async runLifecycleOperation(
operation: () => Promise<OpenCodeLifecycleStatus>,
options: { droppable?: boolean } = {},
): Promise<OpenCodeLifecycleStatus> {
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<void>((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()
}
}
@@ -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<void> {
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())
}
}
@@ -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<void> {
@@ -190,11 +190,15 @@ const runOpenCodeSection = (snippet: string, env: Record<string, string> = {}) =
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', () => {
@@ -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'] } },
@@ -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<void>((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)
})
})
@@ -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', () => {
+6 -4
View File
@@ -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..."