diff --git a/backend/src/services/opencode-plugin-quarantine.ts b/backend/src/services/opencode-plugin-quarantine.ts index 277ac262..8e234aeb 100644 --- a/backend/src/services/opencode-plugin-quarantine.ts +++ b/backend/src/services/opencode-plugin-quarantine.ts @@ -180,8 +180,9 @@ async function requireRealDirectory(dir: string, purpose: string): Promise WRAPPED_COMMANDS_CAP) { + wrappedCommands.delete(wrappedCommands.keys().next().value) + } +} + function replaceCommand(output, command, callID) { if (!lockArgsReference(output, output.args)) { throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host') @@ -57,7 +70,7 @@ function replaceCommand(output, command, callID) { if (!lockCommand(output.args, command)) { throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host') } - wrappedCommands.set(callID, command) + rememberWrapped(callID, command) } export default async function ({ directory, worktree }) { @@ -133,10 +146,10 @@ export default async function ({ directory, worktree }) { }, 'tool.execute.after': async (input, output) => { if (input.tool !== 'bash') return - if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return var wrapped = wrappedCommands.get(input.callID) - if (wrapped === undefined) return wrappedCommands.delete(input.callID) + if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return + if (wrapped === undefined) return if (!bypassed && input.args && input.args.command !== wrapped) { bypassed = true console.error('OpenCode Manager: sandbox enforcement bypass detected for bash call ' + input.callID + '; blocking all further sandboxed commands') @@ -146,4 +159,3 @@ export default async function ({ directory, worktree }) { } ` } - diff --git a/backend/src/services/opencode/proxy-policy.ts b/backend/src/services/opencode/proxy-policy.ts index f09f42ee..b0339001 100644 --- a/backend/src/services/opencode/proxy-policy.ts +++ b/backend/src/services/opencode/proxy-policy.ts @@ -17,7 +17,12 @@ function stripSandboxProxyApiPrefix(pathname: string): string { return pathname } +function isAmbiguousSandboxProxyPath(pathname: string): boolean { + return pathname !== '/' && (pathname.includes('//') || pathname.endsWith('/')) +} + function canonicalizeSandboxProxyPath(pathname: string): string | null { + if (isAmbiguousSandboxProxyPath(pathname)) return null if (!pathname.includes('%')) return stripSandboxProxyApiPrefix(pathname) if (ENCODED_PATH_HAZARD.test(pathname)) return null try { diff --git a/backend/src/services/sandbox/shell-wrapper.ts b/backend/src/services/sandbox/shell-wrapper.ts index 0bad7847..40d4091c 100644 --- a/backend/src/services/sandbox/shell-wrapper.ts +++ b/backend/src/services/sandbox/shell-wrapper.ts @@ -11,7 +11,7 @@ var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)} var PLAN_TIMEOUT_MS = ${sandboxPlanTimeoutMs()} function failClosed(reason) { - process.stdout.write(SANDBOX_UNAVAILABLE_PREFIX + reason + '\\n') + process.stderr.write(SANDBOX_UNAVAILABLE_PREFIX + reason + '\\n') process.exit(1) } diff --git a/backend/test/routes/opencode-proxy.test.ts b/backend/test/routes/opencode-proxy.test.ts index bc095c53..763d008b 100644 --- a/backend/test/routes/opencode-proxy.test.ts +++ b/backend/test/routes/opencode-proxy.test.ts @@ -408,6 +408,52 @@ describe('opencode-proxy routes', () => { expect(upstreamFetch).not.toHaveBeenCalled() }) + it('blocks duplicate-separator PTY creation with 403 when the OpenCode child is enforced', async () => { + isSandboxEnforcedMock.mockReturnValue(true) + const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached')) + globalThis.fetch = upstreamFetch as unknown as typeof fetch + + const res = await app.request('/api/opencode-proxy//pty', { + method: 'POST', + headers: { Authorization: 'Bearer test-internal-token' }, + }) + + expect(res.status).toBe(403) + expect(upstreamFetch).not.toHaveBeenCalled() + }) + + it('blocks trailing-separator PTY creation with 403 when the OpenCode child is enforced', async () => { + isSandboxEnforcedMock.mockReturnValue(true) + const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached')) + globalThis.fetch = upstreamFetch as unknown as typeof fetch + + const res = await app.request('/api/opencode-proxy/pty/', { + method: 'POST', + headers: { Authorization: 'Bearer test-internal-token' }, + }) + + expect(res.status).toBe(403) + expect(upstreamFetch).not.toHaveBeenCalled() + }) + + it('blocks duplicate-separator config mutation with 403 when the OpenCode child is enforced', async () => { + isSandboxEnforcedMock.mockReturnValue(true) + const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached')) + globalThis.fetch = upstreamFetch as unknown as typeof fetch + + const res = await app.request('/api/opencode-proxy//config', { + method: 'PATCH', + headers: { + Authorization: 'Bearer test-internal-token', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ theme: 'dark' }), + }) + + expect(res.status).toBe(403) + expect(upstreamFetch).not.toHaveBeenCalled() + }) + it('forwards custom slash command execution when the OpenCode child is enforced', async () => { isSandboxEnforcedMock.mockReturnValue(true) const upstreamFetch = vi.fn().mockResolvedValue( diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 6a513fc8..ff8c0f21 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -108,7 +108,7 @@ vi.mock('../../src/services/opencode-single-server', async (importOriginal) => { restart: vi.fn(), clearStartupError: vi.fn(), getLastStartupError: vi.fn(), - checkHealth: vi.fn(() => true), + checkHealth: vi.fn().mockResolvedValue(true), markRestartPending: vi.fn(), isRestartPending: vi.fn(), isSandboxEnforced: vi.fn(), diff --git a/backend/test/services/opencode-plugin-quarantine.test.ts b/backend/test/services/opencode-plugin-quarantine.test.ts index 78d42a25..92b74d30 100644 --- a/backend/test/services/opencode-plugin-quarantine.test.ts +++ b/backend/test/services/opencode-plugin-quarantine.test.ts @@ -798,6 +798,32 @@ describe('opencode plugin quarantine', () => { ).toBe('v1') }) + it('quarantines and restores through a legitimate symlinked ancestor directory', async () => { + const realBase = path.join(root, 'real-base') + mkdirSync(path.join(realBase, '.config', 'opencode', 'plugin'), { recursive: true }) + writeFileSync(path.join(realBase, '.config', 'opencode', 'plugin', 'user-plugin.js'), 'user code') + await fs.symlink(realBase, path.join(root, 'linked-base')) + const linkedConfigHome = path.join(root, 'linked-base', '.config') + const linkedConfigPath = path.join(linkedConfigHome, 'opencode', 'opencode.json') + + await quarantineOpenCodePlugins(linkedConfigHome, linkedConfigPath) + + expect(await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin'))).toEqual([]) + expect( + await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin.ocm-quarantine')), + ).toContain('user-plugin.js') + + await restoreQuarantinedOpenCodePlugins(linkedConfigHome, linkedConfigPath) + + expect(await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin'))).toContain('user-plugin.js') + expect( + await fs.readFile(path.join(realBase, '.config', 'opencode', 'plugin', 'user-plugin.js'), 'utf-8'), + ).toBe('user code') + expect( + await fs.readdir(path.join(realBase, '.config', 'opencode', 'plugin.ocm-quarantine')), + ).toEqual([]) + }) + it('round-trips a legitimate plugin file whose name ends in .ocm-conflict', async () => { writeFileSync(path.join(configHome, 'opencode', 'plugin', 'audit.ocm-conflict1'), 'legit plugin') writeConfig({}) diff --git a/backend/test/services/opencode-sandbox-plugin.test.ts b/backend/test/services/opencode-sandbox-plugin.test.ts index 68a4a0ca..af78ad5e 100644 --- a/backend/test/services/opencode-sandbox-plugin.test.ts +++ b/backend/test/services/opencode-sandbox-plugin.test.ts @@ -7,7 +7,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs' import path from 'path' import os from 'os' import { pathToFileURL } from 'url' -import { SANDBOX_PLAN_TIMEOUT_MS } from '../../src/services/opencode-sandbox-plugin' +import { SANDBOX_PLAN_TIMEOUT_MS, WRAPPED_COMMANDS_CAP } from '../../src/services/opencode-sandbox-plugin' import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry' import { quarantineOpenCodePlugins } from '../../src/services/opencode-plugin-quarantine' @@ -568,6 +568,74 @@ describe('ocm-sandbox plugin', () => { guardFor('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'), ) }) + + it('evicts the oldest tracked call once the wrapped command map exceeds its cap', async () => { + process.env.OCM_SANDBOX_ENFORCED = 'true' + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ mode: 'sandbox', command: "msb exec 'echo wrapped'" }), + }) + vi.stubGlobal('fetch', fetchMock) + + const factory = await loadPlugin(configHome) + const hooks = await factory({ directory: '/repo' }) + + const callIDs = Array.from({ length: WRAPPED_COMMANDS_CAP + 1 }, (_, index) => `call-${index}`) + for (const callID of callIDs) { + await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID }, { args: { command: 'echo hi' } }) + } + + await hooks['tool.execute.after']?.( + { tool: 'bash', sessionID: 's', callID: callIDs[0]!, args: { command: 'echo evil' } }, + { title: '', output: '', metadata: {} }, + ) + + const afterEvicted = { args: { command: 'echo next' } } + await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'after-evicted' }, afterEvicted) + expect(afterEvicted.args.command).toBe("msb exec 'echo wrapped'") + + await hooks['tool.execute.after']?.( + { tool: 'bash', sessionID: 's', callID: callIDs[callIDs.length - 1]!, args: { command: 'echo evil' } }, + { title: '', output: '', metadata: {} }, + ) + + const afterBypass = { args: { command: 'echo blocked' } } + await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'after-bypass' }, afterBypass) + expect(afterBypass.args.command).toBe( + guardFor('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'), + ) + }) + + it('removes the tracked call entry before returning on an enforcement-state change', async () => { + process.env.OCM_SANDBOX_ENFORCED = 'true' + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ mode: 'sandbox', command: "msb exec 'echo hi'" }), + }) + vi.stubGlobal('fetch', fetchMock) + + const factory = await loadPlugin(configHome) + const hooks = await factory({ directory: '/repo' }) + const output = { args: { command: 'echo hi' } } + await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'c' }, output) + expect(output.args.command).toBe("msb exec 'echo hi'") + + delete process.env.OCM_SANDBOX_ENFORCED + await hooks['tool.execute.after']?.( + { tool: 'bash', sessionID: 's', callID: 'c', args: { command: 'echo evil-unwrapped' } }, + { title: '', output: '', metadata: {} }, + ) + + process.env.OCM_SANDBOX_ENFORCED = 'true' + await hooks['tool.execute.after']?.( + { tool: 'bash', sessionID: 's', callID: 'c', args: { command: 'echo evil-unwrapped' } }, + { title: '', output: '', metadata: {} }, + ) + + const next = { args: { command: 'echo should-still-be-planned' } } + await hooks['tool.execute.before']?.({ tool: 'bash', sessionID: 's', callID: 'd' }, next) + expect(next.args.command).toBe("msb exec 'echo hi'") + }) }) function resolveOpencodeBinary(): string | null { diff --git a/backend/test/services/opencode/proxy-policy.test.ts b/backend/test/services/opencode/proxy-policy.test.ts index c4995964..d4313c2a 100644 --- a/backend/test/services/opencode/proxy-policy.test.ts +++ b/backend/test/services/opencode/proxy-policy.test.ts @@ -48,6 +48,56 @@ describe('sandbox proxy policy', () => { expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fpty/p1/connect').blocked).toBe(true) }) + it('fails closed on duplicate and trailing separators when enforced', () => { + expect(decideSandboxProxyBlock(true, 'POST', '/pty/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '//pty').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/api//pty').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/api/pty/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1/connect/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/pty//p1/connect').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '//pty/p1/connect').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/%70ty/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/p%74y/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'GET', '/session//ses_1/message').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/message/').blocked).toBe(true) + }) + + it('does not flag the bare root path as ambiguous when enforced', () => { + expect(decideSandboxProxyBlock(true, 'GET', '/')).toEqual({ blocked: false }) + expect(decideSandboxProxyBlock(true, 'POST', '/api')).toEqual({ blocked: false }) + }) + + it('fails closed on duplicate and trailing separators for config, mcp, and auth mutations when enforced', () => { + expect(decideSandboxProxyBlock(true, 'PATCH', '/config/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'PATCH', '//config').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'PATCH', '/api//config').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/mcp/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '//mcp').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'POST', '/api//mcp').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'PUT', '/auth/openai/').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'PUT', '//auth/openai').blocked).toBe(true) + expect(decideSandboxProxyBlock(true, 'PUT', '/api//auth/openai').blocked).toBe(true) + }) + + it('never classifies ambiguous config, mcp, or auth mutation paths when enforced', () => { + expect(isSandboxConfigMutation(true, 'PATCH', '//config')).toBe(false) + expect(isSandboxConfigMutation(true, 'PATCH', '/api//config')).toBe(false) + expect(isSandboxMcpAdd(true, 'POST', '//mcp')).toBe(false) + expect(isSandboxMcpAdd(true, 'POST', '/api//mcp')).toBe(false) + expect(isSandboxAuthWrite(true, 'PUT', '//auth/openai')).toBe(false) + expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai/')).toBe(false) + expect(isSandboxAuthWrite(true, 'PUT', '/api//auth/openai')).toBe(false) + }) + + it('passes mutation bodies through untouched on ambiguous paths since the block decision gates them when enforced', () => { + expect(decideSandboxMutationBody(true, 'PATCH', '//config', JSON.stringify({ theme: 'dark' }))).toEqual({ kind: 'passthrough' }) + expect(decideSandboxMutationBody(true, 'POST', '/api//mcp', JSON.stringify({ + name: 'remote-server', + config: { type: 'remote', url: 'https://example.com/mcp' }, + }))).toEqual({ kind: 'passthrough' }) + expect(decideSandboxMutationBody(true, 'PUT', '/auth/openai/', JSON.stringify({ type: 'api', key: 'k' }))).toEqual({ kind: 'passthrough' }) + }) + it('classifies /api-prefixed config, mcp, and auth writes identically when enforced', () => { expect(isSandboxConfigMutation(true, 'PATCH', '/api/config')).toBe(true) expect(isSandboxConfigMutation(true, 'PATCH', '/api/%63onfig')).toBe(true) diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index fa204cbf..839ebca2 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -1,6 +1,6 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Database } from 'bun:sqlite' -import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' @@ -33,6 +33,10 @@ vi.mock('../../../src/utils/logger', () => ({ const mockExecuteCommand = executeCommand as ReturnType const mockDetectSandboxCapability = detectSandboxCapability as ReturnType +const originalWorkspacePath = process.env.WORKSPACE_PATH +const suiteWorkspaceParent = mkdtempSync(path.join(realpathSync(tmpdir()), 'ocm-runtime-test-')) +process.env.WORKSPACE_PATH = suiteWorkspaceParent + const reposRoot = getReposPath() const worktreesRoot = getScheduleWorktreesPath() const repoADir = path.join(reposRoot, 'repo-a') @@ -63,6 +67,15 @@ describe('SandboxRuntimeService', () => { rmSync(worktreeDir, { recursive: true, force: true }) }) + afterAll(() => { + if (originalWorkspacePath === undefined) { + delete process.env.WORKSPACE_PATH + } else { + process.env.WORKSPACE_PATH = originalWorkspacePath + } + rmSync(suiteWorkspaceParent, { recursive: true, force: true }) + }) + function enableEnforcement(): void { settingsService.updateSettings({ sandbox: { enabled: true } }) mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.6.8' }) diff --git a/backend/test/services/sandbox/shell-wrapper.test.ts b/backend/test/services/sandbox/shell-wrapper.test.ts index 23973513..ee5ddd7b 100644 --- a/backend/test/services/sandbox/shell-wrapper.test.ts +++ b/backend/test/services/sandbox/shell-wrapper.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { promises as fs } from 'fs' import path from 'path' import os from 'os' +import { spawnSync } from 'child_process' import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { SANDBOX_SHELL_FILENAME, @@ -62,4 +63,15 @@ describe('sandbox shell wrapper', () => { expect(source).toContain('OCM_INTERNAL_TOKEN') expect(source).toContain(SANDBOX_UNAVAILABLE_PREFIX) }) + + it('fail-closes to stderr with exit 1 when the sandbox is unavailable', async () => { + await installSandboxShell(configHome) + + const result = spawnSync(getSandboxShellPath(configHome), [], { encoding: 'utf8' }) + + expect(result.status).toBe(1) + expect(result.stdout).toBe('') + expect(result.stderr).toContain(SANDBOX_UNAVAILABLE_PREFIX) + expect(result.stderr).toContain('interactive shell sessions are not available while sandbox enforcement is on') + }) })