mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(sandbox): route host-shell surfaces into microVM via shell wrapper
This commit is contained in:
1 parent
aa3fb48a62
commit
ae117d6a78
57 files changed
+711
-784
No files matched your search
@@ -16,16 +16,19 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get latest tool versions
|
||||
- name: Resolve tool versions (opencode and microsandbox are intentionally pinned)
|
||||
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 "Detected versions: uv=${UV_VERSION}, opencode=${OPENCODE_VERSION}, microsandbox=${MICROSANDBOX_VERSION}"
|
||||
echo "Versions: uv=${UV_VERSION} (latest), opencode=${OPENCODE_VERSION} (pinned), microsandbox=${MICROSANDBOX_VERSION} (pinned)"
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
|
||||
@@ -51,6 +51,7 @@ import { CredentialProvider } from './services/credential-provider'
|
||||
import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { detectSandboxCapability } from './services/sandbox/capability'
|
||||
import { stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
@@ -297,8 +298,8 @@ try {
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
detectSandboxCapability()
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
opencodeServerManager.setLifecycleInitialized(openCodeStatus.healthy)
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
} else {
|
||||
@@ -338,6 +339,7 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
|
||||
sseAggregator.setPendingActionsFetcher(openCodeClient)
|
||||
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
sseAggregator.setEnforcementResolver(() => opencodeServerManager.isSandboxEnforced())
|
||||
sseAggregator.start()
|
||||
|
||||
sseAggregator.setScheduledSessionsResolver(
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createInternalTokenMiddleware } from '../auth/internal-token-middleware'
|
||||
import type { SettingsService } from '../services/settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { getOpenCodeUpstreamBaseUrl } from '../services/opencode/upstream'
|
||||
import {
|
||||
decideSandboxMutationBody,
|
||||
decideSandboxProxyBlock,
|
||||
@@ -50,7 +51,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
if (decision.blocked) {
|
||||
return c.json({ error: decision.reason }, 403)
|
||||
}
|
||||
const upstreamUrl = `http://127.0.0.1:${ENV.OPENCODE.PORT}${pathSuffix}${url.search}`
|
||||
const upstreamUrl = `${getOpenCodeUpstreamBaseUrl(enforced)}${pathSuffix}${url.search}`
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
c.req.raw.headers.forEach((value, key) => {
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as repoService from '../services/repo'
|
||||
import * as archiveService from '../services/archive'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { restartOpenCode } from '../services/opencode-restart'
|
||||
import { restartOpenCodeAfterCommit } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -420,10 +420,10 @@ app.get('/', async (c) => {
|
||||
logger.info(`Updated OpenCode config: ${openCodeConfigPath}`)
|
||||
|
||||
logger.info('Restarting OpenCode server due to workspace config change')
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
const { restartFailed, restartError } = await restartOpenCodeAfterCommit(openCodeSupervisor)
|
||||
|
||||
const updatedRepo = getRepoById(database, id)
|
||||
return c.json(updatedRepo)
|
||||
return c.json(restartFailed ? { ...updatedRepo, restartFailed, restartError } : updatedRepo)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to switch repo config:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
|
||||
@@ -34,7 +34,7 @@ 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'
|
||||
import { restartOpenCode, reloadOpenCodeConfig, getOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
import { restartOpenCode, restartOpenCodeAfterCommit, reloadOpenCodeConfig, getOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
||||
@@ -463,7 +463,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ ...settings, serverRestarted, reloadError })
|
||||
return c.json({ ...settings, serverRestarted, reloadError, ...(sandboxChanged ? { restartRequired: true } : {}) })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update settings:', error)
|
||||
if (error instanceof Error && error.message.startsWith('Invalid SSH key')) {
|
||||
@@ -482,12 +482,13 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const currentSettings = settingsService.getSettings(userId)
|
||||
const settings = settingsService.resetSettings(userId)
|
||||
|
||||
if (sandboxPreferenceChanged(currentSettings.preferences.sandbox, settings.preferences.sandbox)) {
|
||||
const sandboxChanged = sandboxPreferenceChanged(currentSettings.preferences.sandbox, settings.preferences.sandbox)
|
||||
if (sandboxChanged) {
|
||||
logger.info('Sandbox preference changed, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
}
|
||||
|
||||
return c.json(settings)
|
||||
return c.json(sandboxChanged ? { ...settings, restartRequired: true } : settings)
|
||||
} catch (error) {
|
||||
logger.error('Failed to reset settings:', error)
|
||||
return c.json({ error: 'Failed to reset settings' }, 500)
|
||||
@@ -536,9 +537,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
const { restartFailed, restartError } = await restartOpenCodeAfterCommit(openCodeSupervisor)
|
||||
|
||||
return c.json(config)
|
||||
return c.json(restartFailed ? { ...config, restartFailed, restartError } : config)
|
||||
}
|
||||
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(provisionalConfig.content)
|
||||
@@ -733,9 +734,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
const { restartFailed, restartError } = await restartOpenCodeAfterCommit(openCodeSupervisor)
|
||||
|
||||
return c.json(config)
|
||||
return c.json(restartFailed ? { ...config, restartFailed, restartError } : config)
|
||||
}
|
||||
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(existingConfig.content)
|
||||
@@ -1983,7 +1984,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const token = rotateInternalToken(db)
|
||||
logger.info('Manager token rotated, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ token })
|
||||
return c.json({ token, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to rotate manager token:', error)
|
||||
return c.json({ error: 'Failed to rotate manager token' }, 500)
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import path from 'path'
|
||||
import { writeFileAtomic } from '../utils/fs-safe'
|
||||
|
||||
const PLUGIN_FILENAME = 'ocm-gh-env.js'
|
||||
|
||||
const PLUGIN_SOURCE = `const TTL_MS = 5000
|
||||
export function buildGhEnvPluginSource(): string {
|
||||
return `const TTL_MS = 5000
|
||||
let cache = new Map()
|
||||
|
||||
async function fetchGhEnv(cwd) {
|
||||
@@ -39,11 +35,4 @@ export default async function () {
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export function getGhEnvPluginDir(configHome: string): string {
|
||||
return path.join(configHome, 'opencode', 'plugin')
|
||||
}
|
||||
|
||||
export async function installGhEnvPlugin(configHome: string): Promise<void> {
|
||||
await writeFileAtomic(path.join(getGhEnvPluginDir(configHome), PLUGIN_FILENAME), PLUGIN_SOURCE)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import path from 'path'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import { getOpenCodePluginDir, TRUSTED_OPENCODE_PLUGIN_FILENAMES } from './opencode/plugin-registry'
|
||||
import {
|
||||
isRecord,
|
||||
restoreEnforcementSections,
|
||||
@@ -11,7 +12,6 @@ import {
|
||||
type EnforcementRemovedSections,
|
||||
} from './opencode/enforcement-config'
|
||||
|
||||
export const TRUSTED_OPENCODE_PLUGIN_FILENAMES = ['ocm-sandbox.js', 'ocm-gh-env.js'] as const
|
||||
const TRUSTED_TOOL_FILENAMES: readonly string[] = []
|
||||
const PLUGIN_CONFIG_BACKUP_SUFFIX = '.ocm-sandbox-backup'
|
||||
const QUARANTINE_CONFLICT_SUFFIX = '.ocm-conflict'
|
||||
@@ -58,7 +58,7 @@ function deepEqual(left: unknown, right: unknown): boolean {
|
||||
function getPluginDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'plugin'),
|
||||
getOpenCodePluginDir(configHome),
|
||||
path.join(configHome, 'opencode', 'plugins'),
|
||||
path.join(home, '.opencode', 'plugin'),
|
||||
path.join(home, '.opencode', 'plugins'),
|
||||
@@ -571,7 +571,7 @@ async function restoreEnforcementConfigSections(configPath: string): Promise<voi
|
||||
|
||||
export async function quarantineOpenCodePlugins(configHome: string, configPath: string): Promise<void> {
|
||||
await assertNoWellKnownAuthEntries(configHome)
|
||||
const managerPluginDir = path.join(configHome, 'opencode', 'plugin')
|
||||
const managerPluginDir = getOpenCodePluginDir(configHome)
|
||||
for (const dir of getPluginDirs(configHome)) {
|
||||
await moveUntrustedPluginEntries(dir, dir === managerPluginDir ? TRUSTED_OPENCODE_PLUGIN_FILENAMES : [])
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from './opencode-supervisor'
|
||||
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
let restartCoordinator: OpenCodeRestartCoordinator | null = null
|
||||
|
||||
@@ -67,6 +68,26 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts OpenCode for callers that have already persisted their change. A
|
||||
* failed restart must not be reported as a failed write, so the failure is
|
||||
* logged and returned as a flag instead of thrown; the caller returns the
|
||||
* persisted entity so the client can distinguish "saved but needs a restart"
|
||||
* from "nothing was saved".
|
||||
*/
|
||||
export async function restartOpenCodeAfterCommit(
|
||||
supervisor?: OpenCodeSupervisor,
|
||||
): Promise<{ restartFailed: boolean; restartError?: string }> {
|
||||
try {
|
||||
await restartOpenCode(supervisor)
|
||||
return { restartFailed: false }
|
||||
} catch (error) {
|
||||
const restartError = error instanceof Error ? error.message : String(error)
|
||||
logger.error('OpenCode restart failed after the change was persisted', error)
|
||||
return { restartFailed: true, restartError }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads OpenCode configuration via the non-disruptive API patch. This does
|
||||
* NOT drop the server process, so active sessions keep running and there is
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import path from 'path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
|
||||
import { writeFileAtomic } from '../utils/fs-safe'
|
||||
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
|
||||
|
||||
const PLUGIN_FILENAME = 'ocm-sandbox.js'
|
||||
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
|
||||
|
||||
const SANDBOX_PLAN_REQUEST_MARGIN_MS = 30000
|
||||
|
||||
export const SANDBOX_PLAN_TIMEOUT_MS = ENV.SANDBOX.START_TIMEOUT_MS + SANDBOX_PLAN_REQUEST_MARGIN_MS
|
||||
|
||||
const PLUGIN_SOURCE = `var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
|
||||
export function buildSandboxPluginSource(): string {
|
||||
return `var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
|
||||
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
|
||||
|
||||
function guardCommand(reason) {
|
||||
@@ -151,11 +145,5 @@ export default async function ({ directory, worktree }) {
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export function getSandboxPluginDir(configHome: string): string {
|
||||
return path.join(configHome, 'opencode', 'plugin')
|
||||
}
|
||||
|
||||
export async function installSandboxPlugin(configHome: string): Promise<void> {
|
||||
await writeFileAtomic(path.join(getSandboxPluginDir(configHome), PLUGIN_FILENAME), PLUGIN_SOURCE)
|
||||
}
|
||||
@@ -25,11 +25,12 @@ import { patchConfigWithRecovery } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { writeFileContent } from './file-operations'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { installGhEnvPlugin } from './opencode-gh-env-plugin'
|
||||
import { installSandboxPlugin } from './opencode-sandbox-plugin'
|
||||
import { installManagedPlugins } from './opencode/plugin-registry'
|
||||
import { getEnforcedSandboxShellPath, installSandboxShell } from './sandbox/shell-wrapper'
|
||||
import { getOpenCodePluginDiscoveryHome, quarantineOpenCodePlugins, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
|
||||
import { sanitizeConfigForEnforcement } from './opencode/enforcement-config'
|
||||
import { resolveProcessIdentityProvider } from './opencode/process-identity'
|
||||
import { resolveEffectiveServerHost } from './opencode/upstream'
|
||||
import { SandboxRuntimeService } from './sandbox/runtime'
|
||||
import { CredentialProvider } from './credential-provider'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
@@ -38,7 +39,6 @@ export { sanitizeConfigForEnforcement }
|
||||
|
||||
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MIN_SANDBOX_OPENCODE_VERSION = '1.18.16'
|
||||
const SANDBOX_VERIFIED_OPENCODE_VERSIONS = ['1.18.16']
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
|
||||
@@ -135,25 +135,6 @@ const getOpenCodeServerHost = () => ENV.OPENCODE.HOST
|
||||
const getOpenCodeServerPublicUrl = () => ENV.OPENCODE.PUBLIC_URL
|
||||
const getOpenCodeServerUsername = () => ENV.OPENCODE.SERVER_USERNAME
|
||||
|
||||
function isLoopbackBindHost(host: string): boolean {
|
||||
const normalized = host.trim().toLowerCase().replace(/^\[|\]$/g, '')
|
||||
return (
|
||||
normalized === 'localhost' ||
|
||||
normalized === '127.0.0.1' ||
|
||||
normalized === '::1' ||
|
||||
normalized === '::ffff:127.0.0.1' ||
|
||||
normalized.startsWith('127.')
|
||||
)
|
||||
}
|
||||
|
||||
function resolveEffectiveServerHost(enforced: boolean): string {
|
||||
const openCodeServerHost = getOpenCodeServerHost()
|
||||
if (enforced && !isLoopbackBindHost(openCodeServerHost)) {
|
||||
return '127.0.0.1'
|
||||
}
|
||||
return openCodeServerHost
|
||||
}
|
||||
|
||||
function resolveManagerMicrosandboxEnv(): Record<string, string> {
|
||||
const env: Record<string, string> = {
|
||||
MSB_BACKEND: process.env.MSB_BACKEND ?? 'local',
|
||||
@@ -643,8 +624,8 @@ class OpenCodeServerManager {
|
||||
logger.warn('Failed to restore quarantined OpenCode plugins:', error)
|
||||
}
|
||||
try {
|
||||
await installGhEnvPlugin(pluginConfigHome)
|
||||
await installSandboxPlugin(pluginConfigHome)
|
||||
await installManagedPlugins(pluginConfigHome)
|
||||
await installSandboxShell(pluginConfigHome)
|
||||
} catch (error) {
|
||||
if (sandboxEnforced) {
|
||||
logger.error('Failed to install a generated OpenCode plugin; refusing to start an enforced server', error)
|
||||
@@ -712,7 +693,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
: {}),
|
||||
OPENCODE_CONFIG: openCodeConfigPath,
|
||||
...(sandboxEnforced ? { SHELL: '/bin/bash' } : {}),
|
||||
...(sandboxEnforced ? { SHELL: getEnforcedSandboxShellPath() } : {}),
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -1140,8 +1121,8 @@ class OpenCodeServerManager {
|
||||
return compareVersions(this.version, MIN_OPENCODE_VERSION) >= 0
|
||||
}
|
||||
|
||||
getMinSandboxVersion(): string {
|
||||
return MIN_SANDBOX_OPENCODE_VERSION
|
||||
getSandboxVerifiedVersions(): readonly string[] {
|
||||
return SANDBOX_VERIFIED_OPENCODE_VERSIONS
|
||||
}
|
||||
|
||||
isSandboxVersionSupported(): boolean {
|
||||
|
||||
@@ -131,7 +131,6 @@ export class OpenCodeSupervisor {
|
||||
async reloadConfig(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
return this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './upstream'
|
||||
|
||||
export interface ForwardRequest {
|
||||
method: string
|
||||
@@ -35,8 +36,6 @@ export interface OpenCodeClient {
|
||||
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
|
||||
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
|
||||
deleteProviderAuth(providerId: string): Promise<boolean>
|
||||
startMcpAuth(serverName: string, directory?: string): Promise<Response>
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export type OpenCodeClientHost = string | (() => string)
|
||||
@@ -234,28 +233,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async startMcpAuth(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async authenticateMcp(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function formatOpenCodeHostForUrl(host: string): string {
|
||||
return host.includes(':') ? `[${host}]` : host
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(
|
||||
@@ -263,11 +240,7 @@ export function createOpenCodeClient(
|
||||
host?: OpenCodeClientHost,
|
||||
): OpenCodeClient {
|
||||
const resolveConfiguredHost = typeof host === 'function' ? host : () => (host ?? ENV.OPENCODE.HOST)
|
||||
const baseUrl: OpenCodeClientHost = () => {
|
||||
const configuredHost = resolveConfiguredHost()
|
||||
const normalized = configuredHost === '0.0.0.0' ? '127.0.0.1' : configuredHost
|
||||
return `http://${formatOpenCodeHostForUrl(normalized)}:${ENV.OPENCODE.PORT}`
|
||||
}
|
||||
const baseUrl: OpenCodeClientHost = () => getOpenCodeUpstreamBaseUrl(false, resolveConfiguredHost())
|
||||
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import path from 'path'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin'
|
||||
import { buildSandboxPluginSource } from '../opencode-sandbox-plugin'
|
||||
|
||||
export type ManagedOpenCodePlugin = {
|
||||
filename: string
|
||||
buildSource: () => string
|
||||
}
|
||||
|
||||
export const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [
|
||||
{ filename: 'ocm-gh-env.js', buildSource: buildGhEnvPluginSource },
|
||||
{ filename: 'ocm-sandbox.js', buildSource: buildSandboxPluginSource },
|
||||
]
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -32,16 +32,6 @@ const BLOCKED_ENFORCED_ROUTES: ReadonlyArray<{
|
||||
pathPattern: RegExp
|
||||
reason: string
|
||||
}> = [
|
||||
{
|
||||
methods: ['POST'],
|
||||
pathPattern: /^\/session\/[^/]+\/shell$/,
|
||||
reason: 'the session shell endpoint (`!command`) runs in the OpenCode host process',
|
||||
},
|
||||
{
|
||||
methods: ['POST'],
|
||||
pathPattern: /^\/session\/[^/]+\/command$/,
|
||||
reason: 'custom slash commands can run shell templates in the OpenCode host process',
|
||||
},
|
||||
{
|
||||
methods: ['POST'],
|
||||
pathPattern: /^\/pty$/,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
function isLoopbackBindHost(host: string): boolean {
|
||||
const normalized = host.trim().toLowerCase().replace(/^\[|\]$/g, '')
|
||||
return (
|
||||
normalized === 'localhost' ||
|
||||
normalized === '127.0.0.1' ||
|
||||
normalized === '::1' ||
|
||||
normalized === '::ffff:127.0.0.1' ||
|
||||
normalized.startsWith('127.')
|
||||
)
|
||||
}
|
||||
|
||||
function resolveEffectiveHost(enforced: boolean, host: string): string {
|
||||
return enforced && !isLoopbackBindHost(host) ? '127.0.0.1' : host
|
||||
}
|
||||
|
||||
export function resolveEffectiveServerHost(enforced: boolean): string {
|
||||
return resolveEffectiveHost(enforced, ENV.OPENCODE.HOST)
|
||||
}
|
||||
|
||||
function formatOpenCodeHostForUrl(host: string): string {
|
||||
if (host.startsWith('[') && host.endsWith(']')) return host
|
||||
return host.includes(':') ? `[${host}]` : host
|
||||
}
|
||||
|
||||
export function getOpenCodeUpstreamBaseUrl(enforced: boolean, hostOverride?: string | (() => string)): string {
|
||||
const configuredHost = typeof hostOverride === 'function' ? hostOverride() : (hostOverride ?? ENV.OPENCODE.HOST)
|
||||
const effectiveHost = resolveEffectiveHost(enforced, configuredHost)
|
||||
const normalizedHost = effectiveHost === '0.0.0.0' ? '127.0.0.1' : effectiveHost
|
||||
return `http://${formatOpenCodeHostForUrl(normalizedHost)}:${ENV.OPENCODE.PORT}`
|
||||
}
|
||||
@@ -48,7 +48,10 @@ export function detectSandboxCapability(): SandboxCapability {
|
||||
|
||||
const result = spawnSync(executable, buildSandboxVersionArgs(), { encoding: 'utf8', timeout: 10000 })
|
||||
if (result.status !== 0 || result.error) {
|
||||
const reason = 'msb CLI not found or not executable'
|
||||
const detail = result.error
|
||||
? result.error.message
|
||||
: (result.stderr ?? '').trim() || `exit code ${String(result.status)}`
|
||||
const reason = `msb CLI version probe failed at ${executable}: ${detail}`
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
|
||||
@@ -7,6 +7,12 @@ export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
|
||||
|
||||
export const SANDBOX_UNAVAILABLE_PREFIX = 'Sandbox enforcement is on but the sandbox is unavailable: '
|
||||
|
||||
const SANDBOX_PLAN_REQUEST_MARGIN_MS = 30000
|
||||
|
||||
export function sandboxPlanTimeoutMs(): number {
|
||||
return ENV.SANDBOX.START_TIMEOUT_MS + SANDBOX_PLAN_REQUEST_MARGIN_MS
|
||||
}
|
||||
|
||||
let cachedExecutablePath: string | null | undefined
|
||||
let executableTrustValidator: ((candidate: string) => boolean) | null = null
|
||||
|
||||
|
||||
@@ -43,11 +43,22 @@ export type SandboxStatus = {
|
||||
let inFlightBoot: Promise<void> | null = null
|
||||
let lastKnownRunningAt: number | null = null
|
||||
let shutdownRequested = false
|
||||
let stopInProgress = false
|
||||
let canonicalSandboxSpecMemo: Record<string, unknown> | null = null
|
||||
|
||||
export function resetSandboxRuntimeState(): void {
|
||||
inFlightBoot = null
|
||||
lastKnownRunningAt = null
|
||||
shutdownRequested = false
|
||||
stopInProgress = false
|
||||
canonicalSandboxSpecMemo = null
|
||||
}
|
||||
|
||||
function memoizedCanonicalSandboxSpec(): Record<string, unknown> {
|
||||
if (canonicalSandboxSpecMemo === null) {
|
||||
canonicalSandboxSpecMemo = buildCanonicalSandboxSpec()
|
||||
}
|
||||
return canonicalSandboxSpecMemo
|
||||
}
|
||||
|
||||
async function validateSandboxMountRoots(): Promise<void> {
|
||||
@@ -79,13 +90,13 @@ function ensureWorkspaceSandbox(): Promise<void> {
|
||||
return inFlightBoot
|
||||
}
|
||||
inFlightBoot = (async () => {
|
||||
await validateSandboxMountRoots()
|
||||
if (shutdownRequested) {
|
||||
if (shutdownRequested || stopInProgress) {
|
||||
throw new Error('sandbox shutdown is in progress; refusing to boot the workspace sandbox')
|
||||
}
|
||||
if (lastKnownRunningAt !== null && Date.now() - lastKnownRunningAt < SANDBOX_LS_CACHE_MS) {
|
||||
return
|
||||
}
|
||||
await validateSandboxMountRoots()
|
||||
await bootWorkspaceSandbox()
|
||||
})().finally(() => {
|
||||
inFlightBoot = null
|
||||
@@ -95,26 +106,35 @@ function ensureWorkspaceSandbox(): Promise<void> {
|
||||
|
||||
async function bootWorkspaceSandbox(): Promise<void> {
|
||||
try {
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
|
||||
if (!entry) {
|
||||
await createWorkspaceSandbox()
|
||||
const outcome = await inspectSandbox()
|
||||
if (outcome.kind === 'failed' || (outcome.record.config === undefined && outcome.record.active_config === undefined)) {
|
||||
await bootWorkspaceSandboxFromListing()
|
||||
} else {
|
||||
const attestation = await attestWorkspaceSandbox(entry.running)
|
||||
if (!attestation.trusted) {
|
||||
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
} else if (!entry.running) {
|
||||
await startWorkspaceSandbox()
|
||||
const runningAttestation = await attestWorkspaceSandbox(true)
|
||||
if (!runningAttestation.trusted) {
|
||||
logger.warn(
|
||||
`Recreating sandbox ${WORKSPACE_SANDBOX_NAME} that failed running attestation: ${runningAttestation.reason}`,
|
||||
)
|
||||
const inspected = outcome.record
|
||||
if (inspected.active_config !== undefined && inspected.active_config !== null) {
|
||||
const attestation = await attestWorkspaceSandboxConfig(inspected.active_config)
|
||||
if (!attestation.trusted) {
|
||||
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
}
|
||||
} else {
|
||||
const attestation = await attestWorkspaceSandboxConfig(inspected.config)
|
||||
if (!attestation.trusted) {
|
||||
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
} else {
|
||||
await startWorkspaceSandbox()
|
||||
const runningAttestation = await attestWorkspaceSandbox(true)
|
||||
if (!runningAttestation.trusted) {
|
||||
logger.warn(
|
||||
`Recreating sandbox ${WORKSPACE_SANDBOX_NAME} that failed running attestation: ${runningAttestation.reason}`,
|
||||
)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +145,31 @@ async function bootWorkspaceSandbox(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function bootWorkspaceSandboxFromListing(): Promise<void> {
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
|
||||
if (!entry) {
|
||||
await createWorkspaceSandbox()
|
||||
} else {
|
||||
const attestation = await attestWorkspaceSandbox(entry.running)
|
||||
if (!attestation.trusted) {
|
||||
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
} else if (!entry.running) {
|
||||
await startWorkspaceSandbox()
|
||||
const runningAttestation = await attestWorkspaceSandbox(true)
|
||||
if (!runningAttestation.trusted) {
|
||||
logger.warn(
|
||||
`Recreating sandbox ${WORKSPACE_SANDBOX_NAME} that failed running attestation: ${runningAttestation.reason}`,
|
||||
)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxAttestation = { trusted: true } | { trusted: false; reason: string }
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
@@ -187,7 +232,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
|
||||
return { trusted: false, reason: 'msb inspect returned an unexpected config shape' }
|
||||
}
|
||||
|
||||
const canonical = buildCanonicalSandboxSpec()
|
||||
const canonical = memoizedCanonicalSandboxSpec()
|
||||
|
||||
const labels = isRecord(spec.labels) ? spec.labels : {}
|
||||
const canonicalLabels = isRecord(canonical.labels) ? canonical.labels : {}
|
||||
@@ -436,7 +481,11 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
|
||||
return { trusted: true }
|
||||
}
|
||||
|
||||
async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestation> {
|
||||
type SandboxInspectOutcome =
|
||||
| { kind: 'parsed'; record: Record<string, unknown> }
|
||||
| { kind: 'failed'; reason: string }
|
||||
|
||||
async function inspectSandbox(): Promise<SandboxInspectOutcome> {
|
||||
let result: string | { exitCode: number; stdout: string; stderr: string }
|
||||
try {
|
||||
result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxInspectArgs()], {
|
||||
@@ -445,13 +494,13 @@ async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestat
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
} catch (error) {
|
||||
return { trusted: false, reason: `msb inspect failed: ${error instanceof Error ? error.message : String(error)}` }
|
||||
return { kind: 'failed', reason: `msb inspect failed: ${error instanceof Error ? error.message : String(error)}` }
|
||||
}
|
||||
const listing = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
if (listing.exitCode !== 0) {
|
||||
return {
|
||||
trusted: false,
|
||||
kind: 'failed',
|
||||
reason: `msb inspect failed with code ${listing.exitCode}: ${listing.stderr || listing.stdout}`,
|
||||
}
|
||||
}
|
||||
@@ -460,18 +509,26 @@ async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestat
|
||||
try {
|
||||
parsed = JSON.parse(listing.stdout)
|
||||
} catch {
|
||||
return { trusted: false, reason: 'msb inspect returned malformed JSON' }
|
||||
return { kind: 'failed', reason: 'msb inspect returned malformed JSON' }
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return { trusted: false, reason: 'msb inspect returned an unexpected JSON shape' }
|
||||
return { kind: 'failed', reason: 'msb inspect returned an unexpected JSON shape' }
|
||||
}
|
||||
return { kind: 'parsed', record: parsed }
|
||||
}
|
||||
|
||||
async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestation> {
|
||||
const outcome = await inspectSandbox()
|
||||
if (outcome.kind === 'failed') {
|
||||
return { trusted: false, reason: outcome.reason }
|
||||
}
|
||||
if (running) {
|
||||
if (parsed.active_config === undefined || parsed.active_config === null) {
|
||||
if (outcome.record.active_config === undefined || outcome.record.active_config === null) {
|
||||
return { trusted: false, reason: 'msb inspect returned no active configuration for the running sandbox' }
|
||||
}
|
||||
return await attestWorkspaceSandboxConfig(parsed.active_config)
|
||||
return await attestWorkspaceSandboxConfig(outcome.record.active_config)
|
||||
}
|
||||
return await attestWorkspaceSandboxConfig(parsed.config)
|
||||
return await attestWorkspaceSandboxConfig(outcome.record.config)
|
||||
}
|
||||
|
||||
async function createWorkspaceSandbox(): Promise<void> {
|
||||
@@ -604,6 +661,15 @@ export class SandboxRuntimeService {
|
||||
}
|
||||
|
||||
private async stopManagedSandbox(): Promise<void> {
|
||||
stopInProgress = true
|
||||
try {
|
||||
await this.runManagedSandboxStop()
|
||||
} finally {
|
||||
stopInProgress = false
|
||||
}
|
||||
}
|
||||
|
||||
private async runManagedSandboxStop(): Promise<void> {
|
||||
while (inFlightBoot) {
|
||||
try {
|
||||
await inFlightBoot
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import path from 'path'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './command'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
|
||||
export const SANDBOX_SHELL_FILENAME = 'ocm-sandbox-shell'
|
||||
|
||||
const buildWrapperSource = (): string => `import { spawn } from 'child_process'
|
||||
|
||||
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.exit(1)
|
||||
}
|
||||
|
||||
function extractCommand(argv) {
|
||||
for (var index = 0; index < argv.length; index++) {
|
||||
if (argv[index] === '-c' && index + 1 < argv.length) {
|
||||
var command = argv[index + 1]
|
||||
if (typeof command === 'string' && command.length > 0) {
|
||||
return command
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function main() {
|
||||
var command = extractCommand(process.argv.slice(2))
|
||||
if (command === null) {
|
||||
failClosed('interactive shell sessions are not available while sandbox enforcement is on')
|
||||
return
|
||||
}
|
||||
var cwd = process.cwd()
|
||||
var baseUrl = process.env.OCM_INTERNAL_API_URL
|
||||
var token = process.env.OCM_INTERNAL_TOKEN
|
||||
if (!baseUrl || !token) {
|
||||
failClosed('internal API is not configured')
|
||||
return
|
||||
}
|
||||
var controller = new AbortController()
|
||||
var planTimedOut = false
|
||||
var planTimer = setTimeout(function () {
|
||||
planTimedOut = true
|
||||
controller.abort()
|
||||
}, PLAN_TIMEOUT_MS)
|
||||
try {
|
||||
var response = await fetch(baseUrl + '/sandbox/command', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
Authorization: 'Bearer ' + token,
|
||||
},
|
||||
body: JSON.stringify({ directory: cwd, command: command, enforced: true }),
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
failClosed('sandbox plan request failed with status ' + response.status)
|
||||
return
|
||||
}
|
||||
var plan = await response.json()
|
||||
if (plan && typeof plan === 'object' && plan.mode === 'sandbox' && typeof plan.command === 'string' && plan.command.length > 0) {
|
||||
var child = spawn('/bin/sh', ['-c', plan.command], { stdio: 'inherit' })
|
||||
child.on('exit', function (code, signal) {
|
||||
process.exit(code ?? (signal ? 1 : 0))
|
||||
})
|
||||
child.on('error', function (error) {
|
||||
failClosed(error instanceof Error ? error.message : String(error))
|
||||
})
|
||||
} else {
|
||||
var reason = plan && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response'
|
||||
failClosed(reason)
|
||||
}
|
||||
} catch (error) {
|
||||
failClosed(planTimedOut ? 'sandbox plan lookup timed out' : (error instanceof Error ? error.message : String(error)))
|
||||
} finally {
|
||||
clearTimeout(planTimer)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
`
|
||||
|
||||
export function getSandboxShellDir(configHome: string): string {
|
||||
return path.join(configHome, 'ocm')
|
||||
}
|
||||
|
||||
export function getSandboxShellPath(configHome: string): string {
|
||||
return path.join(getSandboxShellDir(configHome), SANDBOX_SHELL_FILENAME)
|
||||
}
|
||||
|
||||
export function getEnforcedSandboxShellPath(): string {
|
||||
return getSandboxShellPath(path.join(getWorkspacePath(), '.config'))
|
||||
}
|
||||
|
||||
export async function installSandboxShell(configHome: string): Promise<void> {
|
||||
const source = `#!${process.execPath}\n${buildWrapperSource()}`
|
||||
await writeFileAtomic(getSandboxShellPath(configHome), source, { mode: 0o700 })
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { EventSource } from 'eventsource'
|
||||
import { logger } from '../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
import type { SSEEventEnvelope, SSEEventPayload } from '@opencode-manager/shared'
|
||||
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './opencode/auth'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './opencode/upstream'
|
||||
import { encodeSSEFrame } from '../utils/sse-frame'
|
||||
|
||||
type SSEClientCallback = (event: string, data: string) => void
|
||||
@@ -45,7 +45,6 @@ interface PendingQuestion {
|
||||
type SessionStatusValue = { type: string } & Record<string, unknown>
|
||||
type SessionStatusMap = Record<string, SessionStatusValue>
|
||||
|
||||
const OPENCODE_PORT = ENV.OPENCODE.PORT
|
||||
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
|
||||
|
||||
class SSEAggregator {
|
||||
@@ -64,9 +63,14 @@ class SSEAggregator {
|
||||
private pendingActionsFetcher: PendingActionsFetcher | null = null
|
||||
private passwordResolver: OpenCodePasswordResolver | null = null
|
||||
private scheduledSessionsResolver: (() => ScheduledSessionRef[]) | null = null
|
||||
private enforcementResolver: (() => boolean) | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
setEnforcementResolver(resolver: (() => boolean) | null): void {
|
||||
this.enforcementResolver = resolver
|
||||
}
|
||||
|
||||
setPendingActionsFetcher(fetcher: PendingActionsFetcher | null): void {
|
||||
this.pendingActionsFetcher = fetcher
|
||||
}
|
||||
@@ -327,7 +331,7 @@ class SSEAggregator {
|
||||
this.upstream = null
|
||||
}
|
||||
|
||||
const url = `http://127.0.0.1:${OPENCODE_PORT}/global/event`
|
||||
const url = `${getOpenCodeUpstreamBaseUrl(this.enforcementResolver?.() ?? false)}/global/event`
|
||||
const wasConnectedBefore = this.everConnected
|
||||
logger.info(`SSE connecting to OpenCode global stream: ${url}`)
|
||||
|
||||
|
||||
@@ -9,8 +9,6 @@ export function createStubOpenCodeClient(overrides: Partial<OpenCodeClient> = {}
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response(JSON.stringify({}), { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response(JSON.stringify({}), { status: 200 })),
|
||||
...overrides,
|
||||
} as OpenCodeClient
|
||||
}
|
||||
@@ -33,8 +33,6 @@ describe('internal/assistant routes', () => {
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
|
||||
|
||||
@@ -85,8 +85,6 @@ describe('internal-opencode-workspaces routes', () => {
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
|
||||
@@ -144,20 +144,20 @@ describe('authenticated opencode proxy routes', () => {
|
||||
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth/authenticate')
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint with 403 when enforced', async () => {
|
||||
it('forwards the session shell endpoint when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/shell', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps host-process shell endpoints blocked when enforcement resolution failed (fail-closed manager state)', async () => {
|
||||
it('forwards the session shell endpoint while enforcement is on', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/shell', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks /api-prefixed PTY creation with 403 when enforced', async () => {
|
||||
@@ -168,10 +168,10 @@ describe('authenticated opencode proxy routes', () => {
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks percent-encoded shell spellings with 403 when enforced', async () => {
|
||||
it('blocks percent-encoded PTY spellings with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/%73hell', { method: 'POST' })
|
||||
const res = await app.request('/api/opencode/%70ty', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
@@ -181,7 +181,7 @@ describe('authenticated opencode proxy routes', () => {
|
||||
it('fails closed on encoded separators in proxied paths when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1%2Fshell', { method: 'POST' })
|
||||
const res = await app.request('/api/opencode/pty%2Fp1', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -302,9 +302,11 @@ describe('opencode-proxy routes', () => {
|
||||
expect(res.headers.get('content-type')).toBe('text/plain')
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint with 403 when the OpenCode child is enforced', async () => {
|
||||
it('forwards the session shell endpoint when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/shell', {
|
||||
@@ -312,16 +314,15 @@ describe('opencode-proxy routes', () => {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('host process')
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps host-process shell endpoints blocked when enforcement resolution failed (fail-closed manager state)', async () => {
|
||||
it('forwards the session shell endpoint while enforcement is on', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/shell', {
|
||||
@@ -329,18 +330,16 @@ describe('opencode-proxy routes', () => {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks percent-encoded shell spellings with 403 when the OpenCode child is enforced', async () => {
|
||||
it('blocks percent-encoded PTY spellings 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/session/ses_1/%73hell', {
|
||||
const res = await app.request('/api/opencode-proxy/%70ty', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
@@ -357,7 +356,7 @@ describe('opencode-proxy routes', () => {
|
||||
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/session/ses_1%2Fshell', {
|
||||
const res = await app.request('/api/opencode-proxy/pty%2Fp1', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
@@ -409,9 +408,11 @@ describe('opencode-proxy routes', () => {
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks custom slash command execution with 403 when the OpenCode child is enforced', async () => {
|
||||
it('forwards custom slash command execution when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/command', {
|
||||
@@ -419,8 +420,8 @@ describe('opencode-proxy routes', () => {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add with 403 when the OpenCode child is enforced', async () => {
|
||||
|
||||
@@ -81,8 +81,6 @@ vi.mock('../../src/services/opencode/client', () => ({
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
|
||||
@@ -49,16 +49,19 @@ describe('entrypoint library wiring', () => {
|
||||
expect(warnIndex).toBeLessThan(chownIndex)
|
||||
})
|
||||
|
||||
it('grants node access to /dev/kvm before dropping privileges', () => {
|
||||
it('grants node access to /dev/kvm before dropping privileges without aborting startup', () => {
|
||||
const entrypoint = read(entrypointPath)
|
||||
expect(entrypoint).toMatch(/^grant_kvm_access\(\) \{/m)
|
||||
const alignIndex = entrypoint.indexOf('if ! align_container_user node; then')
|
||||
const grantCallIndex = entrypoint.indexOf('if ! grant_kvm_access; then')
|
||||
const runuserIndex = entrypoint.indexOf('exec runuser -u node')
|
||||
expect(alignIndex, 'entrypoint must align the container user').toBeGreaterThan(-1)
|
||||
expect(grantCallIndex, 'entrypoint must call grant_kvm_access').toBeGreaterThan(-1)
|
||||
expect(grantCallIndex).toBeGreaterThan(alignIndex)
|
||||
expect(runuserIndex).toBeGreaterThan(grantCallIndex)
|
||||
expect(entrypoint.slice(grantCallIndex, grantCallIndex + 60)).toMatch(/exit 1/)
|
||||
const grantBlock = entrypoint.slice(grantCallIndex, grantCallIndex + 200)
|
||||
expect(grantBlock).toMatch(/WARNING: continuing without \/dev\/kvm access/)
|
||||
expect(grantBlock.slice(0, grantBlock.indexOf('fi'))).not.toMatch(/exit 1/)
|
||||
})
|
||||
|
||||
it('does not re-chown /app when ids change', () => {
|
||||
|
||||
@@ -177,6 +177,7 @@ const runOpenCodeSection = (snippet: string, env: Record<string, string> = {}) =
|
||||
PATH: `${stubDir}:${homeDir}/.opencode/bin:/usr/bin:/bin`,
|
||||
OCM_STUB_LOG: logPath,
|
||||
HOME: homeDir,
|
||||
OPENCODE_BUNDLED_VERSION: '1.18.16',
|
||||
...env,
|
||||
},
|
||||
})
|
||||
@@ -204,6 +205,16 @@ describe('install_opencode', () => {
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('refuses to guess the pinned build when OPENCODE_BUNDLED_VERSION is unset', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`, {
|
||||
OPENCODE_BUNDLED_VERSION: '',
|
||||
})
|
||||
expect(res.status).not.toBe(0)
|
||||
expect(res.stderr).toContain('OPENCODE_BUNDLED_VERSION is not set')
|
||||
expect(curlLog()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('honors an OPENCODE_BUNDLED_VERSION override for the download URL', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`, {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { pathToFileURL } from 'url'
|
||||
import { installGhEnvPlugin, getGhEnvPluginDir } from '../../src/services/opencode-gh-env-plugin'
|
||||
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
|
||||
|
||||
type ShellEnvHook = (
|
||||
input: { cwd: string },
|
||||
@@ -12,7 +12,7 @@ type ShellEnvHook = (
|
||||
type PluginFactory = () => Promise<{ 'shell.env': ShellEnvHook }>
|
||||
|
||||
async function loadPlugin(configHome: string): Promise<PluginFactory> {
|
||||
const file = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
|
||||
const file = path.join(getOpenCodePluginDir(configHome), 'ocm-gh-env.js')
|
||||
const mod = await import(pathToFileURL(file).href)
|
||||
return mod.default as PluginFactory
|
||||
}
|
||||
@@ -22,7 +22,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-ghenv-'))
|
||||
await installGhEnvPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
process.env.OCM_INTERNAL_API_URL = 'http://localhost:5003/api/internal'
|
||||
process.env.OCM_INTERNAL_TOKEN = 'secret-token'
|
||||
})
|
||||
@@ -35,12 +35,12 @@ describe('ocm-gh-env plugin', () => {
|
||||
})
|
||||
|
||||
it('writes the plugin file into the auto-discovery dir', async () => {
|
||||
const file = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
|
||||
const file = path.join(getOpenCodePluginDir(configHome), 'ocm-gh-env.js')
|
||||
await expect(fs.access(file)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('atomically replaces a symlink at the plugin path with a regular file', async () => {
|
||||
const pluginDir = getGhEnvPluginDir(configHome)
|
||||
const pluginDir = getOpenCodePluginDir(configHome)
|
||||
const pluginPath = path.join(pluginDir, 'ocm-gh-env.js')
|
||||
const symlinkTarget = path.join(pluginDir, 'attacker-hook.js')
|
||||
await fs.mkdir(pluginDir, { recursive: true })
|
||||
@@ -48,7 +48,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
await fs.writeFile(symlinkTarget, 'export default async function () {}')
|
||||
await fs.symlink(symlinkTarget, pluginPath)
|
||||
|
||||
await installGhEnvPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
|
||||
const stat = await fs.lstat(pluginPath)
|
||||
expect(stat.isFile()).toBe(true)
|
||||
@@ -62,7 +62,7 @@ describe('ocm-gh-env plugin', () => {
|
||||
await fs.mkdir(blockedHome, { recursive: true })
|
||||
await fs.writeFile(path.join(blockedHome, 'opencode'), 'not a directory')
|
||||
|
||||
await expect(installGhEnvPlugin(blockedHome)).rejects.toThrow()
|
||||
await expect(installManagedPlugins(blockedHome)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('injects fetched GH env into output.env', async () => {
|
||||
|
||||
@@ -6,8 +6,8 @@ import os from 'os'
|
||||
import {
|
||||
quarantineOpenCodePlugins,
|
||||
restoreQuarantinedOpenCodePlugins,
|
||||
TRUSTED_OPENCODE_PLUGIN_FILENAMES,
|
||||
} from '../../src/services/opencode-plugin-quarantine'
|
||||
import { TRUSTED_OPENCODE_PLUGIN_FILENAMES } from '../../src/services/opencode/plugin-registry'
|
||||
|
||||
describe('opencode plugin quarantine', () => {
|
||||
let root: string
|
||||
|
||||
@@ -13,6 +13,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
|
||||
import {
|
||||
restartOpenCode,
|
||||
restartOpenCodeAfterCommit,
|
||||
setOpenCodeRestartCoordinator,
|
||||
} from '../../src/services/opencode-restart'
|
||||
import type { OpenCodeRestartCoordinator } from '../../src/services/opencode-restart-coordinator'
|
||||
@@ -91,3 +92,29 @@ describe('restartOpenCode', () => {
|
||||
expect(managerMock.clearStartupError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('restartOpenCodeAfterCommit', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
it('reports success without a restart error when the restart completes', async () => {
|
||||
managerMock.checkHealth.mockReturnValue(true)
|
||||
|
||||
await expect(restartOpenCodeAfterCommit(createSupervisor(true))).resolves.toEqual({ restartFailed: false })
|
||||
})
|
||||
|
||||
it('reports the failure instead of throwing so the caller can still return the persisted entity', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue('OpenCode health check failed')
|
||||
|
||||
const result = await restartOpenCodeAfterCommit(createSupervisor(false))
|
||||
|
||||
expect(result.restartFailed).toBe(true)
|
||||
expect(result.restartError).toBe('OpenCode health check failed')
|
||||
})
|
||||
})
|
||||
@@ -7,8 +7,8 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { pathToFileURL } from 'url'
|
||||
import { installSandboxPlugin, getSandboxPluginDir, SANDBOX_PLAN_TIMEOUT_MS } from '../../src/services/opencode-sandbox-plugin'
|
||||
import { installGhEnvPlugin, getGhEnvPluginDir } from '../../src/services/opencode-gh-env-plugin'
|
||||
import { SANDBOX_PLAN_TIMEOUT_MS } from '../../src/services/opencode-sandbox-plugin'
|
||||
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
|
||||
import { quarantineOpenCodePlugins } from '../../src/services/opencode-plugin-quarantine'
|
||||
|
||||
type ExecuteBeforeHook = (
|
||||
@@ -26,7 +26,7 @@ type PluginHooks = {
|
||||
type PluginFactory = (ctx: { directory: string; worktree?: string }) => Promise<PluginHooks>
|
||||
|
||||
async function loadPlugin(configHome: string): Promise<PluginFactory> {
|
||||
const file = path.join(getSandboxPluginDir(configHome), 'ocm-sandbox.js')
|
||||
const file = path.join(getOpenCodePluginDir(configHome), 'ocm-sandbox.js')
|
||||
const mod = await import(pathToFileURL(file).href)
|
||||
return mod.default as PluginFactory
|
||||
}
|
||||
@@ -50,7 +50,7 @@ describe('ocm-sandbox plugin', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-sandbox-'))
|
||||
await installSandboxPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
process.env.OCM_INTERNAL_API_URL = 'http://localhost:5003/api/internal'
|
||||
process.env.OCM_INTERNAL_TOKEN = 'secret-token'
|
||||
})
|
||||
@@ -64,14 +64,14 @@ describe('ocm-sandbox plugin', () => {
|
||||
})
|
||||
|
||||
it('writes the plugin file into the auto-discovery dir', async () => {
|
||||
const file = path.join(getSandboxPluginDir(configHome), 'ocm-sandbox.js')
|
||||
const file = path.join(getOpenCodePluginDir(configHome), 'ocm-sandbox.js')
|
||||
await expect(fs.access(file)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('derives the plan deadline from the configured sandbox startup window', async () => {
|
||||
const { ENV } = await import('@opencode-manager/shared/config/env')
|
||||
expect(SANDBOX_PLAN_TIMEOUT_MS).toBeGreaterThan(ENV.SANDBOX.START_TIMEOUT_MS)
|
||||
const pluginSource = await fs.readFile(path.join(getSandboxPluginDir(configHome), 'ocm-sandbox.js'), 'utf-8')
|
||||
const pluginSource = await fs.readFile(path.join(getOpenCodePluginDir(configHome), 'ocm-sandbox.js'), 'utf-8')
|
||||
expect(pluginSource).toContain(`var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}`)
|
||||
})
|
||||
|
||||
@@ -80,11 +80,11 @@ describe('ocm-sandbox plugin', () => {
|
||||
await fs.mkdir(blockedHome, { recursive: true })
|
||||
await fs.writeFile(path.join(blockedHome, 'opencode'), 'not a directory')
|
||||
|
||||
await expect(installSandboxPlugin(blockedHome)).rejects.toThrow()
|
||||
await expect(installManagedPlugins(blockedHome)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('atomically replaces a symlink at the plugin path with a regular file', async () => {
|
||||
const pluginDir = getSandboxPluginDir(configHome)
|
||||
const pluginDir = getOpenCodePluginDir(configHome)
|
||||
const pluginPath = path.join(pluginDir, 'ocm-sandbox.js')
|
||||
const symlinkTarget = path.join(pluginDir, 'attacker-hook.js')
|
||||
await fs.mkdir(pluginDir, { recursive: true })
|
||||
@@ -92,7 +92,7 @@ describe('ocm-sandbox plugin', () => {
|
||||
await fs.writeFile(symlinkTarget, 'export default async function () {}')
|
||||
await fs.symlink(symlinkTarget, pluginPath)
|
||||
|
||||
await installSandboxPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
|
||||
const stat = await fs.lstat(pluginPath)
|
||||
expect(stat.isFile()).toBe(true)
|
||||
@@ -102,10 +102,10 @@ describe('ocm-sandbox plugin', () => {
|
||||
})
|
||||
|
||||
it('installs both generated plugins as regular files containing the generated sources', async () => {
|
||||
await installGhEnvPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
|
||||
const sandboxPath = path.join(getSandboxPluginDir(configHome), 'ocm-sandbox.js')
|
||||
const ghEnvPath = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
|
||||
const sandboxPath = path.join(getOpenCodePluginDir(configHome), 'ocm-sandbox.js')
|
||||
const ghEnvPath = path.join(getOpenCodePluginDir(configHome), 'ocm-gh-env.js')
|
||||
|
||||
const sandboxStat = await fs.lstat(sandboxPath)
|
||||
const ghEnvStat = await fs.lstat(ghEnvPath)
|
||||
@@ -702,7 +702,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-sandbox plugin against the s
|
||||
2,
|
||||
),
|
||||
)
|
||||
await installSandboxPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
mkdirSync(path.join(workDir, '.opencode', 'plugin'), { recursive: true })
|
||||
writeFileSync(
|
||||
path.join(workDir, '.opencode', 'plugin', 'evil.js'),
|
||||
@@ -893,7 +893,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-sandbox plugin against the s
|
||||
2,
|
||||
),
|
||||
)
|
||||
await installSandboxPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
writeFileSync(
|
||||
path.join(workDir, '.opencode', 'plugin', 'evil.js'),
|
||||
`import { writeFileSync } from 'node:fs'\nwriteFileSync(${JSON.stringify(repoMarker)}, 'executed')\nexport default async function () { return {} }\n`,
|
||||
@@ -1090,7 +1090,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-sandbox plugin against the s
|
||||
2,
|
||||
),
|
||||
)
|
||||
await installSandboxPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
|
||||
const runOpencode = (env: Record<string, string>) => new Promise<{ status: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
@@ -1285,7 +1285,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-sandbox plugin against the s
|
||||
2,
|
||||
),
|
||||
)
|
||||
await installSandboxPlugin(configHome)
|
||||
await installManagedPlugins(configHome)
|
||||
|
||||
const runOpencode = (env: Record<string, string>) => new Promise<{ status: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
|
||||
@@ -7,8 +7,6 @@ const createOpenCodeClientMock = vi.hoisted(() => vi.fn(() => ({
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
})))
|
||||
|
||||
const spawnMock = vi.hoisted(() => vi.fn(() => ({
|
||||
@@ -88,16 +86,10 @@ vi.mock('../../src/services/opencode/client', () => ({
|
||||
createOpenCodeClient: createOpenCodeClientMock,
|
||||
}))
|
||||
|
||||
const installSandboxPluginMock = vi.hoisted(() => vi.fn())
|
||||
const installManagedPluginsMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('../../src/services/opencode-sandbox-plugin', () => ({
|
||||
installSandboxPlugin: installSandboxPluginMock,
|
||||
}))
|
||||
|
||||
const installGhEnvPluginMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('../../src/services/opencode-gh-env-plugin', () => ({
|
||||
installGhEnvPlugin: installGhEnvPluginMock,
|
||||
vi.mock('../../src/services/opencode/plugin-registry', () => ({
|
||||
installManagedPlugins: installManagedPluginsMock,
|
||||
}))
|
||||
|
||||
const quarantineOpenCodePluginsMock = vi.hoisted(() => vi.fn())
|
||||
@@ -617,10 +609,15 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('drops a user-supplied HOME serverEnvVars entry from the spawned env', async () => {
|
||||
it('overrides a user-supplied HOME serverEnvVars entry with the plugin discovery home when enforced', async () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => false,
|
||||
isEnabled: () => true,
|
||||
}))
|
||||
execSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd.includes('lsof')) return spawnMock.mock.calls.length > 0 ? '1234\n' : ''
|
||||
if (cmd.includes('opencode --version')) return '1.18.16\n'
|
||||
throw new Error('not found')
|
||||
})
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPreferencesDb({
|
||||
@@ -633,54 +630,6 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
expect(env.HOME).not.toBe('/tmp/evil-home')
|
||||
})
|
||||
|
||||
it('drops executable-resolution and runtime-loader serverEnvVars from the spawned env', async () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => false,
|
||||
}))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPreferencesDb({
|
||||
serverEnvVars: [
|
||||
{ key: 'PATH', value: '/tmp/evil-bin' },
|
||||
{ key: 'BUN_OPTIONS', value: '--preload=/tmp/evil.js' },
|
||||
{ key: 'NODE_OPTIONS', value: '--require /tmp/evil.js' },
|
||||
{ key: 'LD_PRELOAD', value: '/tmp/evil.so' },
|
||||
{ key: 'LD_LIBRARY_PATH', value: '/tmp/evil-lib' },
|
||||
],
|
||||
}))
|
||||
|
||||
await manager.start()
|
||||
|
||||
const env = (spawnMock.mock.calls[0] as unknown as [unknown, unknown, { env: Record<string, string> }])[2].env
|
||||
expect(env.PATH).not.toBe('/tmp/evil-bin')
|
||||
expect(env.BUN_OPTIONS).toBeUndefined()
|
||||
expect(env.NODE_OPTIONS).toBeUndefined()
|
||||
expect(env.LD_PRELOAD).toBeUndefined()
|
||||
expect(env.LD_LIBRARY_PATH).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops shell-selection and shell-startup serverEnvVars from the spawned env', async () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => false,
|
||||
}))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPreferencesDb({
|
||||
serverEnvVars: [
|
||||
{ key: 'SHELL', value: '/workspace/repos/evil/evil-sh' },
|
||||
{ key: 'BASH_ENV', value: '/workspace/repos/evil/rc' },
|
||||
{ key: 'ENV', value: '/workspace/repos/evil/envrc' },
|
||||
],
|
||||
}))
|
||||
|
||||
await manager.start()
|
||||
|
||||
const env = (spawnMock.mock.calls[0] as unknown as [unknown, unknown, { env: Record<string, string> }])[2].env
|
||||
expect(env.SHELL).not.toBe('/workspace/repos/evil/evil-sh')
|
||||
expect(env.BASH_ENV).toBeUndefined()
|
||||
expect(env.ENV).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops config-source and well-known auth serverEnvVars from the spawned env', async () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => false,
|
||||
@@ -768,7 +717,9 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
await manager.start()
|
||||
|
||||
const env = (spawnMock.mock.calls[0] as unknown as [unknown, unknown, { env: Record<string, string> }])[2].env
|
||||
expect(env.SHELL).toBe('/bin/bash')
|
||||
const { getEnforcedSandboxShellPath } = await import('../../src/services/sandbox/shell-wrapper')
|
||||
expect(env.SHELL).toBe(getEnforcedSandboxShellPath())
|
||||
expect(env.SHELL).not.toContain('/repos/')
|
||||
expect(env.BASH_ENV).toBeUndefined()
|
||||
expect(env.ENV).toBeUndefined()
|
||||
} finally {
|
||||
@@ -2282,7 +2233,11 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
throw new Error('not found')
|
||||
})
|
||||
const writeFileMock = fs.writeFile as unknown as ReturnType<typeof vi.fn>
|
||||
writeFileMock.mockRejectedValueOnce(new Error('disk full'))
|
||||
writeFileMock.mockImplementation((filePath: unknown) =>
|
||||
String(filePath).includes('opencode-server-child.json')
|
||||
? Promise.reject(new Error('disk full'))
|
||||
: Promise.resolve(),
|
||||
)
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPasswordDb(null))
|
||||
@@ -2294,6 +2249,7 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
expect((manager as any).serverPid).toBeNull()
|
||||
expect(manager.getLastStartupError()).toContain('Failed to persist the OpenCode child state marker')
|
||||
} finally {
|
||||
;(fs.writeFile as unknown as ReturnType<typeof vi.fn>).mockReset()
|
||||
killSpy.mockRestore()
|
||||
Object.defineProperty(ENV.SERVER, 'NODE_ENV', { value: originalNodeEnv, configurable: true, writable: true })
|
||||
}
|
||||
@@ -2499,19 +2455,18 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
}
|
||||
}, 15000)
|
||||
|
||||
it('installs the sandbox plugin into the same config dir as the gh-env plugin', async () => {
|
||||
it('installs the generated plugins into the same config dir', async () => {
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
await OpenCodeServerManager.getInstance().start()
|
||||
|
||||
expect(installSandboxPluginMock).toHaveBeenCalledWith('/test/workspace/.config')
|
||||
expect(installManagedPluginsMock).toHaveBeenCalledWith('/test/workspace/.config')
|
||||
})
|
||||
|
||||
it('installs both generated plugins into the same auto-discovery config dir', async () => {
|
||||
it('installs all generated plugins into the same auto-discovery config dir', async () => {
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
await OpenCodeServerManager.getInstance().start()
|
||||
|
||||
expect(installGhEnvPluginMock).toHaveBeenCalledWith('/test/workspace/.config')
|
||||
expect(installSandboxPluginMock).toHaveBeenCalledWith('/test/workspace/.config')
|
||||
expect(installManagedPluginsMock).toHaveBeenCalledWith('/test/workspace/.config')
|
||||
})
|
||||
|
||||
it('aborts enforced startup when the gh-env plugin cannot be installed', async () => {
|
||||
@@ -2523,7 +2478,7 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
if (cmd.includes('opencode --version')) return '1.18.16\n'
|
||||
throw new Error('not found')
|
||||
})
|
||||
installGhEnvPluginMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
installManagedPluginsMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPasswordDb(null))
|
||||
@@ -2536,7 +2491,7 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => false,
|
||||
}))
|
||||
installGhEnvPluginMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
installManagedPluginsMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPasswordDb(null))
|
||||
@@ -2647,7 +2602,7 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
if (cmd.includes('opencode --version')) return '1.18.16\n'
|
||||
throw new Error('not found')
|
||||
})
|
||||
installSandboxPluginMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
installManagedPluginsMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPasswordDb(null))
|
||||
@@ -2660,7 +2615,7 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({
|
||||
isEnabled: () => false,
|
||||
}))
|
||||
installSandboxPluginMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
installManagedPluginsMock.mockRejectedValueOnce(new Error('readonly filesystem'))
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const manager = OpenCodeServerManager.getInstance()
|
||||
manager.setDatabase(createPasswordDb(null))
|
||||
@@ -2860,8 +2815,6 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}))
|
||||
|
||||
await manager.start()
|
||||
@@ -2883,10 +2836,10 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
expect(manager.isRestartPending()).toBe(false)
|
||||
})
|
||||
|
||||
it('exposes the minimum sandbox-compatible OpenCode version', async () => {
|
||||
it('exposes the sandbox-verified OpenCode versions as the single version gate', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
|
||||
expect(opencodeServerManager.getMinSandboxVersion()).toBe('1.18.16')
|
||||
expect(opencodeServerManager.getSandboxVerifiedVersions()).toEqual(['1.18.16'])
|
||||
expect(opencodeServerManager.isSandboxVersionSupported()).toBe(false)
|
||||
})
|
||||
|
||||
|
||||
@@ -459,7 +459,7 @@ describe('OpenCodeSupervisor', () => {
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate for the whole reload transition and reopens once healthy', async () => {
|
||||
it('keeps the proxy lifecycle gate open across a config reload so in-flight sessions are never interrupted', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
@@ -469,6 +469,7 @@ describe('OpenCodeSupervisor', () => {
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
manager.setLifecycleInitialized.mockClear()
|
||||
|
||||
let releaseReload!: () => void
|
||||
manager.reloadConfig.mockImplementationOnce(
|
||||
@@ -478,13 +479,13 @@ describe('OpenCodeSupervisor', () => {
|
||||
|
||||
const reload = supervisor.reloadConfig('settings_reload')
|
||||
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
expect(manager.setLifecycleInitialized).not.toHaveBeenCalledWith(false)
|
||||
|
||||
releaseReload()
|
||||
const status = await reload
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
expect(manager.setLifecycleInitialized).not.toHaveBeenCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate while stopping and never reopens it', async () => {
|
||||
|
||||
@@ -206,6 +206,7 @@ describe('OpenCodeClient', () => {
|
||||
|
||||
it('honours an explicit host override instead of OPENCODE_HOST', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalHost = ENV.OPENCODE.HOST
|
||||
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '192.168.1.10', configurable: true, writable: true })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
@@ -220,7 +221,7 @@ describe('OpenCodeClient', () => {
|
||||
|
||||
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
|
||||
} finally {
|
||||
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '127.0.0.1', configurable: true, writable: true })
|
||||
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: originalHost, configurable: true, writable: true })
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
@@ -462,40 +463,4 @@ describe('OpenCodeClient', () => {
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startMcpAuth', () => {
|
||||
it('should build path with encoded serverName and directory param', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.startMcpAuth('foo bar', '/dir')
|
||||
|
||||
expect(capturedUrl?.pathname).toBe('/mcp/foo%20bar/auth')
|
||||
expect(capturedUrl?.searchParams.get('directory')).toBe('/dir')
|
||||
expect(result).toBeInstanceOf(Response)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticateMcp', () => {
|
||||
it('should build path with auth/authenticate suffix', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.authenticateMcp('name', undefined)
|
||||
|
||||
expect(capturedUrl?.pathname).toBe('/mcp/name/auth/authenticate')
|
||||
expect(capturedUrl?.searchParams.has('directory')).toBe(false)
|
||||
expect(result).toBeInstanceOf(Response)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -71,14 +71,6 @@ function createStubClient(
|
||||
async deleteProviderAuth(_providerId: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async startMcpAuth(_serverName: string, _directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async authenticateMcp(_serverName: string, _directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,12 +246,6 @@ describe('patchConfigWithRecovery', () => {
|
||||
async deleteProviderAuth(providerId: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async startMcpAuth(serverName: string, directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async authenticateMcp(serverName: string, directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
}
|
||||
|
||||
const config = { command: { review: 'test' } }
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
isSandboxAuthWrite,
|
||||
SANDBOX_BLOCKED_REASON_PREFIX,
|
||||
SANDBOX_CONFIG_MUTATION_REASON_PREFIX,
|
||||
} from '../../../src/services/opencode/proxy-policy'
|
||||
|
||||
@@ -19,17 +18,12 @@ describe('sandbox proxy policy', () => {
|
||||
expect(decideSandboxProxyBlock(false, 'POST', '/session/s1/command')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint when enforced', () => {
|
||||
const decision = decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell')
|
||||
expect(decision.blocked).toBe(true)
|
||||
if (decision.blocked) {
|
||||
expect(decision.reason).toContain(SANDBOX_BLOCKED_REASON_PREFIX)
|
||||
expect(decision.reason).toContain('host process')
|
||||
}
|
||||
it('forwards the session shell endpoint when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('blocks custom slash command execution when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/command').blocked).toBe(true)
|
||||
it('forwards custom slash command execution when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/command')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('blocks PTY creation and connection when enforced', () => {
|
||||
@@ -41,8 +35,8 @@ describe('sandbox proxy policy', () => {
|
||||
it('treats /api-prefixed execution routes identically to unprefixed routes when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/pty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1/connect').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/shell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/command').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/shell')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/session/ses_1/command')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api/p%74y').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/session')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1')).toEqual({ blocked: false })
|
||||
@@ -51,7 +45,7 @@ describe('sandbox proxy policy', () => {
|
||||
|
||||
it('fails closed on encoded separators inside the /api prefix when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fpty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fsession/ses_1/shell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/api%2Fpty/p1/connect').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies /api-prefixed config, mcp, and auth writes identically when enforced', () => {
|
||||
@@ -80,21 +74,21 @@ describe('sandbox proxy policy', () => {
|
||||
})
|
||||
|
||||
it('blocks percent-encoded spellings of blocked routes when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%73hell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%73%68%65%6c%6c').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%63ommand').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/%70ty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty/%70%31/connect').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/p%74y/p1/connect').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/p%74y').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/p%74y/ses_1/connect').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('fails closed on encoded separators, double-encoded, control, and malformed paths when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%2F..').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1%2Fshell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%5Cx').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%2573hell').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%00').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/shell%zz').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/%c0%ae').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty%2F..').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty%2Fp1').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty%5Cx').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/%2570ty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty%00').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty%zz').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/p%c0%ae').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('passes safely encoded non-execution paths through when enforced', () => {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { getOpenCodeUpstreamBaseUrl, resolveEffectiveServerHost } from '../../../src/services/opencode/upstream'
|
||||
|
||||
const originalHost = ENV.OPENCODE.HOST
|
||||
|
||||
function setHost(value: string): void {
|
||||
Object.defineProperty(ENV.OPENCODE, 'HOST', { value, configurable: true, writable: true })
|
||||
}
|
||||
|
||||
describe('getOpenCodeUpstreamBaseUrl', () => {
|
||||
afterEach(() => {
|
||||
setHost(originalHost)
|
||||
})
|
||||
|
||||
it('leaves an IPv4 host unchanged', () => {
|
||||
setHost('127.0.0.1')
|
||||
expect(getOpenCodeUpstreamBaseUrl(false)).toBe(`http://127.0.0.1:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('leaves a plain hostname unchanged', () => {
|
||||
setHost('opencode.internal')
|
||||
expect(getOpenCodeUpstreamBaseUrl(false)).toBe(`http://opencode.internal:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('brackets a bare IPv6 host', () => {
|
||||
setHost('::1')
|
||||
expect(getOpenCodeUpstreamBaseUrl(false)).toBe(`http://[::1]:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('does not double-bracket an already bracketed IPv6 host', () => {
|
||||
setHost('[::1]')
|
||||
expect(getOpenCodeUpstreamBaseUrl(false)).toBe(`http://[::1]:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('normalizes a wildcard bind to loopback', () => {
|
||||
setHost('0.0.0.0')
|
||||
expect(getOpenCodeUpstreamBaseUrl(false)).toBe(`http://127.0.0.1:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('forces loopback for a non-loopback host while enforcement is active', () => {
|
||||
setHost('192.168.1.10')
|
||||
expect(getOpenCodeUpstreamBaseUrl(true)).toBe(`http://127.0.0.1:${ENV.OPENCODE.PORT}`)
|
||||
expect(getOpenCodeUpstreamBaseUrl(false)).toBe(`http://192.168.1.10:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('keeps an IPv6 loopback host while enforcement is active', () => {
|
||||
setHost('::1')
|
||||
expect(getOpenCodeUpstreamBaseUrl(true)).toBe(`http://[::1]:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
|
||||
it('honours an explicit host override over the configured host', () => {
|
||||
setHost('192.168.1.10')
|
||||
expect(getOpenCodeUpstreamBaseUrl(false, '::1')).toBe(`http://[::1]:${ENV.OPENCODE.PORT}`)
|
||||
expect(getOpenCodeUpstreamBaseUrl(false, () => '10.0.0.5')).toBe(`http://10.0.0.5:${ENV.OPENCODE.PORT}`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveEffectiveServerHost', () => {
|
||||
afterEach(() => {
|
||||
setHost(originalHost)
|
||||
})
|
||||
|
||||
it('treats every loopback spelling as already bound to loopback', () => {
|
||||
for (const host of ['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1', '127.1.2.3', '[::1]']) {
|
||||
setHost(host)
|
||||
expect(resolveEffectiveServerHost(true)).toBe(host)
|
||||
}
|
||||
})
|
||||
|
||||
it('rebinds a non-loopback host to loopback while enforcement is active', () => {
|
||||
setHost('0.0.0.0')
|
||||
expect(resolveEffectiveServerHost(true)).toBe('127.0.0.1')
|
||||
expect(resolveEffectiveServerHost(false)).toBe('0.0.0.0')
|
||||
})
|
||||
})
|
||||
@@ -65,7 +65,8 @@ describe('detectSandboxCapability', () => {
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
expect(result.reason).toContain('msb CLI version probe failed')
|
||||
expect(result.reason).toContain('msb: not found')
|
||||
})
|
||||
|
||||
it('reports unavailable when msb --version fails to spawn', () => {
|
||||
@@ -75,7 +76,8 @@ describe('detectSandboxCapability', () => {
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
expect(result.reason).toContain('msb CLI version probe failed')
|
||||
expect(result.reason).toContain('spawn ENOENT')
|
||||
})
|
||||
|
||||
it('reports available with the trimmed msb version when both probes succeed', () => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/s
|
||||
import { migrate } from '../../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../../src/db/migrations'
|
||||
import { SettingsService } from '../../../src/services/settings'
|
||||
import { buildSandboxExecCommandString, resolveSandboxExecUser, sandboxExecutablePath, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../../src/services/sandbox/command'
|
||||
import { buildSandboxExecCommandString, buildSandboxInspectArgs, resolveSandboxExecUser, sandboxExecutablePath, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../../src/services/sandbox/command'
|
||||
import { SandboxRuntimeService, resetSandboxRuntimeState, stopWorkspaceSandboxOnShutdown } from '../../../src/services/sandbox/runtime'
|
||||
import { executeCommand } from '../../../src/utils/process'
|
||||
import { detectSandboxCapability } from '../../../src/services/sandbox/capability'
|
||||
@@ -220,10 +220,11 @@ describe('SandboxRuntimeService', () => {
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(directory, 'echo hi') })
|
||||
expect(mockExecuteCommand).toHaveBeenCalledWith(
|
||||
[sandboxExecutablePath(), 'ls', '--format', 'json'],
|
||||
[sandboxExecutablePath(), ...buildSandboxInspectArgs()],
|
||||
expect.objectContaining({ ignoreExitCode: true, silent: true }),
|
||||
)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('boots the microVM once for concurrent plans in different repo directories', async () => {
|
||||
@@ -242,8 +243,9 @@ describe('SandboxRuntimeService', () => {
|
||||
|
||||
expect(planA).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(dirA, 'echo a') })
|
||||
expect(planB).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(dirB, 'echo b') })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('accepts a schedule-worktree directory', async () => {
|
||||
@@ -306,14 +308,13 @@ describe('SandboxRuntimeService', () => {
|
||||
mode: 'blocked',
|
||||
reason: 'msb start failed with code 1: vm kernel failed to boot: no memory',
|
||||
})
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(2)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('tolerates a non-zero start exit when the follow-up listing shows the sandbox running', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: stoppedListingOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: trustedInspectOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'already running' })
|
||||
.mockResolvedValueOnce({
|
||||
@@ -327,7 +328,7 @@ describe('SandboxRuntimeService', () => {
|
||||
const plan = await service.planCommand(directory, 'echo hi')
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(directory, 'echo hi') })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(2)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
})
|
||||
@@ -377,11 +378,9 @@ describe('SandboxRuntimeService', () => {
|
||||
it('blocks a signal-terminated start and never caches the sandbox as running without proof', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: stoppedListingOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: trustedInspectOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'Command terminated by signal SIGKILL' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: stoppedListingOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: stoppedListingOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: trustedInspectOutput(), stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'Command terminated by signal SIGKILL' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: stoppedListingOutput(), stderr: '' })
|
||||
@@ -393,7 +392,7 @@ describe('SandboxRuntimeService', () => {
|
||||
reason: 'msb start failed with code 1: Command terminated by signal SIGKILL',
|
||||
})
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(2)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
|
||||
const retried = await service.planCommand(repoADir, 'echo hi')
|
||||
@@ -403,7 +402,7 @@ describe('SandboxRuntimeService', () => {
|
||||
reason: 'msb start failed with code 1: Command terminated by signal SIGKILL',
|
||||
})
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(2)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(4)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('removes and recreates a same-name sandbox that is not labelled as managed', async () => {
|
||||
@@ -812,7 +811,7 @@ describe('SandboxRuntimeService', () => {
|
||||
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('start'))).toHaveLength(1)
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('no active configuration'))
|
||||
})
|
||||
|
||||
@@ -1414,7 +1413,7 @@ describe('SandboxRuntimeService', () => {
|
||||
const second = await service.planCommand(repoBDir, 'echo b')
|
||||
expect(second).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoBDir, 'echo b') })
|
||||
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(2)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
@@ -1729,7 +1728,7 @@ describe('SandboxRuntimeService', () => {
|
||||
}
|
||||
}
|
||||
if (args.includes('inspect')) {
|
||||
return runningInspectOutput(realInspectConfig({ env: [{ key: 'PATH', value: '/evil' }] }))
|
||||
return { exitCode: 0, stdout: runningInspectOutput(realInspectConfig({ env: [{ key: 'PATH', value: '/evil' }] })), stderr: '' }
|
||||
}
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
})
|
||||
@@ -1848,8 +1847,9 @@ describe('SandboxRuntimeService', () => {
|
||||
const plan = await service.planCommand(lateDir, 'echo b')
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(lateDir, 'echo b') })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('ls'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
} finally {
|
||||
rmSync(lateDir, { recursive: true, force: true })
|
||||
}
|
||||
@@ -1885,7 +1885,7 @@ describe('SandboxRuntimeService', () => {
|
||||
const second = await service.planCommand(repoADir, 'echo b')
|
||||
|
||||
expect(second).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available or not writable' })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('stops the managed sandbox using the label filter', async () => {
|
||||
@@ -1913,35 +1913,34 @@ describe('SandboxRuntimeService', () => {
|
||||
|
||||
it('serializes shutdown with an in-flight boot and stops only after the boot completes', async () => {
|
||||
enableEnforcement()
|
||||
let releaseLs: () => void = () => {}
|
||||
const lsGate = new Promise<void>((resolve) => {
|
||||
releaseLs = resolve
|
||||
let releaseInspect: () => void = () => {}
|
||||
const inspectGate = new Promise<void>((resolve) => {
|
||||
releaseInspect = resolve
|
||||
})
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('ls')) {
|
||||
await lsGate
|
||||
return { exitCode: 0, stdout: '[]', stderr: '' }
|
||||
if (args.includes('inspect')) {
|
||||
await inspectGate
|
||||
return inspectedRunningSandbox()
|
||||
}
|
||||
if (args.includes('inspect')) return inspectedRunningSandbox()
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const planning = service.planCommand(repoADir, 'echo a')
|
||||
await vi.waitFor(() => {
|
||||
expect(mockExecuteCommand.mock.calls.some((call) => call[0].includes('ls'))).toBe(true)
|
||||
expect(mockExecuteCommand.mock.calls.some((call) => call[0].includes('inspect'))).toBe(true)
|
||||
})
|
||||
|
||||
const stopping = service.stopWorkspaceSandbox()
|
||||
releaseLs()
|
||||
releaseInspect()
|
||||
const plan = await planning
|
||||
await stopping
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo a') })
|
||||
const calls = mockExecuteCommand.mock.calls
|
||||
const runIndex = calls.findIndex((call) => call[0].includes('run'))
|
||||
const inspectIndex = calls.findIndex((call) => call[0].includes('inspect'))
|
||||
const stopIndex = calls.findIndex((call) => call[0].includes('stop'))
|
||||
expect(runIndex).toBeGreaterThanOrEqual(0)
|
||||
expect(stopIndex).toBeGreaterThan(runIndex)
|
||||
expect(inspectIndex).toBeGreaterThanOrEqual(0)
|
||||
expect(stopIndex).toBeGreaterThan(inspectIndex)
|
||||
})
|
||||
|
||||
it('refuses to boot the workspace sandbox once shutdown is in progress', async () => {
|
||||
@@ -2036,7 +2035,8 @@ describe('SandboxRuntimeService', () => {
|
||||
const plan = await service.planCommand(repoADir, 'echo hi')
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', command: buildSandboxExecCommandString(repoADir, 'echo hi') })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(0)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('attempts the toggle stop even when sandbox capability is unavailable', async () => {
|
||||
@@ -2131,9 +2131,11 @@ describe('SandboxRuntimeService', () => {
|
||||
it('re-uses a create failure to invalidate the running cache', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '[]', stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '[]', stderr: '' })
|
||||
.mockRejectedValueOnce(new Error('Command failed with code 1: no KVM acceleration available'))
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '[]', stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '[]', stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce(inspectedRunningSandbox())
|
||||
|
||||
@@ -2242,7 +2244,7 @@ describe('SandboxRuntimeService', () => {
|
||||
|
||||
expect(plan).toEqual({ mode: 'blocked', reason: expect.stringContaining('failed attestation') })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(1)
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
|
||||
|
||||
const retried = await service.planCommand(repoADir, 'echo again')
|
||||
expect(retried).toEqual({ mode: 'blocked', reason: expect.stringContaining('failed attestation') })
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
SANDBOX_SHELL_FILENAME,
|
||||
getSandboxShellDir,
|
||||
getSandboxShellPath,
|
||||
getEnforcedSandboxShellPath,
|
||||
installSandboxShell,
|
||||
} from '../../../src/services/sandbox/shell-wrapper'
|
||||
import { SANDBOX_UNAVAILABLE_PREFIX } from '../../../src/services/sandbox/command'
|
||||
|
||||
const FORBIDDEN_SHELL_BASENAMES = ['bash', 'zsh', 'sh', 'dash', 'ksh', 'fish', 'nu', 'pwsh', 'powershell', 'cmd']
|
||||
|
||||
describe('sandbox shell wrapper', () => {
|
||||
let configHome: string
|
||||
|
||||
beforeEach(async () => {
|
||||
configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-shell-wrapper-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.rm(configHome, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('derives the sandbox shell directory from the config home', () => {
|
||||
expect(getSandboxShellDir(configHome)).toBe(path.join(configHome, 'ocm'))
|
||||
})
|
||||
|
||||
it('derives the sandbox shell path from the config home', () => {
|
||||
expect(getSandboxShellPath(configHome)).toBe(path.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))
|
||||
})
|
||||
|
||||
it('uses a sandbox shell basename outside the rc-file sourcing basenames so OpenCode never injects shell config', () => {
|
||||
expect(FORBIDDEN_SHELL_BASENAMES).not.toContain(SANDBOX_SHELL_FILENAME)
|
||||
})
|
||||
|
||||
it('installs an executable wrapper whose first line is a shebang targeting the runtime binary', async () => {
|
||||
await installSandboxShell(configHome)
|
||||
|
||||
const wrapperPath = getSandboxShellPath(configHome)
|
||||
const stat = await fs.stat(wrapperPath)
|
||||
expect(stat.mode & 0o777).toBe(0o700)
|
||||
|
||||
const source = await fs.readFile(wrapperPath, 'utf-8')
|
||||
const firstLine = source.split('\n')[0]!
|
||||
expect(firstLine.startsWith('#!')).toBe(true)
|
||||
expect(firstLine).toContain(process.execPath)
|
||||
})
|
||||
|
||||
it('writes a wrapper that plans commands through the internal sandbox endpoint with the enforcement token', async () => {
|
||||
await installSandboxShell(configHome)
|
||||
|
||||
const source = await fs.readFile(getSandboxShellPath(configHome), 'utf-8')
|
||||
expect(source).toContain('/sandbox/command')
|
||||
expect(source).toContain('OCM_INTERNAL_TOKEN')
|
||||
expect(source).toContain(SANDBOX_UNAVAILABLE_PREFIX)
|
||||
})
|
||||
})
|
||||
@@ -89,8 +89,6 @@ describe('ScheduleWorktreeManager', () => {
|
||||
forwardRaw: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -118,8 +118,6 @@ function createOpenCodeClientStub(): OpenCodeClient {
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response('', { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response('', { status: 200 })),
|
||||
} as OpenCodeClient
|
||||
}
|
||||
|
||||
|
||||
@@ -124,8 +124,6 @@ function createOpenCodeClientStub(): OpenCodeClient {
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response('', { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response('', { status: 200 })),
|
||||
} as OpenCodeClient
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,6 @@ function createMockClient(skills: Array<{ name: string; description: string; loc
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,19 @@
|
||||
# Grants the container KVM access and persists microsandbox state so OpenCode
|
||||
# agent commands can run inside a microVM. Linux host with /dev/kvm required.
|
||||
# Use with: docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
|
||||
#
|
||||
# This overlay deliberately does NOT use `privileged: true`. It grants only
|
||||
# /dev/kvm (microVM execution), /dev/net/tun and NET_ADMIN (guest networking
|
||||
# for SANDBOX_NET=public). If msb reports a missing device or capability on a
|
||||
# particular host, add that specific entry rather than enabling full privilege.
|
||||
|
||||
services:
|
||||
app:
|
||||
privileged: true
|
||||
devices:
|
||||
- "/dev/kvm:/dev/kvm"
|
||||
- "/dev/net/tun:/dev/net/tun"
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
environment:
|
||||
- SANDBOX_IMAGE=${SANDBOX_IMAGE:-node:24}
|
||||
- SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G}
|
||||
|
||||
+20
-10
@@ -4,20 +4,21 @@ Run agent shell commands inside an isolated microVM instead of directly in the M
|
||||
|
||||
## Overview
|
||||
|
||||
When sandboxing is enabled, every shell command an OpenCode **agent** runs through the `bash` tool is executed inside a microVM managed by [`msb`](https://github.com/superradcompany/microsandbox) instead of in the container that hosts the Manager and the OpenCode server. The agent still works with the same files in the same layout — the microVM sees the repositories through bind mounts — but the process runs under a different kernel and cannot read Manager or provider secrets from the host filesystem. OpenCode also exposes shell surfaces that bypass the `bash` tool hook; those are **blocked** while enforcement is active (see [Host-Shell Surfaces Under Enforcement](#host-shell-surfaces-under-enforcement)).
|
||||
When sandboxing is enabled, every shell command an OpenCode **agent** runs through the `bash` tool is executed inside a microVM managed by [`msb`](https://github.com/superradcompany/microsandbox) instead of in the container that hosts the Manager and the OpenCode server. The agent still works with the same files in the same layout — the microVM sees the repositories through bind mounts — but the process runs under a different kernel and cannot read Manager or provider secrets from the host filesystem. OpenCode also exposes shell surfaces that bypass the `bash` tool hook; those are routed into the same microVM through a Manager-owned shell wrapper (see [Host-Shell Surfaces Under Enforcement](#host-shell-surfaces-under-enforcement)).
|
||||
|
||||
## What Gets Sandboxed
|
||||
|
||||
Sandboxing hooks into the OpenCode `bash` tool, which is how agents execute shell commands. As a result:
|
||||
Sandboxing covers both the OpenCode `bash` tool and every other path through which OpenCode's host process can start a shell. As a result:
|
||||
|
||||
| Execution path | Sandboxed |
|
||||
|----------------|-----------|
|
||||
| Chat session `bash` tool calls | Yes |
|
||||
| Scheduled run commands | Yes |
|
||||
| Subagent `bash` tool calls | Yes |
|
||||
| WebUI `!command` shell mode (`POST /session/:id/shell`) | Blocked while enforced |
|
||||
| WebUI `!command` shell mode (`POST /session/:id/shell`) | Yes |
|
||||
| Slash-command shell templates (`` !`cmd` ``, `POST /session/:id/command`) | Yes |
|
||||
| Skills and prompt-only slash commands | Yes (no shell to sandbox) |
|
||||
| PTY terminals (`POST /pty`, `/pty/:id/connect`) | Blocked while enforced |
|
||||
| Custom slash commands (`POST /session/:id/command`) | Blocked while enforced |
|
||||
| Local MCP server processes (`mcp` config with `type: "local"` / `command`) | Disabled while enforced |
|
||||
| Dynamically added local MCP servers (`POST /mcp`) | Blocked while enforced |
|
||||
| Formatter commands (`formatter` config) | Disabled while enforced |
|
||||
@@ -31,10 +32,19 @@ Manager-side git operations (clone, fetch, worktree creation, credential setup)
|
||||
|
||||
## Host-Shell Surfaces Under Enforcement
|
||||
|
||||
The `bash` tool hook is not the only way OpenCode's host process can spawn a shell: the session-shell endpoint that powers the WebUI `!command` mode, PTY creation and connection, and custom slash-command execution all run in the host process without passing through `tool.execute.before`. While enforcement is active the Manager's OpenCode proxy — both the authenticated `/api/opencode/*` surface and the internal-token `/api/opencode-proxy` surface — rejects these endpoints with `403` and an actionable reason, so neither an authenticated user nor an internal-token caller can make the OpenCode host process execute a command outside the microVM. The shared policy strictly canonicalizes request paths before matching: percent-encoded spellings of a blocked route (for example `/session/s1/%73hell`) are blocked, and any path containing malformed, double-encoded, control-character, or encoded-separator sequences is refused as unsafe rather than forwarded. The WebUI disables `!command` shell mode with the same explanation. Custom slash commands (including commands whose templates only prompt the model) are unavailable while enforcement is on because the proxy cannot distinguish a prompt template from a shell template without trusting user configuration; disable sandboxing and restart to use them. The same proxy surfaces refuse to dynamically add a local MCP server to the running process: `POST /mcp` is only forwarded while enforcement is on when the body is a provably remote server (`type: "remote"` with a URL) — a local (`type: "local"`) or otherwise command-bearing config is rejected with `403`, so neither surface can start an MCP process in the OpenCode host process. This boundary is enforced by the shared proxy policy in `backend/src/services/opencode/proxy-policy.ts`, which is covered by route tests that pin the blocked surface list.
|
||||
The `bash` tool hook is not the only way OpenCode's host process can spawn a shell. The session-shell endpoint that powers the WebUI `!command` mode, slash-command shell templates (`` !`cmd` `` sequences expanded before the prompt is sent), and PTY sessions all resolve a shell through OpenCode's `shell` configuration rather than through `tool.execute.before`.
|
||||
|
||||
Rather than blocking those endpoints, the Manager redirects them into the same microVM. Enforcement already strips the `shell` key from every configuration source OpenCode reads, so OpenCode falls back to the `SHELL` environment variable of its own process — and the Manager stamps `SHELL` to a generated wrapper (`<workspace>/.config/ocm/ocm-sandbox-shell`, installed at every enforced start). The wrapper receives the command as `-c <command>`, asks the Manager's internal `POST /api/internal/sandbox/command` endpoint for a plan — the identical endpoint the `bash` tool hook uses — and executes the returned `msb exec` command. If the sandbox is unavailable for any reason it prints the reason and exits non-zero, so the surface fails closed instead of silently running on the host.
|
||||
|
||||
The wrapper's filename is deliberately not a recognized shell name, so OpenCode passes the command through verbatim instead of sourcing host startup files. It is installed outside every sandbox bind mount, so code running inside the microVM cannot modify it. A failure to install it aborts an enforced start.
|
||||
|
||||
PTY sessions remain blocked with `403`: they require an interactive TTY that `msb exec --no-tty` cannot provide. The Manager's OpenCode proxy — both the authenticated `/api/opencode/*` surface and the internal-token `/api/opencode-proxy` surface — rejects PTY creation and connection with an actionable reason. The shared policy strictly canonicalizes request paths before matching: percent-encoded spellings of a blocked route (for example `/%70ty`) are blocked, and any path containing malformed, double-encoded, control-character, or encoded-separator sequences is refused as unsafe rather than forwarded. The same proxy surfaces refuse to dynamically add a local MCP server to the running process: `POST /mcp` is only forwarded while enforcement is on when the body is a provably remote server (`type: "remote"` with a URL) — a local (`type: "local"`) or otherwise command-bearing config is rejected with `403`, so neither surface can start an MCP process in the OpenCode host process. This boundary is enforced by the shared proxy policy in `backend/src/services/opencode/proxy-policy.ts`, which is covered by route tests that pin the blocked surface list.
|
||||
|
||||
!!! note "Slash-command shell templates run without a project working directory"
|
||||
OpenCode expands `` !`cmd` `` sequences without setting a working directory, so the wrapper sees the OpenCode server's own directory rather than the session's project. That path is outside the sandbox mount roots, so such expansions fail closed with an explanatory message instead of running on the host. Skills and prompt-only slash commands contain no shell sequences and are unaffected.
|
||||
|
||||
!!! warning "Direct OpenCode port exposure bypasses the proxy boundary"
|
||||
Enforcement is applied in two different places. The `bash` tool rewrite runs as a plugin hook (`ocm-sandbox.js`) inside the OpenCode process itself, so it still guards every `bash` tool call even when clients connect directly to the OpenCode server's own port. The blocked host-shell surfaces and the config-mutation sanitization, by contrast, are applied by the Manager's OpenCode proxy. To keep the proxy authoritative, an enforced OpenCode server is always spawned with a loopback bind: when `OPENCODE_HOST` is not a loopback address, the Manager overrides it with `127.0.0.1` for the child (and logs the override), so callers cannot reach the session-shell, PTY, slash-command, or unsanitized configuration endpoints on the OpenCode port directly — the only external path is the Manager proxy, which applies the enforcement policy. The Manager's own OpenCode client follows the same effective host (loopback while enforced, `OPENCODE_HOST` otherwise), so health checks and every proxied request keep targeting the address the child actually binds, including IPv6 loopback hosts. The override is active only while enforcement is on; with the toggle off, `OPENCODE_HOST` is honored as configured.
|
||||
Enforcement is applied in two different places. The `bash` tool rewrite runs as a plugin hook (`ocm-sandbox.js`) inside the OpenCode process itself, and the shell wrapper is selected by the child process's own environment, so both still apply even when clients connect directly to the OpenCode server's own port. The blocked PTY surfaces and the config-mutation sanitization, by contrast, are applied by the Manager's OpenCode proxy. To keep the proxy authoritative, an enforced OpenCode server is always spawned with a loopback bind: when `OPENCODE_HOST` is not a loopback address, the Manager overrides it with `127.0.0.1` for the child (and logs the override), so callers cannot reach the PTY or unsanitized configuration endpoints on the OpenCode port directly — the only external path is the Manager proxy, which applies the enforcement policy. The Manager's own OpenCode client follows the same effective host (loopback while enforced, `OPENCODE_HOST` otherwise), so health checks and every proxied request keep targeting the address the child actually binds, including IPv6 loopback hosts. The override is active only while enforcement is on; with the toggle off, `OPENCODE_HOST` is honored as configured.
|
||||
|
||||
## Host Requirements
|
||||
|
||||
@@ -61,7 +71,7 @@ All projects share **one** microVM:
|
||||
- Each command supplies its own working directory via `msb exec -w`, so `cd`-ing between projects behaves exactly as it does without sandboxing.
|
||||
- To tear the microVM down, remove it by label:
|
||||
```bash
|
||||
msb rm --label ocm.managed=true
|
||||
msb rm --force --label ocm.managed=true
|
||||
```
|
||||
The next sandboxed command recreates it.
|
||||
- A graceful Manager shutdown always attempts to stop any `ocm.managed=true` microVM (`msb stop --label ocm.managed=true`, with `ignoreExitCode` and a finite timeout), independent of the current toggle state, so a VM is never left detached after a restart, a toggle change with a pending restart, or an earlier shutdown step failing.
|
||||
@@ -97,7 +107,7 @@ Enforcement follows this chain:
|
||||
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.
|
||||
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)
|
||||
```
|
||||
Every other fail-closed reason uses the same `Sandbox enforcement is on but the sandbox is unavailable:` prefix followed by its reason — for example, a sandbox that fails to boot reports the underlying `msb` error after the prefix.
|
||||
@@ -111,11 +121,11 @@ Plugins run as ordinary JavaScript inside the OpenCode process and can touch the
|
||||
- The Manager installs exactly two plugins into the auto-discovery directory (`<workspace>/.config/opencode/plugin`): `ocm-sandbox.js` (the enforcement hook) and `ocm-gh-env.js` (host credential injection for the `shell.env` hook). Both are generated by the Manager and are the only trusted plugin files.
|
||||
- **Repository plugins are never evaluated.** Enforced OpenCode children are started with `OPENCODE_DISABLE_PROJECT_CONFIG=1`, so OpenCode does not read project `opencode.json` files or scan `.opencode/plugin` / `.opencode/plugins` directories — including plugins planted in a repository by an agent using the host-side `write` tool or by a cloned repository itself.
|
||||
- **Configured package plugins are disabled.** On an enforced start the Manager removes the `plugin` array from the global OpenCode config file (`<workspace>/.config/opencode/opencode.json`) and writes a backup of the removed sections next to it; the backup is refreshed with the latest configured array whenever the file sanitizer sees new plugins during enforcement, and the entries are merged back when enforcement is turned off and the server restarts. `installConfiguredPlugins` is skipped while enforcement is on. The running process is additionally guarded by stateless enforcement sanitization: config reloads, settings-driven config saves, and mutating `PATCH /config` requests proxied through either Manager OpenCode proxy surface (`/api/opencode/*` or `/api/opencode-proxy/*`) have the `plugin` array stripped from the patch before it reaches the OpenCode server — a body that is not valid JSON or not a JSON object is refused with `403` rather than forwarded — so a persisted config that still contains a plugin array can never re-activate plugins in the running process. Proxied patches are rewritten for that request only: their removed values are discarded rather than backed up, and the proxy never writes to the config file.
|
||||
- **Config-source environment variables are blocked.** OpenCode reads additional config and plugin sources from `OPENCODE_CONFIG`, `OPENCODE_CONFIG_CONTENT`, `OPENCODE_CONFIG_DIR`, `OPENCODE_AUTH_CONTENT`, `OPENCODE_TEST_HOME`, and `OPENCODE_TEST_MANAGED_CONFIG_DIR`. `OPENCODE_AUTH_CONTENT` replaces the whole auth file and can inject a well-known auth entry that triggers the `.well-known/opencode` remote-config fetch; `OPENCODE_TEST_HOME` redirects the home-based `.opencode` plugin and agent discovery directories; `OPENCODE_TEST_MANAGED_CONFIG_DIR` redirects the system managed-config directory. The Manager blocks all six in user-defined `serverEnvVars`, removes the five overridable ones from the child environment entirely, and stamps `OPENCODE_CONFIG` to the Manager's own global config path, so neither a configured environment variable nor a leaked Manager process environment can introduce a third-party config, plugin, or auth source into a child process. OpenCode also skips external plugin discovery and installation when `OPENCODE_PURE` is truthy, which would silently disable the Manager-owned `ocm-sandbox.js` and `ocm-gh-env.js` hooks; the Manager blocks `OPENCODE_PURE` in user-defined `serverEnvVars`, removes any inherited value from the child environment, and stamps `OPENCODE_PURE=false` after the environment spreads in both modes, so neither a configured entry nor an inherited value can switch pure mode on. Executable-resolution, runtime-loader, and shell-selection variables (`PATH`, `BUN_OPTIONS`, `NODE_OPTIONS`, `LD_PRELOAD`, `LD_LIBRARY_PATH`, `SHELL`, `BASH_ENV`, `ENV`) are reserved in the same contract: the Manager spawns the verified `opencode` executable by its absolute path, removes any inherited `SHELL`, `BASH_ENV`, or `ENV` from the child environment in both modes, and stamps `SHELL` to the Manager-selected absolute `/bin/bash` when enforcement is on — so user environment settings cannot select a repository-controlled shell binary or source repository-controlled startup files (`.bashrc`/`$ENV`/`$BASH_ENV`) before the rewritten `msb exec` command runs.
|
||||
- **Config-source environment variables are blocked.** OpenCode reads additional config and plugin sources from `OPENCODE_CONFIG`, `OPENCODE_CONFIG_CONTENT`, `OPENCODE_CONFIG_DIR`, `OPENCODE_AUTH_CONTENT`, `OPENCODE_TEST_HOME`, and `OPENCODE_TEST_MANAGED_CONFIG_DIR`. `OPENCODE_AUTH_CONTENT` replaces the whole auth file and can inject a well-known auth entry that triggers the `.well-known/opencode` remote-config fetch; `OPENCODE_TEST_HOME` redirects the home-based `.opencode` plugin and agent discovery directories; `OPENCODE_TEST_MANAGED_CONFIG_DIR` redirects the system managed-config directory. The Manager blocks all six in user-defined `serverEnvVars`, removes the five overridable ones from the child environment entirely, and stamps `OPENCODE_CONFIG` to the Manager's own global config path, so neither a configured environment variable nor a leaked Manager process environment can introduce a third-party config, plugin, or auth source into a child process. OpenCode also skips external plugin discovery and installation when `OPENCODE_PURE` is truthy, which would silently disable the Manager-owned `ocm-sandbox.js` and `ocm-gh-env.js` hooks; the Manager removes any inherited value from the child environment and stamps `OPENCODE_PURE=false` after the user environment spreads in both modes, so neither a configured entry nor an inherited value can switch pure mode on. Shell selection is protected by stamping rather than by blocking: the Manager spawns the verified `opencode` executable by its absolute path, removes any inherited `SHELL`, `BASH_ENV`, and `ENV` from the child environment in both modes, and stamps `SHELL` to the Manager-generated sandbox shell wrapper after the user environment spreads when enforcement is on — so a configured or inherited value cannot select a repository-controlled shell binary or source repository-controlled startup files (`.bashrc`/`$ENV`/`$BASH_ENV`), and every host-shell surface that resolves a shell is routed into the microVM instead. Variables that only affect the child's own process (`PATH`, `HOME`, `NODE_OPTIONS`, `BUN_OPTIONS`, `LD_PRELOAD`, `LD_LIBRARY_PATH`) are not blocked in `serverEnvVars`, because the values the enforcement boundary depends on are stamped after the user environment and therefore always win.
|
||||
- **User-dropped global plugins are quarantined.** Any file other than the two Manager-owned plugins found in the global plugin directories (`<workspace>/.config/opencode/plugin`, `<workspace>/.config/opencode/plugins`, `$HOME/.opencode/plugin`, `$HOME/.opencode/plugins`) is moved to a sibling `.ocm-quarantine` directory at an enforced start and restored when enforcement is turned off.
|
||||
- **Fail closed.** If the plugin directory cannot be quarantined or the config cannot be sanitized, the Manager refuses to start an enforced server.
|
||||
- **Defense in depth.** In addition, the sandbox plugin locks the rewritten `bash` command argument after planning and verifies the replacement by reading it back; if neither the planned command nor a blocking guard can be installed — for example another plugin froze the argument object — the hook aborts the tool call instead of letting the original command run on the host, and any detected bypass blocks every subsequent sandboxed command.
|
||||
- **Host-execution config sections are disabled.** OpenCode can spawn host processes outside the `bash` hook from configuration sources, and enforcement disables all of them: local MCP servers (a `mcp` entry with `type: "local"` or a `command`), the whole `formatter` configuration, the `shell` configuration, LSP servers (every enabling `lsp` form, whether a non-empty section or `lsp: true`; only an explicit `lsp: false` survives, since it disables built-in LSP processes), experimental hook commands (`experimental.hook`), and custom provider modules (any `provider` entry carrying an `npm` selector, including a `file://` module, which OpenCode would dynamically import in its host process); remote MCP servers and provider entries without an `npm` selector survive. On an enforced start the Manager removes these sections from the global config file and from every native global config file OpenCode loads (`opencode.json`, `opencode.jsonc`, `config.json` under `<workspace>/.config/opencode`, plus `opencode.json` and `opencode.jsonc` under `$HOME/.opencode`), backs up the removed sections next to each file, and merges them back when enforcement is turned off. The same sections are stripped, without any backup, from every live config reload, every settings-driven config save, and every mutating `/config` request proxied through either Manager OpenCode proxy surface. A proxied `POST /mcp` that would add a local or command-bearing MCP server to the running process is refused with `403`, so only provably remote servers can be added while enforcement is active. Global custom tools — TypeScript/JavaScript modules under `<config>/opencode/tool(s)/` and `$HOME/.opencode/tool(s)/` that run in the OpenCode host process — are quarantined to a sibling `.ocm-quarantine` directory at an enforced start and restored when enforcement is off. Project-level `.opencode/tool(s)/` custom tools are covered by `OPENCODE_DISABLE_PROJECT_CONFIG=1`. The consequence: a configured local MCP server, formatter command, shell, LSP server, hook command, or custom provider module cannot read Manager or provider credentials from the host process during enforcement.
|
||||
- **Host-execution config sections are disabled.** OpenCode can spawn host processes outside the `bash` hook from configuration sources, and enforcement disables all of them: local MCP servers (a `mcp` entry with `type: "local"` or a `command`), the whole `formatter` configuration, the `shell` configuration (removing it is what makes OpenCode fall back to the Manager-stamped sandbox shell wrapper), LSP servers (every enabling `lsp` form, whether a non-empty section or `lsp: true`; only an explicit `lsp: false` survives, since it disables built-in LSP processes), experimental hook commands (`experimental.hook`), and custom provider modules (any `provider` entry carrying an `npm` selector, including a `file://` module, which OpenCode would dynamically import in its host process); remote MCP servers and provider entries without an `npm` selector survive. On an enforced start the Manager removes these sections from the global config file and from every native global config file OpenCode loads (`opencode.json`, `opencode.jsonc`, `config.json` under `<workspace>/.config/opencode`, plus `opencode.json` and `opencode.jsonc` under `$HOME/.opencode`), backs up the removed sections next to each file, and merges them back when enforcement is turned off. The same sections are stripped, without any backup, from every live config reload, every settings-driven config save, and every mutating `/config` request proxied through either Manager OpenCode proxy surface. A proxied `POST /mcp` that would add a local or command-bearing MCP server to the running process is refused with `403`, so only provably remote servers can be added while enforcement is active. Global custom tools — TypeScript/JavaScript modules under `<config>/opencode/tool(s)/` and `$HOME/.opencode/tool(s)/` that run in the OpenCode host process — are quarantined to a sibling `.ocm-quarantine` directory at an enforced start and restored when enforcement is off. Project-level `.opencode/tool(s)/` custom tools are covered by `OPENCODE_DISABLE_PROJECT_CONFIG=1`. The consequence: a configured local MCP server, formatter command, shell, LSP server, hook command, or custom provider module cannot read Manager or provider credentials from the host process during enforcement.
|
||||
- **System managed configuration is sanitized.** OpenCode reads the platform managed-config directory — `/etc/opencode` on Linux, `/Library/Application Support/opencode` on macOS, `%ProgramData%\opencode` on Windows — with the highest file-based priority. On an enforced start the Manager sanitizes `opencode.json` and `opencode.jsonc` from that directory with the same backup-and-restore contract as the native global files, so an org-managed config cannot supply a plugin, local MCP server, formatter, shell, LSP server, or hook to the host process. A managed config that contains a host-execution section and cannot be rewritten (for example a read-only bind mount) aborts the enforced start instead of running with unsanitized managed configuration.
|
||||
- **Well-known remote configuration fails closed.** OpenCode fetches organizational default configuration from `${provider}/.well-known/opencode` whenever an authenticated provider entry is a well-known auth entry, and merges the response — including `plugin`, local MCP, formatter, `shell`, LSP, and hook sections — into the running process. That content is fetched by the OpenCode process at startup, so the Manager cannot sanitize it. On an enforced start the Manager inspects the auth file it owns (`<workspace>/.opencode/state/opencode/auth.json`) and refuses to launch whenever it contains a well-known provider entry, with an error naming the provider and the remediation (remove the provider authentication or disable sandboxing). The `OPENCODE_AUTH_CONTENT` environment variable that could inject such an entry is blocked and stripped from the child environment, and both Manager OpenCode proxy surfaces additionally refuse a `PUT /auth/{provider}` write whose body is a well-known auth entry with `403` while enforcement is active — so a well-known entry cannot be added to the running process after the startup check, which would fetch remote host-executed configuration on a later enforced start. Ordinary `api` and `oauth` auth writes continue to pass through.
|
||||
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useUIState } from '@/stores/uiStateStore'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
const createTestQueryClient = () => new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useServerHealth: vi.fn(),
|
||||
useSTT: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
useSendPromptMutate: vi.fn(),
|
||||
sendPromptPending: vi.fn(() => false),
|
||||
useCommands: vi.fn(),
|
||||
useCommandHandler: vi.fn(),
|
||||
useFileSearch: vi.fn(),
|
||||
useModelSelection: vi.fn(),
|
||||
useVariants: vi.fn(),
|
||||
useSessionAgent: vi.fn(),
|
||||
useAgents: vi.fn(),
|
||||
useUserBash: vi.fn(),
|
||||
useSessionAgentStore: vi.fn(),
|
||||
useSendErrorStore: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: mocks.useServerHealth,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSTT', () => ({
|
||||
useSTT: mocks.useSTT,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: mocks.useMobile,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSendPrompt: () => ({ mutate: mocks.useSendPromptMutate, isPending: mocks.sendPromptPending() }),
|
||||
useAbortSession: () => ({ mutate: vi.fn() }),
|
||||
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useOpenCodeClient: () => ({}),
|
||||
useAgents: () => ({ data: [] }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useCommands', () => ({
|
||||
useCommands: mocks.useCommands,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useCommandHandler', () => ({
|
||||
useCommandHandler: mocks.useCommandHandler,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useFileSearch', () => ({
|
||||
useFileSearch: mocks.useFileSearch,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: mocks.useModelSelection,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useVariants', () => ({
|
||||
useVariants: mocks.useVariants,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSessionAgent', () => ({
|
||||
useSessionAgent: mocks.useSessionAgent,
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/userBashStore', () => ({
|
||||
useUserBash: mocks.useUserBash,
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/sessionAgentStore', () => ({
|
||||
useSessionAgentStore: mocks.useSessionAgentStore,
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/sendErrorStore', () => ({
|
||||
useSendErrorStore: mocks.useSendErrorStore,
|
||||
}))
|
||||
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePermissions: () => ({
|
||||
hasForSession: vi.fn().mockReturnValue(false),
|
||||
setShowDialog: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/components/agent/AgentQuickSelect', () => ({
|
||||
AgentQuickSelect: () => <div>AgentQuickSelect</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/model/ModelQuickSelect', () => ({
|
||||
ModelQuickSelect: () => <div>ModelQuickSelect</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/session-status-indicator', () => ({
|
||||
SessionStatusIndicator: () => <div>SessionStatus</div>,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/command/CommandSuggestions', () => ({
|
||||
CommandSuggestions: () => <div>CommandSuggestions</div>,
|
||||
}))
|
||||
|
||||
vi.mock('./MentionSuggestions', () => ({
|
||||
MentionSuggestions: () => <div>MentionSuggestions</div>,
|
||||
}))
|
||||
|
||||
const defaultProps = {
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
directory: '/test',
|
||||
sessionID: 'test-session',
|
||||
showScrollButton: false,
|
||||
isSessionActive: false,
|
||||
isStreamingResponse: false,
|
||||
onScrollToBottom: vi.fn(),
|
||||
}
|
||||
|
||||
describe('PromptInput sandbox shell-mode gating', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mocks.useSTT.mockReturnValue({
|
||||
isRecording: false,
|
||||
isProcessing: false,
|
||||
isSupported: false,
|
||||
isEnabled: false,
|
||||
interimTranscript: '',
|
||||
transcript: '',
|
||||
startRecording: vi.fn(),
|
||||
stopRecording: vi.fn(),
|
||||
abortRecording: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
})
|
||||
mocks.useCommands.mockReturnValue({ filterCommands: vi.fn() })
|
||||
mocks.useCommandHandler.mockReturnValue({ executeCommand: vi.fn() })
|
||||
mocks.useFileSearch.mockReturnValue({ files: [] })
|
||||
mocks.useModelSelection.mockReturnValue({
|
||||
model: null,
|
||||
modelString: 'test-model',
|
||||
setModel: vi.fn(),
|
||||
setActiveModel: vi.fn().mockReturnValue(false),
|
||||
recentModels: [],
|
||||
favoriteModels: [],
|
||||
toggleFavorite: vi.fn(),
|
||||
isModelStateLoading: false,
|
||||
})
|
||||
mocks.useVariants.mockReturnValue({
|
||||
hasVariants: false,
|
||||
currentVariant: null,
|
||||
cycleVariant: vi.fn(),
|
||||
})
|
||||
mocks.useSessionAgent.mockReturnValue({ agent: 'default' })
|
||||
mocks.useAgents.mockReturnValue({ data: [] })
|
||||
mocks.useUserBash.mockImplementation((selector) => selector({ addUserBashCommand: vi.fn() }))
|
||||
mocks.useSessionAgentStore.mockImplementation((selector) => selector({ setAgent: vi.fn() }))
|
||||
mocks.useSendErrorStore.mockImplementation((selector) => selector({ errors: {} }))
|
||||
useUIState.getState().clearPendingPromptCommand()
|
||||
useUIState.getState().clearPendingPromptFile()
|
||||
})
|
||||
|
||||
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string }) {
|
||||
mocks.useServerHealth.mockReturnValue({
|
||||
data: sandbox === undefined ? undefined : { sandbox },
|
||||
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 },
|
||||
})
|
||||
}
|
||||
|
||||
const renderComponent = () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PromptInput {...defaultProps} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
it('blocks bash mode with an actionable message when the running OpenCode child is enforced', () => {
|
||||
mockHealth({ available: true, enforced: true })
|
||||
|
||||
renderComponent()
|
||||
|
||||
const textarea = screen.getByPlaceholderText('Send a message...')
|
||||
fireEvent.change(textarea, { target: { value: '!' } })
|
||||
|
||||
expect(screen.getByPlaceholderText('Send a message...')).toBeInTheDocument()
|
||||
expect(screen.queryByPlaceholderText('Enter bash command...')).not.toBeInTheDocument()
|
||||
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith(
|
||||
expect.stringContaining('shell mode is disabled'),
|
||||
expect.objectContaining({ id: 'sandbox-bash-mode-disabled' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('allows bash mode when enforcement is off', () => {
|
||||
mockHealth({ available: true, enforced: false })
|
||||
|
||||
renderComponent()
|
||||
|
||||
const textarea = screen.getByPlaceholderText('Send a message...')
|
||||
fireEvent.change(textarea, { target: { value: '!' } })
|
||||
|
||||
expect(screen.getByPlaceholderText('Enter bash command...')).toBeInTheDocument()
|
||||
expect(vi.mocked(showToast.error)).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -29,14 +29,9 @@ const mocks = vi.hoisted(() => ({
|
||||
useSessionAgentStore: vi.fn(),
|
||||
useSendErrorStore: vi.fn(),
|
||||
useSettings: vi.fn(),
|
||||
useServerHealth: vi.fn(),
|
||||
EventContext: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: mocks.useServerHealth,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSTT', () => ({
|
||||
useSTT: mocks.useSTT,
|
||||
}))
|
||||
@@ -170,14 +165,6 @@ describe('PromptInput STT Gesture Tests', () => {
|
||||
mocks.sendPromptPending.mockReturnValue(false)
|
||||
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
mocks.useServerHealth.mockReturnValue({
|
||||
data: { sandbox: { available: true, enforced: false } },
|
||||
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 import('@/hooks/useServerHealth').useServerHealth>)
|
||||
mocks.useSTT.mockReturnValue({
|
||||
isRecording: false,
|
||||
isProcessing: false,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
|
||||
import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useCommands } from '@/hooks/useCommands'
|
||||
import { useCommandHandler } from '@/hooks/useCommandHandler'
|
||||
import { useFileSearch } from '@/hooks/useFileSearch'
|
||||
@@ -219,8 +218,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
const sendPrompt = useSendPrompt(opcodeUrl, directory)
|
||||
const sendShell = useSendShell(opcodeUrl, directory)
|
||||
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
|
||||
const sandboxEnforced = useServerHealth().data?.sandbox?.enforced === true
|
||||
const sandboxShellModeDisabledMessage = 'Sandbox enforcement is on: `!command` shell mode is disabled because it runs in the OpenCode host process. Agent shell commands run inside the microsandbox — send a normal message instead.'
|
||||
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
|
||||
const { filterCommands } = useCommands(opcodeUrl)
|
||||
const { executeCommand } = useCommandHandler({
|
||||
@@ -325,12 +322,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
if (isPromptSubmitPending) return
|
||||
|
||||
if (isBashMode) {
|
||||
if (sandboxEnforced) {
|
||||
showToast.error(sandboxShellModeDisabledMessage, { id: 'sandbox-bash-mode-disabled' })
|
||||
setIsBashMode(false)
|
||||
setPrompt('')
|
||||
return
|
||||
}
|
||||
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
|
||||
addUserBashCommand(command)
|
||||
const submittedPrompt = prompt
|
||||
@@ -1025,11 +1016,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const value = e.target.value
|
||||
|
||||
if (value === '!' && prompt === '') {
|
||||
if (sandboxEnforced) {
|
||||
showToast.error(sandboxShellModeDisabledMessage, { id: 'sandbox-bash-mode-disabled' })
|
||||
setPrompt(value)
|
||||
return
|
||||
}
|
||||
setIsBashMode(true)
|
||||
setPrompt(value)
|
||||
return
|
||||
|
||||
@@ -98,7 +98,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('Commands')
|
||||
await vi.waitFor(() => {
|
||||
@@ -120,7 +120,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
mockUpdateOpenCodeConfig.mockResolvedValueOnce({ ...defaultConfig, restartRequired: true })
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
|
||||
@@ -141,7 +141,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
const restartNowButton = await screen.findByRole('button', { name: /restart now/i })
|
||||
await user.click(restartNowButton)
|
||||
@@ -156,7 +156,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
mockUpdateOpenCodeConfig.mockRejectedValueOnce(new Error('boom'))
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
|
||||
@@ -178,7 +178,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
})
|
||||
|
||||
it('anchors the AGENTS.md card to the settings dialog scrollport', async () => {
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
const header = await screen.findByRole('button', { name: /Global Agent Instructions/i })
|
||||
const card = header.parentElement
|
||||
expect(card?.className).toContain('overflow-clip')
|
||||
@@ -200,7 +200,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(configWithRaw)
|
||||
|
||||
const user = userEvent.setup()
|
||||
const { container } = renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
const { container } = renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ArrowUpCircle, History, ChevronDown, AlertTriangle } from 'lucide-react'
|
||||
import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ChevronDown, AlertTriangle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@@ -56,13 +56,9 @@ interface Agent {
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface OpenCodeConfigManagerProps {
|
||||
hideHealthStatus?: boolean
|
||||
}
|
||||
|
||||
const EXPANDED_SECTION_CONTENT_CLASS = 'p-2 sm:p-4'
|
||||
|
||||
export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConfigManagerProps) {
|
||||
export function OpenCodeConfigManager() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
|
||||
@@ -85,13 +81,11 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen: isRestartPromptOpen,
|
||||
setConfirmOpen: setIsRestartPromptOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
const agentsMdRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -335,88 +329,11 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath)
|
||||
const activeConfig = configs.find((c) => c.name === activeConfigName) ?? null
|
||||
|
||||
return (
|
||||
<div className="space-y-6 min-w-0">
|
||||
{!hideHealthStatus && health && (
|
||||
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center items-center justify-center gap-3">
|
||||
<div className="flex items-center gap-2 flex-wrap justify-center ">
|
||||
<div className={`h-3 w-3 rounded-full ${isUnhealthy ? 'bg-destructive animate-pulse' : 'bg-green-500'}`} />
|
||||
<p className="font-medium text-sm sm:text-base">
|
||||
Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}
|
||||
</p>
|
||||
{health.error && (
|
||||
<p className="text-xs text-destructive">
|
||||
{health.error}
|
||||
</p>
|
||||
)}
|
||||
{health.opencodeVersion && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
OpenCode v{health.opencodeVersion}
|
||||
</p>
|
||||
)}
|
||||
{health.opencodeManagerVersion && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
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}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<ArrowUpCircle className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
)}
|
||||
<span className="text-xs sm:text-sm">Update</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
)}
|
||||
<span className="text-xs sm:text-sm">Restart</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsVersionDialogOpen(true)}
|
||||
>
|
||||
<History className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
<span className="text-xs sm:text-sm">Versions</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{health?.opencodeRestartPending && (
|
||||
<div className="flex flex-col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -29,9 +29,9 @@ function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}
|
||||
return { updateSettingsAsync }
|
||||
}
|
||||
|
||||
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
|
||||
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }, opencodeRestartPending = false) {
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: { sandbox },
|
||||
data: { opencode: 'healthy', opencodeRestartPending, sandbox },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
@@ -57,7 +57,7 @@ describe('SandboxSettings', () => {
|
||||
it('writes only the sandbox preference when toggled and shows the restart notice', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { updateSettingsAsync } = mockUseSettings()
|
||||
mockHealth({ available: true, enforced: false })
|
||||
mockHealth({ available: true, enforced: false }, true)
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useState } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
@@ -10,7 +9,6 @@ import { showToast } from '@/lib/toast'
|
||||
export function SandboxSettings() {
|
||||
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
|
||||
const { data: health } = useServerHealth()
|
||||
const [needsRestart, setNeedsRestart] = useState(false)
|
||||
|
||||
const sandbox = health?.sandbox
|
||||
const isAvailable = sandbox?.available === true
|
||||
@@ -19,7 +17,6 @@ export function SandboxSettings() {
|
||||
const handleToggle = async (next: boolean) => {
|
||||
try {
|
||||
await updateSettingsAsync({ sandbox: { enabled: next } })
|
||||
setNeedsRestart(true)
|
||||
showToast.success(next ? 'Sandboxing enabled' : 'Sandboxing disabled')
|
||||
} catch {
|
||||
showToast.error('Failed to update sandbox preference')
|
||||
@@ -62,7 +59,7 @@ export function SandboxSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{needsRestart && (
|
||||
{health?.opencodeRestartPending && (
|
||||
<Alert>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
|
||||
@@ -180,7 +180,7 @@ export function SettingsDialog() {
|
||||
</div>
|
||||
<ServerEnvVarsSettings />
|
||||
<SandboxSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
<OpenCodeConfigManager />
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
|
||||
@@ -252,7 +252,7 @@ export function SettingsDialog() {
|
||||
<ManagerTokenSettings />
|
||||
<ServerEnvVarsSettings />
|
||||
<SandboxSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
<OpenCodeConfigManager />
|
||||
</div>
|
||||
)}
|
||||
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
||||
|
||||
@@ -43,7 +43,11 @@ grant_kvm_access() {
|
||||
}
|
||||
|
||||
install_opencode() {
|
||||
local opencode_version="${OPENCODE_BUNDLED_VERSION:-1.18.16}"
|
||||
local opencode_version="${OPENCODE_BUNDLED_VERSION:-}"
|
||||
if [ -z "$opencode_version" ]; then
|
||||
echo "ERROR: OPENCODE_BUNDLED_VERSION is not set; refusing to guess the pinned OpenCode build" >&2
|
||||
return 1
|
||||
fi
|
||||
echo "Installing OpenCode ${opencode_version}..."
|
||||
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
|
||||
@@ -98,7 +102,7 @@ if [ "$OPENCODE_VERSION" != "unknown" ]; then
|
||||
echo "OpenCode version meets minimum requirement (>=$MIN_OPENCODE_VERSION)"
|
||||
else
|
||||
echo "OpenCode version $OPENCODE_VERSION is below minimum required version $MIN_OPENCODE_VERSION"
|
||||
echo "Reinstalling bundled OpenCode version ${OPENCODE_BUNDLED_VERSION:-1.18.16}..."
|
||||
echo "Reinstalling bundled OpenCode version ${OPENCODE_BUNDLED_VERSION}..."
|
||||
install_opencode
|
||||
|
||||
OPENCODE_VERSION=$(opencode --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "unknown")
|
||||
@@ -129,7 +133,7 @@ if ! align_container_user node; then
|
||||
fi
|
||||
|
||||
if ! grant_kvm_access; then
|
||||
exit 1
|
||||
echo "WARNING: continuing without /dev/kvm access; agent sandboxing will report itself unavailable" >&2
|
||||
fi
|
||||
|
||||
warn_if_workspace_owner_differs /workspace "$OCM_TARGET_UID" "$OCM_TARGET_GID"
|
||||
|
||||
@@ -119,34 +119,17 @@ export const DEFAULT_SERVER_ENV_VARS = [
|
||||
] as const satisfies readonly ServerEnvVar[];
|
||||
|
||||
export const BLOCKED_SERVER_ENV_KEYS = [
|
||||
'HOME',
|
||||
'SHELL',
|
||||
'BASH_ENV',
|
||||
'ENV',
|
||||
'OPENCODE_SERVER_PASSWORD',
|
||||
'OPENCODE_SERVER_USERNAME',
|
||||
'OPENCODE_CONFIG',
|
||||
'OPENCODE_CONFIG_CONTENT',
|
||||
'OPENCODE_CONFIG_DIR',
|
||||
'OPENCODE_PURE',
|
||||
'OPENCODE_AUTH_CONTENT',
|
||||
'OPENCODE_TEST_HOME',
|
||||
'OPENCODE_TEST_MANAGED_CONFIG_DIR',
|
||||
'XDG_DATA_HOME',
|
||||
'XDG_STATE_HOME',
|
||||
'XDG_CONFIG_HOME',
|
||||
'PATH',
|
||||
'MSB_PATH',
|
||||
'MSB_LIBKRUNFW_PATH',
|
||||
'MSB_HOME',
|
||||
'MSB_BACKEND',
|
||||
'MSB_PROFILE',
|
||||
'MSB_API_URL',
|
||||
'MSB_API_KEY',
|
||||
'BUN_OPTIONS',
|
||||
'NODE_OPTIONS',
|
||||
'LD_PRELOAD',
|
||||
'LD_LIBRARY_PATH',
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_GIT_IDENTITY: GitIdentity = {
|
||||
|
||||
Reference in new issue
Block a user