mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(sandbox): add KVM-backed agent sandboxing via microsandbox
This commit is contained in:
1 parent
1d477bdee4
commit
aa3fb48a62
80 files changed
+17304
-204
No files matched your search
@@ -130,6 +130,32 @@ PASSKEY_ORIGIN=http://localhost:5003
|
||||
# VAPID_PRIVATE_KEY=
|
||||
# VAPID_SUBJECT=mailto:you@yourdomain.com
|
||||
|
||||
# ============================================
|
||||
# Agent Sandboxing (microsandbox)
|
||||
# Sandboxed agent commands run inside a microVM managed by msb. Linux host
|
||||
# with /dev/kvm is required; enable the sandbox overlay to grant the container
|
||||
# KVM access and persist sandbox state:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
|
||||
# ============================================
|
||||
# OCI image the microVM boots from (guest default user: node, uid 1000)
|
||||
# SANDBOX_IMAGE=node:24
|
||||
# MicroVM memory (e.g. 4G)
|
||||
# SANDBOX_MEMORY=4G
|
||||
# MicroVM CPU count
|
||||
# SANDBOX_CPUS=2
|
||||
# Guest identity sandboxed commands run as: a numeric uid, a numeric uid:gid,
|
||||
# or a guest username. Defaults to PUID so the guest identity always matches
|
||||
# the workspace owner; a guest username is resolved to the Manager's uid:gid.
|
||||
# When a configured numeric identity cannot match the workspace owner,
|
||||
# enforcement is reported unavailable.
|
||||
# SANDBOX_EXEC_USER=${PUID:-1000}
|
||||
# Network mode for the microVM (public or private)
|
||||
# SANDBOX_NET=public
|
||||
# Timeout for microVM startup, in milliseconds
|
||||
# SANDBOX_START_TIMEOUT_MS=300000
|
||||
# Timeout for a single sandboxed command, in milliseconds
|
||||
# SANDBOX_EXEC_TIMEOUT_MS=600000
|
||||
|
||||
# ============================================
|
||||
# Frontend Configuration (Vite)
|
||||
# These are optional - frontend uses defaults if not set
|
||||
|
||||
@@ -20,10 +20,12 @@ jobs:
|
||||
id: versions
|
||||
run: |
|
||||
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=$(git ls-remote --tags --sort=-v:refname https://github.com/anomalyco/opencode.git 'refs/tags/v[0-9]*' | head -1 | sed 's/.*refs\/tags\/v//')
|
||||
OPENCODE_VERSION=1.18.16
|
||||
MICROSANDBOX_VERSION=0.6.8
|
||||
echo "uv=${UV_VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "opencode=${OPENCODE_VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Detected versions: uv=${UV_VERSION}, opencode=${OPENCODE_VERSION}"
|
||||
echo "microsandbox=${MICROSANDBOX_VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Detected versions: uv=${UV_VERSION}, opencode=${OPENCODE_VERSION}, microsandbox=${MICROSANDBOX_VERSION}"
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
@@ -60,6 +62,7 @@ jobs:
|
||||
build-args: |
|
||||
UV_VERSION=${{ steps.versions.outputs.uv }}
|
||||
OPENCODE_VERSION=${{ steps.versions.outputs.opencode }}
|
||||
MICROSANDBOX_VERSION=${{ steps.versions.outputs.microsandbox }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
target: runner
|
||||
|
||||
+35
-3
@@ -1,4 +1,4 @@
|
||||
FROM node:24.13.0 AS base
|
||||
FROM node:24.13.0-trixie AS base
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
git \
|
||||
@@ -59,7 +59,8 @@ RUN pnpm --filter frontend build
|
||||
FROM base AS runner
|
||||
|
||||
ARG UV_VERSION=latest
|
||||
ARG OPENCODE_VERSION=latest
|
||||
ARG OPENCODE_VERSION=1.18.16
|
||||
ARG MICROSANDBOX_VERSION=0.6.8
|
||||
# Bump TOOLS_CACHEBUST (e.g. via --build-arg) to force a fresh uv/opencode
|
||||
# install without invalidating the rest of the build cache.
|
||||
ARG TOOLS_CACHEBUST=0
|
||||
@@ -87,6 +88,34 @@ RUN echo "Installing uv=${UV_VERSION} opencode=${OPENCODE_VERSION} (cachebust=${
|
||||
ln -s /opt/opencode/bin/opencode /usr/local/bin/opencode && \
|
||||
echo "opencode ${OPENCODE_VERSION} installed successfully"
|
||||
|
||||
RUN echo "Installing microsandbox=${MICROSANDBOX_VERSION} (cachebust=${TOOLS_CACHEBUST})" && \
|
||||
MSB_ARCH=$(uname -m) && \
|
||||
if [ "$MSB_ARCH" = "x86_64" ] || [ "$MSB_ARCH" = "amd64" ]; then MSB_TARGET="x86_64"; \
|
||||
elif [ "$MSB_ARCH" = "aarch64" ] || [ "$MSB_ARCH" = "arm64" ]; then MSB_TARGET="aarch64"; \
|
||||
else echo "ERROR: microsandbox does not support architecture: $MSB_ARCH" >&2; exit 1; fi && \
|
||||
MSB_BUNDLE="microsandbox-linux-${MSB_TARGET}.tar.gz" && \
|
||||
case "${MICROSANDBOX_VERSION}" in v*) MSB_VERSION="${MICROSANDBOX_VERSION}" ;; *) MSB_VERSION="v${MICROSANDBOX_VERSION}" ;; esac && \
|
||||
MSB_BASE_URL="https://github.com/superradcompany/microsandbox/releases/download/${MSB_VERSION}" && \
|
||||
curl -fsSL "${MSB_BASE_URL}/${MSB_BUNDLE}" -o "/tmp/${MSB_BUNDLE}" && \
|
||||
curl -fsSL "${MSB_BASE_URL}/checksums.sha256" -o /tmp/checksums.sha256 && \
|
||||
cd /tmp && \
|
||||
grep -F "${MSB_BUNDLE}" checksums.sha256 | sha256sum -c --quiet - && \
|
||||
mkdir -p /opt/microsandbox/bin /opt/microsandbox/lib && \
|
||||
tar -xzf "/tmp/${MSB_BUNDLE}" -C /tmp && \
|
||||
install -m 755 /tmp/msb /opt/microsandbox/bin/msb && \
|
||||
ln -sf msb /opt/microsandbox/bin/microsandbox && \
|
||||
ln -s /opt/microsandbox/bin/msb /usr/local/bin/msb && \
|
||||
MSB_LIB=$(find /tmp -maxdepth 1 -type f -name 'libkrunfw.so.*.*.*' | head -1) && \
|
||||
MSB_LIB_NAME=$(basename "$MSB_LIB") && \
|
||||
MSB_LIB_ABI=${MSB_LIB_NAME#libkrunfw.so.} && \
|
||||
MSB_LIB_ABI=${MSB_LIB_ABI%%.*} && \
|
||||
install -m 644 "$MSB_LIB" "/opt/microsandbox/lib/${MSB_LIB_NAME}" && \
|
||||
ln -sf "$MSB_LIB_NAME" "/opt/microsandbox/lib/libkrunfw.so.${MSB_LIB_ABI}" && \
|
||||
ln -sf "libkrunfw.so.${MSB_LIB_ABI}" /opt/microsandbox/lib/libkrunfw.so && \
|
||||
rm -f "/tmp/${MSB_BUNDLE}" /tmp/checksums.sha256 /tmp/msb /tmp/libkrunfw.so.* && \
|
||||
chmod -R a+rX /opt/microsandbox && \
|
||||
msb --version
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=5003
|
||||
@@ -94,6 +123,9 @@ ENV OPENCODE_SERVER_PORT=5551
|
||||
ENV DATABASE_PATH=/app/data/opencode.db
|
||||
ENV WORKSPACE_PATH=/workspace
|
||||
ENV XDG_CACHE_HOME=/home/node/.cache
|
||||
ENV OPENCODE_BUNDLED_VERSION=${OPENCODE_VERSION}
|
||||
ENV MSB_PATH=/usr/local/bin/msb
|
||||
ENV MSB_LIBKRUNFW_PATH=/opt/microsandbox/lib/libkrunfw.so
|
||||
|
||||
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/shared ./shared
|
||||
@@ -110,7 +142,7 @@ COPY scripts/lib/container-user.sh /usr/local/lib/ocm/container-user.sh
|
||||
COPY scripts/docker-entrypoint.sh /docker-entrypoint.sh
|
||||
RUN chmod +x /docker-entrypoint.sh
|
||||
|
||||
RUN mkdir -p /workspace /app/data /home/node/.cache /home/node/.opencode && \
|
||||
RUN mkdir -p /workspace /app/data /home/node/.cache /home/node/.opencode /home/node/.microsandbox && \
|
||||
chown -R node:node /workspace /app/data /home/node
|
||||
|
||||
EXPOSE 5003 5100 5101 5102 5103
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "pnpm run test:bun && pnpm run test:vitest",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts src/routes/session-pins.test.ts",
|
||||
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts test/routes/internal-sandbox.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts src/routes/session-pins.test.ts",
|
||||
"test:vitest": "vitest run",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:watch": "vitest --watch",
|
||||
|
||||
+14
-16
@@ -39,6 +39,7 @@ import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
@@ -50,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 { stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { OpenCodeRestartCoordinator } from './services/opencode-restart-coordinator'
|
||||
@@ -104,7 +106,10 @@ app.use('/*', cors({
|
||||
const db = initializeDatabase(DB_PATH)
|
||||
const auth = createAuth(db)
|
||||
const requireAuth = createAuthMiddleware(auth)
|
||||
const openCodeClient = createOpenCodeClient(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
const openCodeClient = createOpenCodeClient(
|
||||
() => new SettingsService(db).getOpenCodeServerPassword(),
|
||||
() => opencodeServerManager.getEffectiveServerHost(),
|
||||
)
|
||||
|
||||
import { DEFAULT_AGENTS_MD } from './constants'
|
||||
|
||||
@@ -293,6 +298,7 @@ try {
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
opencodeServerManager.setLifecycleInitialized(openCodeStatus.healthy)
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
} else {
|
||||
@@ -373,21 +379,7 @@ protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
app.post('/api/opencode/mcp/:name/auth', requireAuth, async (c) => {
|
||||
const serverName = c.req.param('name')
|
||||
const directory = c.req.query('directory')
|
||||
return openCodeClient.startMcpAuth(serverName, directory)
|
||||
})
|
||||
|
||||
app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => {
|
||||
const serverName = c.req.param('name')
|
||||
const directory = c.req.query('directory')
|
||||
return openCodeClient.authenticateMcp(serverName, directory)
|
||||
})
|
||||
|
||||
app.all('/api/opencode/*', requireAuth, async (c) => {
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
})
|
||||
app.route('/api/opencode', createAuthenticatedOpenCodeProxyRoutes(openCodeClient, requireAuth))
|
||||
|
||||
const isProduction = ENV.SERVER.NODE_ENV === 'production'
|
||||
|
||||
@@ -483,6 +475,12 @@ const shutdown = async (signal: string) => {
|
||||
} catch (error) {
|
||||
logger.error('Error during shutdown:', error)
|
||||
}
|
||||
try {
|
||||
await stopWorkspaceSandboxOnShutdown(db)
|
||||
logger.info('Workspace sandbox stopped')
|
||||
} catch (error) {
|
||||
logger.error('Error stopping workspace sandbox:', error)
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import { githubFetch } from '../utils/github'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SandboxRuntimeService } from '../services/sandbox/runtime'
|
||||
|
||||
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
|
||||
const GITHUB_REPO_NAME = 'opencode-manager'
|
||||
@@ -94,6 +96,22 @@ export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSu
|
||||
opencodeRestartPending: opencodeServerManager.isRestartPending(),
|
||||
}
|
||||
|
||||
try {
|
||||
const runtimeStatus = new SandboxRuntimeService(db).getStatus()
|
||||
response.sandbox = {
|
||||
...runtimeStatus,
|
||||
enforced: opencodeServerManager.isSandboxEnforced(),
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to collect sandbox status', error)
|
||||
response.sandbox = {
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: opencodeServerManager.isSandboxEnforced(),
|
||||
reason: error instanceof Error ? error.message : 'sandbox status unavailable',
|
||||
}
|
||||
}
|
||||
|
||||
if (lifecycle) {
|
||||
response.opencodeLifecycle = lifecycle
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
|
||||
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
|
||||
import { createInternalAssistantRoutes } from './assistant'
|
||||
import { createInternalGitCredentialsRoutes } from './git-credentials'
|
||||
import { createInternalSandboxRoutes } from './sandbox'
|
||||
|
||||
export function createInternalRoutes(
|
||||
db: Database,
|
||||
@@ -36,5 +37,6 @@ export function createInternalRoutes(
|
||||
app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db))
|
||||
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
|
||||
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
|
||||
app.route('/sandbox', createInternalSandboxRoutes(db))
|
||||
return app
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { existsSync, mkdtempSync, readdirSync, statSync } from 'fs'
|
||||
import * as fsp from 'fs/promises'
|
||||
import { createReadStream } from 'fs'
|
||||
import { dirname, join } from 'path'
|
||||
import { Readable } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
@@ -94,11 +95,23 @@ export interface ExtractResult {
|
||||
staging: string
|
||||
}
|
||||
|
||||
function isStdinClosedError(error: unknown): boolean {
|
||||
if (typeof error !== 'object' || error === null) return false
|
||||
const code = (error as { code?: unknown }).code
|
||||
return code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'EPIPE'
|
||||
}
|
||||
|
||||
export async function extractPartsToStaging(uploadId: string, totalParts: number, gzip: boolean): Promise<ExtractResult> {
|
||||
if (!isValidTotalParts(totalParts)) {
|
||||
throw new Error(TOTAL_PARTS_INVALID_MESSAGE)
|
||||
}
|
||||
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
if (!existsSync(getPartPath(uploadId, i))) {
|
||||
throw new Error(`missing part ${i} for upload ${uploadId}`)
|
||||
}
|
||||
}
|
||||
|
||||
const stagingParent = getStagingRoot()
|
||||
mkdirSyncSafe(stagingParent)
|
||||
const staging = mkdtempSync(join(stagingParent, 'recv-'))
|
||||
@@ -110,30 +123,40 @@ export async function extractPartsToStaging(uploadId: string, totalParts: number
|
||||
const stderrChunks: Buffer[] = []
|
||||
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
|
||||
|
||||
const tarDone = new Promise<void>((resolve, reject) => {
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) resolve()
|
||||
else {
|
||||
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
|
||||
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
|
||||
}
|
||||
})
|
||||
const tarDone = new Promise<number | null>((resolve, reject) => {
|
||||
child.on('close', (code) => resolve(code))
|
||||
child.on('error', reject)
|
||||
})
|
||||
tarDone.catch(() => {})
|
||||
|
||||
try {
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
const partPath = getPartPath(uploadId, i)
|
||||
if (!existsSync(partPath)) {
|
||||
throw new Error(`missing part ${i} for upload ${uploadId}`)
|
||||
let writeError: unknown = null
|
||||
const partStreams = Readable.from(
|
||||
(async function* () {
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
for await (const chunk of createReadStream(getPartPath(uploadId, i))) {
|
||||
yield chunk
|
||||
}
|
||||
}
|
||||
await pipeline(createReadStream(partPath), child.stdin, { end: i === totalParts - 1 })
|
||||
}
|
||||
await tarDone
|
||||
})(),
|
||||
)
|
||||
try {
|
||||
await pipeline(partStreams, child.stdin, { end: true })
|
||||
} catch (err) {
|
||||
writeError = err
|
||||
}
|
||||
|
||||
if (writeError && !isStdinClosedError(writeError)) {
|
||||
if (!child.killed) child.kill('SIGKILL')
|
||||
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
|
||||
throw err
|
||||
throw writeError
|
||||
}
|
||||
|
||||
const exitCode = await tarDone
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
|
||||
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
|
||||
throw new Error(`tar exited with code ${exitCode}${stderr ? `: ${stderr}` : ''}`)
|
||||
}
|
||||
|
||||
let extractedRoot = staging
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
const SandboxCommandRequestSchema = z.object({
|
||||
directory: z.string().min(1),
|
||||
command: z.string().min(1),
|
||||
enforced: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export function createInternalSandboxRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
app.post('/command', async (c) => {
|
||||
let body: unknown
|
||||
try {
|
||||
body = await c.req.json()
|
||||
} catch {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
const parsed = SandboxCommandRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
return c.json(
|
||||
await new SandboxRuntimeService(db).planCommand(parsed.data.directory, parsed.data.command, parsed.data.enforced === true),
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Failed to plan sandbox command', error)
|
||||
return c.json({ mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import {
|
||||
decideSandboxMutationBody,
|
||||
decideSandboxProxyBlock,
|
||||
isSandboxAuthWrite,
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
} from '../services/opencode/proxy-policy'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
|
||||
export function createAuthenticatedOpenCodeProxyRoutes(
|
||||
openCodeClient: OpenCodeClient,
|
||||
requireAuth: MiddlewareHandler,
|
||||
): Hono {
|
||||
const app = new Hono()
|
||||
|
||||
app.all('/*', requireAuth, async (c) => {
|
||||
if (!opencodeServerManager.isLifecycleInitialized()) {
|
||||
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
|
||||
}
|
||||
|
||||
const enforced = opencodeServerManager.isSandboxEnforced()
|
||||
const pathSuffix = new URL(c.req.url).pathname.replace(/^\/api\/opencode/, '') || '/'
|
||||
const decision = decideSandboxProxyBlock(enforced, c.req.method, pathSuffix)
|
||||
if (decision.blocked) {
|
||||
return c.json({ error: decision.reason }, 403)
|
||||
}
|
||||
if (isSandboxConfigMutation(enforced, c.req.method, pathSuffix) || isSandboxMcpAdd(enforced, c.req.method, pathSuffix) || isSandboxAuthWrite(enforced, c.req.method, pathSuffix)) {
|
||||
const rawBody = await c.req.text()
|
||||
const bodyDecision = decideSandboxMutationBody(enforced, c.req.method, pathSuffix, rawBody)
|
||||
if (bodyDecision.kind === 'reject') {
|
||||
return c.json({ error: bodyDecision.reason }, 403)
|
||||
}
|
||||
const headers = new Headers(c.req.raw.headers)
|
||||
headers.delete('content-length')
|
||||
return openCodeClient.forwardRaw(new Request(c.req.url, {
|
||||
method: c.req.method,
|
||||
headers,
|
||||
body: bodyDecision.kind === 'sanitized' ? bodyDecision.body : rawBody,
|
||||
}))
|
||||
}
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -3,6 +3,14 @@ import type { Database } from 'bun:sqlite'
|
||||
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 {
|
||||
decideSandboxMutationBody,
|
||||
decideSandboxProxyBlock,
|
||||
isSandboxAuthWrite,
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
} from '../services/opencode/proxy-policy'
|
||||
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
@@ -25,6 +33,10 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
|
||||
app.all('/*', async (c) => {
|
||||
if (!opencodeServerManager.isLifecycleInitialized()) {
|
||||
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
|
||||
}
|
||||
|
||||
const connectionHeader = c.req.header('connection')?.toLowerCase() ?? ''
|
||||
const upgradeHeader = c.req.header('upgrade')?.toLowerCase() ?? ''
|
||||
if (connectionHeader.includes('upgrade') && upgradeHeader === 'websocket') {
|
||||
@@ -33,6 +45,11 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
|
||||
const url = new URL(c.req.url)
|
||||
const pathSuffix = url.pathname.replace(/^\/api\/opencode-proxy/, '') || '/'
|
||||
const enforced = opencodeServerManager.isSandboxEnforced()
|
||||
const decision = decideSandboxProxyBlock(enforced, c.req.method, pathSuffix)
|
||||
if (decision.blocked) {
|
||||
return c.json({ error: decision.reason }, 403)
|
||||
}
|
||||
const upstreamUrl = `http://127.0.0.1:${ENV.OPENCODE.PORT}${pathSuffix}${url.search}`
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
@@ -49,7 +66,16 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
|
||||
let requestBody: RequestInit['body'] = undefined
|
||||
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
|
||||
requestBody = c.req.raw.body
|
||||
if (isSandboxConfigMutation(enforced, c.req.method, pathSuffix) || isSandboxMcpAdd(enforced, c.req.method, pathSuffix) || isSandboxAuthWrite(enforced, c.req.method, pathSuffix)) {
|
||||
const rawBody = await c.req.text()
|
||||
const bodyDecision = decideSandboxMutationBody(enforced, c.req.method, pathSuffix, rawBody)
|
||||
if (bodyDecision.kind === 'reject') {
|
||||
return c.json({ error: bodyDecision.reason }, 403)
|
||||
}
|
||||
requestBody = bodyDecision.kind === 'sanitized' ? bodyDecision.body : rawBody
|
||||
} else {
|
||||
requestBody = c.req.raw.body
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,8 @@ import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { resolveSandboxWorkDirectory } from '../services/sandbox/command'
|
||||
import path from 'path'
|
||||
|
||||
function resolveRepo(database: Database, id: number): Repo | null {
|
||||
@@ -314,7 +316,33 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: body || 'Failed to create workspace' }, response.status as ContentfulStatusCode)
|
||||
}
|
||||
|
||||
return c.json(body ? JSON.parse(body) : { success: true })
|
||||
let workspace: unknown
|
||||
try {
|
||||
workspace = body ? JSON.parse(body) : { success: true }
|
||||
} catch {
|
||||
return c.json({ error: 'Failed to create workspace' }, 500)
|
||||
}
|
||||
|
||||
const workspaceRecord = workspace as { id?: unknown; directory?: unknown } | null
|
||||
if (
|
||||
workspaceRecord &&
|
||||
typeof workspaceRecord.directory === 'string' &&
|
||||
opencodeServerManager.isSandboxEnforced() &&
|
||||
(await resolveSandboxWorkDirectory(workspaceRecord.directory)) === null
|
||||
) {
|
||||
if (typeof workspaceRecord.id === 'string' && workspaceRecord.id.length > 0) {
|
||||
await openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceRecord.id)}`,
|
||||
directory: repo.fullPath,
|
||||
}).catch(() => {})
|
||||
}
|
||||
return c.json({
|
||||
error: 'OpenCode worktrees are not available while sandboxing is enabled because they are created outside the sandboxed project roots',
|
||||
}, 400)
|
||||
}
|
||||
|
||||
return c.json(workspace)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create workspace:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
|
||||
+152
-28
@@ -13,6 +13,7 @@ import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/sh
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
OpenCodeConfigSchema,
|
||||
type SandboxPreferences,
|
||||
} from '../types/settings'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
import {
|
||||
@@ -27,7 +28,9 @@ import { logger } from '../utils/logger'
|
||||
import {
|
||||
discoverModelsCached,
|
||||
} from '../utils/discovery-cache'
|
||||
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
|
||||
import { opencodeServerManager, ConfigReloadError, isSandboxVerifiedOpenCodeVersion, getSandboxVerifiedOpenCodeVersions } from '../services/opencode-single-server'
|
||||
import { sanitizeConfigForEnforcementResult, type EnforcementRemovedSections } from '../services/opencode/enforcement-config'
|
||||
import { isSandboxEnforcementActive } from '../services/sandbox/enforcement'
|
||||
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
@@ -83,14 +86,16 @@ function getOpenCodeInstallMethod(): string {
|
||||
|
||||
function getOpenCodeConfigContentToWrite(
|
||||
rawContent: string,
|
||||
sourceConfig: Record<string, unknown>,
|
||||
appliedConfig?: Record<string, unknown>,
|
||||
removedFields?: string[]
|
||||
removedFields?: string[],
|
||||
enforcementRemoved = false,
|
||||
): string {
|
||||
if (!appliedConfig || !removedFields || removedFields.length === 0) {
|
||||
return rawContent
|
||||
if ((removedFields && removedFields.length > 0) || enforcementRemoved) {
|
||||
return JSON.stringify(appliedConfig ?? sourceConfig, null, 2)
|
||||
}
|
||||
|
||||
return JSON.stringify(appliedConfig, null, 2)
|
||||
return rawContent
|
||||
}
|
||||
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
@@ -215,6 +220,14 @@ function needsOpenCodeRestart(
|
||||
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
|
||||
}
|
||||
|
||||
function sandboxPreferenceChanged(
|
||||
previous: SandboxPreferences | undefined,
|
||||
next: SandboxPreferences | undefined,
|
||||
): boolean {
|
||||
if (next === undefined) return false
|
||||
return JSON.stringify(previous ?? {}) !== JSON.stringify(next)
|
||||
}
|
||||
|
||||
function parseOptionalRepoId(value: string | undefined): number | undefined {
|
||||
if (value === undefined) return undefined
|
||||
const parsed = parseInt(value, 10)
|
||||
@@ -236,6 +249,28 @@ function hasConfiguredPlugins(config: Record<string, unknown> | undefined): bool
|
||||
return Array.isArray(config?.plugin) && config.plugin.length > 0
|
||||
}
|
||||
|
||||
type EnforcementSanitization = {
|
||||
patchTarget: Record<string, unknown>
|
||||
removed: EnforcementRemovedSections
|
||||
}
|
||||
|
||||
function sanitizeConfigPatchForEnforcement(config: Record<string, unknown>): EnforcementSanitization {
|
||||
const { sanitized, removed } = sanitizeConfigForEnforcementResult(config, opencodeServerManager.isSandboxEnforced())
|
||||
return { patchTarget: sanitized, removed }
|
||||
}
|
||||
|
||||
function contentForEnforcedDefaultWrite(
|
||||
rawContent: string,
|
||||
config: Record<string, unknown>,
|
||||
): { content: string; enforcementRemoved: boolean } {
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(config)
|
||||
const enforcementRemoved = Object.keys(sanitization.removed).length > 0
|
||||
if (!enforcementRemoved) {
|
||||
return { content: rawContent, enforcementRemoved }
|
||||
}
|
||||
return { content: JSON.stringify(sanitization.patchTarget, null, 2), enforcementRemoved }
|
||||
}
|
||||
|
||||
function execWithTimeout(
|
||||
command: string | [executable: string, ...args: string[]],
|
||||
timeoutMs: number,
|
||||
@@ -400,6 +435,13 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const currentSettings = settingsService.getSettings(userId)
|
||||
const settings = settingsService.updateSettings(validated.preferences, userId)
|
||||
|
||||
const sandboxChanged = sandboxPreferenceChanged(currentSettings.preferences.sandbox, validated.preferences.sandbox)
|
||||
|
||||
if (sandboxChanged) {
|
||||
logger.info('Sandbox preference changed, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
}
|
||||
|
||||
let serverRestarted = false
|
||||
|
||||
const credentialsChanged = validated.preferences.gitCredentials !== undefined &&
|
||||
@@ -437,7 +479,14 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
app.delete('/', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const currentSettings = settingsService.getSettings(userId)
|
||||
const settings = settingsService.resetSettings(userId)
|
||||
|
||||
if (sandboxPreferenceChanged(currentSettings.preferences.sandbox, settings.preferences.sandbox)) {
|
||||
logger.info('Sandbox preference changed, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
}
|
||||
|
||||
return c.json(settings)
|
||||
} catch (error) {
|
||||
logger.error('Failed to reset settings:', error)
|
||||
@@ -473,8 +522,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
)
|
||||
|
||||
if (hasConfiguredPlugins(provisionalConfig.content)) {
|
||||
const { content: contentToWrite } = contentForEnforcedDefaultWrite(provisionalConfig.rawContent, provisionalConfig.content)
|
||||
const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, {
|
||||
content: provisionalConfig.rawContent,
|
||||
content: contentToWrite,
|
||||
isDefault: true,
|
||||
}, userId)
|
||||
|
||||
@@ -483,7 +533,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, provisionalConfig.rawContent)
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -491,7 +541,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, provisionalConfig.content)
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(provisionalConfig.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, sanitization.patchTarget)
|
||||
if (!patchResult.success) {
|
||||
settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId)
|
||||
return c.json({
|
||||
@@ -504,8 +555,10 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
provisionalConfig.rawContent,
|
||||
sanitization.patchTarget,
|
||||
patchResult.appliedConfig,
|
||||
patchResult.removedFields
|
||||
patchResult.removedFields,
|
||||
Object.keys(sanitization.removed).length > 0,
|
||||
)
|
||||
const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, {
|
||||
content: contentToWrite,
|
||||
@@ -552,7 +605,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId)
|
||||
const previousContent = existingConfig?.content
|
||||
|
||||
const config = settingsService.updateOpenCodeConfig(configName, validated, userId)
|
||||
let config = settingsService.updateOpenCodeConfig(configName, validated, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
@@ -562,13 +615,22 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (restartRequired) {
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
const { content: contentToWrite, enforcementRemoved } = contentForEnforcedDefaultWrite(config.rawContent, config.content)
|
||||
if (enforcementRemoved) {
|
||||
const persisted = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!persisted) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
config = persisted
|
||||
}
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
logger.info('OpenCode configuration change requires a server restart; deferring until requested')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ ...config, restartRequired: true })
|
||||
} else {
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(config.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, sanitization.patchTarget)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config saved but failed to apply',
|
||||
@@ -579,9 +641,14 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
const removedFields = patchResult.removedFields ?? []
|
||||
const contentToWrite = removedFields.length > 0
|
||||
? JSON.stringify(patchResult.appliedConfig ?? config.content, null, 2)
|
||||
: config.rawContent
|
||||
const enforcementRemoved = Object.keys(sanitization.removed).length > 0
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
config.rawContent,
|
||||
sanitization.patchTarget,
|
||||
patchResult.appliedConfig,
|
||||
removedFields,
|
||||
enforcementRemoved,
|
||||
)
|
||||
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
@@ -596,6 +663,17 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
return c.json({ ...persisted, removedFields })
|
||||
}
|
||||
|
||||
if (enforcementRemoved) {
|
||||
logger.info('Config applied with host-execution sections removed by sandbox enforcement')
|
||||
const persisted = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!persisted) {
|
||||
return c.json({
|
||||
error: 'OpenCode config was removed while applying sandbox enforcement',
|
||||
}, 409)
|
||||
}
|
||||
return c.json(persisted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,13 +717,20 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
if (hasConfiguredPlugins(existingConfig.content)) {
|
||||
const { content: contentToWrite, enforcementRemoved } = contentForEnforcedDefaultWrite(existingConfig.rawContent, existingConfig.content)
|
||||
if (enforcementRemoved) {
|
||||
const updated = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!updated) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
}
|
||||
const config = settingsService.setDefaultOpenCodeConfig(configName, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, existingConfig.rawContent)
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -653,7 +738,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, existingConfig.content)
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(existingConfig.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, sanitization.patchTarget)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config validation failed',
|
||||
@@ -665,8 +751,10 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
existingConfig.rawContent,
|
||||
sanitization.patchTarget,
|
||||
patchResult.appliedConfig,
|
||||
patchResult.removedFields
|
||||
patchResult.removedFields,
|
||||
Object.keys(sanitization.removed).length > 0,
|
||||
)
|
||||
const updatedConfig = settingsService.updateOpenCodeConfig(configName, {
|
||||
content: contentToWrite,
|
||||
@@ -849,7 +937,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json({ error: 'Failed to get default config after rollback' }, 500)
|
||||
}
|
||||
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
const { content: contentToWrite, enforcementRemoved } = contentForEnforcedDefaultWrite(config.rawContent, config.content)
|
||||
if (enforcementRemoved) {
|
||||
settingsService.updateOpenCodeConfig(config.name, { content: contentToWrite }, userId)
|
||||
}
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Rolled back to config '${rollbackConfig}'`)
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
@@ -896,6 +988,19 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
logger.info(`Current OpenCode version: ${oldVersion}`)
|
||||
|
||||
try {
|
||||
if (isSandboxEnforcementActive(db)) {
|
||||
const verified = getSandboxVerifiedOpenCodeVersions()
|
||||
logger.warn('OpenCode upgrade blocked while sandbox enforcement is active')
|
||||
return c.json({
|
||||
success: false,
|
||||
error: 'OpenCode upgrade is disabled while sandbox enforcement is active',
|
||||
details: `Sandbox enforcement only accepts verified OpenCode builds (${verified.join(', ')}). Disable Agent Sandboxing in Settings and restart the OpenCode server before upgrading.`,
|
||||
oldVersion,
|
||||
newVersion: oldVersion,
|
||||
upgraded: false,
|
||||
}, 409)
|
||||
}
|
||||
|
||||
const installMethod = getOpenCodeInstallMethod()
|
||||
logger.info(`Running opencode upgrade --method ${installMethod} with 90s timeout...`)
|
||||
const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade --method ${installMethod} 2>&1`, 90000)
|
||||
@@ -1003,15 +1108,20 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
published_at: string
|
||||
prerelease: boolean
|
||||
}>
|
||||
|
||||
|
||||
const enforcementActive = isSandboxEnforcementActive(db)
|
||||
const versions = releases
|
||||
.filter(r => !r.prerelease)
|
||||
.map(r => ({
|
||||
version: r.tag_name.replace(/^v/, ''),
|
||||
tag: r.tag_name,
|
||||
name: r.name,
|
||||
publishedAt: r.published_at
|
||||
}))
|
||||
.map(r => {
|
||||
const version = r.tag_name.replace(/^v/, '')
|
||||
return {
|
||||
version,
|
||||
tag: r.tag_name,
|
||||
name: r.name,
|
||||
publishedAt: r.published_at,
|
||||
installable: !enforcementActive || isSandboxVerifiedOpenCodeVersion(version),
|
||||
}
|
||||
})
|
||||
|
||||
const currentVersion = opencodeServerManager.getVersion()
|
||||
|
||||
@@ -1041,6 +1151,18 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
throw new Error('Invalid version format. Must be in MAJOR.MINOR.PATCH format (e.g., 1.2.27)')
|
||||
}
|
||||
|
||||
if (isSandboxEnforcementActive(db) && !isSandboxVerifiedOpenCodeVersion(versionWithoutPrefix)) {
|
||||
const verified = getSandboxVerifiedOpenCodeVersions()
|
||||
logger.warn(`OpenCode v${versionWithoutPrefix} install blocked while sandbox enforcement is active`)
|
||||
return c.json({
|
||||
success: false,
|
||||
error: `OpenCode v${versionWithoutPrefix} is not verified for sandbox enforcement`,
|
||||
details: `Sandbox enforcement only accepts verified OpenCode builds (${verified.join(', ')}).`,
|
||||
oldVersion,
|
||||
newVersion: oldVersion,
|
||||
}, 409)
|
||||
}
|
||||
|
||||
logger.info(`Installing OpenCode version: ${version}`)
|
||||
const versionArg = version.startsWith('v') ? version : `v${version}`
|
||||
const installMethod = getOpenCodeInstallMethod()
|
||||
@@ -1819,11 +1941,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
try {
|
||||
await opencodeServerManager.restart()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
} catch (restartError) {
|
||||
try {
|
||||
settingsService.restoreOpenCodeServerPasswordState(previousPasswordState)
|
||||
await opencodeServerManager.restart()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
sseAggregator.reconnect()
|
||||
} catch (restoreError) {
|
||||
logger.error('Failed to restore OpenCode server auth runtime after restart failure:', restoreError)
|
||||
@@ -1859,6 +1981,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
app.post('/manager-token/rotate', async (c) => {
|
||||
try {
|
||||
const token = rotateInternalToken(db)
|
||||
logger.info('Manager token rotated, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ token })
|
||||
} catch (error) {
|
||||
logger.error('Failed to rotate manager token:', error)
|
||||
|
||||
@@ -13,8 +13,8 @@ import {
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
|
||||
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { ensureAssistantRepo } from '../db/queries'
|
||||
@@ -24,7 +24,7 @@ const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
|
||||
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
|
||||
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
|
||||
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
|
||||
const ASSISTANT_OPENCODE_DIR = '.opencode'
|
||||
const ASSISTANT_OPENCODE_DIR = ASSISTANT_OPENCODE_DIR_NAME
|
||||
const ASSISTANT_INTERNAL_TOKEN_FILENAME = 'internal-token'
|
||||
const ASSISTANT_SKILLS_DIR = 'skills'
|
||||
const ASSISTANT_SCHEDULES_SKILL_DIR = 'schedule-management'
|
||||
@@ -37,9 +37,8 @@ const ASSISTANT_DEFAULT_AGENT_NAME = 'assistant'
|
||||
const ASSISTANT_DEFAULT_AGENT_FILENAME = `${ASSISTANT_DEFAULT_AGENT_NAME}.md`
|
||||
|
||||
export function getAssistantModeDirectory(): string {
|
||||
const reposPath = getReposPath()
|
||||
const assistantDir = path.join(reposPath, ASSISTANT_MODE_DIR)
|
||||
const resolvedReposRoot = path.resolve(reposPath)
|
||||
const assistantDir = getAssistantModePath()
|
||||
const resolvedReposRoot = path.resolve(getReposPath())
|
||||
const resolvedAssistantDir = path.resolve(assistantDir)
|
||||
|
||||
if (!resolvedAssistantDir.startsWith(resolvedReposRoot)) {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
import { writeFileAtomic } from '../utils/fs-safe'
|
||||
|
||||
const PLUGIN_FILENAME = 'ocm-gh-env.js'
|
||||
|
||||
@@ -47,11 +45,5 @@ export function getGhEnvPluginDir(configHome: string): string {
|
||||
}
|
||||
|
||||
export async function installGhEnvPlugin(configHome: string): Promise<void> {
|
||||
try {
|
||||
const dir = getGhEnvPluginDir(configHome)
|
||||
await mkdirSafe(dir)
|
||||
await fs.writeFile(path.join(dir, PLUGIN_FILENAME), PLUGIN_SOURCE, 'utf-8')
|
||||
} catch (error) {
|
||||
logger.warn('Failed to install gh-env OpenCode plugin:', error)
|
||||
}
|
||||
await writeFileAtomic(path.join(getGhEnvPluginDir(configHome), PLUGIN_FILENAME), PLUGIN_SOURCE)
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import { lstat, realpath } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import {
|
||||
isRecord,
|
||||
restoreEnforcementSections,
|
||||
sanitizeEnforcementSections,
|
||||
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'
|
||||
const QUARANTINE_MANIFEST_FILENAME = '.ocm-quarantine-manifest.json'
|
||||
|
||||
export function getOpenCodePluginDiscoveryHome(): string {
|
||||
return process.env.HOME ?? '/home/node'
|
||||
}
|
||||
|
||||
type PluginConfigBackup = {
|
||||
originalPlugins?: unknown
|
||||
sanitizedConfig?: Record<string, unknown>
|
||||
plugin?: unknown
|
||||
removedSections?: EnforcementRemovedSections
|
||||
}
|
||||
|
||||
type QuarantineManifestEntry = {
|
||||
original: string
|
||||
order: number
|
||||
}
|
||||
|
||||
type QuarantineManifest = {
|
||||
version: 1
|
||||
entries: Record<string, QuarantineManifestEntry>
|
||||
}
|
||||
|
||||
function deepEqual(left: unknown, right: unknown): boolean {
|
||||
if (left === right) return true
|
||||
if (Array.isArray(left) && Array.isArray(right)) {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((value, index) => deepEqual(value, right[index]))
|
||||
}
|
||||
if (left !== null && right !== null && typeof left === 'object' && typeof right === 'object') {
|
||||
const leftRecord = left as Record<string, unknown>
|
||||
const rightRecord = right as Record<string, unknown>
|
||||
const leftKeys = Object.keys(leftRecord).sort()
|
||||
const rightKeys = Object.keys(rightRecord).sort()
|
||||
if (leftKeys.length !== rightKeys.length) return false
|
||||
return leftKeys.every((key, index) => key === rightKeys[index] && deepEqual(leftRecord[key], rightRecord[key]))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function getPluginDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'plugin'),
|
||||
path.join(configHome, 'opencode', 'plugins'),
|
||||
path.join(home, '.opencode', 'plugin'),
|
||||
path.join(home, '.opencode', 'plugins'),
|
||||
]
|
||||
}
|
||||
|
||||
function getToolDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'tool'),
|
||||
path.join(configHome, 'opencode', 'tools'),
|
||||
path.join(home, '.opencode', 'tool'),
|
||||
path.join(home, '.opencode', 'tools'),
|
||||
]
|
||||
}
|
||||
|
||||
function getNativeOpenCodeConfigPaths(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'opencode.json'),
|
||||
path.join(configHome, 'opencode', 'opencode.jsonc'),
|
||||
path.join(configHome, 'opencode', 'config.json'),
|
||||
path.join(home, '.opencode', 'opencode.json'),
|
||||
path.join(home, '.opencode', 'opencode.jsonc'),
|
||||
]
|
||||
}
|
||||
|
||||
function getSystemManagedConfigDir(): string {
|
||||
switch (process.platform) {
|
||||
case 'darwin':
|
||||
return '/Library/Application Support/opencode'
|
||||
case 'win32':
|
||||
return path.join(process.env.ProgramData || 'C:\\ProgramData', 'opencode')
|
||||
default:
|
||||
return '/etc/opencode'
|
||||
}
|
||||
}
|
||||
|
||||
function getManagedConfigPaths(): string[] {
|
||||
const dirs = [getSystemManagedConfigDir()]
|
||||
const override = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR
|
||||
if (override !== undefined && override.trim() !== '') {
|
||||
dirs.push(override)
|
||||
}
|
||||
return [...new Set(dirs)].flatMap((dir) =>
|
||||
['opencode.json', 'opencode.jsonc'].map((file) => path.join(dir, file)),
|
||||
)
|
||||
}
|
||||
|
||||
function getEnforcementConfigPaths(configHome: string, configPath: string): string[] {
|
||||
return [...new Set([configPath, ...getNativeOpenCodeConfigPaths(configHome), ...getManagedConfigPaths()])]
|
||||
}
|
||||
|
||||
function getAuthFilePath(configHome: string): string {
|
||||
return path.join(path.dirname(configHome), '.opencode', 'state', 'opencode', 'auth.json')
|
||||
}
|
||||
|
||||
async function assertNoWellKnownAuthEntries(configHome: string): Promise<void> {
|
||||
const authPath = getAuthFilePath(configHome)
|
||||
let content: string
|
||||
try {
|
||||
content = await fs.readFile(authPath, 'utf-8')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw new Error(
|
||||
`cannot inspect OpenCode auth file ${authPath}: ${error instanceof Error ? error.message : String(error)}; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
let auth: unknown
|
||||
try {
|
||||
auth = JSON.parse(content)
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`cannot parse OpenCode auth file ${authPath}: ${error instanceof Error ? error.message : String(error)}; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
if (!isRecord(auth)) {
|
||||
throw new Error(
|
||||
`OpenCode auth file ${authPath} has an unexpected top-level shape; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
for (const [providerId, entry] of Object.entries(auth)) {
|
||||
if (!isRecord(entry)) {
|
||||
throw new Error(
|
||||
`OpenCode auth entry ${providerId} in ${authPath} cannot be inspected; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
if (entry.type === 'wellknown') {
|
||||
throw new Error(
|
||||
`refusing to start an enforced OpenCode server: provider ${providerId} authenticates through well-known remote configuration (.well-known/opencode) that the Manager cannot sanitize; remove the provider authentication or disable sandboxing`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pathExists(target: string): Promise<boolean> {
|
||||
try {
|
||||
await fs.access(target)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function requireRealDirectory(dir: string, purpose: string): Promise<boolean> {
|
||||
let stat
|
||||
try {
|
||||
stat = await lstat(dir)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return false
|
||||
throw new Error(`cannot inspect ${purpose} ${dir}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
if (stat.isSymbolicLink()) {
|
||||
throw new Error(`${purpose} ${dir} is a symbolic link; refusing to quarantine or restore through a redirected directory`)
|
||||
}
|
||||
if (!stat.isDirectory()) {
|
||||
throw new Error(`${purpose} ${dir} is not a directory; refusing to quarantine or restore through it`)
|
||||
}
|
||||
const resolved = path.resolve(dir)
|
||||
const canonical = await realpath(dir)
|
||||
if (canonical !== resolved) {
|
||||
throw new Error(`${purpose} ${dir} resolves to ${canonical} instead of ${resolved}; refusing to quarantine or restore through a redirected directory`)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function quarantineConflictSuffixMatch(name: string): string | null {
|
||||
const separatorIndex = name.lastIndexOf(QUARANTINE_CONFLICT_SUFFIX)
|
||||
if (separatorIndex === -1) return null
|
||||
const suffix = name.slice(separatorIndex + QUARANTINE_CONFLICT_SUFFIX.length)
|
||||
if (!/^\d+$/.test(suffix)) return null
|
||||
return name.slice(0, separatorIndex)
|
||||
}
|
||||
|
||||
function isSingleBasenameComponent(name: string): boolean {
|
||||
return (
|
||||
name !== '' &&
|
||||
name !== '.' &&
|
||||
name !== '..' &&
|
||||
!name.includes('/') &&
|
||||
!name.includes('\\') &&
|
||||
path.basename(name) === name
|
||||
)
|
||||
}
|
||||
|
||||
function assertPathContainedWithin(parent: string, child: string, purpose: string): string {
|
||||
const relative = path.relative(parent, child)
|
||||
if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
|
||||
throw new Error(`${purpose} path ${child} escapes ${parent}; refusing to restore outside the plugin directory`)
|
||||
}
|
||||
return path.join(parent, relative)
|
||||
}
|
||||
|
||||
async function resolveQuarantineTarget(quarantineDir: string, name: string): Promise<string> {
|
||||
const stored = name === QUARANTINE_MANIFEST_FILENAME
|
||||
? `${name}${QUARANTINE_CONFLICT_SUFFIX}1`
|
||||
: name
|
||||
const original = path.join(quarantineDir, stored)
|
||||
if (!(await pathExists(original))) return original
|
||||
for (let index = 1; ; index++) {
|
||||
const candidate = path.join(quarantineDir, `${stored}${QUARANTINE_CONFLICT_SUFFIX}${index}`)
|
||||
if (!(await pathExists(candidate))) return candidate
|
||||
}
|
||||
}
|
||||
|
||||
async function readQuarantineManifest(quarantineDir: string): Promise<QuarantineManifest> {
|
||||
try {
|
||||
const parsed = JSON.parse(await fs.readFile(path.join(quarantineDir, QUARANTINE_MANIFEST_FILENAME), 'utf-8')) as unknown
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
const record = parsed as { version?: unknown; entries?: unknown }
|
||||
if (record.version === 1 && record.entries && typeof record.entries === 'object' && !Array.isArray(record.entries)) {
|
||||
return { version: 1, entries: record.entries as Record<string, QuarantineManifestEntry> }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// no manifest yet
|
||||
}
|
||||
return { version: 1, entries: {} }
|
||||
}
|
||||
|
||||
async function writeQuarantineManifest(quarantineDir: string, manifest: QuarantineManifest): Promise<void> {
|
||||
await writeFileAtomic(path.join(quarantineDir, QUARANTINE_MANIFEST_FILENAME), JSON.stringify(manifest, null, 2))
|
||||
}
|
||||
|
||||
async function recordQuarantinedEntry(
|
||||
manifest: QuarantineManifest,
|
||||
storedName: string,
|
||||
originalName: string,
|
||||
): Promise<void> {
|
||||
const existingOrders = Object.values(manifest.entries)
|
||||
.filter((record) => record.original === originalName)
|
||||
.map((record) => record.order)
|
||||
const order = storedName === originalName ? 1 : (existingOrders.length > 0 ? Math.max(...existingOrders) + 1 : 1)
|
||||
manifest.entries[storedName] = { original: originalName, order }
|
||||
}
|
||||
|
||||
async function moveUntrustedPluginEntries(
|
||||
dir: string,
|
||||
trustedNames: readonly string[],
|
||||
purpose = 'plugin directory',
|
||||
): Promise<void> {
|
||||
if (!(await requireRealDirectory(dir, purpose))) return
|
||||
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await fs.readdir(dir)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw new Error(`cannot inspect plugin directory ${dir}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
|
||||
const untrusted = entries.filter((name) => !trustedNames.includes(name))
|
||||
if (untrusted.length === 0) return
|
||||
|
||||
const quarantineDir = `${dir}.ocm-quarantine`
|
||||
await mkdirSafe(quarantineDir)
|
||||
if (!(await requireRealDirectory(quarantineDir, 'quarantine directory'))) {
|
||||
throw new Error(`cannot create quarantine directory ${quarantineDir}`)
|
||||
}
|
||||
const manifest = await readQuarantineManifest(quarantineDir)
|
||||
for (const name of untrusted) {
|
||||
const source = path.join(dir, name)
|
||||
const target = await resolveQuarantineTarget(quarantineDir, name)
|
||||
await fs.rename(source, target)
|
||||
await recordQuarantinedEntry(manifest, path.basename(target), name)
|
||||
}
|
||||
await writeQuarantineManifest(quarantineDir, manifest)
|
||||
logger.warn(`Quarantined ${untrusted.length} untrusted OpenCode plugin file(s) from ${dir}`)
|
||||
}
|
||||
|
||||
async function restorePluginEntries(dir: string): Promise<void> {
|
||||
const quarantineDir = `${dir}.ocm-quarantine`
|
||||
if (!(await requireRealDirectory(quarantineDir, 'quarantine directory'))) return
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await fs.readdir(quarantineDir)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw error
|
||||
}
|
||||
|
||||
await mkdirSafe(dir)
|
||||
if (!(await requireRealDirectory(dir, 'plugin directory'))) {
|
||||
throw new Error(`cannot create plugin directory ${dir}`)
|
||||
}
|
||||
|
||||
const manifest = await readQuarantineManifest(quarantineDir)
|
||||
const storedNames = entries.filter((name) => name !== QUARANTINE_MANIFEST_FILENAME)
|
||||
|
||||
const byOriginal = new Map<string, Array<{ stored: string; order: number }>>()
|
||||
const manifestless: string[] = []
|
||||
for (const stored of storedNames) {
|
||||
const record = manifest.entries[stored]
|
||||
if (
|
||||
record &&
|
||||
isSingleBasenameComponent(stored) &&
|
||||
typeof record.original === 'string' &&
|
||||
isSingleBasenameComponent(record.original) &&
|
||||
typeof record.order === 'number' &&
|
||||
Number.isFinite(record.order)
|
||||
) {
|
||||
const list = byOriginal.get(record.original) ?? []
|
||||
list.push({ stored, order: record.order })
|
||||
byOriginal.set(record.original, list)
|
||||
} else {
|
||||
manifestless.push(stored)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [original, copies] of byOriginal) {
|
||||
copies.sort((left, right) => left.order - right.order)
|
||||
const primary = copies[0]!
|
||||
const target = assertPathContainedWithin(dir, path.join(dir, original), 'restore target')
|
||||
if (await pathExists(target)) continue
|
||||
const source = assertPathContainedWithin(quarantineDir, path.join(quarantineDir, primary.stored), 'restore source')
|
||||
await fs.rename(source, target)
|
||||
}
|
||||
|
||||
for (const name of manifestless) {
|
||||
const base = quarantineConflictSuffixMatch(name)
|
||||
if (base !== null) {
|
||||
const baseIsOriginal = manifest.entries[base] !== undefined || storedNames.includes(base)
|
||||
if (baseIsOriginal) continue
|
||||
}
|
||||
const target = assertPathContainedWithin(dir, path.join(dir, name), 'restore target')
|
||||
if (await pathExists(target)) continue
|
||||
const source = assertPathContainedWithin(quarantineDir, path.join(quarantineDir, name), 'restore source')
|
||||
await fs.rename(source, target)
|
||||
}
|
||||
|
||||
await fs.rm(path.join(quarantineDir, QUARANTINE_MANIFEST_FILENAME), { force: true })
|
||||
|
||||
const remaining = (await fs.readdir(quarantineDir)).filter((name) => name !== QUARANTINE_MANIFEST_FILENAME)
|
||||
if (remaining.length > 0) {
|
||||
logger.warn(
|
||||
`Left ${remaining.length} conflicted quarantined OpenCode plugin copy/copies recoverable in ${quarantineDir}: ${remaining.join(', ')}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function readPluginConfigBackup(backupPath: string): Promise<PluginConfigBackup | null> {
|
||||
try {
|
||||
const parsed = parseJsonc(await fs.readFile(backupPath, 'utf-8')) as unknown
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as PluginConfigBackup
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function backupRemovedSections(backup: PluginConfigBackup | null): EnforcementRemovedSections {
|
||||
if (backup !== null && backup.removedSections !== undefined && isRecord(backup.removedSections)) {
|
||||
return backup.removedSections as EnforcementRemovedSections
|
||||
}
|
||||
const legacyPlugins = backup !== null && Array.isArray(backup.originalPlugins)
|
||||
? backup.originalPlugins
|
||||
: backup?.plugin
|
||||
return Array.isArray(legacyPlugins) ? { plugin: legacyPlugins } : {}
|
||||
}
|
||||
|
||||
async function existingFileMode(filePath: string): Promise<number | undefined> {
|
||||
try {
|
||||
return (await fs.stat(filePath)).mode & 0o777
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function describeRemovedSections(removed: EnforcementRemovedSections): string {
|
||||
const parts: string[] = []
|
||||
if (Array.isArray(removed.plugin) && removed.plugin.length > 0) {
|
||||
parts.push(`${removed.plugin.length} configured OpenCode plugin(s)`)
|
||||
}
|
||||
if (isRecord(removed.mcp) && Object.keys(removed.mcp).length > 0) {
|
||||
parts.push(`${Object.keys(removed.mcp).length} local MCP server(s)`)
|
||||
}
|
||||
if (isRecord(removed.provider) && Object.keys(removed.provider).length > 0) {
|
||||
parts.push(`${Object.keys(removed.provider).length} custom provider module(s)`)
|
||||
}
|
||||
if (removed.formatter !== undefined) {
|
||||
parts.push('the formatter configuration')
|
||||
}
|
||||
if (removed.shell !== undefined) {
|
||||
parts.push('the shell configuration')
|
||||
}
|
||||
if (removed.lsp !== undefined) {
|
||||
parts.push('the LSP server configuration')
|
||||
}
|
||||
if (removed.experimentalHook !== undefined) {
|
||||
parts.push('experimental hook commands')
|
||||
}
|
||||
return parts.length > 0 ? parts.join(', ') : 'all host-execution config sections'
|
||||
}
|
||||
|
||||
function reconcileRemovedSections(
|
||||
prior: EnforcementRemovedSections,
|
||||
current: EnforcementRemovedSections,
|
||||
): EnforcementRemovedSections {
|
||||
const merged: EnforcementRemovedSections = {}
|
||||
|
||||
if (current.plugin !== undefined) {
|
||||
merged.plugin = current.plugin
|
||||
} else if (Array.isArray(prior.plugin) && prior.plugin.length > 0) {
|
||||
merged.plugin = prior.plugin
|
||||
}
|
||||
|
||||
const priorMcp = isRecord(prior.mcp) ? prior.mcp : {}
|
||||
const currentMcp = isRecord(current.mcp) ? current.mcp : {}
|
||||
const mergedMcp: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(priorMcp)) {
|
||||
if (!(name in currentMcp)) {
|
||||
mergedMcp[name] = entry
|
||||
}
|
||||
}
|
||||
for (const [name, entry] of Object.entries(currentMcp)) {
|
||||
mergedMcp[name] = entry
|
||||
}
|
||||
if (Object.keys(mergedMcp).length > 0) {
|
||||
merged.mcp = mergedMcp
|
||||
}
|
||||
|
||||
const priorProvider = isRecord(prior.provider) ? prior.provider : {}
|
||||
const currentProvider = isRecord(current.provider) ? current.provider : {}
|
||||
const mergedProvider: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(priorProvider)) {
|
||||
if (!(name in currentProvider)) {
|
||||
mergedProvider[name] = entry
|
||||
}
|
||||
}
|
||||
for (const [name, entry] of Object.entries(currentProvider)) {
|
||||
mergedProvider[name] = entry
|
||||
}
|
||||
if (Object.keys(mergedProvider).length > 0) {
|
||||
merged.provider = mergedProvider
|
||||
}
|
||||
|
||||
for (const key of ['formatter', 'shell', 'lsp', 'experimentalHook'] as const) {
|
||||
if (current[key] !== undefined) {
|
||||
merged[key] = current[key]
|
||||
} else if (prior[key] !== undefined) {
|
||||
merged[key] = prior[key]
|
||||
}
|
||||
}
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
async function sanitizeEnforcementConfigSections(configPath: string): Promise<void> {
|
||||
let content: string
|
||||
try {
|
||||
content = await fs.readFile(configPath, 'utf-8')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw error
|
||||
}
|
||||
|
||||
let config: Record<string, unknown>
|
||||
try {
|
||||
config = parseJsonc(content) as Record<string, unknown>
|
||||
} catch (error) {
|
||||
throw new Error(`cannot parse OpenCode config ${configPath} for enforcement sanitization: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
const backupPath = `${configPath}${PLUGIN_CONFIG_BACKUP_SUFFIX}`
|
||||
const hasBackup = await pathExists(backupPath)
|
||||
const pluginArray = Array.isArray(config.plugin) ? config.plugin : []
|
||||
const { sanitized, removed } = sanitizeEnforcementSections(config)
|
||||
if (
|
||||
!hasBackup &&
|
||||
pluginArray.length === 0 &&
|
||||
removed.mcp === undefined &&
|
||||
removed.formatter === undefined &&
|
||||
removed.shell === undefined &&
|
||||
removed.lsp === undefined &&
|
||||
removed.experimentalHook === undefined &&
|
||||
removed.provider === undefined
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
let effectiveRemoved = removed
|
||||
if (hasBackup) {
|
||||
const backup = await readPluginConfigBackup(backupPath)
|
||||
if (backup !== null) {
|
||||
const priorRemoved = backupRemovedSections(backup)
|
||||
if (backup.sanitizedConfig !== undefined && deepEqual(backup.sanitizedConfig, config)) {
|
||||
effectiveRemoved = priorRemoved
|
||||
} else {
|
||||
effectiveRemoved = reconcileRemovedSections(priorRemoved, removed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const backupContent = JSON.stringify(
|
||||
{
|
||||
originalPlugins: effectiveRemoved.plugin,
|
||||
sanitizedConfig: sanitized,
|
||||
removedSections: effectiveRemoved,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
await writeFileAtomic(backupPath, backupContent, { mode: await existingFileMode(backupPath) })
|
||||
await writeFileAtomic(configPath, JSON.stringify(sanitized, null, 2), { mode: await existingFileMode(configPath) })
|
||||
logger.warn(`Removed ${describeRemovedSections(effectiveRemoved)} from ${configPath} while sandbox enforcement is active`)
|
||||
}
|
||||
|
||||
async function restoreEnforcementConfigSections(configPath: string): Promise<void> {
|
||||
const backupPath = `${configPath}${PLUGIN_CONFIG_BACKUP_SUFFIX}`
|
||||
if (!(await pathExists(backupPath))) return
|
||||
|
||||
let backupContent: string
|
||||
let currentContent: string
|
||||
try {
|
||||
backupContent = await fs.readFile(backupPath, 'utf-8')
|
||||
currentContent = await fs.readFile(configPath, 'utf-8')
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
let removed: EnforcementRemovedSections
|
||||
let currentConfig: Record<string, unknown>
|
||||
try {
|
||||
const backupRecord = parseJsonc(backupContent) as Record<string, unknown>
|
||||
removed = isRecord(backupRecord.removedSections)
|
||||
? backupRecord.removedSections
|
||||
: {
|
||||
plugin: Array.isArray(backupRecord.originalPlugins)
|
||||
? backupRecord.originalPlugins
|
||||
: Array.isArray(backupRecord.plugin) ? backupRecord.plugin : [],
|
||||
}
|
||||
currentConfig = parseJsonc(currentContent) as Record<string, unknown>
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
const restored = restoreEnforcementSections(currentConfig, removed)
|
||||
const restoredContent = JSON.stringify(restored, null, 2)
|
||||
if (restoredContent !== currentContent) {
|
||||
await writeFileAtomic(configPath, restoredContent, { mode: await existingFileMode(configPath) })
|
||||
}
|
||||
await fs.rm(backupPath, { force: true })
|
||||
}
|
||||
|
||||
export async function quarantineOpenCodePlugins(configHome: string, configPath: string): Promise<void> {
|
||||
await assertNoWellKnownAuthEntries(configHome)
|
||||
const managerPluginDir = path.join(configHome, 'opencode', 'plugin')
|
||||
for (const dir of getPluginDirs(configHome)) {
|
||||
await moveUntrustedPluginEntries(dir, dir === managerPluginDir ? TRUSTED_OPENCODE_PLUGIN_FILENAMES : [])
|
||||
}
|
||||
for (const dir of getToolDirs(configHome)) {
|
||||
await moveUntrustedPluginEntries(dir, TRUSTED_TOOL_FILENAMES, 'custom tool directory')
|
||||
}
|
||||
for (const nativeConfigPath of getEnforcementConfigPaths(configHome, configPath)) {
|
||||
await sanitizeEnforcementConfigSections(nativeConfigPath)
|
||||
}
|
||||
}
|
||||
|
||||
export async function restoreQuarantinedOpenCodePlugins(configHome: string, configPath: string): Promise<void> {
|
||||
for (const dir of getPluginDirs(configHome)) {
|
||||
await restorePluginEntries(dir)
|
||||
}
|
||||
for (const dir of getToolDirs(configHome)) {
|
||||
await restorePluginEntries(dir)
|
||||
}
|
||||
for (const nativeConfigPath of getEnforcementConfigPaths(configHome, configPath)) {
|
||||
await restoreEnforcementConfigSections(nativeConfigPath)
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,22 @@ export function getOpenCodeRestartCoordinator(): OpenCodeRestartCoordinator | nu
|
||||
return restartCoordinator
|
||||
}
|
||||
|
||||
function restartFailureError(): Error {
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
return new Error(startupError ?? 'OpenCode server restart did not complete successfully')
|
||||
}
|
||||
|
||||
async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean> {
|
||||
if (supervisor) {
|
||||
return (await supervisor.restart('settings_restart')).healthy
|
||||
}
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
return opencodeServerManager.checkHealth()
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
return healthy
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,13 +46,23 @@ async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean>
|
||||
export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
|
||||
if (restartCoordinator) {
|
||||
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor))
|
||||
if (!result.healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
return { resumedSessionIDs: result.resumedSessionIDs }
|
||||
}
|
||||
if (supervisor) {
|
||||
await supervisor.restart('settings_restart')
|
||||
const status = await supervisor.restart('settings_restart')
|
||||
if (!status.healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
} else {
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
}
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
@@ -55,7 +74,11 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
|
||||
*/
|
||||
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (supervisor) {
|
||||
await supervisor.reloadConfig('settings_reload')
|
||||
const status = await supervisor.reloadConfig('settings_reload')
|
||||
if (!status.healthy) {
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
throw new Error(startupError ?? 'OpenCode server reload did not complete successfully')
|
||||
}
|
||||
return
|
||||
}
|
||||
await opencodeServerManager.reloadConfig()
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
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'
|
||||
|
||||
const PLUGIN_FILENAME = 'ocm-sandbox.js'
|
||||
|
||||
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)}
|
||||
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
|
||||
|
||||
function guardCommand(reason) {
|
||||
var safe = String(SANDBOX_UNAVAILABLE_PREFIX + reason).replace(/'/g, "'\\\\''")
|
||||
return "printf '%s\\\\n' '" + safe + "' >&2; exit 1"
|
||||
}
|
||||
|
||||
function lockArgsReference(output, args) {
|
||||
try {
|
||||
Object.defineProperty(output, 'args', {
|
||||
get: function () { return args },
|
||||
set: function () {},
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
})
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
var descriptor = Object.getOwnPropertyDescriptor(output, 'args')
|
||||
return !!descriptor && descriptor.configurable === false && typeof descriptor.get === 'function'
|
||||
}
|
||||
|
||||
function lockCommand(args, command) {
|
||||
var current = null
|
||||
try {
|
||||
Object.defineProperty(args, 'command', {
|
||||
get: function () { return command },
|
||||
set: function () {},
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
})
|
||||
current = args.command
|
||||
} catch (error) {
|
||||
try {
|
||||
args.command = command
|
||||
current = args.command
|
||||
} catch (ignored) {
|
||||
current = null
|
||||
}
|
||||
}
|
||||
return current === command
|
||||
}
|
||||
|
||||
var wrappedCommands = new Map()
|
||||
var bypassed = false
|
||||
|
||||
function replaceCommand(output, command, callID) {
|
||||
if (!lockArgsReference(output, output.args)) {
|
||||
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
|
||||
}
|
||||
if (!lockCommand(output.args, command)) {
|
||||
throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host')
|
||||
}
|
||||
wrappedCommands.set(callID, command)
|
||||
}
|
||||
|
||||
export default async function ({ directory, worktree }) {
|
||||
return {
|
||||
'tool.execute.before': async (input, output) => {
|
||||
if (input.tool !== 'bash') return
|
||||
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
|
||||
if (typeof output.args?.command !== 'string') {
|
||||
if (!lockArgsReference(output, output.args)) {
|
||||
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
|
||||
}
|
||||
return
|
||||
}
|
||||
if (bypassed) {
|
||||
replaceCommand(output, guardCommand('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'), input.callID)
|
||||
return
|
||||
}
|
||||
var baseUrl = process.env.OCM_INTERNAL_API_URL
|
||||
var token = process.env.OCM_INTERNAL_TOKEN
|
||||
if (!baseUrl || !token) {
|
||||
replaceCommand(output, guardCommand('sandbox plan lookup unavailable: internal API is not configured'), input.callID)
|
||||
return
|
||||
}
|
||||
var replacement = null
|
||||
var sessionDir = worktree || directory
|
||||
var effectiveDirectory = sessionDir
|
||||
var requestedWorkdir = output.args.workdir
|
||||
if (typeof requestedWorkdir === 'string' && requestedWorkdir.length > 0) {
|
||||
if (requestedWorkdir.charAt(0) === '/') {
|
||||
effectiveDirectory = requestedWorkdir
|
||||
} else {
|
||||
effectiveDirectory = sessionDir.replace(/\\/+$/, '') + '/' + requestedWorkdir
|
||||
}
|
||||
}
|
||||
var controller = new AbortController()
|
||||
var planTimedOut = false
|
||||
var planTimer = setTimeout(function () {
|
||||
planTimedOut = true
|
||||
controller.abort()
|
||||
}, PLAN_TIMEOUT_MS)
|
||||
try {
|
||||
var res = await fetch(baseUrl + '/sandbox/command', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
Authorization: 'Bearer ' + token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
directory: effectiveDirectory,
|
||||
command: output.args.command,
|
||||
enforced: true,
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (!res.ok) {
|
||||
replacement = guardCommand('sandbox plan request failed with status ' + res.status)
|
||||
} else {
|
||||
var plan = await res.json()
|
||||
if (plan && typeof plan === 'object' && plan.mode === 'sandbox' && typeof plan.command === 'string' && plan.command.length > 0) {
|
||||
replacement = plan.command
|
||||
} else {
|
||||
replacement = guardCommand(plan && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response')
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
replacement = guardCommand(planTimedOut ? 'sandbox plan lookup timed out' : (error instanceof Error ? error.message : String(error)))
|
||||
} finally {
|
||||
clearTimeout(planTimer)
|
||||
}
|
||||
if (replacement !== null) {
|
||||
replaceCommand(output, replacement, input.callID)
|
||||
}
|
||||
},
|
||||
'tool.execute.after': async (input, output) => {
|
||||
if (input.tool !== 'bash') return
|
||||
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
|
||||
var wrapped = wrappedCommands.get(input.callID)
|
||||
if (wrapped === undefined) return
|
||||
wrappedCommands.delete(input.callID)
|
||||
if (!bypassed && input.args && input.args.command !== wrapped) {
|
||||
bypassed = true
|
||||
console.error('OpenCode Manager: sandbox enforcement bypass detected for bash call ' + input.callID + '; blocking all further sandboxed commands')
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
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)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -65,6 +65,7 @@ export class OpenCodeSupervisor {
|
||||
private attemptedRecoveryActions: OpenCodeRecoveryAction[] = []
|
||||
private consecutiveFailures = 0
|
||||
private operationInProgress = false
|
||||
private operationTail: Promise<void> = Promise.resolve()
|
||||
private updatedAt = new Date().toISOString()
|
||||
|
||||
constructor(
|
||||
@@ -89,6 +90,7 @@ export class OpenCodeSupervisor {
|
||||
async start(): Promise<OpenCodeLifecycleStatus> {
|
||||
await this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
await this.openCodeServerManager.start()
|
||||
@@ -113,6 +115,7 @@ export class OpenCodeSupervisor {
|
||||
async restart(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
return this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
@@ -128,6 +131,7 @@ export class OpenCodeSupervisor {
|
||||
async reloadConfig(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
return this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
@@ -160,6 +164,7 @@ export class OpenCodeSupervisor {
|
||||
|
||||
await this.runLifecycleOperation(async () => {
|
||||
this.setState('stopping')
|
||||
this.closeLifecycleGate()
|
||||
await this.openCodeServerManager.stop()
|
||||
this.setState('stopped')
|
||||
return this.getStatus()
|
||||
@@ -191,16 +196,20 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
private async runLifecycleOperation(operation: () => Promise<OpenCodeLifecycleStatus>): Promise<OpenCodeLifecycleStatus> {
|
||||
if (this.operationInProgress) {
|
||||
return this.getStatus()
|
||||
}
|
||||
const previousTail = this.operationTail
|
||||
let releaseTail!: () => void
|
||||
this.operationTail = new Promise<void>((resolve) => {
|
||||
releaseTail = resolve
|
||||
})
|
||||
|
||||
await previousTail
|
||||
this.operationInProgress = true
|
||||
try {
|
||||
return await operation()
|
||||
} finally {
|
||||
this.operationInProgress = false
|
||||
this.touch()
|
||||
releaseTail()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,6 +222,7 @@ export class OpenCodeSupervisor {
|
||||
|
||||
this.consecutiveFailures += 1
|
||||
this.setState('unhealthy')
|
||||
this.closeLifecycleGate()
|
||||
this.lastError = this.openCodeServerManager.getLastStartupError() ?? 'OpenCode health check failed'
|
||||
|
||||
if (respectThreshold && this.consecutiveFailures < this.failureThreshold) {
|
||||
@@ -223,10 +233,20 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
private async recover(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
this.closeLifecycleGate()
|
||||
|
||||
if (this.openCodeServerManager.isLastStartupErrorNonRecoverable()) {
|
||||
return this.failWithoutRecovery()
|
||||
}
|
||||
|
||||
this.setState('recovering')
|
||||
logger.warn(`OpenCode unhealthy during ${reason}, entering recovery`)
|
||||
|
||||
for (const action of OPENCODE_RECOVERY_ACTIONS) {
|
||||
if (this.openCodeServerManager.isLastStartupErrorNonRecoverable()) {
|
||||
return this.failWithoutRecovery()
|
||||
}
|
||||
|
||||
this.activeRecoveryAction = action
|
||||
this.attemptedRecoveryActions.push(action)
|
||||
this.touch()
|
||||
@@ -249,6 +269,17 @@ export class OpenCodeSupervisor {
|
||||
|
||||
this.activeRecoveryAction = null
|
||||
this.setState('failed')
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
private failWithoutRecovery(): OpenCodeLifecycleStatus {
|
||||
const message = this.lastError ?? this.openCodeServerManager.getLastStartupError() ?? 'OpenCode failed with a non-recoverable startup error'
|
||||
logger.error(`OpenCode failed with a non-recoverable startup error; skipping configuration recovery: ${message}`)
|
||||
this.activeRecoveryAction = null
|
||||
this.attemptedRecoveryActions = []
|
||||
this.setState('failed')
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
@@ -349,12 +380,17 @@ export class OpenCodeSupervisor {
|
||||
logger.info(`Started OpenCode supervisor health polling (${this.pollIntervalMs}ms)`)
|
||||
}
|
||||
|
||||
private closeLifecycleGate(): void {
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
}
|
||||
|
||||
private markHealthy(): void {
|
||||
this.state = 'healthy'
|
||||
this.lastError = null
|
||||
this.activeRecoveryAction = null
|
||||
this.attemptedRecoveryActions = []
|
||||
this.consecutiveFailures = 0
|
||||
this.openCodeServerManager.setLifecycleInitialized(true)
|
||||
this.touch()
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,10 @@ export interface OpenCodeClient {
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export type OpenCodeClientHost = string | (() => string)
|
||||
|
||||
export interface FetchOpenCodeClientConfig {
|
||||
baseUrl: string
|
||||
baseUrl: OpenCodeClientHost
|
||||
basicAuth: string | null
|
||||
passwordResolver?: OpenCodePasswordResolver
|
||||
fetchFn?: typeof fetch
|
||||
@@ -53,6 +55,10 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
return this.config.fetchFn ?? fetch
|
||||
}
|
||||
|
||||
private resolveBaseUrl(): string {
|
||||
return typeof this.config.baseUrl === 'function' ? this.config.baseUrl() : this.config.baseUrl
|
||||
}
|
||||
|
||||
private async getBasicAuth(): Promise<string> {
|
||||
if (!this.config.passwordResolver) {
|
||||
return this.config.basicAuth ?? ''
|
||||
@@ -62,7 +68,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.config.baseUrl + req.path)
|
||||
const url = new URL(this.resolveBaseUrl() + req.path)
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
@@ -248,9 +254,20 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(passwordOverride?: string | OpenCodePasswordResolver): OpenCodeClient {
|
||||
const host = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
|
||||
const baseUrl = `http://${host}:${ENV.OPENCODE.PORT}`
|
||||
function formatOpenCodeHostForUrl(host: string): string {
|
||||
return host.includes(':') ? `[${host}]` : host
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(
|
||||
passwordOverride?: string | OpenCodePasswordResolver,
|
||||
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 passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
export type EnforcementRemovedSections = Record<string, unknown>
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function sanitizeConfigForEnforcement(
|
||||
config: Record<string, unknown>,
|
||||
enforced: boolean,
|
||||
): Record<string, unknown> {
|
||||
return sanitizeConfigForEnforcementResult(config, enforced).sanitized
|
||||
}
|
||||
|
||||
export function sanitizeConfigForEnforcementResult(
|
||||
config: Record<string, unknown>,
|
||||
enforced: boolean,
|
||||
): { sanitized: Record<string, unknown>; removed: EnforcementRemovedSections } {
|
||||
if (!enforced) {
|
||||
return { sanitized: config, removed: {} }
|
||||
}
|
||||
const { sanitized, removed } = sanitizeEnforcementSections(config)
|
||||
if (Object.keys(removed).length === 0) {
|
||||
return { sanitized: config, removed: {} }
|
||||
}
|
||||
if (Array.isArray(removed.plugin)) {
|
||||
logger.warn(`Stripped ${removed.plugin.length} configured OpenCode plugin(s) from the live config while sandbox enforcement is active`)
|
||||
}
|
||||
if (isRecord(removed.mcp)) {
|
||||
logger.warn(`Disabled ${Object.keys(removed.mcp).length} local MCP server(s) from the live config while sandbox enforcement is active`)
|
||||
}
|
||||
if (isRecord(removed.provider)) {
|
||||
logger.warn(`Disabled ${Object.keys(removed.provider).length} custom provider module(s) from the live config while sandbox enforcement is active`)
|
||||
}
|
||||
if (removed.formatter !== undefined) {
|
||||
logger.warn('Disabled formatter execution from the live config while sandbox enforcement is active')
|
||||
}
|
||||
if (removed.shell !== undefined) {
|
||||
logger.warn('Disabled the shell configuration from the live config while sandbox enforcement is active')
|
||||
}
|
||||
if (removed.lsp !== undefined) {
|
||||
logger.warn('Disabled LSP server configuration from the live config while sandbox enforcement is active')
|
||||
}
|
||||
if (removed.experimentalHook !== undefined) {
|
||||
logger.warn('Disabled experimental hook commands from the live config while sandbox enforcement is active')
|
||||
}
|
||||
return { sanitized, removed }
|
||||
}
|
||||
|
||||
export function isLocalMcpServerEntry(entry: unknown): boolean {
|
||||
if (!isRecord(entry)) return false
|
||||
return entry.type === 'local' || Array.isArray(entry.command)
|
||||
}
|
||||
|
||||
export function isCustomProviderEntry(entry: unknown): boolean {
|
||||
return isRecord(entry) && typeof entry.npm === 'string'
|
||||
}
|
||||
|
||||
export function sanitizeEnforcementSections(config: Record<string, unknown>): {
|
||||
sanitized: Record<string, unknown>
|
||||
removed: EnforcementRemovedSections
|
||||
} {
|
||||
const sanitized: Record<string, unknown> = { ...config }
|
||||
const removed: EnforcementRemovedSections = {}
|
||||
|
||||
if (Array.isArray(config.plugin) && config.plugin.length > 0) {
|
||||
delete sanitized.plugin
|
||||
removed.plugin = config.plugin
|
||||
}
|
||||
|
||||
if (config.formatter !== undefined) {
|
||||
delete sanitized.formatter
|
||||
removed.formatter = config.formatter
|
||||
}
|
||||
|
||||
if (config.shell !== undefined) {
|
||||
delete sanitized.shell
|
||||
removed.shell = config.shell
|
||||
}
|
||||
|
||||
const mcp = config.mcp
|
||||
if (isRecord(mcp)) {
|
||||
const retained: Record<string, unknown> = {}
|
||||
const removedMcp: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(mcp)) {
|
||||
if (isLocalMcpServerEntry(entry)) {
|
||||
removedMcp[name] = entry
|
||||
} else {
|
||||
retained[name] = entry
|
||||
}
|
||||
}
|
||||
if (Object.keys(removedMcp).length > 0) {
|
||||
removed.mcp = removedMcp
|
||||
if (Object.keys(retained).length > 0) {
|
||||
sanitized.mcp = retained
|
||||
} else {
|
||||
delete sanitized.mcp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const provider = config.provider
|
||||
if (isRecord(provider)) {
|
||||
const retainedProvider: Record<string, unknown> = {}
|
||||
const removedProvider: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(provider)) {
|
||||
if (isCustomProviderEntry(entry)) {
|
||||
removedProvider[name] = entry
|
||||
} else {
|
||||
retainedProvider[name] = entry
|
||||
}
|
||||
}
|
||||
if (Object.keys(removedProvider).length > 0) {
|
||||
removed.provider = removedProvider
|
||||
if (Object.keys(retainedProvider).length > 0) {
|
||||
sanitized.provider = retainedProvider
|
||||
} else {
|
||||
delete sanitized.provider
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const lsp = config.lsp
|
||||
if (lsp !== undefined && lsp !== false) {
|
||||
delete sanitized.lsp
|
||||
removed.lsp = lsp
|
||||
}
|
||||
|
||||
const experimental = config.experimental
|
||||
if (isRecord(experimental) && experimental.hook !== undefined) {
|
||||
const retainedExperimental: Record<string, unknown> = { ...experimental }
|
||||
delete retainedExperimental.hook
|
||||
removed.experimentalHook = experimental.hook
|
||||
if (Object.keys(retainedExperimental).length > 0) {
|
||||
sanitized.experimental = retainedExperimental
|
||||
} else {
|
||||
delete sanitized.experimental
|
||||
}
|
||||
}
|
||||
|
||||
return { sanitized, removed }
|
||||
}
|
||||
|
||||
export function restoreEnforcementSections(
|
||||
config: Record<string, unknown>,
|
||||
removed: EnforcementRemovedSections,
|
||||
): Record<string, unknown> {
|
||||
const restored: Record<string, unknown> = { ...config }
|
||||
|
||||
for (const [key, value] of Object.entries(removed)) {
|
||||
if (key === 'plugin') {
|
||||
if (Array.isArray(value) && value.length > 0 && restored.plugin === undefined) {
|
||||
restored.plugin = value
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (key === 'mcp' && isRecord(value)) {
|
||||
const currentMcp = isRecord(restored.mcp) ? { ...(restored.mcp as Record<string, unknown>) } : {}
|
||||
for (const [name, entry] of Object.entries(value)) {
|
||||
if (currentMcp[name] === undefined) {
|
||||
currentMcp[name] = entry
|
||||
}
|
||||
}
|
||||
restored.mcp = currentMcp
|
||||
continue
|
||||
}
|
||||
if (key === 'provider' && isRecord(value)) {
|
||||
const currentProvider = isRecord(restored.provider) ? { ...(restored.provider as Record<string, unknown>) } : {}
|
||||
for (const [name, entry] of Object.entries(value)) {
|
||||
if (currentProvider[name] === undefined) {
|
||||
currentProvider[name] = entry
|
||||
}
|
||||
}
|
||||
restored.provider = currentProvider
|
||||
continue
|
||||
}
|
||||
if (key === 'experimentalHook') {
|
||||
const experimental = isRecord(restored.experimental)
|
||||
? { ...(restored.experimental as Record<string, unknown>) }
|
||||
: {}
|
||||
if (experimental.hook === undefined) {
|
||||
experimental.hook = value
|
||||
restored.experimental = experimental
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (restored[key] === undefined) {
|
||||
restored[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return restored
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { readFileSync, readdirSync } from 'fs'
|
||||
|
||||
export type ProcessStat = {
|
||||
pgrp: number
|
||||
startToken: string
|
||||
}
|
||||
|
||||
export type ProcessGroupMember = {
|
||||
pid: number
|
||||
startToken: string
|
||||
}
|
||||
|
||||
export type ProcessIdentityProvider = {
|
||||
attested: boolean
|
||||
readProcessStat(pid: number): ProcessStat | null
|
||||
readProcessGroupMembers(pgid: number): ProcessGroupMember[]
|
||||
}
|
||||
|
||||
function parseProcessStat(stat: string): ProcessStat | null {
|
||||
const commEnd = stat.lastIndexOf(')')
|
||||
if (commEnd === -1) return null
|
||||
const fields = stat.slice(commEnd + 2).split(' ')
|
||||
const pgrp = Number(fields[2])
|
||||
const startToken = fields[19]
|
||||
if (!Number.isInteger(pgrp) || pgrp <= 0) return null
|
||||
if (startToken === undefined || startToken === '') return null
|
||||
return { pgrp, startToken }
|
||||
}
|
||||
|
||||
const LINUX_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
|
||||
attested: true,
|
||||
readProcessStat(pid) {
|
||||
try {
|
||||
return parseProcessStat(readFileSync(`/proc/${pid}/stat`, 'utf-8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
readProcessGroupMembers(pgid) {
|
||||
const members: ProcessGroupMember[] = []
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = readdirSync('/proc')
|
||||
} catch {
|
||||
return members
|
||||
}
|
||||
if (!Array.isArray(entries)) return members
|
||||
for (const entry of entries) {
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const pid = Number(entry)
|
||||
const stat = this.readProcessStat(pid)
|
||||
if (stat !== null && stat.pgrp === pgid) {
|
||||
members.push({ pid, startToken: stat.startToken })
|
||||
}
|
||||
}
|
||||
return members
|
||||
},
|
||||
}
|
||||
|
||||
const DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
|
||||
attested: false,
|
||||
readProcessStat() {
|
||||
return null
|
||||
},
|
||||
readProcessGroupMembers() {
|
||||
return []
|
||||
},
|
||||
}
|
||||
|
||||
let cachedProvider: ProcessIdentityProvider | null = null
|
||||
let forcedProvider: ProcessIdentityProvider | null = null
|
||||
|
||||
export function resolveProcessIdentityProvider(): ProcessIdentityProvider {
|
||||
if (cachedProvider !== null) return cachedProvider
|
||||
cachedProvider = forcedProvider ??
|
||||
(process.platform === 'linux' ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER)
|
||||
return cachedProvider
|
||||
}
|
||||
|
||||
export function resetProcessIdentityProvider(): void {
|
||||
cachedProvider = null
|
||||
}
|
||||
|
||||
export function forceProcessAttestation(attested: boolean | null): void {
|
||||
forcedProvider = attested === null ? null : attested ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER
|
||||
cachedProvider = null
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
|
||||
|
||||
export type SandboxProxyDecision = { blocked: true; reason: string } | { blocked: false }
|
||||
|
||||
export const SANDBOX_BLOCKED_REASON_PREFIX = 'Sandbox enforcement is on; host-process shell execution is disabled: '
|
||||
|
||||
export const SANDBOX_CONFIG_MUTATION_REASON_PREFIX =
|
||||
'Sandbox enforcement is on; config mutations that could re-enable host-process execution are disabled: '
|
||||
|
||||
const ENCODED_PATH_HAZARD =
|
||||
/%(?:2f|5c|25|00|01|02|03|04|05|06|07|08|09|0a|0b|0c|0d|0e|0f|10|11|12|13|14|15|16|17|18|19|1a|1b|1c|1d|1e|1f|7f)/i
|
||||
|
||||
function stripSandboxProxyApiPrefix(pathname: string): string {
|
||||
if (pathname === '/api' || pathname.startsWith('/api/')) {
|
||||
return pathname.slice(4) || '/'
|
||||
}
|
||||
return pathname
|
||||
}
|
||||
|
||||
function canonicalizeSandboxProxyPath(pathname: string): string | null {
|
||||
if (!pathname.includes('%')) return stripSandboxProxyApiPrefix(pathname)
|
||||
if (ENCODED_PATH_HAZARD.test(pathname)) return null
|
||||
try {
|
||||
return stripSandboxProxyApiPrefix(decodeURIComponent(pathname))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const BLOCKED_ENFORCED_ROUTES: ReadonlyArray<{
|
||||
methods: readonly string[]
|
||||
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$/,
|
||||
reason: 'PTY creation runs commands in the OpenCode host process',
|
||||
},
|
||||
{
|
||||
methods: ['GET', 'POST'],
|
||||
pathPattern: /^\/pty\/[^/]+\/connect$/,
|
||||
reason: 'PTY connections drive processes in the OpenCode host process',
|
||||
},
|
||||
]
|
||||
|
||||
export function decideSandboxProxyBlock(enforced: boolean, method: string, pathname: string): SandboxProxyDecision {
|
||||
if (!enforced) {
|
||||
return { blocked: false }
|
||||
}
|
||||
const normalizedMethod = method.toUpperCase()
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return {
|
||||
blocked: true,
|
||||
reason: `${SANDBOX_BLOCKED_REASON_PREFIX}the request path could not be safely canonicalized`,
|
||||
}
|
||||
}
|
||||
for (const route of BLOCKED_ENFORCED_ROUTES) {
|
||||
if (route.methods.includes(normalizedMethod) && route.pathPattern.test(canonicalPath)) {
|
||||
return { blocked: true, reason: `${SANDBOX_BLOCKED_REASON_PREFIX}${route.reason}` }
|
||||
}
|
||||
}
|
||||
return { blocked: false }
|
||||
}
|
||||
|
||||
export function isSandboxConfigMutation(enforced: boolean, method: string, pathname: string): boolean {
|
||||
if (!enforced) {
|
||||
return false
|
||||
}
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return false
|
||||
}
|
||||
return method.toUpperCase() === 'PATCH' && canonicalPath === '/config'
|
||||
}
|
||||
|
||||
export function isSandboxMcpAdd(enforced: boolean, method: string, pathname: string): boolean {
|
||||
if (!enforced) {
|
||||
return false
|
||||
}
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return false
|
||||
}
|
||||
return method.toUpperCase() === 'POST' && canonicalPath === '/mcp'
|
||||
}
|
||||
|
||||
export function isSandboxAuthWrite(enforced: boolean, method: string, pathname: string): boolean {
|
||||
if (!enforced) {
|
||||
return false
|
||||
}
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return false
|
||||
}
|
||||
return method.toUpperCase() === 'PUT' && /^\/auth\/[^/]+$/.test(canonicalPath)
|
||||
}
|
||||
|
||||
export type SandboxConfigBodyDecision =
|
||||
| { kind: 'passthrough' }
|
||||
| { kind: 'sanitized'; body: string }
|
||||
| { kind: 'reject'; reason: string }
|
||||
|
||||
export function decideSandboxConfigBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (!isSandboxConfigMutation(enforced, method, pathname)) {
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawBody)
|
||||
} catch {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the config mutation body is not valid JSON`,
|
||||
}
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the config mutation body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
return { kind: 'sanitized', body: JSON.stringify(sanitizeConfigForEnforcement(parsed, true)) }
|
||||
}
|
||||
|
||||
export function decideSandboxMcpAddBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (!isSandboxMcpAdd(enforced, method, pathname)) {
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawBody)
|
||||
} catch {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body is not valid JSON`,
|
||||
}
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
const config = parsed.config
|
||||
if (
|
||||
!isRecord(config) ||
|
||||
config.type !== 'remote' ||
|
||||
typeof config.url !== 'string' ||
|
||||
config.command !== undefined ||
|
||||
config.environment !== undefined
|
||||
) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}only remote MCP servers can be added while enforcement is active`,
|
||||
}
|
||||
}
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
|
||||
export function decideSandboxAuthBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (!isSandboxAuthWrite(enforced, method, pathname)) {
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawBody)
|
||||
} catch {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the auth body is not valid JSON`,
|
||||
}
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the auth body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
if (parsed.type === 'wellknown') {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}well-known provider authentication loads remote host-executed code and cannot be added while enforcement is active`,
|
||||
}
|
||||
}
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
|
||||
export function decideSandboxMutationBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (isSandboxMcpAdd(enforced, method, pathname)) {
|
||||
return decideSandboxMcpAddBody(enforced, method, pathname, rawBody)
|
||||
}
|
||||
if (isSandboxAuthWrite(enforced, method, pathname)) {
|
||||
return decideSandboxAuthBody(enforced, method, pathname, rawBody)
|
||||
}
|
||||
return decideSandboxConfigBody(enforced, method, pathname, rawBody)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { accessSync, constants } from 'fs'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { buildSandboxVersionArgs, resolveSandboxExecutable, resetSandboxExecutableCache, resolveSandboxExecUserUid } from './command'
|
||||
|
||||
export type SandboxCapability = {
|
||||
available: boolean
|
||||
reason?: string
|
||||
msbVersion?: string
|
||||
}
|
||||
|
||||
let cachedCapability: SandboxCapability | null = null
|
||||
|
||||
export function detectSandboxCapability(): SandboxCapability {
|
||||
if (cachedCapability) {
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
try {
|
||||
accessSync('/dev/kvm', constants.R_OK | constants.W_OK)
|
||||
} catch {
|
||||
const reason = '/dev/kvm is not available or not writable; pass --device /dev/kvm and run on a KVM-capable Linux host'
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
const execUserUid = resolveSandboxExecUserUid()
|
||||
if (
|
||||
execUserUid !== null &&
|
||||
typeof process.getuid === 'function' &&
|
||||
typeof process.getgid === 'function' &&
|
||||
execUserUid !== process.getuid()
|
||||
) {
|
||||
const reason = `SANDBOX_EXEC_USER resolves to uid ${execUserUid}, which does not match the Manager workspace owner uid ${process.getuid()}; sandboxed commands could not write to the mounted project roots. Set SANDBOX_EXEC_USER=${process.getuid()}:${process.getgid()} or leave it unset`
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
const executable = resolveSandboxExecutable()
|
||||
if (executable === null) {
|
||||
const reason = 'msb CLI not found or not executable'
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
const result = spawnSync(executable, buildSandboxVersionArgs(), { encoding: 'utf8', timeout: 10000 })
|
||||
if (result.status !== 0 || result.error) {
|
||||
const reason = 'msb CLI not found or not executable'
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
cachedCapability = {
|
||||
available: true,
|
||||
msbVersion: result.stdout.trim(),
|
||||
}
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
export function resetSandboxCapabilityCache(): void {
|
||||
cachedCapability = null
|
||||
resetSandboxExecutableCache()
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
import path from 'path'
|
||||
import { accessSync, constants, realpathSync, statSync } from 'fs'
|
||||
import { realpath } from 'fs/promises'
|
||||
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
|
||||
|
||||
export const SANDBOX_UNAVAILABLE_PREFIX = 'Sandbox enforcement is on but the sandbox is unavailable: '
|
||||
|
||||
let cachedExecutablePath: string | null | undefined
|
||||
let executableTrustValidator: ((candidate: string) => boolean) | null = null
|
||||
|
||||
export function overrideSandboxExecutableTrustValidator(validator: ((candidate: string) => boolean) | null): void {
|
||||
executableTrustValidator = validator
|
||||
resetSandboxExecutableCache()
|
||||
}
|
||||
|
||||
function isPathWithinRoot(root: string, target: string): boolean {
|
||||
const relative = path.relative(path.resolve(root), path.resolve(target))
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function isWritableByManager(stat: { uid: number; gid: number; mode: number }): boolean {
|
||||
if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
|
||||
if (stat.uid === process.getuid() && (stat.mode & 0o200) !== 0) return true
|
||||
if (stat.gid === process.getgid() && (stat.mode & 0o020) !== 0) return true
|
||||
}
|
||||
return (stat.mode & 0o002) !== 0
|
||||
}
|
||||
|
||||
function pathPrefixes(target: string): string[] {
|
||||
const resolved = path.resolve(target)
|
||||
const parts = resolved.split(path.sep).filter((part) => part !== '')
|
||||
const prefixes: string[] = []
|
||||
let current = path.parse(resolved).root
|
||||
for (const part of parts) {
|
||||
current = path.join(current, part)
|
||||
prefixes.push(current)
|
||||
}
|
||||
return prefixes
|
||||
}
|
||||
|
||||
function isTrustedExecutablePath(candidate: string): boolean {
|
||||
if (executableTrustValidator !== null) {
|
||||
return executableTrustValidator(candidate)
|
||||
}
|
||||
let canonical: string
|
||||
try {
|
||||
canonical = realpathSync(candidate)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
const roots = sandboxMountRoots()
|
||||
for (const target of [candidate, canonical]) {
|
||||
if (roots.some((root) => isPathWithinRoot(root, target))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for (const target of new Set([candidate, canonical])) {
|
||||
for (const prefix of pathPrefixes(target)) {
|
||||
try {
|
||||
if (isWritableByManager(statSync(prefix))) {
|
||||
return false
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function computeSandboxExecutablePath(): string | null {
|
||||
const configured = ENV.SANDBOX.MSB_PATH.trim()
|
||||
const candidates: string[] = []
|
||||
if (path.isAbsolute(configured)) {
|
||||
candidates.push(configured)
|
||||
} else {
|
||||
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
|
||||
if (directory === '') continue
|
||||
candidates.push(path.join(directory, configured))
|
||||
}
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
accessSync(candidate, constants.X_OK)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (isTrustedExecutablePath(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function resolveSandboxExecutable(): string | null {
|
||||
if (cachedExecutablePath !== undefined) return cachedExecutablePath
|
||||
cachedExecutablePath = computeSandboxExecutablePath()
|
||||
return cachedExecutablePath
|
||||
}
|
||||
|
||||
export function sandboxExecutablePath(): string {
|
||||
return resolveSandboxExecutable() ?? ENV.SANDBOX.MSB_PATH
|
||||
}
|
||||
|
||||
export function resetSandboxExecutableCache(): void {
|
||||
cachedExecutablePath = undefined
|
||||
}
|
||||
|
||||
export function buildSandboxVersionArgs(): string[] {
|
||||
return ['--version']
|
||||
}
|
||||
|
||||
export function sandboxMountRoots(): string[] {
|
||||
return [getReposPath(), getScheduleWorktreesPath()]
|
||||
}
|
||||
|
||||
export function sandboxSecretMaskPath(): string {
|
||||
return getAssistantOpenCodeDir()
|
||||
}
|
||||
|
||||
export function quoteForShell(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`
|
||||
}
|
||||
|
||||
export function buildSandboxCreateArgs(): string[] {
|
||||
return [
|
||||
'run',
|
||||
'-d',
|
||||
'--name',
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
'--label',
|
||||
'ocm.managed=true',
|
||||
'--label',
|
||||
`ocm.net=${ENV.SANDBOX.NET}`,
|
||||
'-m',
|
||||
ENV.SANDBOX.MEMORY,
|
||||
'-c',
|
||||
String(ENV.SANDBOX.CPUS),
|
||||
'--net',
|
||||
ENV.SANDBOX.NET,
|
||||
'-u',
|
||||
resolveSandboxExecUser(),
|
||||
...sandboxMountRoots().flatMap((root) => ['--mount-dir', `${root}:${root}`]),
|
||||
'--tmpfs',
|
||||
sandboxSecretMaskPath(),
|
||||
'-w',
|
||||
getReposPath(),
|
||||
ENV.SANDBOX.IMAGE,
|
||||
'--',
|
||||
'sleep',
|
||||
'infinity',
|
||||
]
|
||||
}
|
||||
|
||||
export function buildSandboxInspectArgs(): string[] {
|
||||
return ['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json']
|
||||
}
|
||||
|
||||
export function buildSandboxRemoveArgs(): string[] {
|
||||
return ['rm', '--force', WORKSPACE_SANDBOX_NAME]
|
||||
}
|
||||
|
||||
export function buildSandboxListArgs(): string[] {
|
||||
return ['ls', '--format', 'json']
|
||||
}
|
||||
|
||||
export function buildSandboxStartArgs(): string[] {
|
||||
return ['start', WORKSPACE_SANDBOX_NAME]
|
||||
}
|
||||
|
||||
export function buildSandboxStopManagedArgs(): string[] {
|
||||
return ['stop', '--label', 'ocm.managed=true']
|
||||
}
|
||||
|
||||
export type SandboxNetworkPolicyRule = {
|
||||
direction: string
|
||||
destination: Record<string, unknown> | string
|
||||
protocols: unknown[]
|
||||
ports: unknown[]
|
||||
action: string
|
||||
}
|
||||
|
||||
export type SandboxNetworkPolicy = {
|
||||
default_egress: string
|
||||
default_ingress: string
|
||||
rules: SandboxNetworkPolicyRule[]
|
||||
}
|
||||
|
||||
const SUPPORTED_SANDBOX_NETWORK_PROFILES = ['public', 'private', 'host'] as const
|
||||
const TERMINAL_SANDBOX_NETWORK_PROFILES = new Set(['all', 'none'])
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function stableJson(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map((item) => stableJson(item)).join(',')}]`
|
||||
}
|
||||
if (isPlainRecord(value)) {
|
||||
return `{${Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`)
|
||||
.join(',')}}`
|
||||
}
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
export function resolveExpectedSandboxNetworkPolicy(netProfile: string): SandboxNetworkPolicy | null {
|
||||
const tokens = netProfile.split(',').map((token) => token.trim()).filter((token) => token !== '')
|
||||
if (tokens.length === 0) {
|
||||
return null
|
||||
}
|
||||
const groups: string[] = []
|
||||
for (const token of tokens) {
|
||||
if (TERMINAL_SANDBOX_NETWORK_PROFILES.has(token)) {
|
||||
return null
|
||||
}
|
||||
if (!(SUPPORTED_SANDBOX_NETWORK_PROFILES as readonly string[]).includes(token)) {
|
||||
return null
|
||||
}
|
||||
if (!groups.includes(token)) {
|
||||
groups.push(token)
|
||||
}
|
||||
}
|
||||
return {
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
...groups.map((group) => ({ direction: 'egress', destination: { group }, protocols: [], ports: [], action: 'allow' })),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function canonicalSandboxNetworkRuleKey(rule: unknown): string | null {
|
||||
if (!isPlainRecord(rule)) return null
|
||||
if (typeof rule.direction !== 'string' || typeof rule.action !== 'string') return null
|
||||
if (!Array.isArray(rule.protocols) || !Array.isArray(rule.ports)) return null
|
||||
const protocols = [...rule.protocols].map(String).sort().join(',')
|
||||
const ports = [...rule.ports].map(String).sort().join(',')
|
||||
return `${rule.direction}|${stableJson(rule.destination)}|${protocols}|${ports}|${rule.action}`
|
||||
}
|
||||
|
||||
export function sandboxNetworkPolicyMismatch(inspected: unknown, expected: SandboxNetworkPolicy): string | null {
|
||||
if (!isPlainRecord(inspected) || typeof inspected.default_egress !== 'string' || typeof inspected.default_ingress !== 'string') {
|
||||
return 'sandbox network policy is missing or malformed'
|
||||
}
|
||||
if (inspected.default_egress !== expected.default_egress) {
|
||||
return `sandbox network default_egress ${inspected.default_egress} does not match the deny policy required by the configured network profile; unrestricted egress is not allowed`
|
||||
}
|
||||
if (inspected.default_ingress !== expected.default_ingress) {
|
||||
return `sandbox network default_ingress ${inspected.default_ingress} does not match the configured network profile`
|
||||
}
|
||||
if (!Array.isArray(inspected.rules)) {
|
||||
return 'sandbox network policy is missing or malformed'
|
||||
}
|
||||
const inspectedKeys: string[] = []
|
||||
for (const rule of inspected.rules) {
|
||||
const key = canonicalSandboxNetworkRuleKey(rule)
|
||||
if (key === null) {
|
||||
return 'sandbox network policy contains a rule that does not match the configured network profile'
|
||||
}
|
||||
inspectedKeys.push(key)
|
||||
}
|
||||
const expectedKeys = expected.rules.map((rule) => {
|
||||
const key = canonicalSandboxNetworkRuleKey(rule)
|
||||
return key === null ? `unexpected:${stableJson(rule)}` : key
|
||||
})
|
||||
if (inspectedKeys.length !== expectedKeys.length) {
|
||||
return `sandbox network policy rules do not match the configured network profile (expected ${expectedKeys.length}, found ${inspectedKeys.length})`
|
||||
}
|
||||
const sortedInspected = [...inspectedKeys].sort()
|
||||
const sortedExpected = [...expectedKeys].sort()
|
||||
for (let index = 0; index < sortedExpected.length; index++) {
|
||||
if (sortedInspected[index] !== sortedExpected[index]) {
|
||||
return 'sandbox network policy contains a rule that does not match the configured network profile'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function parseMemoryMib(value: string): number | null {
|
||||
const match = /^(\d+(?:\.\d+)?)([gGmM])?$/.exec(value.trim())
|
||||
if (match === null) return null
|
||||
const number = Number(match[1])
|
||||
if (!Number.isFinite(number) || number < 0) return null
|
||||
const unit = match[2]
|
||||
if (unit === undefined || unit === 'M' || unit === 'm') return Math.floor(number)
|
||||
return Math.floor(number * 1024)
|
||||
}
|
||||
|
||||
function parseSandboxCreateArgs(args: string[]): {
|
||||
name: string
|
||||
labels: Record<string, string>
|
||||
memory: string
|
||||
cpus: number
|
||||
user: string
|
||||
mountDirs: string[]
|
||||
tmpfs: string | null
|
||||
workdir: string
|
||||
image: string
|
||||
cmd: string[]
|
||||
} {
|
||||
const labels: Record<string, string> = {}
|
||||
const mountDirs: string[] = []
|
||||
let name = ''
|
||||
let memory = ''
|
||||
let cpus = 0
|
||||
let user = ''
|
||||
let tmpfs: string | null = null
|
||||
let workdir = ''
|
||||
let image = ''
|
||||
let cmd: string[] = []
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const token = args[i]!
|
||||
if (token === '--') {
|
||||
cmd = args.slice(i + 1)
|
||||
break
|
||||
}
|
||||
const value = args[i + 1]
|
||||
switch (token) {
|
||||
case '--name': name = value ?? ''; i += 1; break
|
||||
case '--label': {
|
||||
if (value !== undefined) {
|
||||
const separator = value.indexOf('=')
|
||||
if (separator >= 0) labels[value.slice(0, separator)] = value.slice(separator + 1)
|
||||
}
|
||||
i += 1
|
||||
break
|
||||
}
|
||||
case '-m': memory = value ?? ''; i += 1; break
|
||||
case '-c': cpus = Number(value); i += 1; break
|
||||
case '--net': i += 1; break
|
||||
case '-u': user = value ?? ''; i += 1; break
|
||||
case '--mount-dir': if (value !== undefined) mountDirs.push(value); i += 1; break
|
||||
case '--tmpfs': tmpfs = value ?? null; i += 1; break
|
||||
case '-w': workdir = value ?? ''; i += 1; break
|
||||
case '-d': break
|
||||
default:
|
||||
if (image === '' && !token.startsWith('-')) image = token
|
||||
}
|
||||
}
|
||||
return { name, labels, memory, cpus, user, mountDirs, tmpfs, workdir, image, cmd }
|
||||
}
|
||||
|
||||
export function buildCanonicalSandboxSpec(): Record<string, unknown> {
|
||||
const args = parseSandboxCreateArgs(buildSandboxCreateArgs())
|
||||
const memoryMib = parseMemoryMib(args.memory)
|
||||
const bindMounts = args.mountDirs.map((spec) => {
|
||||
const separator = spec.indexOf(':')
|
||||
const host = separator >= 0 ? spec.slice(0, separator) : spec
|
||||
const guest = separator >= 0 ? spec.slice(separator + 1) : spec
|
||||
return {
|
||||
type: 'Bind',
|
||||
host,
|
||||
guest,
|
||||
options: { readonly: false, noexec: false, nosuid: false, nodev: false },
|
||||
stat_virtualization: 'strict',
|
||||
host_permissions: 'private',
|
||||
follow_root_symlinks: false,
|
||||
quota_mib: null,
|
||||
}
|
||||
})
|
||||
return {
|
||||
name: args.name,
|
||||
image: {
|
||||
Oci: {
|
||||
reference: args.image,
|
||||
},
|
||||
},
|
||||
resources: {
|
||||
cpus: args.cpus,
|
||||
memory_mib: memoryMib,
|
||||
max_cpus: args.cpus,
|
||||
max_memory_mib: memoryMib,
|
||||
},
|
||||
runtime: {
|
||||
workdir: args.workdir,
|
||||
shell: null,
|
||||
scripts: {},
|
||||
entrypoint: null,
|
||||
cmd: args.cmd,
|
||||
hostname: null,
|
||||
user: args.user,
|
||||
log_level: null,
|
||||
metrics_sample_interval_ms: null,
|
||||
disable_metrics_sample: false,
|
||||
},
|
||||
env: [],
|
||||
labels: args.labels,
|
||||
rlimits: [],
|
||||
mounts: [
|
||||
...bindMounts,
|
||||
...(args.tmpfs !== null
|
||||
? [{ type: 'Tmpfs', guest: args.tmpfs, size_mib: null, options: { readonly: false, noexec: false, nosuid: false, nodev: false } }]
|
||||
: []),
|
||||
],
|
||||
patches: [],
|
||||
network: { enabled: true, ports: [] },
|
||||
init: null,
|
||||
pull_policy: 'IfMissing',
|
||||
security_profile: 'default',
|
||||
lifecycle: { ephemeral: false, max_duration_secs: null, idle_timeout_secs: null },
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSandboxWorkDirectory(directory: string): Promise<string | null> {
|
||||
let resolvedDirectory: string
|
||||
try {
|
||||
resolvedDirectory = await realpath(directory)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
for (const root of sandboxMountRoots()) {
|
||||
let resolvedRoot: string
|
||||
try {
|
||||
resolvedRoot = await realpath(root)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const relative = path.relative(resolvedRoot, resolvedDirectory)
|
||||
if (relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))) {
|
||||
return path.join(root, relative)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function resolveSandboxExecUser(): string {
|
||||
const configured = ENV.SANDBOX.EXEC_USER.trim()
|
||||
if (/^\d+$/.test(configured)) {
|
||||
return typeof process.getgid === 'function' ? `${configured}:${process.getgid()}` : configured
|
||||
}
|
||||
if (/^\d+:\d+$/.test(configured)) {
|
||||
return configured
|
||||
}
|
||||
if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
|
||||
return `${process.getuid()}:${process.getgid()}`
|
||||
}
|
||||
return configured
|
||||
}
|
||||
|
||||
export function resolveSandboxExecUserUid(): number | null {
|
||||
const uid = resolveSandboxExecUser().split(':')[0]
|
||||
if (uid === undefined || !/^\d+$/.test(uid)) return null
|
||||
return Number(uid)
|
||||
}
|
||||
|
||||
export function buildSandboxExecCommandString(directory: string, command: string): string {
|
||||
const timeoutSeconds = Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)
|
||||
return `${quoteForShell(sandboxExecutablePath())} exec ${WORKSPACE_SANDBOX_NAME} --no-tty -q -u ${quoteForShell(resolveSandboxExecUser())} -w ${quoteForShell(directory)} --timeout ${timeoutSeconds}s -- sh -c ${quoteForShell(command)}`
|
||||
}
|
||||
|
||||
export function buildBlockedCommand(reason: string): string {
|
||||
const message = `${SANDBOX_UNAVAILABLE_PREFIX}${reason}`
|
||||
return `printf '%s\n' ${quoteForShell(message)} >&2; exit 1`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { SandboxRuntimeService } from './runtime'
|
||||
import { opencodeServerManager } from '../opencode-single-server'
|
||||
|
||||
export function isSandboxEnforcementActive(db: Database): boolean {
|
||||
let preferenceEnabled = false
|
||||
try {
|
||||
preferenceEnabled = new SandboxRuntimeService(db).isEnabled()
|
||||
} catch (error) {
|
||||
logger.warn('Failed to read the sandbox preference; treating sandbox enforcement as active:', error)
|
||||
return true
|
||||
}
|
||||
return preferenceEnabled || opencodeServerManager.isSandboxEnforced()
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import path from 'path'
|
||||
import { lstat, realpath } from 'fs/promises'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { executeCommand } from '../../utils/process'
|
||||
import { mkdirSafe } from '../../utils/fs-safe'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { SettingsService } from '../settings'
|
||||
import { detectSandboxCapability } from './capability'
|
||||
import {
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
buildCanonicalSandboxSpec,
|
||||
buildSandboxCreateArgs,
|
||||
buildSandboxExecCommandString,
|
||||
buildSandboxInspectArgs,
|
||||
buildSandboxListArgs,
|
||||
buildSandboxRemoveArgs,
|
||||
buildSandboxStartArgs,
|
||||
buildSandboxStopManagedArgs,
|
||||
resolveExpectedSandboxNetworkPolicy,
|
||||
resolveSandboxWorkDirectory,
|
||||
sandboxExecutablePath,
|
||||
sandboxMountRoots,
|
||||
sandboxNetworkPolicyMismatch,
|
||||
} from './command'
|
||||
|
||||
const SANDBOX_LS_CACHE_MS = 5000
|
||||
const SANDBOX_LS_TIMEOUT_MS = 15000
|
||||
const SANDBOX_STOP_TIMEOUT_MS = 30000
|
||||
|
||||
export type SandboxPlan =
|
||||
| { mode: 'host' }
|
||||
| { mode: 'sandbox'; command: string }
|
||||
| { mode: 'blocked'; reason: string }
|
||||
|
||||
export type SandboxStatus = {
|
||||
available: boolean
|
||||
enabled: boolean
|
||||
reason?: string
|
||||
msbVersion?: string
|
||||
}
|
||||
|
||||
let inFlightBoot: Promise<void> | null = null
|
||||
let lastKnownRunningAt: number | null = null
|
||||
let shutdownRequested = false
|
||||
|
||||
export function resetSandboxRuntimeState(): void {
|
||||
inFlightBoot = null
|
||||
lastKnownRunningAt = null
|
||||
shutdownRequested = false
|
||||
}
|
||||
|
||||
async function validateSandboxMountRoots(): Promise<void> {
|
||||
for (const root of sandboxMountRoots()) {
|
||||
const resolvedRoot = path.resolve(root)
|
||||
let stat
|
||||
try {
|
||||
stat = await lstat(root)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode !== 'ENOENT') {
|
||||
throw new Error(`cannot inspect sandbox mount root ${root}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
await mkdirSafe(root)
|
||||
stat = await lstat(root)
|
||||
}
|
||||
if (stat.isSymbolicLink()) {
|
||||
throw new Error(`sandbox mount root ${root} is a symbolic link; refusing to mount a redirected project root`)
|
||||
}
|
||||
const canonical = await realpath(root)
|
||||
if (canonical !== resolvedRoot) {
|
||||
throw new Error(`sandbox mount root ${root} resolves to ${canonical} instead of ${resolvedRoot}; refusing to mount a redirected project root`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ensureWorkspaceSandbox(): Promise<void> {
|
||||
if (inFlightBoot) {
|
||||
return inFlightBoot
|
||||
}
|
||||
inFlightBoot = (async () => {
|
||||
await validateSandboxMountRoots()
|
||||
if (shutdownRequested) {
|
||||
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 bootWorkspaceSandbox()
|
||||
})().finally(() => {
|
||||
inFlightBoot = null
|
||||
})
|
||||
return inFlightBoot
|
||||
}
|
||||
|
||||
async function bootWorkspaceSandbox(): Promise<void> {
|
||||
try {
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lastKnownRunningAt = Date.now()
|
||||
} catch (error) {
|
||||
lastKnownRunningAt = null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxAttestation = { trusted: true } | { trusted: false; reason: string }
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function resolveInspectSpec(config: unknown): Record<string, unknown> | null {
|
||||
if (!isRecord(config)) return null
|
||||
const wrapped = config.spec
|
||||
if (isRecord(wrapped) && (isRecord(wrapped.image) || Array.isArray(wrapped.mounts) || isRecord(wrapped.labels) || isRecord(wrapped.network))) {
|
||||
return wrapped
|
||||
}
|
||||
if (isRecord(config.image) || Array.isArray(config.mounts) || isRecord(config.labels) || isRecord(config.network)) {
|
||||
return config
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function inspectImageReference(image: unknown): string | null {
|
||||
if (!isRecord(image)) return null
|
||||
const oci = image.Oci
|
||||
if (!isRecord(oci) || typeof oci.reference !== 'string') return null
|
||||
return oci.reference
|
||||
}
|
||||
|
||||
function sameStringArray(left: unknown, right: unknown): boolean {
|
||||
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
|
||||
return left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
function emptyArrayMismatch(value: unknown, path: string): string | null {
|
||||
if (!Array.isArray(value) || value.length > 0) {
|
||||
return `sandbox configuration ${path} must be empty`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type ParsedSandboxMount =
|
||||
| { kind: 'bind'; host: string; guest: string; readonly: boolean }
|
||||
| { kind: 'tmpfs'; guest: string; readonly: boolean }
|
||||
| { kind: 'other' }
|
||||
|
||||
function parseInspectMount(mount: unknown): ParsedSandboxMount | null {
|
||||
if (!isRecord(mount) || typeof mount.type !== 'string') return null
|
||||
const readonly = (isRecord(mount.options) && mount.options.readonly === true) || mount.readonly === true
|
||||
if (mount.type === 'Bind') {
|
||||
if (typeof mount.host !== 'string' || typeof mount.guest !== 'string') return null
|
||||
return { kind: 'bind', host: mount.host, guest: mount.guest, readonly }
|
||||
}
|
||||
if (mount.type === 'Tmpfs') {
|
||||
if (typeof mount.guest !== 'string') return null
|
||||
return { kind: 'tmpfs', guest: mount.guest, readonly }
|
||||
}
|
||||
return { kind: 'other' }
|
||||
}
|
||||
|
||||
async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAttestation> {
|
||||
const spec = resolveInspectSpec(config)
|
||||
if (spec === null) {
|
||||
return { trusted: false, reason: 'msb inspect returned an unexpected config shape' }
|
||||
}
|
||||
|
||||
const canonical = buildCanonicalSandboxSpec()
|
||||
|
||||
const labels = isRecord(spec.labels) ? spec.labels : {}
|
||||
const canonicalLabels = isRecord(canonical.labels) ? canonical.labels : {}
|
||||
if (labels['ocm.managed'] !== 'true') {
|
||||
return { trusted: false, reason: 'sandbox is not labelled ocm.managed=true' }
|
||||
}
|
||||
if (labels['ocm.net'] !== canonicalLabels['ocm.net']) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox network profile ${String(labels['ocm.net'])} does not match ${canonicalLabels['ocm.net']}`,
|
||||
}
|
||||
}
|
||||
|
||||
const imageReference = inspectImageReference(spec.image)
|
||||
const canonicalImageReference = inspectImageReference(canonical.image)
|
||||
if (imageReference === null) {
|
||||
return { trusted: false, reason: 'sandbox image is not an OCI reference' }
|
||||
}
|
||||
if (canonicalImageReference !== null && imageReference !== canonicalImageReference) {
|
||||
return { trusted: false, reason: `sandbox image ${imageReference} does not match ${canonicalImageReference}` }
|
||||
}
|
||||
const image = isRecord(spec.image) ? spec.image : {}
|
||||
const oci = isRecord(image.Oci) ? image.Oci : null
|
||||
const rootDisk = oci !== null && isRecord(oci.root_disk) ? oci.root_disk : null
|
||||
if (rootDisk !== null && rootDisk.kind === 'disk-image') {
|
||||
return { trusted: false, reason: 'sandbox image must not attach a host disk image' }
|
||||
}
|
||||
|
||||
const canonicalMounts = Array.isArray(canonical.mounts) ? canonical.mounts : []
|
||||
const expectedRoots = new Set<string>()
|
||||
const expectedRealRoots = new Set<string>()
|
||||
let maskGuest: string | null = null
|
||||
for (const rawMount of canonicalMounts) {
|
||||
const mount = parseInspectMount(rawMount)
|
||||
if (mount?.kind === 'bind') {
|
||||
const resolvedRoot = path.resolve(mount.host)
|
||||
expectedRoots.add(resolvedRoot)
|
||||
try {
|
||||
expectedRealRoots.add(await realpath(resolvedRoot))
|
||||
} catch {
|
||||
return { trusted: false, reason: `cannot resolve the canonical bind mount root ${resolvedRoot}` }
|
||||
}
|
||||
} else if (mount?.kind === 'tmpfs') {
|
||||
maskGuest = path.resolve(mount.guest)
|
||||
}
|
||||
}
|
||||
|
||||
const mounts = Array.isArray(spec.mounts) ? spec.mounts : []
|
||||
const bindRoots = new Set<string>()
|
||||
let maskSeen = false
|
||||
for (let mountIndex = 0; mountIndex < mounts.length; mountIndex++) {
|
||||
const rawMount = mounts[mountIndex]
|
||||
const mount = parseInspectMount(rawMount)
|
||||
if (mount === null) {
|
||||
return { trusted: false, reason: 'sandbox has an unrecognized mount entry' }
|
||||
}
|
||||
if (mount.kind === 'bind') {
|
||||
const hostPath = path.resolve(mount.host)
|
||||
if (mount.readonly) {
|
||||
return { trusted: false, reason: 'sandbox has a read-only project bind mount' }
|
||||
}
|
||||
const mountOptions = isRecord(rawMount) && isRecord(rawMount.options) ? rawMount.options : {}
|
||||
for (const flag of ['noexec', 'nosuid', 'nodev'] as const) {
|
||||
if (mountOptions[flag] === true) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].options.${flag} does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rawMount.stat_virtualization !== 'strict') {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].stat_virtualization does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (rawMount.host_permissions !== 'private') {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].host_permissions does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (rawMount.follow_root_symlinks !== false) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].follow_root_symlinks does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (rawMount.quota_mib !== null) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].quota_mib does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (hostPath !== path.resolve(mount.guest) || !expectedRoots.has(hostPath)) {
|
||||
return { trusted: false, reason: 'sandbox has an unexpected bind mount' }
|
||||
}
|
||||
let realHost: string
|
||||
try {
|
||||
realHost = await realpath(mount.host)
|
||||
} catch {
|
||||
return { trusted: false, reason: `sandbox bind mount host ${mount.host} does not exist on the host` }
|
||||
}
|
||||
if (!expectedRealRoots.has(realHost)) {
|
||||
return { trusted: false, reason: 'sandbox bind mount resolves outside the expected project roots' }
|
||||
}
|
||||
bindRoots.add(hostPath)
|
||||
} else if (mount.kind === 'tmpfs') {
|
||||
if (maskGuest === null || path.resolve(mount.guest) !== maskGuest) {
|
||||
return { trusted: false, reason: `sandbox has an unexpected tmpfs mount at ${mount.guest}` }
|
||||
}
|
||||
if (maskSeen) {
|
||||
return { trusted: false, reason: 'sandbox has a duplicate assistant mask mount' }
|
||||
}
|
||||
maskSeen = true
|
||||
const tmpfsMountOptions = isRecord(rawMount) && isRecord(rawMount.options) ? rawMount.options : {}
|
||||
for (const flag of ['readonly', 'noexec', 'nosuid', 'nodev'] as const) {
|
||||
if (tmpfsMountOptions[flag] === true) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].options.${flag} does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rawMount.size_mib !== null) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].size_mib does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return { trusted: false, reason: 'sandbox has an unexpected mount type' }
|
||||
}
|
||||
}
|
||||
if (bindRoots.size !== expectedRoots.size || [...expectedRoots].some((root) => !bindRoots.has(root))) {
|
||||
return { trusted: false, reason: 'sandbox is missing one of the project bind mounts' }
|
||||
}
|
||||
if (!maskSeen) {
|
||||
return { trusted: false, reason: `sandbox is missing the assistant .opencode mask at ${maskGuest}` }
|
||||
}
|
||||
|
||||
const resources = isRecord(spec.resources) ? spec.resources : {}
|
||||
const canonicalResources = isRecord(canonical.resources) ? canonical.resources : {}
|
||||
if (resources.cpus !== canonicalResources.cpus) {
|
||||
return { trusted: false, reason: `sandbox cpus ${String(resources.cpus)} does not match ${String(canonicalResources.cpus)}` }
|
||||
}
|
||||
if (resources.memory_mib !== canonicalResources.memory_mib) {
|
||||
return { trusted: false, reason: `sandbox memory does not match ${String(canonicalResources.memory_mib)}` }
|
||||
}
|
||||
if (resources.max_cpus !== canonicalResources.max_cpus) {
|
||||
return { trusted: false, reason: `sandbox max cpus ${String(resources.max_cpus)} does not match ${String(canonicalResources.max_cpus)}` }
|
||||
}
|
||||
if (resources.max_memory_mib !== canonicalResources.max_memory_mib) {
|
||||
return { trusted: false, reason: `sandbox max memory does not match ${String(canonicalResources.max_memory_mib)}` }
|
||||
}
|
||||
|
||||
const runtime = isRecord(spec.runtime) ? spec.runtime : {}
|
||||
const canonicalRuntime = isRecord(canonical.runtime) ? canonical.runtime : {}
|
||||
if (runtime.workdir !== canonicalRuntime.workdir) {
|
||||
return { trusted: false, reason: `sandbox workdir ${String(runtime.workdir)} does not match ${String(canonicalRuntime.workdir)}` }
|
||||
}
|
||||
if (runtime.user !== canonicalRuntime.user) {
|
||||
return { trusted: false, reason: `sandbox user ${String(runtime.user)} does not match ${String(canonicalRuntime.user)}` }
|
||||
}
|
||||
if (!sameStringArray(runtime.cmd, canonicalRuntime.cmd)) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.cmd does not match the canonical specification' }
|
||||
}
|
||||
if (runtime.entrypoint !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.entrypoint must be empty' }
|
||||
}
|
||||
if (runtime.shell !== canonicalRuntime.shell) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.shell does not match the canonical specification' }
|
||||
}
|
||||
if (!isRecord(runtime.scripts) || Object.keys(runtime.scripts).length > 0) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.scripts must be empty' }
|
||||
}
|
||||
if (runtime.hostname !== canonicalRuntime.hostname) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.hostname does not match the canonical specification' }
|
||||
}
|
||||
if (runtime.metrics_sample_interval_ms !== canonicalRuntime.metrics_sample_interval_ms) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.metrics_sample_interval_ms does not match the canonical specification' }
|
||||
}
|
||||
if (runtime.disable_metrics_sample !== canonicalRuntime.disable_metrics_sample) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.disable_metrics_sample does not match the canonical specification' }
|
||||
}
|
||||
|
||||
const network = isRecord(spec.network) ? spec.network : {}
|
||||
if (network.enabled !== true) {
|
||||
return { trusted: false, reason: 'sandbox networking is disabled' }
|
||||
}
|
||||
if (!Array.isArray(network.ports) || network.ports.length > 0) {
|
||||
return { trusted: false, reason: 'sandbox configuration network.ports must be empty' }
|
||||
}
|
||||
const expectedPolicy = resolveExpectedSandboxNetworkPolicy(ENV.SANDBOX.NET)
|
||||
if (expectedPolicy === null) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox network profile ${ENV.SANDBOX.NET} cannot be attested; supported profiles are public, private, host`,
|
||||
}
|
||||
}
|
||||
const policyMismatch = sandboxNetworkPolicyMismatch(network.policy, expectedPolicy)
|
||||
if (policyMismatch !== null) {
|
||||
return { trusted: false, reason: policyMismatch }
|
||||
}
|
||||
|
||||
const secretsConfig = network.secrets
|
||||
if (secretsConfig !== undefined && secretsConfig !== null) {
|
||||
if (!isRecord(secretsConfig) || !Array.isArray(secretsConfig.secrets)) {
|
||||
return { trusted: false, reason: 'sandbox configuration network.secrets is malformed' }
|
||||
}
|
||||
if (secretsConfig.secrets.length > 0) {
|
||||
return { trusted: false, reason: 'sandbox configuration network.secrets must be empty' }
|
||||
}
|
||||
}
|
||||
|
||||
const emptyMismatch = emptyArrayMismatch(spec.patches, 'patches')
|
||||
if (emptyMismatch !== null) return { trusted: false, reason: emptyMismatch }
|
||||
const rlimitsMismatch = emptyArrayMismatch(spec.rlimits, 'rlimits')
|
||||
if (rlimitsMismatch !== null) return { trusted: false, reason: rlimitsMismatch }
|
||||
|
||||
if (spec.init !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration init must be empty' }
|
||||
}
|
||||
if (spec.pull_policy !== 'IfMissing') {
|
||||
return { trusted: false, reason: `sandbox pull policy ${String(spec.pull_policy)} must be IfMissing` }
|
||||
}
|
||||
if (spec.security_profile !== 'default') {
|
||||
return { trusted: false, reason: 'sandbox configuration security_profile must be default' }
|
||||
}
|
||||
const lifecycle = isRecord(spec.lifecycle) ? spec.lifecycle : {}
|
||||
if (lifecycle.ephemeral !== false) {
|
||||
return { trusted: false, reason: 'sandbox configuration lifecycle.ephemeral must be false' }
|
||||
}
|
||||
if (lifecycle.max_duration_secs !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration lifecycle.max_duration_secs must be empty' }
|
||||
}
|
||||
if (lifecycle.idle_timeout_secs !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration lifecycle.idle_timeout_secs must be empty' }
|
||||
}
|
||||
if (spec.manifest_digest !== undefined && spec.manifest_digest !== null) {
|
||||
if (typeof spec.manifest_digest !== 'string' || spec.manifest_digest === '') {
|
||||
return { trusted: false, reason: 'sandbox manifest digest is malformed' }
|
||||
}
|
||||
}
|
||||
|
||||
return { trusted: true }
|
||||
}
|
||||
|
||||
async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestation> {
|
||||
let result: string | { exitCode: number; stdout: string; stderr: string }
|
||||
try {
|
||||
result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxInspectArgs()], {
|
||||
ignoreExitCode: true,
|
||||
silent: true,
|
||||
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)}` }
|
||||
}
|
||||
const listing = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
if (listing.exitCode !== 0) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `msb inspect failed with code ${listing.exitCode}: ${listing.stderr || listing.stdout}`,
|
||||
}
|
||||
}
|
||||
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(listing.stdout)
|
||||
} catch {
|
||||
return { trusted: false, reason: 'msb inspect returned malformed JSON' }
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return { trusted: false, reason: 'msb inspect returned an unexpected JSON shape' }
|
||||
}
|
||||
if (running) {
|
||||
if (parsed.active_config === undefined || parsed.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(parsed.config)
|
||||
}
|
||||
|
||||
async function createWorkspaceSandbox(): Promise<void> {
|
||||
await executeCommand([sandboxExecutablePath(), ...buildSandboxCreateArgs()], {
|
||||
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
|
||||
})
|
||||
const attestation = await attestWorkspaceSandbox(true)
|
||||
if (!attestation.trusted) {
|
||||
throw new Error(`newly created sandbox ${WORKSPACE_SANDBOX_NAME} failed attestation: ${attestation.reason}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeWorkspaceSandbox(): Promise<void> {
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxRemoveArgs()], {
|
||||
ignoreExitCode: true,
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const removal = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
if (removal.exitCode !== 0) {
|
||||
throw new Error(`msb rm failed with code ${removal.exitCode}: ${removal.stderr || removal.stdout}`)
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxLsEntry = {
|
||||
name?: unknown
|
||||
status?: unknown
|
||||
state?: unknown
|
||||
}
|
||||
|
||||
async function listSandboxes(): Promise<SandboxLsEntry[]> {
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxListArgs()], {
|
||||
ignoreExitCode: true,
|
||||
silent: true,
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const listing = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
if (listing.exitCode !== 0) {
|
||||
throw new Error(`msb ls failed with code ${listing.exitCode}: ${listing.stderr || listing.stdout}`)
|
||||
}
|
||||
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(listing.stdout)
|
||||
} catch {
|
||||
throw new Error(`msb ls returned malformed JSON (${listing.stdout.slice(0, 200)})`)
|
||||
}
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw new Error('msb ls returned an unexpected JSON shape (expected a top-level array)')
|
||||
}
|
||||
return parsed as SandboxLsEntry[]
|
||||
}
|
||||
|
||||
function findWorkspaceSandboxEntry(entries: SandboxLsEntry[]): { running: boolean } | null {
|
||||
for (const value of entries) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
|
||||
const entry = value as SandboxLsEntry
|
||||
if (entry.name !== WORKSPACE_SANDBOX_NAME) continue
|
||||
const status = entry.status ?? entry.state
|
||||
return { running: String(status).toLowerCase() === 'running' }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function startWorkspaceSandbox(): Promise<void> {
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStartArgs()], {
|
||||
ignoreExitCode: true,
|
||||
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
if (typeof result === 'string' || result.exitCode === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
if (entry?.running) {
|
||||
return
|
||||
}
|
||||
throw new Error(`msb start failed with code ${result.exitCode}: ${result.stderr || result.stdout}`)
|
||||
}
|
||||
|
||||
export class SandboxRuntimeService {
|
||||
constructor(private readonly db: Database) {}
|
||||
|
||||
isEnabled(): boolean {
|
||||
return this.isSandboxEnabled()
|
||||
}
|
||||
|
||||
getStatus(): SandboxStatus {
|
||||
const capability = detectSandboxCapability()
|
||||
return {
|
||||
available: capability.available,
|
||||
enabled: this.isEnabled(),
|
||||
...(capability.reason !== undefined ? { reason: capability.reason } : {}),
|
||||
...(capability.msbVersion !== undefined ? { msbVersion: capability.msbVersion } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
async planCommand(directory: string, command: string, enforced = false): Promise<SandboxPlan> {
|
||||
if (!enforced && !this.isEnabled()) {
|
||||
return { mode: 'host' }
|
||||
}
|
||||
const capability = detectSandboxCapability()
|
||||
if (!capability.available) {
|
||||
return { mode: 'blocked', reason: capability.reason ?? 'Sandbox capability is unavailable' }
|
||||
}
|
||||
const workDirectory = await resolveSandboxWorkDirectory(directory)
|
||||
if (workDirectory === null) {
|
||||
return {
|
||||
mode: 'blocked',
|
||||
reason: `working directory is outside the sandboxed project roots (${sandboxMountRoots().join(', ')})`,
|
||||
}
|
||||
}
|
||||
try {
|
||||
await ensureWorkspaceSandbox()
|
||||
return { mode: 'sandbox', command: buildSandboxExecCommandString(workDirectory, command) }
|
||||
} catch (error) {
|
||||
logger.error('Failed to prepare the workspace sandbox', error)
|
||||
return { mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
async stopWorkspaceSandbox(): Promise<void> {
|
||||
shutdownRequested = true
|
||||
await this.stopManagedSandbox()
|
||||
}
|
||||
|
||||
async stopWorkspaceSandboxForToggle(): Promise<void> {
|
||||
await this.stopManagedSandbox()
|
||||
}
|
||||
|
||||
private async stopManagedSandbox(): Promise<void> {
|
||||
while (inFlightBoot) {
|
||||
try {
|
||||
await inFlightBoot
|
||||
} catch {
|
||||
// a settled boot is done; keep waiting for any other admitted boot
|
||||
}
|
||||
}
|
||||
lastKnownRunningAt = null
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStopManagedArgs()], {
|
||||
ignoreExitCode: true,
|
||||
timeout: SANDBOX_STOP_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const stopResult = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
if (stopResult.exitCode !== 0) {
|
||||
try {
|
||||
await confirmManagedSandboxStopped()
|
||||
logger.warn(`msb stop failed with code ${stopResult.exitCode} but the workspace sandbox is confirmed stopped: ${stopResult.stderr || stopResult.stdout}`)
|
||||
} catch (error) {
|
||||
logger.error('Failed to confirm the workspace sandbox stopped:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private isSandboxEnabled(): boolean {
|
||||
return new SettingsService(this.db).getSettings('default').preferences.sandbox?.enabled === true
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmManagedSandboxStopped(): Promise<void> {
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
if (entry !== null && entry.running) {
|
||||
throw new Error('msb stop failed to stop the workspace sandbox; the managed microVM is still running')
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopWorkspaceSandboxOnShutdown(db: Database): Promise<void> {
|
||||
await new SandboxRuntimeService(db).stopWorkspaceSandbox()
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import { executeCommand } from '../utils/process'
|
||||
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSyncSafe } from '../utils/fs-safe'
|
||||
import { resolveSandboxWorkDirectory } from './sandbox/command'
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
|
||||
export interface ScheduleWorktreeContext {
|
||||
directory: string
|
||||
@@ -89,16 +91,18 @@ export class ScheduleWorktreeManager {
|
||||
{ directory: repo.fullPath },
|
||||
)
|
||||
|
||||
// Re-point the workspace to our run branch and base
|
||||
await executeCommand(['git', '-C', createdWorkspace.directory, 'checkout', '-B', runBranch, baseRef], { env })
|
||||
const workspaceDirectory = await this.resolveWorkspaceDirectory(createdWorkspace.directory)
|
||||
|
||||
if (!existsSync(createdWorkspace.directory)) {
|
||||
throw new Error(`OpenCode workspace directory was not created at: ${createdWorkspace.directory}`)
|
||||
// Re-point the workspace to our run branch and base
|
||||
await executeCommand(['git', '-C', workspaceDirectory, 'checkout', '-B', runBranch, baseRef], { env })
|
||||
|
||||
if (!existsSync(workspaceDirectory)) {
|
||||
throw new Error(`OpenCode workspace directory was not created at: ${workspaceDirectory}`)
|
||||
}
|
||||
|
||||
return {
|
||||
directory: createdWorkspace.directory,
|
||||
worktreePath: createdWorkspace.directory,
|
||||
directory: workspaceDirectory,
|
||||
worktreePath: workspaceDirectory,
|
||||
runBranch,
|
||||
workspaceId: createdWorkspace.id,
|
||||
}
|
||||
@@ -289,6 +293,17 @@ export class ScheduleWorktreeManager {
|
||||
return null
|
||||
}
|
||||
|
||||
private async resolveWorkspaceDirectory(directory: string): Promise<string> {
|
||||
if (!opencodeServerManager.isSandboxEnforced()) {
|
||||
return directory
|
||||
}
|
||||
const workDirectory = await resolveSandboxWorkDirectory(directory)
|
||||
if (workDirectory === null) {
|
||||
throw new Error(`OpenCode workspace directory is outside the sandboxed project roots: ${directory}`)
|
||||
}
|
||||
return workDirectory
|
||||
}
|
||||
|
||||
private async buildGitEnv(repo: Repo, sshSetup: boolean, silent: boolean): Promise<Record<string, string>> {
|
||||
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
|
||||
const sshEnv = sshSetup ? this.gitAuthService.getSSHEnvironment() : {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import path from 'path'
|
||||
import { promises as fs, mkdirSync, accessSync, constants } from 'node:fs'
|
||||
|
||||
interface MkdirSafeOptions {
|
||||
@@ -9,6 +10,19 @@ function isPermissionError(error: unknown): boolean {
|
||||
return code === 'EACCES' || code === 'EPERM'
|
||||
}
|
||||
|
||||
export async function writeFileAtomic(filePath: string, content: string, options: { mode?: number } = {}): Promise<void> {
|
||||
const dir = path.dirname(filePath)
|
||||
await mkdirSafe(dir)
|
||||
const tempPath = path.join(dir, `.${path.basename(filePath)}.ocm-tmp-${process.pid}-${Date.now()}`)
|
||||
try {
|
||||
await fs.writeFile(tempPath, content, { encoding: 'utf-8', mode: options.mode ?? 0o600 })
|
||||
await fs.rename(tempPath, filePath)
|
||||
} catch (error) {
|
||||
await fs.rm(tempPath, { force: true }).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function mkdirSafe(dirPath: string, options: MkdirSafeOptions = {}): Promise<void> {
|
||||
try {
|
||||
await fs.mkdir(dirPath, { ...options, recursive: true })
|
||||
|
||||
@@ -77,18 +77,26 @@ export async function executeCommand(
|
||||
}
|
||||
})
|
||||
|
||||
proc.on('close', (code: number | null) => {
|
||||
proc.on('close', (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (isResolved) return
|
||||
|
||||
isResolved = true
|
||||
if (timeoutId) clearTimeout(timeoutId)
|
||||
|
||||
|
||||
const terminatedBySignal = code === null && signal !== null
|
||||
const exitCode = code === null ? 1 : code
|
||||
const failureDetail = terminatedBySignal ? `signal ${signal}` : `code ${code}`
|
||||
|
||||
if (options.ignoreExitCode) {
|
||||
resolve({ exitCode: code || 0, stdout, stderr })
|
||||
resolve({
|
||||
exitCode,
|
||||
stdout,
|
||||
stderr: terminatedBySignal ? `${stderr}Command terminated by signal ${signal}` : stderr,
|
||||
})
|
||||
} else if (code === 0) {
|
||||
resolve(stdout)
|
||||
} else {
|
||||
const error = new Error(`Command failed with code ${code}: ${stderr || stdout}`)
|
||||
const error = new Error(`Command failed with ${failureDetail}: ${stderr || stdout}`)
|
||||
if (!options.silent) {
|
||||
logger.error(`Command failed: ${args.join(' ')}`, error)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
isRestartPending: vi.fn(() => false),
|
||||
isSandboxEnforced: vi.fn(() => false),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -22,22 +23,36 @@ vi.mock('bun:sqlite', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/sandbox/capability', () => ({
|
||||
detectSandboxCapability: vi.fn(),
|
||||
}))
|
||||
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { createHealthRoutes } from '../../src/routes/health'
|
||||
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
|
||||
import type { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
const mockDetectSandboxCapability = detectSandboxCapability as ReturnType<typeof vi.fn>
|
||||
const mockIsSandboxEnforced = opencodeServerManager.isSandboxEnforced as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('Health Routes', () => {
|
||||
let healthApp: ReturnType<typeof createHealthRoutes>
|
||||
let mockDb: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available or not writable' })
|
||||
mockIsSandboxEnforced.mockReturnValue(false)
|
||||
|
||||
const mockPrepareGet = vi.fn()
|
||||
const mockQueryGet = vi.fn()
|
||||
mockDb = {
|
||||
prepare: vi.fn(() => ({
|
||||
get: mockPrepareGet,
|
||||
})),
|
||||
query: vi.fn(() => ({
|
||||
get: mockQueryGet,
|
||||
})),
|
||||
} as any
|
||||
|
||||
healthApp = createHealthRoutes(mockDb)
|
||||
@@ -101,6 +116,156 @@ describe('Health Routes', () => {
|
||||
expect(json.database).toBe('disconnected')
|
||||
})
|
||||
|
||||
it('should include sandbox availability and enforcement in the payload', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.3.1' })
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
mockDb.query().get.mockReturnValue({
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({ available: true, enabled: true, enforced: true, msbVersion: 'msb 0.3.1' })
|
||||
})
|
||||
|
||||
it('should keep the overall status unchanged when the sandbox runtime is unavailable', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: false,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports enabled-but-not-enforced when the preference is enabled but the child has not restarted', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockDb.query().get.mockReturnValue({
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: true,
|
||||
enforced: false,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an enforced running child even when the sandbox runtime is unavailable', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
mockDb.query().get.mockReturnValue({
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: true,
|
||||
enforced: true,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an enforced running child while a disable-pending restart still runs it', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: true,
|
||||
reason: '/dev/kvm is not available or not writable',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 200 with a safe sandbox status when the sandbox status lookup throws', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockDb.query.mockImplementationOnce(() => {
|
||||
throw new Error('user_preferences table is unavailable')
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: false,
|
||||
reason: 'user_preferences table is unavailable',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the running child enforcement in the fallback payload when the sandbox status lookup throws', async () => {
|
||||
mockDb.prepare().get.mockReturnValue({ 1: 1 })
|
||||
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
|
||||
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
|
||||
mockIsSandboxEnforced.mockReturnValue(true)
|
||||
mockDb.query.mockImplementationOnce(() => {
|
||||
throw new Error('user_preferences table is unavailable')
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json.status).toBe('healthy')
|
||||
expect(json.sandbox).toEqual({
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: true,
|
||||
reason: 'user_preferences table is unavailable',
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 503 when health check throws an error', async () => {
|
||||
mockDb.prepare().get.mockImplementationOnce(() => {
|
||||
throw new Error('Database error')
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, mock, vi } from 'bun:test'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { mkdirSync, rmSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createInternalRoutes } from '../../src/routes/internal'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { createOpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { buildSandboxExecCommandString, resolveSandboxExecUser, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../src/services/sandbox/command'
|
||||
import { executeCommand } from '../../src/utils/process'
|
||||
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
|
||||
import { getReposPath, getScheduleWorktreesPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
|
||||
|
||||
function trustedRunningInspect(): { exitCode: number; stdout: string; stderr: string } {
|
||||
const memoryMatch = /^(\d+(?:\.\d+)?)([gGmM])?$/.exec(ENV.SANDBOX.MEMORY)
|
||||
const memoryMib = memoryMatch
|
||||
? memoryMatch[2] === undefined || memoryMatch[2] === 'M' || memoryMatch[2] === 'm'
|
||||
? Math.floor(Number(memoryMatch[1]))
|
||||
: Math.floor(Number(memoryMatch[1]) * 1024)
|
||||
: 0
|
||||
const bindMount = (host: string) => ({
|
||||
type: 'Bind',
|
||||
host,
|
||||
guest: host,
|
||||
options: { readonly: false, noexec: false, nosuid: false, nodev: false },
|
||||
stat_virtualization: 'strict',
|
||||
host_permissions: 'private',
|
||||
follow_root_symlinks: false,
|
||||
quota_mib: null,
|
||||
})
|
||||
const config = {
|
||||
name: WORKSPACE_SANDBOX_NAME,
|
||||
image: { Oci: { reference: ENV.SANDBOX.IMAGE, root_disk: { kind: 'managed', size_mib: 4096 } } },
|
||||
resources: { cpus: ENV.SANDBOX.CPUS, memory_mib: memoryMib, max_cpus: ENV.SANDBOX.CPUS, max_memory_mib: memoryMib },
|
||||
runtime: {
|
||||
workdir: getReposPath(),
|
||||
shell: null,
|
||||
scripts: {},
|
||||
entrypoint: null,
|
||||
cmd: ['sleep', 'infinity'],
|
||||
hostname: null,
|
||||
user: resolveSandboxExecUser(),
|
||||
log_level: null,
|
||||
metrics_sample_interval_ms: null,
|
||||
disable_metrics_sample: false,
|
||||
},
|
||||
env: [],
|
||||
labels: { 'ocm.managed': 'true', 'ocm.net': ENV.SANDBOX.NET },
|
||||
rlimits: [],
|
||||
mounts: [
|
||||
bindMount(getReposPath()),
|
||||
bindMount(getScheduleWorktreesPath()),
|
||||
{ type: 'Tmpfs', guest: sandboxSecretMaskPath(), size_mib: null, options: { readonly: false, noexec: false, nosuid: false, nodev: false } },
|
||||
],
|
||||
patches: [],
|
||||
network: {
|
||||
enabled: true,
|
||||
ports: [],
|
||||
policy: {
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
},
|
||||
max_connections: null,
|
||||
trust_host_cas: false,
|
||||
},
|
||||
init: null,
|
||||
pull_policy: 'IfMissing',
|
||||
security_profile: 'default',
|
||||
lifecycle: { ephemeral: false, max_duration_secs: null, idle_timeout_secs: null },
|
||||
manifest_digest: 'sha256:0000000000000000000000000000000000000000000000000000000000000000',
|
||||
}
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: JSON.stringify({
|
||||
name: WORKSPACE_SANDBOX_NAME,
|
||||
status: 'Running',
|
||||
config,
|
||||
created_at: '2026-08-12T00:00:00Z',
|
||||
updated_at: '2026-08-12T00:00:00Z',
|
||||
active_config: config,
|
||||
pending_changes: [],
|
||||
}),
|
||||
stderr: '',
|
||||
}
|
||||
}
|
||||
|
||||
mock.module('../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(async (args: string[]) => {
|
||||
if (args.includes('inspect')) return trustedRunningInspect()
|
||||
return { exitCode: 0, stdout: '[]', stderr: '' }
|
||||
}),
|
||||
}))
|
||||
|
||||
mock.module('../../src/services/sandbox/capability', () => ({
|
||||
detectSandboxCapability: vi.fn(() => ({ available: true, msbVersion: 'msb 0.3.1' })),
|
||||
resetSandboxCapabilityCache: () => {},
|
||||
}))
|
||||
|
||||
const mockExecuteCommand = executeCommand as ReturnType<typeof vi.fn>
|
||||
const mockDetectSandboxCapability = detectSandboxCapability as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('internal sandbox routes', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
let app: Hono
|
||||
let token: string
|
||||
let repoDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
mockExecuteCommand.mockClear()
|
||||
mockDetectSandboxCapability.mockReset()
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.3.1' })
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
const openCodeClient = createOpenCodeClient()
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, stubWorktreeManager)
|
||||
const notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
app = new Hono()
|
||||
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient))
|
||||
token = getOrCreateInternalToken(db)
|
||||
repoDir = path.join(getReposPath(), 'sandbox-route-test')
|
||||
mkdirSync(repoDir, { recursive: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
rmSync(repoDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function postCommand(body: unknown, auth = true) {
|
||||
return app.request('/api/internal/sandbox/command', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(auth ? { authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('POST /command returns 401 without bearer token', async () => {
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' }, false)
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('POST /command returns host mode when the sandbox preference is off', async () => {
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ mode: 'host' })
|
||||
expect(mockExecuteCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /command returns a wrapped sandbox command when enforcement is on', async () => {
|
||||
settingsService.updateSettings({ sandbox: { enabled: true } })
|
||||
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
mode: 'sandbox',
|
||||
command: buildSandboxExecCommandString(repoDir, 'echo hi'),
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /command returns 400 for a malformed body', async () => {
|
||||
const res = await postCommand({ directory: '', command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(await res.json()).toEqual({ error: 'Invalid request' })
|
||||
})
|
||||
|
||||
it('POST /command blocks an enabled request when the capability is unavailable instead of running on the host', async () => {
|
||||
settingsService.updateSettings({ sandbox: { enabled: true } })
|
||||
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
|
||||
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
|
||||
expect(mockExecuteCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /command never returns host mode for an enforced request even when the preference is off', async () => {
|
||||
const res = await postCommand({ directory: repoDir, command: 'echo hi', enforced: true })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
mode: 'sandbox',
|
||||
command: buildSandboxExecCommandString(repoDir, 'echo hi'),
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /command blocks an enforced request for a directory outside the project roots', async () => {
|
||||
const res = await postCommand({ directory: '/etc', command: 'echo hi', enforced: true })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { mode: string; reason?: string }
|
||||
expect(body.mode).toBe('blocked')
|
||||
expect(String(body.reason)).toContain('outside the sandboxed project roots')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,405 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from '../../src/routes/opencode-auth-proxy'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
|
||||
const isSandboxEnforcedMock = vi.hoisted(() => vi.fn().mockReturnValue(false))
|
||||
const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: { isSandboxEnforced: isSandboxEnforcedMock, isLifecycleInitialized: isLifecycleInitializedMock },
|
||||
OpenCodeServerManager: class {},
|
||||
getSandboxVerifiedOpenCodeVersions: () => [],
|
||||
isSandboxVerifiedOpenCodeVersion: () => false,
|
||||
sanitizeConfigForEnforcement: (config: Record<string, unknown>) => config,
|
||||
ConfigReloadError: class extends Error {},
|
||||
NonRecoverableStartupError: class extends Error {},
|
||||
}))
|
||||
|
||||
const forwardRawMock = vi.hoisted(() => vi.fn<OpenCodeClient['forwardRaw']>(async () => new Response('ok', { status: 200 })))
|
||||
|
||||
vi.mock('../../src/services/opencode/client', () => ({
|
||||
createOpenCodeClient: vi.fn(),
|
||||
}))
|
||||
|
||||
const passThroughAuth: MiddlewareHandler = async (c, next) => {
|
||||
await next()
|
||||
}
|
||||
|
||||
function buildApp() {
|
||||
const app = new Hono()
|
||||
app.route(
|
||||
'/api/opencode',
|
||||
createAuthenticatedOpenCodeProxyRoutes({ forwardRaw: forwardRawMock } as unknown as OpenCodeClient, passThroughAuth),
|
||||
)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('authenticated opencode proxy routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
isLifecycleInitializedMock.mockReturnValue(true)
|
||||
forwardRawMock.mockResolvedValue(new Response('ok', { status: 200 }))
|
||||
})
|
||||
|
||||
it('returns 503 and never forwards when the OpenCode lifecycle is not initialized', async () => {
|
||||
isLifecycleInitializedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/message')
|
||||
expect(res.status).toBe(503)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 503 through the proxy gate on a below-threshold health failure and reopens once the supervisor recovers', async () => {
|
||||
const lifecycle = { initialized: true }
|
||||
isLifecycleInitializedMock.mockImplementation(() => lifecycle.initialized)
|
||||
const manager = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
isOperationInProgress: vi.fn(() => false),
|
||||
checkHealth: vi.fn().mockResolvedValue(true),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
}
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
|
||||
failureThreshold: 2,
|
||||
watchEnabled: false,
|
||||
})
|
||||
await supervisor.start()
|
||||
|
||||
const healthyRes = await buildApp().request('/api/opencode/session/ses_1/message')
|
||||
expect(healthyRes.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
const status = await supervisor.checkNow('manual')
|
||||
expect(status.state).toBe('unhealthy')
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
const blockedRes = await buildApp().request('/api/opencode/session/ses_1/message')
|
||||
expect(blockedRes.status).toBe(503)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(true)
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(lifecycle.initialized).toBe(true)
|
||||
|
||||
const reopenedRes = await buildApp().request('/api/opencode/session/ses_1/message')
|
||||
expect(reopenedRes.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('forwards ordinary endpoints when enforcement is off', async () => {
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/message')
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 503 for MCP auth endpoints when the OpenCode lifecycle is not initialized', async () => {
|
||||
isLifecycleInitializedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp/evil-server/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(res.status).toBe(503)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards MCP auth endpoints through the lifecycle-gated proxy when initialized', async () => {
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp/evil-server/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = forwardRawMock.mock.calls[0]![0] as Request
|
||||
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth')
|
||||
})
|
||||
|
||||
it('forwards MCP auth authenticate endpoints through the lifecycle-gated proxy when initialized', async () => {
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp/evil-server/auth/authenticate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = forwardRawMock.mock.calls[0]![0] as Request
|
||||
expect(forwarded.url).toContain('/api/opencode/mcp/evil-server/auth/authenticate')
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint with 403 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()
|
||||
})
|
||||
|
||||
it('keeps host-process shell endpoints blocked when enforcement resolution failed (fail-closed manager state)', 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()
|
||||
})
|
||||
|
||||
it('blocks /api-prefixed PTY creation with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/api/pty', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks percent-encoded shell 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' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
})
|
||||
|
||||
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' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards safely encoded non-execution paths when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/session/ses_1/%6dessage')
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sanitizes plugins from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.theme).toBe('dark')
|
||||
expect(forwarded.plugin).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sanitizes local MCP servers and formatter config from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
formatter: { command: 'prettier' },
|
||||
mcp: { local: { type: 'local', command: ['node', 'server.js'] } },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.formatter).toBeUndefined()
|
||||
expect(forwarded.mcp).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a malformed PATCH /config body with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{not json',
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
})
|
||||
|
||||
it('forwards PATCH /config mutations raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.plugin).toEqual(['opencode-plugin-npm'])
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('only remote MCP servers')
|
||||
})
|
||||
|
||||
it('forwards a remote MCP server add when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards MCP server adds raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'local-server',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as { config: { type: string } }
|
||||
expect(forwarded.config.type).toBe('local')
|
||||
})
|
||||
|
||||
it('sanitizes LSP servers and experimental hooks from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
lsp: { typescript: { command: ['typescript-language-server'] } },
|
||||
experimental: {
|
||||
hook: { file_edited: [{ command: ['chmod', '+x', 'x'] }] },
|
||||
chatMaxRetries: 4,
|
||||
},
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.lsp).toBeUndefined()
|
||||
expect(forwarded.experimental).toEqual({ chatMaxRetries: 4 })
|
||||
})
|
||||
|
||||
it('forwards a PATCH /config mutation without host-execution sections unchanged when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme: 'dark' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({ theme: 'dark' })
|
||||
})
|
||||
|
||||
it('rejects a well-known auth write with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
expect(forwardRawMock).not.toHaveBeenCalled()
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Sandbox enforcement is on')
|
||||
expect(body.error).toContain('well-known')
|
||||
})
|
||||
|
||||
it('forwards api and oauth auth writes when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/auth/anthropic', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'api', key: 'sk-test' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({ type: 'api', key: 'sk-test' })
|
||||
})
|
||||
|
||||
it('forwards auth writes raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.type).toBe('wellknown')
|
||||
})
|
||||
|
||||
it('strips custom provider npm selectors from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const app = buildApp()
|
||||
const res = await app.request('/api/opencode/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'x',
|
||||
provider: {
|
||||
evil: { npm: 'file:///repo/evil-provider.js' },
|
||||
builtin: { options: { apiKey: 'k' } },
|
||||
},
|
||||
}),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(forwardRawMock).toHaveBeenCalledTimes(1)
|
||||
const forwarded = JSON.parse(await (forwardRawMock.mock.calls[0]![0] as Request).text()) as Record<string, unknown>
|
||||
expect(forwarded.model).toBe('x')
|
||||
expect(forwarded.provider).toEqual({ builtin: { options: { apiKey: 'k' } } })
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { createOpenCodeProxyRoutes } from '../../src/routes/opencode-proxy'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
@@ -12,6 +13,19 @@ vi.mock('../../src/services/internal-token', () => ({
|
||||
getOrCreateInternalToken: vi.fn().mockReturnValue('test-internal-token'),
|
||||
}))
|
||||
|
||||
const isSandboxEnforcedMock = vi.hoisted(() => vi.fn().mockReturnValue(false))
|
||||
const isLifecycleInitializedMock = vi.hoisted(() => vi.fn().mockReturnValue(true))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: { isSandboxEnforced: isSandboxEnforcedMock, isLifecycleInitialized: isLifecycleInitializedMock },
|
||||
OpenCodeServerManager: class {},
|
||||
getSandboxVerifiedOpenCodeVersions: () => [],
|
||||
isSandboxVerifiedOpenCodeVersion: () => false,
|
||||
sanitizeConfigForEnforcement: (config: Record<string, unknown>) => config,
|
||||
ConfigReloadError: class extends Error {},
|
||||
NonRecoverableStartupError: class extends Error {},
|
||||
}))
|
||||
|
||||
const mockSettingsService = {
|
||||
getOpenCodeServerPassword: vi.fn().mockReturnValue('test-password'),
|
||||
} as unknown as SettingsService
|
||||
@@ -24,6 +38,8 @@ describe('opencode-proxy routes', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
isLifecycleInitializedMock.mockReturnValue(true)
|
||||
originalFetch = globalThis.fetch
|
||||
app = new Hono()
|
||||
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(mockDb, mockSettingsService))
|
||||
@@ -40,6 +56,20 @@ describe('opencode-proxy routes', () => {
|
||||
expect(body.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('returns 503 and never forwards when the OpenCode lifecycle is not initialized', async () => {
|
||||
isLifecycleInitializedMock.mockReturnValue(false)
|
||||
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/message', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 401 with invalid bearer token', async () => {
|
||||
const res = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer wrong-token' },
|
||||
@@ -271,4 +301,503 @@ describe('opencode-proxy routes', () => {
|
||||
expect(res.headers.get('transfer-encoding')).toBeNull()
|
||||
expect(res.headers.get('content-type')).toBe('text/plain')
|
||||
})
|
||||
|
||||
it('blocks the session shell endpoint 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/shell', {
|
||||
method: 'POST',
|
||||
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')
|
||||
})
|
||||
|
||||
it('keeps host-process shell endpoints blocked when enforcement resolution failed (fail-closed manager state)', 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/shell', {
|
||||
method: 'POST',
|
||||
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')
|
||||
})
|
||||
|
||||
it('blocks percent-encoded shell 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', {
|
||||
method: 'POST',
|
||||
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')
|
||||
})
|
||||
|
||||
it('fails closed on encoded separators in proxied paths 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%2Fshell', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards safely encoded non-execution paths when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
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/%6dessage', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks PTY creation with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/pty', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks /api-prefixed PTY creation with 403 when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/api/pty', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks custom slash command execution 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/command', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add 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/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
|
||||
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('only remote MCP servers')
|
||||
})
|
||||
|
||||
it('rejects a command-bearing MCP add without an explicit local type with 403 when 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/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { command: ['npx', 'evil-server'] },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(upstreamFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards a remote MCP server add when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
})
|
||||
})
|
||||
|
||||
it('forwards MCP server adds raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'local-server',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as { config: { type: string } }
|
||||
expect(forwarded.config.type).toBe('local')
|
||||
})
|
||||
|
||||
it('sanitizes LSP servers and experimental hooks from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
lsp: { typescript: { command: ['typescript-language-server'] } },
|
||||
experimental: {
|
||||
hook: { file_edited: [{ command: ['chmod', '+x', 'x'] }] },
|
||||
chatMaxRetries: 4,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded.lsp).toBeUndefined()
|
||||
expect(forwarded.experimental).toEqual({ chatMaxRetries: 4 })
|
||||
})
|
||||
|
||||
it('forwards ordinary agent endpoints when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
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/prompt_async', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sanitizes plugins from a PATCH /config mutation when the OpenCode child is enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded.theme).toBe('dark')
|
||||
expect(forwarded.plugin).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sanitizes local MCP servers and formatter config from a PATCH /config mutation when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
formatter: { command: 'prettier' },
|
||||
mcp: { local: { type: 'local', command: ['node', 'server.js'] } },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(fetchCall[1].body as string) as Record<string, unknown>
|
||||
expect(forwarded.formatter).toBeUndefined()
|
||||
expect(forwarded.mcp).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a malformed PATCH /config body with 403 when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('should not be reached'))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{not json',
|
||||
})
|
||||
|
||||
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')
|
||||
})
|
||||
|
||||
it('forwards PATCH /config mutations raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/config', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ theme: 'dark', plugin: ['opencode-plugin-npm'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded.plugin).toEqual(['opencode-plugin-npm'])
|
||||
})
|
||||
|
||||
it('forwards non-config mutations raw when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/session/ses_1/message', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ content: 'hello' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded.content).toBe('hello')
|
||||
})
|
||||
|
||||
it('rejects a well-known auth write with 403 when 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/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
|
||||
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('well-known')
|
||||
})
|
||||
|
||||
it('forwards api and oauth auth writes when enforced', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(true)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/auth/anthropic', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ type: 'api', key: 'sk-test' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded).toEqual({ type: 'api', key: 'sk-test' })
|
||||
})
|
||||
|
||||
it('forwards auth writes raw when enforcement is off', async () => {
|
||||
isSandboxEnforcedMock.mockReturnValue(false)
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(
|
||||
new Response('ok', { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
)
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const res = await app.request('/api/opencode-proxy/auth/sso.example.com', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-internal-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ type: 'wellknown', key: 'SSO_TOKEN', token: 't' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const fetchCall = upstreamFetch.mock.calls[0] as [string, RequestInit]
|
||||
const forwarded = JSON.parse(await new Response(fetchCall[1].body as ReadableStream).text()) as Record<string, unknown>
|
||||
expect(forwarded.type).toBe('wellknown')
|
||||
})
|
||||
|
||||
it('returns 503 through the proxy gate on a below-threshold health failure and reopens once the supervisor recovers', async () => {
|
||||
const lifecycle = { initialized: true }
|
||||
isLifecycleInitializedMock.mockImplementation(() => lifecycle.initialized)
|
||||
const manager = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
isOperationInProgress: vi.fn(() => false),
|
||||
checkHealth: vi.fn().mockResolvedValue(true),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
}
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
|
||||
failureThreshold: 2,
|
||||
watchEnabled: false,
|
||||
})
|
||||
await supervisor.start()
|
||||
|
||||
const upstreamFetch = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }))
|
||||
globalThis.fetch = upstreamFetch as unknown as typeof fetch
|
||||
|
||||
const healthyRes = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
expect(healthyRes.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
const status = await supervisor.checkNow('manual')
|
||||
expect(status.state).toBe('unhealthy')
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
const blockedRes = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
expect(blockedRes.status).toBe(503)
|
||||
expect(upstreamFetch).toHaveBeenCalledTimes(1)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(true)
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(lifecycle.initialized).toBe(true)
|
||||
|
||||
const reopenedRes = await app.request('/api/opencode-proxy/doc', {
|
||||
headers: { Authorization: 'Bearer test-internal-token' },
|
||||
})
|
||||
expect(reopenedRes.status).toBe(200)
|
||||
expect(upstreamFetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -33,6 +33,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: {
|
||||
clearStartupError: vi.fn(),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
isSandboxEnforced: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -53,6 +54,7 @@ const mockScheduleService = {} as ScheduleService
|
||||
describe('Repo Routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(false)
|
||||
})
|
||||
|
||||
describe('POST /:id/access', () => {
|
||||
@@ -320,4 +322,62 @@ describe('Repo Routes', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/workspaces', () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
}
|
||||
|
||||
it('refuses and cleans up a workspace created outside the project roots while sandboxing is enforced', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(true)
|
||||
|
||||
const forward = vi.fn(async () =>
|
||||
new Response(
|
||||
JSON.stringify({ id: 'wrk_outside', directory: '/workspace/.opencode/state/workspaces/wrk_outside', branch: null }),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
|
||||
const res = await app.request('/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('not available while sandboxing is enabled')
|
||||
expect(forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
path: '/experimental/workspace/wrk_outside',
|
||||
directory: '/tmp/test-repo',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('allows workspace creation when sandboxing is not enforced', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
vi.mocked(opencodeServerManager.isSandboxEnforced).mockReturnValue(false)
|
||||
|
||||
const forward = vi.fn(async () =>
|
||||
new Response(
|
||||
JSON.stringify({ id: 'wrk_ok', directory: '/workspace/.opencode/state/workspaces/wrk_ok', branch: null }),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
|
||||
const res = await app.request('/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { id: string }
|
||||
expect(body.id).toBe('wrk_ok')
|
||||
expect(forward).not.toHaveBeenCalledWith(expect.objectContaining({ method: 'DELETE' }))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -5,8 +5,10 @@ import { createSettingsRoutes } from '../../src/routes/settings'
|
||||
import { encryptSecret } from '../../src/utils/crypto'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: class Database {},
|
||||
@@ -19,6 +21,8 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
getVersion: vi.fn(),
|
||||
fetchVersion: vi.fn(),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
checkHealth: vi.fn(() => true),
|
||||
reinitializeBinDirectory: vi.fn(),
|
||||
},
|
||||
ConfigReloadError: class ConfigReloadError extends Error {
|
||||
@@ -181,8 +185,81 @@ describe('OpenCode Server Auth Routes', () => {
|
||||
const restored = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string } | undefined
|
||||
expect(restored?.value).toBe(previous.value)
|
||||
})
|
||||
|
||||
it('keeps the proxy lifecycle gate closed during the supervised restart and reopens only after a verified healthy restart', async () => {
|
||||
const lifecycle = { initialized: false }
|
||||
const { app: supervisedApp, manager } = createSupervisedApp(db, lifecycle)
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
|
||||
const patchPromise = supervisedApp.request('/api/settings/opencode-server-auth', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: 'testpassword123' }),
|
||||
})
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
releaseRestart()
|
||||
const response = await patchPromise
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(lifecycle.initialized).toBe(true)
|
||||
expect(await response.json()).toEqual({ isSet: true, source: 'db' })
|
||||
expect(db.prepare('SELECT 1 FROM app_secrets WHERE key = ?').get('opencode_server_password')).toBeDefined()
|
||||
})
|
||||
|
||||
it('fails the auth update and restores the prior password when the supervised restart ends unhealthy, keeping the proxy gate closed', async () => {
|
||||
insertPassword('testpassword123')
|
||||
const previous = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string }
|
||||
const lifecycle = { initialized: false }
|
||||
const { app: supervisedApp, manager } = createSupervisedApp(db, lifecycle)
|
||||
manager.checkHealth.mockResolvedValue(false)
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const response = await supervisedApp.request('/api/settings/opencode-server-auth', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: null }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(manager.restart).toHaveBeenCalledTimes(2)
|
||||
expect(lifecycle.initialized).toBe(false)
|
||||
|
||||
const restored = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get('opencode_server_password') as { value: string } | undefined
|
||||
expect(restored?.value).toBe(previous.value)
|
||||
})
|
||||
})
|
||||
|
||||
function createSupervisedApp(db: Database, lifecycle: { initialized: boolean }) {
|
||||
const manager = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
isOperationInProgress: vi.fn(() => false),
|
||||
checkHealth: vi.fn().mockResolvedValue(true),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn((value: boolean) => { lifecycle.initialized = value }),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
}
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, {} as SettingsService, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
const routes = createSettingsRoutes(db, {} as GitAuthService, {} as OpenCodeClient, supervisor)
|
||||
return { app: new Hono().route('/api/settings', routes), manager }
|
||||
}
|
||||
|
||||
function insertPassword(password: string) {
|
||||
const encrypted = encryptSecret(password)
|
||||
const now = Date.now()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -49,6 +49,18 @@ describe('entrypoint library wiring', () => {
|
||||
expect(warnIndex).toBeLessThan(chownIndex)
|
||||
})
|
||||
|
||||
it('grants node access to /dev/kvm before dropping privileges', () => {
|
||||
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(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/)
|
||||
})
|
||||
|
||||
it('does not re-chown /app when ids change', () => {
|
||||
const entrypoint = read(entrypointPath)
|
||||
|
||||
@@ -66,6 +78,55 @@ describe('entrypoint library wiring', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('microsandbox runtime install', () => {
|
||||
const dockerfile = read(dockerfilePath)
|
||||
|
||||
it('declares MICROSANDBOX_VERSION next to the other tool args', () => {
|
||||
expect(dockerfile).toMatch(/ARG MICROSANDBOX_VERSION=0\.6\.8/)
|
||||
})
|
||||
|
||||
it('resolves the release URL from MICROSANDBOX_VERSION, not only the log message', () => {
|
||||
const microsandboxRun = dockerfile.slice(dockerfile.indexOf('Installing microsandbox='), dockerfile.indexOf('msb --version'))
|
||||
expect(microsandboxRun).toMatch(/releases\/download\/\$\{MSB_VERSION\}/)
|
||||
expect(microsandboxRun).toMatch(/MSB_VERSION="v\$\{MICROSANDBOX_VERSION\}"/)
|
||||
})
|
||||
|
||||
it('pins a tested version and avoids unauthenticated GitHub API lookups', () => {
|
||||
const microsandboxRun = dockerfile.slice(dockerfile.indexOf('Installing microsandbox='), dockerfile.indexOf('msb --version'))
|
||||
expect(microsandboxRun).not.toMatch(/releases\/latest\/download/)
|
||||
expect(microsandboxRun).not.toContain('install.microsandbox.dev')
|
||||
expect(microsandboxRun).not.toMatch(/api\.github\.com/)
|
||||
})
|
||||
|
||||
it('passes the same MICROSANDBOX_VERSION from the docker-build workflow', () => {
|
||||
const workflow = read(join(repoRoot, '.github/workflows/docker-build.yml'))
|
||||
expect(workflow).toContain('MICROSANDBOX_VERSION=0.6.8')
|
||||
expect(workflow).toContain('MICROSANDBOX_VERSION=${{ steps.versions.outputs.microsandbox }}')
|
||||
})
|
||||
|
||||
it('downloads the arch-specific bundle and verifies its checksum', () => {
|
||||
const microsandboxRun = dockerfile.slice(dockerfile.indexOf('Installing microsandbox='), dockerfile.indexOf('msb --version'))
|
||||
expect(microsandboxRun).toMatch(/MSB_BUNDLE="microsandbox-linux-\$\{MSB_TARGET\}\.tar\.gz"/)
|
||||
expect(microsandboxRun).toMatch(/MSB_TARGET="x86_64"/)
|
||||
expect(microsandboxRun).toMatch(/MSB_TARGET="aarch64"/)
|
||||
expect(microsandboxRun).toMatch(/checksums\.sha256/)
|
||||
expect(microsandboxRun).toMatch(/sha256sum -c --quiet/)
|
||||
})
|
||||
|
||||
it('installs msb and libkrunfw under /opt/microsandbox with the runtime symlinks', () => {
|
||||
expect(dockerfile).toContain('/opt/microsandbox/bin/msb')
|
||||
expect(dockerfile).toContain('/usr/local/bin/msb')
|
||||
expect(dockerfile).toContain('/opt/microsandbox/lib/libkrunfw.so')
|
||||
expect(dockerfile).toMatch(/chmod -R a\+rX \/opt\/microsandbox/)
|
||||
expect(dockerfile).toMatch(/msb --version/)
|
||||
})
|
||||
|
||||
it('keeps the state directory writable by the node user', () => {
|
||||
expect(dockerfile).toMatch(/mkdir -p \/workspace \/app\/data \/home\/node\/\.cache \/home\/node\/\.opencode \/home\/node\/\.microsandbox/)
|
||||
expect(dockerfile).toMatch(/chown -R node:node \/workspace \/app\/data \/home\/node/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspace ownership configuration', () => {
|
||||
it('exposes PUID and PGID environment defaults in docker-compose.yml', () => {
|
||||
const compose = read(composePath)
|
||||
@@ -124,6 +185,28 @@ describe('workspace ownership configuration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandbox compose overlay', () => {
|
||||
const overlayPath = join(repoRoot, 'docker-compose.sandbox.yml')
|
||||
const overlay = read(overlayPath)
|
||||
|
||||
it('defaults SANDBOX_EXEC_USER from PUID so the guest identity tracks the workspace owner', () => {
|
||||
expect(overlay).toContain('- SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}}')
|
||||
})
|
||||
|
||||
it('keeps the base compose free of KVM and privileged flags', () => {
|
||||
const compose = read(composePath)
|
||||
expect(compose).not.toContain('privileged')
|
||||
expect(compose).not.toContain('/dev/kvm')
|
||||
})
|
||||
|
||||
it('grants KVM and persists microsandbox state only in the overlay', () => {
|
||||
expect(overlay).toContain('privileged: true')
|
||||
expect(overlay).toContain('"/dev/kvm:/dev/kvm"')
|
||||
expect(overlay).toContain('microsandbox-data:/home/node/.microsandbox')
|
||||
expect(overlay).toMatch(/^volumes:\n(?:.*\n)*?\s+microsandbox-data:/m)
|
||||
})
|
||||
})
|
||||
|
||||
describe('named-volume migration recipe', () => {
|
||||
const runMigrationShell = (src: string, dst: string) => {
|
||||
const scriptDir = mkdtempSync(join(tmpdir(), 'migrate-script-'))
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { mkdirSync, writeFileSync, rmSync, chmodSync, existsSync, readFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { repoRoot } from '../helpers/repo-root'
|
||||
|
||||
const entrypointPath = join(repoRoot, 'scripts/docker-entrypoint.sh')
|
||||
|
||||
let stubDir: string
|
||||
let logPath: string
|
||||
|
||||
const writeStub = (name: string, body: string) => {
|
||||
const file = join(stubDir, name)
|
||||
writeFileSync(file, `#!/bin/bash\n${body}\n`)
|
||||
chmodSync(file, 0o755)
|
||||
}
|
||||
|
||||
const extractGrantKvmAccess = () => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const match = entrypoint.match(/^grant_kvm_access\(\) \{\n[\s\S]*?\n\}/m)
|
||||
if (!match) throw new Error('grant_kvm_access() not found in docker-entrypoint.sh')
|
||||
return match[0]
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubDir = join(tmpdir(), `ocm-entrypoint-${Date.now()}-${Math.random().toString(36).slice(2)}`)
|
||||
mkdirSync(stubDir, { recursive: true })
|
||||
logPath = join(stubDir, 'calls.log')
|
||||
|
||||
writeStub('stat', `echo "${'${OCM_STUB_DEV_GID:-44}'}"`)
|
||||
writeStub('getent', `
|
||||
if [ "$1" = "group" ] && [ "$2" = "${'${OCM_STUB_DEV_GID:-44}'}" ]; then
|
||||
echo "${'${OCM_STUB_GROUP_HOLDER}'}:x:$2:"
|
||||
exit 0
|
||||
fi
|
||||
exit 2`)
|
||||
writeStub('groupadd', `echo "groupadd $*" >> "$OCM_STUB_LOG"`)
|
||||
writeStub('usermod', `echo "usermod $*" >> "$OCM_STUB_LOG"`)
|
||||
writeStub('runuser', `echo "runuser $*" >> "$OCM_STUB_LOG"
|
||||
exit ${'${OCM_STUB_RUNUSER_EXIT:-0}'}`)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(stubDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const runScript = (snippet: string, env: Record<string, string> = {}) => {
|
||||
const scriptPath = join(stubDir, 'test.sh')
|
||||
writeFileSync(scriptPath, `set -e\n${extractGrantKvmAccess()}\n${snippet}\n`)
|
||||
return spawnSync('bash', [scriptPath], {
|
||||
encoding: 'utf-8',
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `${stubDir}:${process.env.PATH}`,
|
||||
OCM_STUB_LOG: logPath,
|
||||
...env,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const stubCalls = () => {
|
||||
if (!existsSync(logPath)) return []
|
||||
return readFileSync(logPath, 'utf-8').split('\n').filter(Boolean)
|
||||
}
|
||||
|
||||
const mockDevice = () => {
|
||||
const dev = join(stubDir, 'dev-kvm')
|
||||
writeFileSync(dev, '')
|
||||
return dev
|
||||
}
|
||||
|
||||
describe('grant_kvm_access', () => {
|
||||
it('is a no-op when the device does not exist', () => {
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(join(stubDir, 'missing-device'))}; echo ok`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('ok')
|
||||
expect(stubCalls()).toEqual([])
|
||||
})
|
||||
|
||||
it('is a no-op when the device gid is not numeric', () => {
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(mockDevice())}; echo ok`, {
|
||||
OCM_STUB_DEV_GID: 'abc',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('ok')
|
||||
expect(stubCalls()).toEqual([])
|
||||
})
|
||||
|
||||
it('reuses the existing group holding the device gid', () => {
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)}; echo ok`, {
|
||||
OCM_STUB_DEV_GID: '44',
|
||||
OCM_STUB_GROUP_HOLDER: 'video',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('Granted node access')
|
||||
expect(stubCalls().some((c) => c === 'usermod -aG video node')).toBe(true)
|
||||
expect(stubCalls().some((c) => c.startsWith('runuser -u node -- test -r'))).toBe(true)
|
||||
expect(stubCalls().some((c) => c.startsWith('runuser -u node -- test -w'))).toBe(true)
|
||||
})
|
||||
|
||||
it('creates a matching group when none holds the device gid', () => {
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)}; echo ok`, {
|
||||
OCM_STUB_DEV_GID: '232',
|
||||
OCM_STUB_GROUP_HOLDER: '',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('Granted node access')
|
||||
expect(stubCalls().some((c) => c === 'groupadd -g 232 kvm')).toBe(true)
|
||||
expect(stubCalls().some((c) => c.startsWith('usermod -aG kvm node'))).toBe(true)
|
||||
})
|
||||
|
||||
it('fails clearly when the group cannot be created', () => {
|
||||
writeStub('groupadd', `echo "groupadd $*" >> "$OCM_STUB_LOG"\nexit 1`)
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)} || echo "failed"`, {
|
||||
OCM_STUB_DEV_GID: '232',
|
||||
OCM_STUB_GROUP_HOLDER: '',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('failed')
|
||||
expect(res.stderr).toMatch(/could not create group/)
|
||||
})
|
||||
|
||||
it('fails clearly when node cannot be added to the group', () => {
|
||||
writeStub('usermod', `echo "usermod $*" >> "$OCM_STUB_LOG"\nexit 1`)
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)} || echo "failed"`, {
|
||||
OCM_STUB_GROUP_HOLDER: 'video',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('failed')
|
||||
expect(res.stderr).toMatch(/could not add node to group/)
|
||||
})
|
||||
|
||||
it('fails clearly when the node user cannot open the device', () => {
|
||||
const dev = mockDevice()
|
||||
const res = runScript(`grant_kvm_access ${JSON.stringify(dev)} || echo "failed"`, {
|
||||
OCM_STUB_GROUP_HOLDER: 'video',
|
||||
OCM_STUB_RUNUSER_EXIT: '1',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('failed')
|
||||
expect(res.stderr).toMatch(/node cannot access/)
|
||||
})
|
||||
})
|
||||
|
||||
const extractInstallOpencode = () => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const match = entrypoint.match(/^install_opencode\(\) \{\n[\s\S]*?\n\}/m)
|
||||
if (!match) throw new Error('install_opencode() not found in docker-entrypoint.sh')
|
||||
return match[0]
|
||||
}
|
||||
|
||||
const extractOpenCodeInstallSection = () => {
|
||||
const entrypoint = readFileSync(entrypointPath, 'utf-8')
|
||||
const startMarker = 'echo "Checking OpenCode installation..."'
|
||||
const endMarker = 'echo "Starting OpenCode Manager Backend..."'
|
||||
const start = entrypoint.indexOf(startMarker)
|
||||
const end = entrypoint.indexOf(endMarker)
|
||||
if (start === -1 || end === -1 || end <= start) {
|
||||
throw new Error('OpenCode install section not found in docker-entrypoint.sh')
|
||||
}
|
||||
return entrypoint.slice(start, end)
|
||||
}
|
||||
|
||||
const runOpenCodeSection = (snippet: string, env: Record<string, string> = {}) => {
|
||||
const scriptPath = join(stubDir, 'test.sh')
|
||||
const homeDir = join(stubDir, 'home')
|
||||
writeFileSync(scriptPath, `set -e\n${snippet}\n`)
|
||||
return spawnSync('bash', [scriptPath], {
|
||||
encoding: 'utf-8',
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `${stubDir}:${homeDir}/.opencode/bin:/usr/bin:/bin`,
|
||||
OCM_STUB_LOG: logPath,
|
||||
HOME: homeDir,
|
||||
...env,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const stubInstallTools = () => {
|
||||
writeStub('curl', `echo "curl $*" >> "$OCM_STUB_LOG"
|
||||
rm -rf /tmp/opencode /tmp/opencode.tar.gz
|
||||
mkdir -p "$HOME/.opencode/bin"
|
||||
printf '#!/bin/bash\\necho 1.18.16\\n' > "$HOME/.opencode/bin/opencode"
|
||||
chmod +x "$HOME/.opencode/bin/opencode"
|
||||
printf 'fake binary\\n' > /tmp/opencode`)
|
||||
writeStub('tar', `echo "tar $*" >> "$OCM_STUB_LOG"`)
|
||||
}
|
||||
|
||||
const curlLog = () => stubCalls().filter((c) => c.startsWith('curl '))
|
||||
|
||||
describe('install_opencode', () => {
|
||||
it('installs the bundled verified version, never latest', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`)
|
||||
expect(res.status).toBe(0)
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('honors an OPENCODE_BUNDLED_VERSION override for the download URL', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\ninstall_opencode`, {
|
||||
OPENCODE_BUNDLED_VERSION: '1.22.0',
|
||||
})
|
||||
expect(res.status).toBe(0)
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.22\.0\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('reinstalls the bundled verified version when opencode is missing', () => {
|
||||
stubInstallTools()
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('OpenCode not found. Installing...')
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
|
||||
it('repairs a below-minimum opencode with the bundled verified version, not latest', () => {
|
||||
stubInstallTools()
|
||||
writeStub('opencode', `echo "opencode version 1.0.0"`)
|
||||
const res = runOpenCodeSection(`${extractInstallOpencode()}\n${extractOpenCodeInstallSection()}`)
|
||||
expect(res.status).toBe(0)
|
||||
expect(res.stdout).toContain('below minimum required version')
|
||||
const urls = curlLog().join(' ')
|
||||
expect(urls).toMatch(/\/releases\/download\/v1\.18\.16\//)
|
||||
expect(urls).not.toContain('/releases/latest/download/')
|
||||
})
|
||||
})
|
||||
@@ -724,3 +724,31 @@ describe('installAssistantWorkspace', () => {
|
||||
expect(result.defaultAgent?.created).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('assistant mode directory contract', () => {
|
||||
it('resolves the assistant directory from the shared sandbox mount owner', async () => {
|
||||
const ws = await createTempAssistantWorkspace()
|
||||
try {
|
||||
const { getAssistantModePath, getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
|
||||
const { getAssistantModeDirectory } = await import('../../src/services/assistant-mode')
|
||||
const { sandboxSecretMaskPath } = await import('../../src/services/sandbox/command')
|
||||
|
||||
expect(getAssistantModeDirectory()).toBe(getAssistantModePath())
|
||||
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
|
||||
expect(getAssistantOpenCodeDir()).toBe(path.join(ws.assistantDir, '.opencode'))
|
||||
} finally {
|
||||
await ws.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the internal token underneath the sandboxed assistant .opencode directory', async () => {
|
||||
const ws = await createTempAssistantWorkspace()
|
||||
try {
|
||||
const { getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
|
||||
const tokenPath = path.join(ws.assistantDir, '.opencode/internal-token')
|
||||
expect(tokenPath).toContain(getAssistantOpenCodeDir())
|
||||
} finally {
|
||||
await ws.cleanup()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,32 @@ describe('ocm-gh-env plugin', () => {
|
||||
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 pluginPath = path.join(pluginDir, 'ocm-gh-env.js')
|
||||
const symlinkTarget = path.join(pluginDir, 'attacker-hook.js')
|
||||
await fs.mkdir(pluginDir, { recursive: true })
|
||||
await fs.rm(pluginPath, { force: true })
|
||||
await fs.writeFile(symlinkTarget, 'export default async function () {}')
|
||||
await fs.symlink(symlinkTarget, pluginPath)
|
||||
|
||||
await installGhEnvPlugin(configHome)
|
||||
|
||||
const stat = await fs.lstat(pluginPath)
|
||||
expect(stat.isFile()).toBe(true)
|
||||
expect(stat.isSymbolicLink()).toBe(false)
|
||||
expect(await fs.readFile(pluginPath, 'utf-8')).toContain('shell.env')
|
||||
expect(await fs.readFile(symlinkTarget, 'utf-8')).toBe('export default async function () {}')
|
||||
})
|
||||
|
||||
it('throws when the plugin file cannot be written instead of swallowing the failure', async () => {
|
||||
const blockedHome = path.join(configHome, 'blocked')
|
||||
await fs.mkdir(blockedHome, { recursive: true })
|
||||
await fs.writeFile(path.join(blockedHome, 'opencode'), 'not a directory')
|
||||
|
||||
await expect(installGhEnvPlugin(blockedHome)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('injects fetched GH env into output.env', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const managerMock = vi.hoisted(() => ({
|
||||
getLastStartupError: vi.fn<() => string | null>(() => null),
|
||||
clearStartupError: vi.fn<() => void>(),
|
||||
restart: vi.fn<() => Promise<void>>(),
|
||||
checkHealth: vi.fn<() => boolean>(() => true),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: managerMock,
|
||||
}))
|
||||
|
||||
import {
|
||||
restartOpenCode,
|
||||
setOpenCodeRestartCoordinator,
|
||||
} from '../../src/services/opencode-restart'
|
||||
import type { OpenCodeRestartCoordinator } from '../../src/services/opencode-restart-coordinator'
|
||||
import type { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
function createSupervisor(healthy: boolean): OpenCodeSupervisor {
|
||||
return {
|
||||
restart: vi.fn().mockResolvedValue({ healthy }),
|
||||
reloadConfig: vi.fn(),
|
||||
} as unknown as OpenCodeSupervisor
|
||||
}
|
||||
|
||||
function createCoordinator(healthy: boolean, resumedSessionIDs: string[] = []): OpenCodeRestartCoordinator {
|
||||
return {
|
||||
runWithResume: vi.fn(async (restart: () => Promise<boolean>) => ({
|
||||
healthy: healthy ?? (await restart()),
|
||||
resumedSessionIDs,
|
||||
})),
|
||||
} as unknown as OpenCodeRestartCoordinator
|
||||
}
|
||||
|
||||
describe('restartOpenCode', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
setOpenCodeRestartCoordinator(null)
|
||||
})
|
||||
|
||||
it('throws with the startup failure reason when the coordinator reports an unhealthy restart', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting')
|
||||
setOpenCodeRestartCoordinator(createCoordinator(false))
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(true))).rejects.toThrow(
|
||||
'OpenCode version 1.18.15 does not support sandboxed bash tool rewriting',
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves resumed session IDs only when the coordinator reports a healthy restart', async () => {
|
||||
setOpenCodeRestartCoordinator(createCoordinator(true, ['session-1', 'session-2']))
|
||||
|
||||
const result = await restartOpenCode(createSupervisor(true))
|
||||
|
||||
expect(result).toEqual({ resumedSessionIDs: ['session-1', 'session-2'] })
|
||||
})
|
||||
|
||||
it('throws with the startup failure reason when the supervisor restart is unhealthy without a coordinator', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue('OpenCode server failed to become healthy')
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(false))).rejects.toThrow('OpenCode server failed to become healthy')
|
||||
})
|
||||
|
||||
it('returns without resumed sessions when the supervisor restart is healthy without a coordinator', async () => {
|
||||
const supervisor = createSupervisor(true)
|
||||
|
||||
const result = await restartOpenCode(supervisor)
|
||||
|
||||
expect(result).toEqual({ resumedSessionIDs: [] })
|
||||
expect(supervisor.restart).toHaveBeenCalledWith('settings_restart')
|
||||
})
|
||||
|
||||
it('uses a generic failure message when no startup error is recorded', async () => {
|
||||
managerMock.getLastStartupError.mockReturnValue(null)
|
||||
|
||||
await expect(restartOpenCode(createSupervisor(false))).rejects.toThrow(
|
||||
'OpenCode server restart did not complete successfully',
|
||||
)
|
||||
})
|
||||
|
||||
it('propagates a manager restart failure when no supervisor is provided', async () => {
|
||||
managerMock.restart.mockRejectedValue(new Error('server failed to become healthy'))
|
||||
|
||||
await expect(restartOpenCode()).rejects.toThrow('server failed to become healthy')
|
||||
expect(managerMock.clearStartupError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ensureDirectoryExists, writeFileContent } from '../../src/services/file-operations'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
@@ -36,6 +36,8 @@ interface FakeManager {
|
||||
reloadConfig: ReturnType<typeof vi.fn>
|
||||
clearStartupError: ReturnType<typeof vi.fn>
|
||||
getLastStartupError: ReturnType<typeof vi.fn>
|
||||
isLastStartupErrorNonRecoverable: ReturnType<typeof vi.fn>
|
||||
setLifecycleInitialized: ReturnType<typeof vi.fn>
|
||||
getPort: ReturnType<typeof vi.fn>
|
||||
getVersion: ReturnType<typeof vi.fn>
|
||||
getMinVersion: ReturnType<typeof vi.fn>
|
||||
@@ -51,6 +53,10 @@ interface FakeSettingsService {
|
||||
}
|
||||
|
||||
describe('OpenCodeSupervisor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const createManager = (): FakeManager => ({
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -60,6 +66,8 @@ describe('OpenCodeSupervisor', () => {
|
||||
reloadConfig: vi.fn().mockResolvedValue(undefined),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
isLastStartupErrorNonRecoverable: vi.fn(() => false),
|
||||
setLifecycleInitialized: vi.fn(),
|
||||
getPort: vi.fn(() => 5551),
|
||||
getVersion: vi.fn(() => '1.0.137'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
@@ -122,6 +130,65 @@ describe('OpenCodeSupervisor', () => {
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('opens the proxy lifecycle gate when the managed child is attested healthy', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('keeps the proxy lifecycle gate closed when startup fails non-recoverably', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.healthy).toBe(false)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate when recovery is exhausted and reopens it once health returns', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('startup failed'))
|
||||
manager.checkHealth
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true)
|
||||
|
||||
const failed = await supervisor.start()
|
||||
expect(failed.healthy).toBe(false)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('does not recover polling failures until the threshold is reached', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
@@ -137,6 +204,35 @@ describe('OpenCodeSupervisor', () => {
|
||||
expect(status.state).toBe('unhealthy')
|
||||
expect(status.failureCount).toBe(1)
|
||||
expect(manager.restart).not.toHaveBeenCalled()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate on a below-threshold health failure and reopens it once health returns', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 2,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
|
||||
const unhealthy = await supervisor.checkNow('manual')
|
||||
|
||||
expect(unhealthy.state).toBe('unhealthy')
|
||||
expect(unhealthy.failureCount).toBe(1)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
expect(manager.restart).not.toHaveBeenCalled()
|
||||
|
||||
manager.checkHealth.mockResolvedValueOnce(true)
|
||||
|
||||
const recovered = await supervisor.checkNow('manual')
|
||||
|
||||
expect(recovered.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('captures debug state before debug recovery', async () => {
|
||||
@@ -171,4 +267,306 @@ describe('OpenCodeSupervisor', () => {
|
||||
|
||||
expect(manager.checkHealth).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not run configuration recovery for a non-recoverable startup failure', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('OpenCode version 1.18.15 does not support sandboxed bash tool rewriting'))
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.state).toBe('failed')
|
||||
expect(status.healthy).toBe(false)
|
||||
expect(status.lastError).toContain('does not support sandboxed bash tool rewriting')
|
||||
expect(manager.restart).not.toHaveBeenCalled()
|
||||
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
|
||||
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(writeFileContent).not.toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('does not run configuration recovery when a manual restart fails non-recoverably', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.restart.mockRejectedValueOnce(new Error('Failed to quarantine untrusted OpenCode plugins'))
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
|
||||
const status = await supervisor.restart('settings_restart')
|
||||
|
||||
expect(status.state).toBe('failed')
|
||||
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
|
||||
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(writeFileContent).not.toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('stops the recovery ladder when a recovery restart fails non-recoverably', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('startup failed'))
|
||||
manager.checkHealth.mockResolvedValue(false)
|
||||
manager.restart.mockImplementation(async () => {
|
||||
manager.isLastStartupErrorNonRecoverable.mockReturnValue(true)
|
||||
throw new Error('Failed to install the sandbox OpenCode plugin')
|
||||
})
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.state).toBe('failed')
|
||||
expect(status.lastError).toContain('Failed to install the sandbox OpenCode plugin')
|
||||
expect(manager.restart).toHaveBeenCalledTimes(1)
|
||||
expect(settings.archiveBrokenConfig).not.toHaveBeenCalled()
|
||||
expect(settings.restoreToLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(settings.updateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(settings.createOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(writeFileContent).not.toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('still follows the normal recovery ladder for a recoverable startup failure', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('OpenCode config validation failed: command.review: Invalid'))
|
||||
manager.checkHealth
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.state).toBe('healthy')
|
||||
expect(settings.archiveBrokenConfig).toHaveBeenCalledWith('default')
|
||||
expect(settings.restoreToLastKnownGoodConfig).toHaveBeenCalledWith('default')
|
||||
expect(settings.updateOpenCodeConfig).toHaveBeenCalled()
|
||||
expect(writeFileContent).toHaveBeenCalled()
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
|
||||
it('executes a restart requested during an active restart after the active restart completes', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const first = supervisor.restart('settings_restart')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
|
||||
const second = supervisor.restart('manual')
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(manager.restart).toHaveBeenCalledTimes(1)
|
||||
|
||||
releaseRestart()
|
||||
|
||||
const [firstStatus, secondStatus] = await Promise.all([first, second])
|
||||
|
||||
expect(manager.restart).toHaveBeenCalledTimes(2)
|
||||
expect(firstStatus.healthy).toBe(true)
|
||||
expect(secondStatus.healthy).toBe(true)
|
||||
})
|
||||
|
||||
it('executes a reload requested during an active reload after the active reload completes', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
let releaseReload!: () => void
|
||||
manager.reloadConfig.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseReload = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const first = supervisor.reloadConfig('settings_reload')
|
||||
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
|
||||
|
||||
const second = supervisor.reloadConfig('manual')
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(manager.reloadConfig).toHaveBeenCalledTimes(1)
|
||||
|
||||
releaseReload()
|
||||
|
||||
const [firstStatus, secondStatus] = await Promise.all([first, second])
|
||||
|
||||
expect(manager.reloadConfig).toHaveBeenCalledTimes(2)
|
||||
expect(firstStatus.healthy).toBe(true)
|
||||
expect(secondStatus.healthy).toBe(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate for the whole restart transition and reopens once healthy', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const restart = supervisor.restart('settings_restart')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseRestart()
|
||||
const status = await restart
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate for the whole reload transition and reopens once healthy', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseReload!: () => void
|
||||
manager.reloadConfig.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseReload = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const reload = supervisor.reloadConfig('settings_reload')
|
||||
await vi.waitFor(() => expect(manager.reloadConfig).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseReload()
|
||||
const status = await reload
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate while stopping and never reopens it', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseStop!: () => void
|
||||
manager.stop.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseStop = resolve }),
|
||||
)
|
||||
|
||||
const stopPromise = supervisor.stop()
|
||||
await vi.waitFor(() => expect(manager.stop).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseStop()
|
||||
await stopPromise
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
|
||||
it('closes the proxy lifecycle gate while recovering a polling failure until health returns', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
await supervisor.start()
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValueOnce(false)
|
||||
|
||||
const recovering = supervisor.checkNow('manual')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(false)
|
||||
|
||||
releaseRestart()
|
||||
const status = await recovering
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(manager.setLifecycleInitialized).toHaveBeenLastCalledWith(true)
|
||||
})
|
||||
|
||||
it('executes a stop requested during an active restart after the restart completes', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
watchEnabled: false,
|
||||
})
|
||||
|
||||
let releaseRestart!: () => void
|
||||
manager.restart.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => { releaseRestart = resolve }),
|
||||
)
|
||||
manager.checkHealth.mockResolvedValue(true)
|
||||
|
||||
const restart = supervisor.restart('manual')
|
||||
await vi.waitFor(() => expect(manager.restart).toHaveBeenCalledTimes(1))
|
||||
|
||||
const stopPromise = supervisor.stop()
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(manager.stop).not.toHaveBeenCalled()
|
||||
|
||||
releaseRestart()
|
||||
|
||||
await Promise.all([restart, stopPromise])
|
||||
|
||||
expect(manager.restart).toHaveBeenCalledTimes(1)
|
||||
expect(manager.stop).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -203,6 +203,68 @@ describe('OpenCodeClient', () => {
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('honours an explicit host override instead of OPENCODE_HOST', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
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) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient('testpassword', '127.0.0.1')
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
|
||||
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(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('brackets an IPv6 loopback host in the request URL', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient('testpassword', '::1')
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
|
||||
expect(capturedUrl?.origin).toBe('http://[::1]:5551')
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves a lazy host override on every request', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
const hosts: string[] = []
|
||||
let currentHost = '192.168.1.10'
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
hosts.push(input instanceof URL ? input.hostname : new URL(input.toString()).hostname)
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient('testpassword', () => currentHost)
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
currentHost = '127.0.0.1'
|
||||
await client.forward({ method: 'GET', path: '/doc' })
|
||||
|
||||
expect(hosts).toEqual(['192.168.1.10', '127.0.0.1'])
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('forwardRaw', () => {
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
decideSandboxProxyBlock,
|
||||
decideSandboxConfigBody,
|
||||
decideSandboxMcpAddBody,
|
||||
decideSandboxAuthBody,
|
||||
decideSandboxMutationBody,
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
isSandboxAuthWrite,
|
||||
SANDBOX_BLOCKED_REASON_PREFIX,
|
||||
SANDBOX_CONFIG_MUTATION_REASON_PREFIX,
|
||||
} from '../../../src/services/opencode/proxy-policy'
|
||||
|
||||
describe('sandbox proxy policy', () => {
|
||||
it('passes every route through when enforcement is off', () => {
|
||||
expect(decideSandboxProxyBlock(false, 'POST', '/session/s1/shell')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(false, 'POST', '/pty')).toEqual({ blocked: false })
|
||||
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('blocks custom slash command execution when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/command').blocked).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks PTY creation and connection when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1/connect').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/pty/p1/connect').blocked).toBe(true)
|
||||
})
|
||||
|
||||
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/p%74y').blocked).toBe(true)
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/session')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/pty/p1')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/api/session/ses_1/message')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
it('classifies /api-prefixed config, mcp, and auth writes identically when enforced', () => {
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/api/config')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/api/%63onfig')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/api/config/')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/api/mcp')).toBe(true)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/api/mcp/')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/api/auth/openai')).toBe(true)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/api/auth/openai/extra')).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves non-execution routes reachable when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/message')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/pty/p1')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'DELETE', '/pty/p1')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/config')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/prompt_async')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('ignores methods that do not match a blocked route', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/shell')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/pty')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/command')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
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', '/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)
|
||||
})
|
||||
|
||||
it('passes safely encoded non-execution paths through when enforced', () => {
|
||||
expect(decideSandboxProxyBlock(true, 'GET', '/session/ses_1/%6dessage')).toEqual({ blocked: false })
|
||||
expect(decideSandboxProxyBlock(true, 'POST', '/session/ses_1/prompt%5Fasync')).toEqual({ blocked: false })
|
||||
})
|
||||
|
||||
it('classifies only enforced PATCH /config as a config mutation', () => {
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/config')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/%63onfig')).toBe(true)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/config/')).toBe(false)
|
||||
expect(isSandboxConfigMutation(true, 'PATCH', '/project')).toBe(false)
|
||||
expect(isSandboxConfigMutation(true, 'POST', '/config')).toBe(false)
|
||||
expect(isSandboxConfigMutation(true, 'GET', '/config')).toBe(false)
|
||||
expect(isSandboxConfigMutation(false, 'PATCH', '/config')).toBe(false)
|
||||
})
|
||||
|
||||
it('passes non-config mutation bodies through untouched', () => {
|
||||
expect(decideSandboxConfigBody(true, 'GET', '/config', '')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxConfigBody(true, 'POST', '/config', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxConfigBody(true, 'PATCH', '/session/s1/message', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxConfigBody(false, 'PATCH', '/config', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('strips configured plugins from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
theme: 'dark',
|
||||
plugin: ['opencode-plugin-npm'],
|
||||
mcp: { remote: { type: 'remote', url: 'https://example.com' } },
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.theme).toBe('dark')
|
||||
expect(body.plugin).toBeUndefined()
|
||||
expect(body.mcp).toEqual({ remote: { type: 'remote', url: 'https://example.com' } })
|
||||
}
|
||||
})
|
||||
|
||||
it('strips local MCP servers and formatter config from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
formatter: { command: 'prettier' },
|
||||
mcp: { local: { type: 'local', command: ['node', 'server.js'] }, remote: { type: 'remote', url: 'https://example.com' } },
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.formatter).toBeUndefined()
|
||||
expect(body.mcp).toEqual({ remote: { type: 'remote', url: 'https://example.com' } })
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves a config mutation with no host-execution sections unchanged when enforced', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ theme: 'dark' }))
|
||||
expect(decision).toEqual({ kind: 'sanitized', body: JSON.stringify({ theme: 'dark' }) })
|
||||
})
|
||||
|
||||
it('fails closed on malformed or non-object config mutation bodies when enforced', () => {
|
||||
const invalidJson = decideSandboxConfigBody(true, 'PATCH', '/config', '{not json')
|
||||
expect(invalidJson.kind).toBe('reject')
|
||||
if (invalidJson.kind === 'reject') {
|
||||
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
}
|
||||
|
||||
const emptyBody = decideSandboxConfigBody(true, 'PATCH', '/config', '')
|
||||
expect(emptyBody.kind).toBe('reject')
|
||||
|
||||
const arrayBody = decideSandboxConfigBody(true, 'PATCH', '/config', '[]')
|
||||
expect(arrayBody.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('strips LSP servers and experimental hook commands from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
lsp: { typescript: { command: ['typescript-language-server', '--stdio'] } },
|
||||
experimental: {
|
||||
hook: { file_edited: [{ command: ['chmod', '+x', 'script.sh'] }] },
|
||||
chatMaxRetries: 4,
|
||||
},
|
||||
model: 'x',
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.lsp).toBeUndefined()
|
||||
expect(body.experimental).toEqual({ chatMaxRetries: 4 })
|
||||
expect(body.model).toBe('x')
|
||||
}
|
||||
})
|
||||
|
||||
it('strips the shell configuration from an enforced config mutation', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
shell: { command: '/repo/bin/evil-shell', args: [] },
|
||||
model: 'x',
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.shell).toBeUndefined()
|
||||
expect(body.model).toBe('x')
|
||||
}
|
||||
})
|
||||
|
||||
it('strips an enabling lsp boolean from an enforced config mutation while keeping an explicit false', () => {
|
||||
const enabled = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ lsp: true, model: 'x' }))
|
||||
expect(enabled.kind).toBe('sanitized')
|
||||
if (enabled.kind === 'sanitized') {
|
||||
expect(JSON.parse(enabled.body)).toEqual({ model: 'x' })
|
||||
}
|
||||
|
||||
const disabled = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({ lsp: false, model: 'x' }))
|
||||
expect(disabled).toEqual({ kind: 'sanitized', body: JSON.stringify({ lsp: false, model: 'x' }) })
|
||||
})
|
||||
|
||||
it('drops the experimental section entirely when only its hook carries commands', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
experimental: { hook: { session_completed: [{ command: ['echo', 'done'] }] } },
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.experimental).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('classifies only enforced POST /mcp as an MCP add', () => {
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/mcp')).toBe(true)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/%6dcp')).toBe(true)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/mcp/')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'POST', '/mcp/my-server/connect')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'GET', '/mcp')).toBe(false)
|
||||
expect(isSandboxMcpAdd(true, 'DELETE', '/mcp')).toBe(false)
|
||||
expect(isSandboxMcpAdd(false, 'POST', '/mcp')).toBe(false)
|
||||
})
|
||||
|
||||
it('passes non-MCP-add bodies through untouched', () => {
|
||||
expect(decideSandboxMcpAddBody(true, 'GET', '/mcp', '')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxMcpAddBody(true, 'POST', '/mcp/my-server/connect', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxMcpAddBody(false, 'POST', '/mcp', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('rejects a local MCP server add while enforced', () => {
|
||||
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'], environment: { TOKEN: 'secret' } },
|
||||
}))
|
||||
expect(decision.kind).toBe('reject')
|
||||
if (decision.kind === 'reject') {
|
||||
expect(decision.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
expect(decision.reason).toContain('only remote MCP servers')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a command-bearing MCP add even without an explicit local type while enforced', () => {
|
||||
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { command: ['npx', 'evil-server'] },
|
||||
}))
|
||||
expect(decision.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('passes a provably remote MCP server add through while enforced', () => {
|
||||
const decision = decideSandboxMcpAddBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}))
|
||||
expect(decision).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('rejects malformed or non-object MCP add bodies while enforced', () => {
|
||||
const invalidJson = decideSandboxMcpAddBody(true, 'POST', '/mcp', '{not json')
|
||||
expect(invalidJson.kind).toBe('reject')
|
||||
if (invalidJson.kind === 'reject') {
|
||||
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
}
|
||||
|
||||
const arrayBody = decideSandboxMcpAddBody(true, 'POST', '/mcp', '[]')
|
||||
expect(arrayBody.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('dispatches MCP adds before config mutations and leaves other bodies untouched', () => {
|
||||
expect(decideSandboxMutationBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'evil',
|
||||
config: { type: 'local', command: ['node', 'server.js'] },
|
||||
})).kind).toBe('reject')
|
||||
expect(decideSandboxMutationBody(true, 'POST', '/mcp', JSON.stringify({
|
||||
name: 'remote-server',
|
||||
config: { type: 'remote', url: 'https://example.com/mcp' },
|
||||
}))).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxMutationBody(true, 'PATCH', '/config', JSON.stringify({ theme: 'dark' }))).toEqual({
|
||||
kind: 'sanitized',
|
||||
body: JSON.stringify({ theme: 'dark' }),
|
||||
})
|
||||
expect(decideSandboxMutationBody(true, 'POST', '/session/s1/message', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('strips custom provider npm selectors from an enforced config mutation while keeping built-in providers', () => {
|
||||
const decision = decideSandboxConfigBody(true, 'PATCH', '/config', JSON.stringify({
|
||||
model: 'x',
|
||||
provider: {
|
||||
'openai-native': { options: { apiKey: 'k' } },
|
||||
evil: { npm: 'file:///repo/evil-provider.js', options: { token: 't' } },
|
||||
remote: { npm: '@scope/remote-provider', models: { 'm-1': { name: 'M1' } } },
|
||||
},
|
||||
}))
|
||||
expect(decision.kind).toBe('sanitized')
|
||||
if (decision.kind === 'sanitized') {
|
||||
const body = JSON.parse(decision.body) as Record<string, unknown>
|
||||
expect(body.model).toBe('x')
|
||||
expect(body.provider).toEqual({ 'openai-native': { options: { apiKey: 'k' } } })
|
||||
}
|
||||
})
|
||||
|
||||
it('classifies only enforced PUT /auth/{provider} as an auth write', () => {
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai')).toBe(true)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/auth/%6fpenai')).toBe(true)
|
||||
expect(isSandboxAuthWrite(true, 'POST', '/auth/openai')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'DELETE', '/auth/openai')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'GET', '/auth/openai')).toBe(false)
|
||||
expect(isSandboxAuthWrite(true, 'PUT', '/auth/openai/extra')).toBe(false)
|
||||
expect(isSandboxAuthWrite(false, 'PUT', '/auth/openai')).toBe(false)
|
||||
})
|
||||
|
||||
it('passes non-auth-write bodies through untouched', () => {
|
||||
expect(decideSandboxAuthBody(true, 'GET', '/auth/openai', '')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxAuthBody(true, 'DELETE', '/auth/openai', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxAuthBody(true, 'PUT', '/config', '{}')).toEqual({ kind: 'passthrough' })
|
||||
expect(decideSandboxAuthBody(false, 'PUT', '/auth/openai', '{}')).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('rejects a well-known auth write while enforced', () => {
|
||||
const decision = decideSandboxAuthBody(true, 'PUT', '/auth/sso.example.com', JSON.stringify({
|
||||
type: 'wellknown',
|
||||
key: 'SSO_TOKEN',
|
||||
token: 't',
|
||||
}))
|
||||
expect(decision.kind).toBe('reject')
|
||||
if (decision.kind === 'reject') {
|
||||
expect(decision.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
expect(decision.reason).toContain('well-known')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a malformed or non-object auth write body while enforced', () => {
|
||||
const invalidJson = decideSandboxAuthBody(true, 'PUT', '/auth/openai', '{not json')
|
||||
expect(invalidJson.kind).toBe('reject')
|
||||
if (invalidJson.kind === 'reject') {
|
||||
expect(invalidJson.reason).toContain(SANDBOX_CONFIG_MUTATION_REASON_PREFIX)
|
||||
}
|
||||
|
||||
const arrayBody = decideSandboxAuthBody(true, 'PUT', '/auth/openai', '[]')
|
||||
expect(arrayBody.kind).toBe('reject')
|
||||
})
|
||||
|
||||
it('passes api and oauth auth writes through while enforced', () => {
|
||||
const api = decideSandboxAuthBody(true, 'PUT', '/auth/anthropic', JSON.stringify({
|
||||
type: 'api',
|
||||
key: 'sk-test',
|
||||
}))
|
||||
expect(api).toEqual({ kind: 'passthrough' })
|
||||
|
||||
const oauth = decideSandboxAuthBody(true, 'PUT', '/auth/github', JSON.stringify({
|
||||
type: 'oauth',
|
||||
access: 'a',
|
||||
refresh: 'r',
|
||||
expires: 1,
|
||||
}))
|
||||
expect(oauth).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
|
||||
it('dispatches auth writes before config mutations in the combined body decision', () => {
|
||||
expect(decideSandboxMutationBody(true, 'PUT', '/auth/evil', JSON.stringify({
|
||||
type: 'wellknown',
|
||||
key: 'K',
|
||||
token: 't',
|
||||
})).kind).toBe('reject')
|
||||
expect(decideSandboxMutationBody(true, 'PUT', '/auth/openai', JSON.stringify({
|
||||
type: 'api',
|
||||
key: 'k',
|
||||
}))).toEqual({ kind: 'passthrough' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { accessSync, realpathSync, statSync } from 'fs'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { detectSandboxCapability, resetSandboxCapabilityCache } from '../../../src/services/sandbox/capability'
|
||||
import { logger } from '../../../src/utils/logger'
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
accessSync: vi.fn(),
|
||||
realpathSync: vi.fn((candidate: string) => candidate),
|
||||
statSync: vi.fn(() => ({ uid: 0, gid: 0, mode: 0o755 })),
|
||||
constants: {
|
||||
R_OK: 4,
|
||||
W_OK: 2,
|
||||
X_OK: 1,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
spawnSync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockAccessSync = accessSync as unknown as ReturnType<typeof vi.fn>
|
||||
const mockSpawnSync = spawnSync as unknown as ReturnType<typeof vi.fn>
|
||||
const mockRealpathSync = realpathSync as unknown as ReturnType<typeof vi.fn>
|
||||
const mockStatSync = statSync as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('detectSandboxCapability', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
mockRealpathSync.mockImplementation((candidate: string) => candidate)
|
||||
mockStatSync.mockReturnValue({ uid: 0, gid: 0, mode: 0o755 })
|
||||
resetSandboxCapabilityCache()
|
||||
})
|
||||
afterEach(() => {
|
||||
resetSandboxCapabilityCache()
|
||||
})
|
||||
|
||||
it('reports unavailable when /dev/kvm is not accessible or writable', () => {
|
||||
mockAccessSync.mockImplementation(() => {
|
||||
throw new Error('ENOENT')
|
||||
})
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toContain('/dev/kvm')
|
||||
expect(mockSpawnSync).not.toHaveBeenCalled()
|
||||
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('/dev/kvm'))
|
||||
})
|
||||
|
||||
it('reports unavailable when msb --version exits with a non-zero status', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: 1, stdout: '', stderr: 'msb: not found' })
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
})
|
||||
|
||||
it('reports unavailable when msb --version fails to spawn', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: null, stdout: '', stderr: '', error: new Error('spawn ENOENT') })
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
})
|
||||
|
||||
it('reports available with the trimmed msb version when both probes succeed', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result).toEqual({ available: true, msbVersion: 'msb 0.3.1' })
|
||||
})
|
||||
|
||||
it('reports unavailable when an explicit exec user uid does not match the manager uid', async () => {
|
||||
process.env.SANDBOX_EXEC_USER = '2000'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
|
||||
'../../../src/services/sandbox/capability'
|
||||
)
|
||||
const { logger } = await import('../../../src/utils/logger')
|
||||
const { spawnSync } = await import('child_process')
|
||||
const { accessSync } = await import('fs')
|
||||
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation(() => {})
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
const getuid = vi.spyOn(proc, 'getuid').mockReturnValue(1000)
|
||||
const getgid = vi.spyOn(proc, 'getgid').mockReturnValue(1000)
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toContain('SANDBOX_EXEC_USER')
|
||||
expect(result.reason).toContain('1000')
|
||||
expect(spawnSync).not.toHaveBeenCalled()
|
||||
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('SANDBOX_EXEC_USER'))
|
||||
expect(getuid).toHaveBeenCalled()
|
||||
expect(getgid).toHaveBeenCalled()
|
||||
} finally {
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
vi.restoreAllMocks()
|
||||
}
|
||||
})
|
||||
|
||||
it('memoizes the probe result until the cache is reset', () => {
|
||||
mockAccessSync.mockImplementation(() => {})
|
||||
mockSpawnSync.mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
|
||||
const first = detectSandboxCapability()
|
||||
const second = detectSandboxCapability()
|
||||
|
||||
expect(mockSpawnSync).toHaveBeenCalledTimes(1)
|
||||
expect(second).toBe(first)
|
||||
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const third = detectSandboxCapability()
|
||||
|
||||
expect(mockSpawnSync).toHaveBeenCalledTimes(2)
|
||||
expect(third).toEqual(first)
|
||||
})
|
||||
|
||||
it('resolves a relative MSB_PATH against PATH to one absolute executable before probing the version', async () => {
|
||||
const { mkdtempSync, writeFileSync, rmSync } = await vi.importActual<typeof import('fs')>('fs')
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-bin-'))
|
||||
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = fakeBin
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
|
||||
'../../../src/services/sandbox/capability'
|
||||
)
|
||||
const { spawnSync } = await import('child_process')
|
||||
const { accessSync } = await import('fs')
|
||||
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation(() => {})
|
||||
;(spawnSync as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(true)
|
||||
expect(spawnSync).toHaveBeenCalledWith(
|
||||
path.join(fakeBin, 'msb'),
|
||||
['--version'],
|
||||
expect.objectContaining({ encoding: 'utf8' }),
|
||||
)
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('reports unavailable when a relative MSB_PATH cannot be resolved on PATH', async () => {
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = '/nonexistent-ocm-bin'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { detectSandboxCapability, resetSandboxCapabilityCache } = await import(
|
||||
'../../../src/services/sandbox/capability'
|
||||
)
|
||||
const { spawnSync } = await import('child_process')
|
||||
const { accessSync } = await import('fs')
|
||||
;(accessSync as ReturnType<typeof vi.fn>).mockImplementation((target: string) => {
|
||||
if (target === '/dev/kvm') return
|
||||
throw new Error('ENOENT')
|
||||
})
|
||||
;(spawnSync as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0, stdout: 'msb 0.3.1\n', stderr: '' })
|
||||
resetSandboxCapabilityCache()
|
||||
|
||||
const result = detectSandboxCapability()
|
||||
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.reason).toBe('msb CLI not found or not executable')
|
||||
expect(spawnSync).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,616 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
SANDBOX_UNAVAILABLE_PREFIX,
|
||||
buildBlockedCommand,
|
||||
buildCanonicalSandboxSpec,
|
||||
buildSandboxCreateArgs,
|
||||
buildSandboxInspectArgs,
|
||||
buildSandboxListArgs,
|
||||
buildSandboxRemoveArgs,
|
||||
buildSandboxStartArgs,
|
||||
buildSandboxStopManagedArgs,
|
||||
buildSandboxVersionArgs,
|
||||
quoteForShell,
|
||||
resolveExpectedSandboxNetworkPolicy,
|
||||
resolveSandboxExecUser,
|
||||
resolveSandboxExecUserUid,
|
||||
sandboxMountRoots,
|
||||
sandboxNetworkPolicyMismatch,
|
||||
sandboxSecretMaskPath,
|
||||
} from '../../../src/services/sandbox/command'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('sandbox command builders', () => {
|
||||
it('builds the version probe as exactly --version', () => {
|
||||
expect(buildSandboxVersionArgs()).toEqual(['--version'])
|
||||
})
|
||||
|
||||
it('builds inspect args targeting the shared workspace sandbox with JSON output', () => {
|
||||
expect(buildSandboxInspectArgs()).toEqual(['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json'])
|
||||
})
|
||||
|
||||
it('builds remove args that force-remove the shared workspace sandbox', () => {
|
||||
expect(buildSandboxRemoveArgs()).toEqual(['rm', '--force', WORKSPACE_SANDBOX_NAME])
|
||||
})
|
||||
|
||||
it('builds list args that emit machine-readable JSON for all sandboxes', () => {
|
||||
expect(buildSandboxListArgs()).toEqual(['ls', '--format', 'json'])
|
||||
})
|
||||
|
||||
it('builds start args targeting the shared workspace sandbox', () => {
|
||||
expect(buildSandboxStartArgs()).toEqual(['start', WORKSPACE_SANDBOX_NAME])
|
||||
})
|
||||
|
||||
it('builds managed-stop args that filter by the ocm.managed label', () => {
|
||||
expect(buildSandboxStopManagedArgs()).toEqual(['stop', '--label', 'ocm.managed=true'])
|
||||
})
|
||||
|
||||
it('escapes embedded single quotes so values survive a shell round-trip', () => {
|
||||
const value = "echo 'a'b'"
|
||||
expect(quoteForShell(value)).toBe(`'echo '\\''a'\\''b'\\'''`)
|
||||
|
||||
const result = spawnSync('sh', ['-c', `printf '%s' ${quoteForShell(value)}`], { encoding: 'utf8' })
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe(value)
|
||||
})
|
||||
|
||||
it('builds create args with exactly two identical-path bind mounts and the detached flag', () => {
|
||||
const args = buildSandboxCreateArgs()
|
||||
|
||||
expect(args[0]).toBe('run')
|
||||
expect(args).toContain('-d')
|
||||
expect(args).toContain('--name')
|
||||
expect(args[args.indexOf('--name') + 1]).toBe(WORKSPACE_SANDBOX_NAME)
|
||||
expect(args[args.indexOf('-w') + 1]).toBe(getReposPath())
|
||||
expect(args[args.indexOf('-u') + 1]).toBe(resolveSandboxExecUser())
|
||||
|
||||
const labelArgs: string[] = []
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const value = args[i + 1]
|
||||
if (args[i] === '--label' && value !== undefined) {
|
||||
labelArgs.push(value)
|
||||
}
|
||||
}
|
||||
expect(labelArgs).toContain('ocm.managed=true')
|
||||
expect(labelArgs).toContain(`ocm.net=${ENV.SANDBOX.NET}`)
|
||||
|
||||
const mountArgs: string[] = []
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const value = args[i + 1]
|
||||
if (args[i] === '--mount-dir' && value !== undefined) {
|
||||
mountArgs.push(value)
|
||||
}
|
||||
}
|
||||
expect(mountArgs).toEqual(sandboxMountRoots().map((root) => `${root}:${root}`))
|
||||
expect(mountArgs[0]).toBe(`${getReposPath()}:${getReposPath()}`)
|
||||
expect(mountArgs[1]).toBe(`${getScheduleWorktreesPath()}:${getScheduleWorktreesPath()}`)
|
||||
})
|
||||
|
||||
it('masks the assistant .opencode directory with a tmpfs overlay', () => {
|
||||
const args = buildSandboxCreateArgs()
|
||||
|
||||
expect(args[args.indexOf('--tmpfs') + 1]).toBe(getAssistantOpenCodeDir())
|
||||
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
|
||||
})
|
||||
|
||||
it('never mounts the SSH/config/state workspace directories', () => {
|
||||
const joined = buildSandboxCreateArgs().join(' ')
|
||||
const workspacePath = path.dirname(getReposPath())
|
||||
|
||||
expect(joined).not.toContain(`${workspacePath}/.config`)
|
||||
expect(joined).not.toContain(`${workspacePath}/config`)
|
||||
expect(joined).not.toContain('auth.json')
|
||||
expect(joined).not.toContain(`${workspacePath}/.opencode`)
|
||||
expect(joined).not.toContain('/.opencode/state')
|
||||
})
|
||||
|
||||
it('derives a canonical spec from the create args matching the security configuration', () => {
|
||||
const spec = buildCanonicalSandboxSpec()
|
||||
const labels = spec.labels as Record<string, string>
|
||||
const resources = spec.resources as Record<string, number>
|
||||
const runtime = spec.runtime as Record<string, unknown>
|
||||
const mounts = spec.mounts as Array<Record<string, unknown>>
|
||||
const network = spec.network as Record<string, unknown>
|
||||
const lifecycle = spec.lifecycle as Record<string, unknown>
|
||||
|
||||
expect(spec.name).toBe(WORKSPACE_SANDBOX_NAME)
|
||||
const canonicalImage = spec.image as Record<string, { reference: string } | undefined>
|
||||
expect(canonicalImage.Oci?.reference).toBe(ENV.SANDBOX.IMAGE)
|
||||
expect(labels['ocm.managed']).toBe('true')
|
||||
expect(labels['ocm.net']).toBe(ENV.SANDBOX.NET)
|
||||
expect(resources.cpus).toBe(ENV.SANDBOX.CPUS)
|
||||
expect(typeof resources.memory_mib).toBe('number')
|
||||
expect(runtime.workdir).toBe(getReposPath())
|
||||
expect(runtime.user).toBe(resolveSandboxExecUser())
|
||||
expect(runtime.cmd).toEqual(['sleep', 'infinity'])
|
||||
expect(runtime.entrypoint).toBeNull()
|
||||
expect(spec.patches).toEqual([])
|
||||
expect(network.enabled).toBe(true)
|
||||
expect(network.ports).toEqual([])
|
||||
expect(lifecycle.ephemeral).toBe(false)
|
||||
expect(lifecycle.max_duration_secs).toBeNull()
|
||||
expect(lifecycle.idle_timeout_secs).toBeNull()
|
||||
|
||||
const binds = mounts.filter((mount) => mount.type === 'Bind')
|
||||
expect(binds).toHaveLength(2)
|
||||
expect(binds.map((mount) => mount.host)).toEqual([getReposPath(), getScheduleWorktreesPath()])
|
||||
for (const mount of binds) {
|
||||
expect(mount.guest).toBe(mount.host)
|
||||
const options = mount.options as Record<string, boolean>
|
||||
expect(options.readonly).toBe(false)
|
||||
expect(options.noexec).toBe(false)
|
||||
expect(options.nosuid).toBe(false)
|
||||
expect(options.nodev).toBe(false)
|
||||
expect(mount.stat_virtualization).toBe('strict')
|
||||
expect(mount.host_permissions).toBe('private')
|
||||
expect(mount.follow_root_symlinks).toBe(false)
|
||||
expect(mount.quota_mib).toBeNull()
|
||||
}
|
||||
|
||||
const tmpfs = mounts.find((mount) => mount.type === 'Tmpfs')
|
||||
expect(tmpfs?.guest).toBe(getAssistantOpenCodeDir())
|
||||
expect((tmpfs as Record<string, unknown>).size_mib).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts real repo dirs and schedule worktrees while rejecting config, missing, and unrelated paths', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-roots-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'repos')
|
||||
const schedules = path.join(tmp, 'schedule-worktrees')
|
||||
mkdirSync(path.join(repos, 'org', 'repo', 'subdir'), { recursive: true })
|
||||
mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true })
|
||||
mkdirSync(path.join(tmp, '.config', 'opencode'), { recursive: true })
|
||||
|
||||
process.env.WORKSPACE_PATH = tmp
|
||||
const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
await expect(resolveSandboxWorkDirectory(repos)).resolves.toBe(repos)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'org', 'repo', 'subdir'))).resolves.toBe(
|
||||
path.join(repos, 'org', 'repo', 'subdir'),
|
||||
)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(schedules, 'job-1-run-2'))).resolves.toBe(
|
||||
path.join(schedules, 'job-1-run-2'),
|
||||
)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, '..', '.config', 'opencode'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(`${repos}-extra`)).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'missing'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory('/etc')).resolves.toBeNull()
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns canonical guest paths for symlinks inside the roots and null for escapes', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-escape-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'repos')
|
||||
const schedules = path.join(tmp, 'schedule-worktrees')
|
||||
mkdirSync(path.join(tmp, 'outside'), { recursive: true })
|
||||
mkdirSync(path.join(repos, 'repo'), { recursive: true })
|
||||
mkdirSync(path.join(repos, 'other-repo'), { recursive: true })
|
||||
mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true })
|
||||
symlinkSync(path.join(tmp, 'outside'), path.join(repos, 'repo', 'escape'))
|
||||
symlinkSync(path.join(repos, 'other-repo'), path.join(repos, 'repo', 'inside-link'))
|
||||
symlinkSync(path.join(schedules, 'job-1-run-2'), path.join(repos, 'repo', 'cross-root-link'))
|
||||
|
||||
process.env.WORKSPACE_PATH = tmp
|
||||
const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo'))).resolves.toBe(path.join(repos, 'repo'))
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape', 'nested'))).resolves.toBeNull()
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'inside-link'))).resolves.toBe(
|
||||
path.join(repos, 'other-repo'),
|
||||
)
|
||||
await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'cross-root-link'))).resolves.toBe(
|
||||
path.join(schedules, 'job-1-run-2'),
|
||||
)
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('targets the shared sandbox with a per-command working directory and a verbatim guest payload', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-'))
|
||||
const msbPath = path.join(fakeBin, 'msb')
|
||||
const captureFile = path.join(fakeBin, 'payload.txt')
|
||||
writeFileSync(
|
||||
msbPath,
|
||||
[
|
||||
'#!/bin/sh',
|
||||
'payload=""',
|
||||
'prev=""',
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
|
||||
' prev="$arg"',
|
||||
'done',
|
||||
`printf '%s' "$payload" > "${captureFile}"`,
|
||||
'sh -c "$payload"',
|
||||
].join('\n'),
|
||||
{ mode: 0o755 },
|
||||
)
|
||||
process.env.MSB_PATH = msbPath
|
||||
try {
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { buildSandboxExecCommandString, resolveSandboxExecUser } = mod
|
||||
|
||||
const directory = path.join(getReposPath(), 'foo')
|
||||
const command = 'echo "it\'s a test" && echo line2 | tr a-z A-Z\necho after-newline'
|
||||
const exec = buildSandboxExecCommandString(directory, command)
|
||||
|
||||
expect(exec).toBe(
|
||||
`${quoteForShell(msbPath)} exec ${WORKSPACE_SANDBOX_NAME} --no-tty -q -u ${quoteForShell(resolveSandboxExecUser())} -w ${quoteForShell(directory)} --timeout ${Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)}s -- sh -c ${quoteForShell(command)}`,
|
||||
)
|
||||
|
||||
const result = spawnSync('sh', ['-c', exec], {
|
||||
encoding: 'utf8',
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe("it's a test\nLINE2\nafter-newline\n")
|
||||
expect(readFileSync(captureFile, 'utf8')).toBe(command)
|
||||
} finally {
|
||||
delete process.env.MSB_PATH
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('passes MSB_PATH and the resolved exec identity to msb as single literal arguments', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-hostile-'))
|
||||
const captureFile = path.join(fakeBin, 'argv.txt')
|
||||
const msbPath = path.join(fakeBin, 'my msb')
|
||||
const hostileUser = 'node; echo hacked'
|
||||
writeFileSync(
|
||||
msbPath,
|
||||
[
|
||||
'#!/bin/sh',
|
||||
`printf '%s\\n' "$0" "$@" > "${captureFile}"`,
|
||||
'payload=""',
|
||||
'prev=""',
|
||||
'for arg in "$@"; do',
|
||||
' if [ "$prev" = "-c" ]; then payload="$arg"; fi',
|
||||
' prev="$arg"',
|
||||
'done',
|
||||
'sh -c "$payload"',
|
||||
].join('\n'),
|
||||
{ mode: 0o755 },
|
||||
)
|
||||
|
||||
try {
|
||||
process.env.MSB_PATH = msbPath
|
||||
process.env.SANDBOX_EXEC_USER = hostileUser
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { buildSandboxExecCommandString, resolveSandboxExecUser } = mod
|
||||
|
||||
const directory = path.join(getReposPath(), 'foo')
|
||||
const command = 'echo hostile-ok'
|
||||
const exec = buildSandboxExecCommandString(directory, command)
|
||||
|
||||
const result = spawnSync('sh', ['-c', exec], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH ?? ''}` },
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe('hostile-ok\n')
|
||||
|
||||
const resolvedUser = resolveSandboxExecUser()
|
||||
expect(resolvedUser).toMatch(/^\d+:\d+$/)
|
||||
|
||||
const argv = readFileSync(captureFile, 'utf8').split('\n')
|
||||
expect(argv[0]).toBe(msbPath)
|
||||
expect(argv[argv.indexOf('-u') + 1]).toBe(resolvedUser)
|
||||
expect(argv[argv.indexOf('-w') + 1]).toBe(directory)
|
||||
expect(argv[argv.indexOf('-c') + 1]).toBe(command)
|
||||
expect(argv.join(' ')).not.toContain(hostileUser)
|
||||
} finally {
|
||||
delete process.env.MSB_PATH
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves the named exec user default to the manager uid:gid', () => {
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
|
||||
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
|
||||
|
||||
expect(resolveSandboxExecUser()).toBe('1001:1002')
|
||||
expect(resolveSandboxExecUserUid()).toBe(1001)
|
||||
})
|
||||
|
||||
it('aligns a numeric exec user with the manager gid', async () => {
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
|
||||
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
|
||||
process.env.SANDBOX_EXEC_USER = '1001'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command')
|
||||
expect(resolveSandboxExecUser()).toBe('1001:1002')
|
||||
} finally {
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps an explicit uid:gid exec user verbatim', async () => {
|
||||
process.env.SANDBOX_EXEC_USER = '1000:1000'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command')
|
||||
expect(resolveSandboxExecUser()).toBe('1000:1000')
|
||||
} finally {
|
||||
delete process.env.SANDBOX_EXEC_USER
|
||||
}
|
||||
})
|
||||
|
||||
it('builds a blocked command that exits non-zero and writes the reason to stderr', () => {
|
||||
const reason = "KVM is unavailable (it's not a hypervisor host)"
|
||||
const command = buildBlockedCommand(reason)
|
||||
const message = `${SANDBOX_UNAVAILABLE_PREFIX}${reason}`
|
||||
|
||||
expect(SANDBOX_UNAVAILABLE_PREFIX).toBe('Sandbox enforcement is on but the sandbox is unavailable: ')
|
||||
expect(command).toBe(`printf '%s\n' ${quoteForShell(message)} >&2; exit 1`)
|
||||
|
||||
const result = spawnSync('sh', ['-c', command], { encoding: 'utf8' })
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toBe(`${message}\n`)
|
||||
expect(result.stdout).toBe('')
|
||||
})
|
||||
|
||||
it('resolves a relative MSB_PATH to one absolute executable found on PATH', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-resolve-'))
|
||||
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = fakeBin
|
||||
try {
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = mod
|
||||
|
||||
expect(resolveSandboxExecutable()).toBe(path.join(fakeBin, 'msb'))
|
||||
expect(sandboxExecutablePath()).toBe(path.join(fakeBin, 'msb'))
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns null when a relative MSB_PATH has no executable candidate on PATH', async () => {
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = '/nonexistent-ocm-bin'
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
}
|
||||
})
|
||||
|
||||
it('returns an absolute MSB_PATH verbatim without consulting PATH', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-abs-'))
|
||||
const msbPath = path.join(fakeBin, 'my msb')
|
||||
writeFileSync(msbPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
process.env.MSB_PATH = msbPath
|
||||
try {
|
||||
vi.resetModules()
|
||||
const mod = await import('../../../src/services/sandbox/command')
|
||||
mod.overrideSandboxExecutableTrustValidator(() => true)
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = mod
|
||||
|
||||
expect(resolveSandboxExecutable()).toBe(msbPath)
|
||||
expect(sandboxExecutablePath()).toBe(msbPath)
|
||||
} finally {
|
||||
delete process.env.MSB_PATH
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an msb executable located inside a mounted project root', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-mount-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
const originalPath = process.env.PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'workspace', 'repos')
|
||||
mkdirSync(path.join(repos, 'bin'), { recursive: true })
|
||||
writeFileSync(path.join(repos, 'bin', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
|
||||
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
|
||||
process.env.PATH = path.join(repos, 'bin')
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
process.env.PATH = originalPath
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an msb executable whose symlink resolves into a mounted project root', async () => {
|
||||
const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-symlink-'))
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
const originalPath = process.env.PATH
|
||||
try {
|
||||
const repos = path.join(tmp, 'workspace', 'repos')
|
||||
const bin = path.join(tmp, 'bin')
|
||||
mkdirSync(path.join(repos, 'evil'), { recursive: true })
|
||||
mkdirSync(bin)
|
||||
writeFileSync(path.join(repos, 'evil', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
symlinkSync(path.join(repos, 'evil', 'msb'), path.join(bin, 'msb'))
|
||||
|
||||
process.env.WORKSPACE_PATH = path.join(tmp, 'workspace')
|
||||
process.env.PATH = bin
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
if (originalWorkspacePath === undefined) {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
} else {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
}
|
||||
process.env.PATH = originalPath
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an msb executable writable by the manager user or a parent directory', async () => {
|
||||
const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-writable-'))
|
||||
writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
const originalPath = process.env.PATH
|
||||
process.env.PATH = fakeBin
|
||||
try {
|
||||
vi.resetModules()
|
||||
const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command')
|
||||
|
||||
expect(resolveSandboxExecutable()).toBeNull()
|
||||
expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH)
|
||||
} finally {
|
||||
process.env.PATH = originalPath
|
||||
rmSync(fakeBin, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('sandbox network policy attestation helpers', () => {
|
||||
const publicPolicy = {
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
}
|
||||
|
||||
it('resolves the public profile to the deny-by-default fixture policy', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public')).toEqual(publicPolicy)
|
||||
})
|
||||
|
||||
it('composes comma-separated profiles with a single DNS rule in profile order', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public,private,host')).toEqual({
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' },
|
||||
{ direction: 'egress', destination: { group: 'host' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('deduplicates repeated profiles', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public, public')).toEqual(publicPolicy)
|
||||
})
|
||||
|
||||
it('returns null for terminal, unknown, or empty profiles', () => {
|
||||
expect(resolveExpectedSandboxNetworkPolicy('all')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy('none')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy('public,unknown')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy('')).toBeNull()
|
||||
expect(resolveExpectedSandboxNetworkPolicy(' ')).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts the source-faithful public policy fixture', () => {
|
||||
expect(sandboxNetworkPolicyMismatch(publicPolicy, resolveExpectedSandboxNetworkPolicy('public')!)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a policy with an allow-all wildcard rule', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [
|
||||
publicPolicy.rules[0],
|
||||
{ direction: 'egress', destination: { any: true }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects a policy whose profile rule is broadened to specific protocols and ports', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [
|
||||
publicPolicy.rules[0],
|
||||
{ direction: 'egress', destination: { group: 'public' }, protocols: ['tcp'], ports: [443], action: 'allow' },
|
||||
],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects a policy carrying stale rules from another profile', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [
|
||||
...publicPolicy.rules,
|
||||
{ direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' },
|
||||
],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects a policy missing a required rule', () => {
|
||||
const inspected = {
|
||||
...publicPolicy,
|
||||
rules: [publicPolicy.rules[0]],
|
||||
}
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy')
|
||||
})
|
||||
|
||||
it('rejects an allow egress default with an unrestricted-egress reason', () => {
|
||||
const inspected = { default_egress: 'allow', default_ingress: 'allow', rules: [] }
|
||||
const mismatch = sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)
|
||||
expect(mismatch).toContain('unrestricted egress')
|
||||
})
|
||||
|
||||
it('rejects an altered ingress default', () => {
|
||||
const inspected = { ...publicPolicy, default_ingress: 'deny' }
|
||||
expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('default_ingress')
|
||||
})
|
||||
|
||||
it('rejects a missing or malformed policy', () => {
|
||||
const expected = resolveExpectedSandboxNetworkPolicy('public')!
|
||||
expect(sandboxNetworkPolicyMismatch(undefined, expected)).toContain('missing or malformed')
|
||||
expect(sandboxNetworkPolicyMismatch({ default_egress: 'deny' }, expected)).toContain('missing or malformed')
|
||||
expect(sandboxNetworkPolicyMismatch({ ...publicPolicy, rules: 'not-an-array' }, expected)).toContain('missing or malformed')
|
||||
expect(sandboxNetworkPolicyMismatch(
|
||||
{ ...publicPolicy, rules: [{ direction: 'egress', destination: { group: 'dns' }, action: 'allow' }] },
|
||||
expected,
|
||||
)).toContain('network policy')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { DEFAULT_USER_PREFERENCES, UserPreferencesSchema } from '@opencode-manager/shared/schemas'
|
||||
|
||||
describe('sandbox config', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.SANDBOX_IMAGE
|
||||
})
|
||||
|
||||
it('defaults sandbox.enabled to false in the persisted preference contract', () => {
|
||||
const prefs = UserPreferencesSchema.parse(DEFAULT_USER_PREFERENCES)
|
||||
expect(prefs.sandbox?.enabled).toBe(false)
|
||||
})
|
||||
|
||||
it('round-trips sandbox.enabled when set to true', () => {
|
||||
const prefs = UserPreferencesSchema.parse({
|
||||
...DEFAULT_USER_PREFERENCES,
|
||||
sandbox: { enabled: true },
|
||||
})
|
||||
expect(prefs.sandbox).toEqual({ enabled: true })
|
||||
})
|
||||
|
||||
it('falls back ENV.SANDBOX.IMAGE to the default when SANDBOX_IMAGE is unset', async () => {
|
||||
delete process.env.SANDBOX_IMAGE
|
||||
vi.resetModules()
|
||||
const { ENV } = await import('@opencode-manager/shared/config/env')
|
||||
const { DEFAULTS } = await import('@opencode-manager/shared/config/defaults')
|
||||
expect(ENV.SANDBOX.IMAGE).toBe(DEFAULTS.SANDBOX.IMAGE)
|
||||
})
|
||||
|
||||
it('honors SANDBOX_IMAGE when set before module import', async () => {
|
||||
process.env.SANDBOX_IMAGE = 'node:22-alpine'
|
||||
vi.resetModules()
|
||||
const { ENV } = await import('@opencode-manager/shared/config/env')
|
||||
expect(ENV.SANDBOX.IMAGE).toBe('node:22-alpine')
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'
|
||||
import { execSync } from 'child_process'
|
||||
import { mkdtempSync, existsSync, mkdirSync, writeFileSync } from 'fs'
|
||||
import { mkdtempSync, existsSync, mkdirSync, writeFileSync, symlinkSync, unlinkSync, rmSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import path from 'path'
|
||||
import { rm } from 'fs/promises'
|
||||
@@ -20,6 +20,14 @@ vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
const opencodeServerManagerMock = vi.hoisted(() => ({
|
||||
isSandboxEnforced: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: opencodeServerManagerMock,
|
||||
}))
|
||||
|
||||
describe('buildRepoEnvForRepo', () => {
|
||||
it('includes OCM_GIT_REPO_ID and OCM_GIT_REPO_CWD when id is provided', async () => {
|
||||
const { buildRepoEnvForRepo } = await import('../../src/services/schedule-worktree')
|
||||
@@ -85,6 +93,10 @@ describe('ScheduleWorktreeManager', () => {
|
||||
authenticateMcp: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(false)
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
tmpDir = mkdtempSync(path.join(tmpdir(), 'schedule-worktree-test-'))
|
||||
tmpRoot = tmpDir
|
||||
@@ -335,6 +347,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
branch: null,
|
||||
})
|
||||
mockOpenCodeClient.postJson = mockPost
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
@@ -366,6 +379,116 @@ describe('ScheduleWorktreeManager', () => {
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('prepare falls back to raw git when the workspace directory is outside the sandboxed project roots', async () => {
|
||||
const workspaceId = 'ws-outside-456'
|
||||
const outsideDirectory = path.join(path.dirname(tmpDir), 'ocm-outside-workspace')
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: outsideDirectory,
|
||||
branch: null,
|
||||
})
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
|
||||
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
mockOpenCodeClient.forward = deleteMock
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 31, branch: null }
|
||||
const runId = 6
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.worktreePath).toBe(path.join(scheduleWorktreesRoot, 'job-31-run-6'))
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
expect(deleteMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${workspaceId}`,
|
||||
}),
|
||||
)
|
||||
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
it('uses an OpenCode workspace outside the mount roots as-is when sandboxing is not enforced', async () => {
|
||||
const outsideDirectory = path.join(path.dirname(tmpDir), 'ocm-off-workspace')
|
||||
const workspaceId = 'ws-off-123'
|
||||
execSync(`git -C "${baseRepoPath}" worktree add --detach "${outsideDirectory}" origin/main`, { env })
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: outsideDirectory,
|
||||
branch: null,
|
||||
})
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 32, branch: null }
|
||||
const runId = 1
|
||||
|
||||
try {
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
expect(ctx!.directory).toBe(outsideDirectory)
|
||||
|
||||
const branch = execSync(`git -C "${outsideDirectory}" rev-parse --abbrev-ref HEAD`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branch).toBe('schedule/32/run-1')
|
||||
} finally {
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, outsideDirectory).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to raw git when an enforced workspace directory is a symlink escaping the project roots', async () => {
|
||||
const escapeTarget = path.join(path.dirname(tmpDir), 'ocm-escape-target')
|
||||
const escapeLink = path.join(tmpDir, 'ocm-escape-link')
|
||||
mkdirSync(escapeTarget, { recursive: true })
|
||||
symlinkSync(escapeTarget, escapeLink)
|
||||
|
||||
const workspaceId = 'ws-escape-999'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: escapeLink,
|
||||
branch: null,
|
||||
})
|
||||
opencodeServerManagerMock.isSandboxEnforced.mockReturnValue(true)
|
||||
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
mockOpenCodeClient.forward = deleteMock
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 33, branch: null }
|
||||
const runId = 1
|
||||
|
||||
try {
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.worktreePath).toBe(path.join(scheduleWorktreesRoot, 'job-33-run-1'))
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
expect(deleteMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${workspaceId}`,
|
||||
}),
|
||||
)
|
||||
} finally {
|
||||
unlinkSync(escapeLink)
|
||||
rmSync(escapeTarget, { recursive: true, force: true })
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, path.join(scheduleWorktreesRoot, 'job-33-run-1')).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
it('prepare falls back to raw git when postJson rejects', async () => {
|
||||
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('API unavailable'))
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { executeCommand } from '../../src/utils/process'
|
||||
|
||||
describe('executeCommand signal handling', () => {
|
||||
it('reports a signal-terminated child as a non-zero exit code when exit codes are ignored', async () => {
|
||||
const result = await executeCommand(['sh', '-c', 'kill -KILL $$'], {
|
||||
ignoreExitCode: true,
|
||||
silent: true,
|
||||
})
|
||||
const structured = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
expect(structured.exitCode).not.toBe(0)
|
||||
expect(structured.stderr).toContain('Command terminated by signal SIGKILL')
|
||||
})
|
||||
|
||||
it('rejects a signal-terminated child when exit codes are enforced', async () => {
|
||||
await expect(executeCommand(['sh', '-c', 'kill -KILL $$'], { silent: true })).rejects.toThrow(
|
||||
'Command failed with signal SIGKILL',
|
||||
)
|
||||
})
|
||||
|
||||
it('resolves a zero exit code as success when exit codes are ignored', async () => {
|
||||
const result = await executeCommand(['sh', '-c', 'true'], { ignoreExitCode: true, silent: true })
|
||||
|
||||
expect(result).toEqual({ exitCode: 0, stdout: '', stderr: '' })
|
||||
})
|
||||
})
|
||||
@@ -17,6 +17,7 @@ export default defineConfig({
|
||||
'test/routes/internal-notifications.test.ts',
|
||||
'test/routes/internal-settings.test.ts',
|
||||
'test/routes/internal-repos.test.ts',
|
||||
'test/routes/internal-sandbox.test.ts',
|
||||
'src/db/model-state.test.ts',
|
||||
'src/routes/providers.test.ts',
|
||||
'src/routes/repos.test.ts',
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Agent Sandboxing overlay (microsandbox / msb)
|
||||
# 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
|
||||
|
||||
services:
|
||||
app:
|
||||
privileged: true
|
||||
devices:
|
||||
- "/dev/kvm:/dev/kvm"
|
||||
environment:
|
||||
- SANDBOX_IMAGE=${SANDBOX_IMAGE:-node:24}
|
||||
- SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G}
|
||||
- SANDBOX_CPUS=${SANDBOX_CPUS:-2}
|
||||
- SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}}
|
||||
- SANDBOX_NET=${SANDBOX_NET:-public}
|
||||
- SANDBOX_START_TIMEOUT_MS=${SANDBOX_START_TIMEOUT_MS:-300000}
|
||||
- SANDBOX_EXEC_TIMEOUT_MS=${SANDBOX_EXEC_TIMEOUT_MS:-600000}
|
||||
volumes:
|
||||
- microsandbox-data:/home/node/.microsandbox
|
||||
|
||||
volumes:
|
||||
microsandbox-data:
|
||||
driver: local
|
||||
@@ -295,6 +295,44 @@ Why the repo mount uses the host path as the container path:
|
||||
|
||||
With a fresh Docker volume, first startup imports the host OpenCode config and state, and after you add `${OCM_REPOS_HOST_PATH}` in the Manager UI, previously existing chats appear under the discovered repositories.
|
||||
|
||||
## Agent Sandboxing Overlay
|
||||
|
||||
Optional KVM-backed agent sandboxing (see [Agent Sandboxing](../features/sandboxing.md)). The sandbox overlay (`docker-compose.sandbox.yml`) grants the container KVM access, passes sandbox tuning through from `.env`, and persists microsandbox state:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
privileged: true
|
||||
devices:
|
||||
- "/dev/kvm:/dev/kvm"
|
||||
environment:
|
||||
- SANDBOX_IMAGE=${SANDBOX_IMAGE:-node:24}
|
||||
- SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G}
|
||||
- SANDBOX_CPUS=${SANDBOX_CPUS:-2}
|
||||
- SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}}
|
||||
- SANDBOX_NET=${SANDBOX_NET:-public}
|
||||
- SANDBOX_START_TIMEOUT_MS=${SANDBOX_START_TIMEOUT_MS:-300000}
|
||||
- SANDBOX_EXEC_TIMEOUT_MS=${SANDBOX_EXEC_TIMEOUT_MS:-600000}
|
||||
volumes:
|
||||
- microsandbox-data:/home/node/.microsandbox
|
||||
|
||||
volumes:
|
||||
microsandbox-data:
|
||||
driver: local
|
||||
```
|
||||
|
||||
Start the Manager with the overlay:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
|
||||
```
|
||||
|
||||
The overlay requires a Linux host with `/dev/kvm`. Docker Desktop on macOS and Windows cannot provide `/dev/kvm`, so the sandbox toggle in Settings stays disabled there.
|
||||
|
||||
`SANDBOX_EXEC_USER` defaults to the numeric `PUID` (falling back to `1000`), and the Manager runs every sandboxed command as that numeric uid (with the Manager's gid). Because the entrypoint realigns the container's `node` account to `PUID`/`PGID` and re-owns `/workspace`, a non-1000 `PUID` (for example `PUID=1001`) writes to the mounted repositories with the same identity as the workspace owner. If a configured `SANDBOX_EXEC_USER` cannot match the workspace owner, the toggle reports enforcement as unavailable instead of running broken commands.
|
||||
|
||||
The `microsandbox-data` volume persists microsandbox's own state (downloaded images, firmware cache) across container recreations, alongside the workspace and data volumes.
|
||||
|
||||
## Health Checks
|
||||
|
||||
The container includes health checks:
|
||||
@@ -444,6 +482,9 @@ By default, the OpenCode server binds to `127.0.0.1` inside the container and is
|
||||
|
||||
You only need to expose the OpenCode server on an external interface if you have a specific use case that requires other services or machines to connect directly to it.
|
||||
|
||||
!!! warning "Sandbox enforcement is proxy-scoped"
|
||||
Part of agent-sandboxing enforcement — the blocked session-shell/PTY/slash-command endpoints and config-mutation sanitization — is applied by the Manager's OpenCode proxy on port 5003, not by the OpenCode server itself. The `bash` tool rewrite, by contrast, runs as a plugin hook inside the OpenCode process, so it still guards direct connections to the OpenCode server. While sandboxing is enforced the Manager forces the OpenCode server to bind loopback, so external clients cannot reach the OpenCode port directly and bypass the proxy-applied endpoint blocking and config sanitization; exposing port `5551:5551` is only effective with sandboxing disabled (see [Agent Sandboxing](../features/sandboxing.md)).
|
||||
|
||||
### How to Expose Safely
|
||||
|
||||
To expose the OpenCode server on the host network:
|
||||
@@ -475,4 +516,4 @@ The password can be configured in two ways:
|
||||
|
||||
### Startup Guard
|
||||
|
||||
If you set `OPENCODE_HOST=0.0.0.0` (or any non-localhost host) without configuring a password (either via env var or UI), the managed OpenCode server will refuse to start with an error message explaining how to fix it. The OpenCode Manager UI/API may remain available so you can configure a password and restart the managed server.
|
||||
If you set `OPENCODE_HOST=0.0.0.0` (or any non-localhost host) without configuring a password (either via env var or UI), the managed OpenCode server will refuse to start with an error message explaining how to fix it. The OpenCode Manager UI/API may remain available so you can configure a password and restart the managed server. (While agent sandboxing is enforced the server is forced onto a loopback bind regardless of `OPENCODE_HOST`, so this password guard is skipped — the server is not actually reachable externally.)
|
||||
@@ -108,6 +108,22 @@ When configured, users can enable push notifications in Settings → Notificatio
|
||||
| `OPENCODE_IMPORT_CONFIG_PATH` | Existing standalone OpenCode `opencode.json` to import on first startup | - |
|
||||
| `OPENCODE_IMPORT_STATE_PATH` | Existing standalone OpenCode state directory to import on first startup | - |
|
||||
|
||||
## Agent Sandboxing
|
||||
|
||||
Sandboxed agent commands run inside a microVM managed by `msb` (see [Agent Sandboxing](../features/sandboxing.md)). Requires a Linux host with `/dev/kvm` and the sandbox compose overlay.
|
||||
|
||||
| Variable | Description | Default |
|
||||
|----------|-------------|---------|
|
||||
| `MSB_PATH` | Path to the `msb` executable | `msb` |
|
||||
| `MSB_LIBKRUNFW_PATH` | Path to the `libkrunfw` firmware library used by `msb` (set in the container image) | `/opt/microsandbox/lib/libkrunfw.so` |
|
||||
| `SANDBOX_IMAGE` | OCI image the microVM boots from | `node:24` |
|
||||
| `SANDBOX_MEMORY` | MicroVM memory (e.g. `4G`) | `4G` |
|
||||
| `SANDBOX_CPUS` | MicroVM CPU count | `2` |
|
||||
| `SANDBOX_EXEC_USER` | Guest identity sandboxed commands run as: a numeric `uid`, a numeric `uid:gid`, or a guest username. A numeric uid must match the Manager's effective uid (`PUID`); the compose overlay defaults it to `${PUID:-1000}`. A guest username is resolved to the Manager's effective `uid:gid` so writes to the mounted project roots always succeed. When a configured numeric identity cannot write the workspace, enforcement is reported unavailable | `${PUID:-1000}` via the overlay, otherwise `node` |
|
||||
| `SANDBOX_NET` | Network mode for the microVM: `public`, `private`, or `host`, or a comma-separated composition (for example `public,host`). Passed to `msb run --net` and attested against the profile's canonical network policy | `public` |
|
||||
| `SANDBOX_START_TIMEOUT_MS` | Timeout for microVM startup, in milliseconds | `300000` |
|
||||
| `SANDBOX_EXEC_TIMEOUT_MS` | Timeout for a single sandboxed command, in milliseconds | `600000` |
|
||||
|
||||
## Timeouts
|
||||
|
||||
| Variable | Description | Default |
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
# Agent Sandboxing
|
||||
|
||||
Run agent shell commands inside an isolated microVM instead of directly in the Manager container. Sandboxing is a hardening option for untrusted agent code, not a per-project permission boundary.
|
||||
|
||||
## 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)).
|
||||
|
||||
## What Gets Sandboxed
|
||||
|
||||
Sandboxing hooks into the OpenCode `bash` tool, which is how agents execute shell commands. 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 |
|
||||
| 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 |
|
||||
| LSP server processes (`lsp` config, any enabling form) | Disabled while enforced |
|
||||
| Experimental hook commands (`experimental.hook` config) | Disabled while enforced |
|
||||
| Global custom tools (`<config>/opencode/tool(s)/`, `$HOME/.opencode/tool(s)/`) | Quarantined while enforced |
|
||||
| Manager-side git operations (`backend/src/services/repo.ts`) | No |
|
||||
| OpenCode `read` / `write` / `edit` file tools | No |
|
||||
|
||||
Manager-side git operations (clone, fetch, worktree creation, credential setup) run directly in the container so the Manager can manage repositories regardless of the sandbox setting. OpenCode's file tools keep operating on the host filesystem — the same files the microVM sees through its bind mounts — so editing a file and running a command against it behave exactly as they do without sandboxing.
|
||||
|
||||
## 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.
|
||||
|
||||
!!! 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.
|
||||
|
||||
## Host Requirements
|
||||
|
||||
Sandboxing requires KVM, which means a Linux host:
|
||||
|
||||
- The host must expose `/dev/kvm` to the container. Start the Manager with the sandbox overlay:
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
|
||||
```
|
||||
- Docker Desktop on macOS and Windows cannot provide `/dev/kvm`. On those platforms the sandbox toggle stays disabled and the Settings UI shows the reason.
|
||||
|
||||
Because enforcement requires KVM, it is inherently limited to Linux. On non-Linux hosts the enforced code path fails closed, and unenforced production operation tracks the OpenCode server as a direct child instead of relying on `/proc` process identity attestation, so starting the Manager in production mode on macOS keeps working with the sandbox toggle off.
|
||||
|
||||
If the host meets the requirements, the Settings UI displays the detected `msb` version; otherwise it shows why sandboxing is unavailable.
|
||||
|
||||
## Scope and Lifecycle
|
||||
|
||||
All projects share **one** microVM:
|
||||
|
||||
- The microVM is named `ocm-workspace` and is created detached (`msb run -d`), booted on the first sandboxed command, and reused for every subsequent command.
|
||||
- It mounts `/workspace/repos` and `/workspace/schedule-worktrees` at identical guest paths. This covers every repository, every repository worktree, the assistant-mode project (`repos/assistant`), and every schedule worktree.
|
||||
- The assistant-mode `.opencode` directory (`repos/assistant/.opencode`, which holds the internal API token plus the managed assistant skills and agents) is masked inside the microVM with a guest-memory `tmpfs` overlay. Guest shell processes see an empty directory there and cannot read the token, while OpenCode's host-side config and skill loading keeps operating on the real directory.
|
||||
- Because the mount roots are the two parent directories, repositories cloned and schedule worktrees created after the microVM booted are visible inside it immediately — there is nothing to remount.
|
||||
- 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
|
||||
```
|
||||
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.
|
||||
- Disabling sandboxing does not stop the microVM at toggle time: the stop runs when the OpenCode server restarts into the disabled state, so a background guest process cannot outlive an enforced-to-disabled restart. That stop is confirmed — it only completes once the managed microVM is listed as stopped or absent, and the restart fails closed if the VM cannot be confirmed stopped — and it is reversible: re-enabling sandboxing and restarting boots the microVM again.
|
||||
- Before reusing an existing `ocm-workspace` microVM, the Manager verifies it was created by the Manager: it must carry the `ocm.managed=true` label, boot from the configured `SANDBOX_IMAGE`, run with the configured CPUs/memory/workdir, keep networking enabled, mount exactly `/workspace/repos` and `/workspace/schedule-worktrees` as writable identical-path bind mounts, and carry exactly one tmpfs: the assistant `.opencode` mask. The effective network policy is also attested against the resolved policy of the configured `SANDBOX_NET` profile (`public`, `private`, `host`, or a comma-separated composition): the inspected `default_egress`/`default_ingress` and every rule must match the profile's canonical policy exactly, so a sandbox labelled with the configured profile that actually carries an allow-all rule, a rule broadened to specific protocols or ports, stale rules from another profile, or altered defaults is recreated rather than reused. Any named volume, disk image, extra tmpfs (including one masking a project root), extra bind mount (for example one exposing `/workspace/config`), or missing mask fails the check. An instance that fails any of these checks is force-removed and recreated from the centralized create arguments, so an unmanaged or stale instance is never started or used. The attestation parses the real `msb inspect --format json` contract of the pinned `msb` CLI (`MICROSANDBOX_VERSION`), which is tested against fixtures copied from that contract.
|
||||
|
||||
A session rooted outside the two mounted roots (for example `/workspace` itself) is refused with a clear error rather than silently escaping the sandbox.
|
||||
|
||||
## What Is Not Mounted
|
||||
|
||||
These host paths stay outside the microVM:
|
||||
|
||||
| Host path | Contents |
|
||||
|-----------|----------|
|
||||
| `/workspace/config` | SSH `known_hosts`, `ssh_config` |
|
||||
| `/workspace/.ssh-keys` | SSH private keys for repository access |
|
||||
| `/workspace/.config` | OpenCode configuration and generated plugins |
|
||||
| `/workspace/.opencode/state` | Provider credentials (`auth.json`) |
|
||||
| `repos/assistant/.opencode` (masked) | Assistant internal API token — hidden inside the microVM behind a `tmpfs` overlay |
|
||||
|
||||
The consequence: sandboxed commands cannot read Manager or provider secrets, and they cannot modify the OpenCode configuration or the installed plugins. The assistant-mode `.opencode` directory is bind-visible on the host for OpenCode's own config and skill loading, but inside the microVM it is replaced by an empty in-memory filesystem, so the internal API bearer token it contains is unreadable by guest shell code.
|
||||
|
||||
## Blast Radius
|
||||
|
||||
The microVM shares one kernel and one filesystem namespace across all projects. This boundary protects the Manager container and its secrets from agent code; it does **not** isolate one repository from another. Repositories remain mutually accessible inside the sandbox, exactly as they are on the host.
|
||||
|
||||
## Enabling and Enforcement Model
|
||||
|
||||
Enforcement follows this chain:
|
||||
|
||||
1. **Toggle** — Enable **Sandbox** in Settings. If `/dev/kvm` is unavailable the toggle cannot be turned on and the capability reason is shown; if the runtime later becomes unavailable while the preference stays enabled, the toggle remains turned on and every sandboxed command fails closed with the reason instead of running on the host.
|
||||
2. **Restart** — Changing the preference marks the OpenCode server restart as pending. The new enforcement value is only applied to newly spawned OpenCode processes, so a restart is required. When an enforced server starts, the Manager terminates the previous server's process group — the detached OpenCode child plus every host-process descendant it spawned, including a shell command or MCP process started while enforcement was off — waits for all members to exit, escalates to `SIGKILL` on the group if needed, and refuses to start the enforced server if any member survives, so no unenforced host-executed process can outlive the transition. Non-detached development children are terminated by PID only, preserving the existing hot-reload behavior.
|
||||
3. **Stamp** — On startup the Manager resolves the preference (not the runtime probe) and stamps every spawned OpenCode child environment with `OCM_SANDBOX_ENFORCED=true` whenever the preference is enabled. A missing or broken sandbox runtime therefore keeps enforcement active and blocks commands with the capability reason rather than silently running them on the host. If the preference itself cannot be read, the Manager fails closed the same way: it treats enforcement as active, terminates any attested predecessor and port-owning server so no unenforced child stays reachable, and aborts startup as non-recoverable with the settings error. User-defined environment variables cannot override this value.
|
||||
4. **OpenCode build** — Sandbox enforcement rewrites `bash` tool arguments through the plugin `tool.execute.before` hook, a behavior that depends on the OpenCode build. The container image ships a pinned OpenCode build (`1.18.16`), and the Manager refuses to start an enforced server unless the installed build is one of the versions verified by the black-box hook contract test (currently `1.18.16`), failing closed with a clear error instead of trusting an unverified build to run agent commands on the host. While enforcement is active (the persisted preference or a running enforced child), the Settings UI disables the Update action and the unverified rows in the Versions dialog, and the Manager rejects `POST /opencode-upgrade` and any unverified `POST /opencode-install-version` request, so the installed build can never be replaced with an unverified release; installing a verified version remains allowed. The container entrypoint also repairs a missing or below-minimum `opencode` by reinstalling the bundled build rather than the latest release.
|
||||
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:
|
||||
```
|
||||
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.
|
||||
|
||||
The enforcement value is stamped into the OpenCode child process at startup and is authoritative for its lifetime. The plugin reports that stamp to the planning endpoint, so an enforced child can never fall back to host execution — even if the toggle is turned off before the required restart, the running OpenCode server keeps executing sandboxed until it is restarted.
|
||||
|
||||
## Plugin Policy Under Enforcement
|
||||
|
||||
Plugins run as ordinary JavaScript inside the OpenCode process and can touch the host filesystem and process APIs without going through the `bash` tool, so sandbox enforcement must make sure that **only Manager-owned plugin code** is evaluated in the host process:
|
||||
|
||||
- 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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
One documented consequence: because project config files are disabled while enforcement is on, the assistant-mode workspace's project-level `opencode.json`, agents, and skills (under `repos/assistant/.opencode`) are not loaded for assistant sessions during enforcement. The assistant workspace directory and its `AGENTS.md` guidance still load, but its default agent and managed skills are unavailable until sandboxing is disabled and the server restarts.
|
||||
|
||||
## Worktree Placement
|
||||
|
||||
The Manager only creates agent worktrees under the two mounted roots, so every supported project plans in sandbox mode while the secret-bearing `.opencode/state` directory stays unmounted:
|
||||
|
||||
- **Scheduled runs** — OpenCode's experimental workspace API would place run worktrees beneath `.opencode/state`. The schedule runner detects that location, deletes the API workspace, and falls back to a raw git worktree under `/workspace/schedule-worktrees` (`job-<id>-run-<runId>`), which is mounted. A worktree returned by the API that already lives under a mounted root is used as-is.
|
||||
- **User-created OpenCode worktrees** — the same API creates these outside the mounted roots, so while sandboxing is enforced the Manager refuses the creation with a clear error instead of handing the session a directory that cannot be sandboxed. Disable sandboxing (and restart) to use them.
|
||||
- **Local repositories outside `/workspace/repos`** — external repositories are symlinked into `repos/`; the link target is not mounted, so an agent session in one of them is refused with the "outside the sandboxed project roots" error. Move the repository under `/workspace/repos` or disable sandboxing.
|
||||
|
||||
## Caveats
|
||||
|
||||
- **First-command latency** — The first sandboxed command after a container start pays the image pull and microVM boot cost once for all projects. This is bounded by `SANDBOX_START_TIMEOUT_MS` (default 5 minutes).
|
||||
- **Image contents** — `SANDBOX_IMAGE` is the OCI image the microVM boots from. It must contain the toolchain the agent expects, including `git` if the agent runs git commands.
|
||||
- **Workspace identity** — Sandboxed commands run as the Manager's effective uid (and gid), which the entrypoint aligns to `PUID`/`PGID`. The overlay defaults `SANDBOX_EXEC_USER` to `PUID`, so a non-1000 `PUID` (for example `1001`) still writes to the mounted repositories as the workspace owner. If a configured numeric `SANDBOX_EXEC_USER` cannot match the workspace owner, the toggle reports enforcement as unavailable with the reason instead of enabling a broken sandbox.
|
||||
- **Permission patterns** — OpenCode `permission` rules are matched against the rewritten command (`msb exec ...`), not the agent's original text. Command-pattern permission rules must be reviewed when enforcement is on.
|
||||
- **Plugin lockdown** — While enforcement is on, only the Manager-owned plugins load (see [Plugin Policy Under Enforcement](#plugin-policy-under-enforcement)); repository, project, and user-configured plugins are not evaluated in the host process. As defense in depth, the sandbox plugin also locks the `command` argument after rewriting, so any plugin that did manage to load cannot unwrap a sandboxed `bash` command, and a detected bypass blocks every subsequent sandboxed command.
|
||||
- **Host credentials** — Credentials injected by the `shell.env` hook (`ocm-gh-env.js`) are not forwarded into the microVM, so agent-run `git push` / `gh` calls that depend on those injected credentials fail inside the sandbox by design. Credentials that are themselves visible inside the microVM remain usable — a token or credential helper stored in a mounted repository, an authenticated remote URL, or a credential supplied directly to the command — because the microVM's networking is enabled.
|
||||
- **Assistant internal API** — The assistant-mode `.opencode` directory is masked in the microVM, so the internal API token it holds is not readable there. Assistant sessions can still manage repos, schedules, notifications, and settings through the Manager's host-side integrations; agent-run `curl` against the internal API using the masked token fails inside a sandbox by design.
|
||||
@@ -198,6 +198,7 @@ export const settingsApi = {
|
||||
tag: string
|
||||
name: string
|
||||
publishedAt: string
|
||||
installable: boolean
|
||||
}>
|
||||
currentVersion: string | null
|
||||
}> => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type OpenCodeConfigContent,
|
||||
type ModelConfig,
|
||||
type ProviderConfig,
|
||||
type SandboxPreferences,
|
||||
type SkillFileInfo,
|
||||
type CreateSkillRequest,
|
||||
type UpdateSkillRequest,
|
||||
@@ -20,7 +21,7 @@ import {
|
||||
} from '@opencode-manager/shared'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
|
||||
|
||||
export interface CustomCommand {
|
||||
@@ -71,6 +72,7 @@ export interface UserPreferences {
|
||||
repoSortMode?: 'recent' | 'manual' | 'name'
|
||||
serverEnvVars?: Array<{ key: string; value: string }>
|
||||
disabledDefaultServerEnvVars?: string[]
|
||||
sandbox?: SandboxPreferences
|
||||
}
|
||||
|
||||
export interface SettingsResponse {
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
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,9 +29,14 @@ 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,
|
||||
}))
|
||||
@@ -165,6 +170,14 @@ 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,5 +1,6 @@
|
||||
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'
|
||||
@@ -218,6 +219,8 @@ 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({
|
||||
@@ -322,6 +325,12 @@ 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
|
||||
@@ -1016,6 +1025,11 @@ 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
|
||||
|
||||
@@ -336,6 +336,10 @@ 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
|
||||
|
||||
@@ -365,13 +369,19 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
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}
|
||||
disabled={upgradeOpenCodeMutation.isPending || sandboxEnforced}
|
||||
title={updateBlockedReason}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { SandboxSettings } from './SandboxSettings'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
vi.mock('@/hooks/useSettings')
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn() },
|
||||
}))
|
||||
|
||||
function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}) {
|
||||
const updateSettingsAsync = vi.fn().mockResolvedValue(undefined)
|
||||
vi.mocked(useSettings).mockReturnValue({
|
||||
settings: undefined,
|
||||
preferences: { sandbox: { enabled: false } },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
updateSettings: vi.fn(),
|
||||
updateSettingsAsync,
|
||||
resetSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
isResetting: false,
|
||||
...overrides,
|
||||
})
|
||||
return { updateSettingsAsync }
|
||||
}
|
||||
|
||||
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: { 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 },
|
||||
} as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
describe('SandboxSettings', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('reflects the persisted sandbox preference', () => {
|
||||
mockUseSettings({ preferences: { sandbox: { enabled: true } } })
|
||||
mockHealth({ available: true, enforced: false })
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
expect(screen.getByRole('switch')).toBeChecked()
|
||||
})
|
||||
|
||||
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 })
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
await user.click(screen.getByRole('switch'))
|
||||
|
||||
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true } })
|
||||
expect(screen.getByText('Restart the OpenCode server to apply sandbox changes.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disables the switch with a visible reason when microVMs are unavailable', () => {
|
||||
mockUseSettings()
|
||||
mockHealth({ available: false, enforced: false, reason: 'KVM is not available on this host' })
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
expect(screen.getByRole('switch')).toBeDisabled()
|
||||
expect(screen.getByText('KVM is not available on this host')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('still allows disabling an already-enabled preference when microVMs become unavailable', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
|
||||
mockHealth({ available: false, enforced: false, reason: 'KVM is not available on this host' })
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
const toggle = screen.getByRole('switch')
|
||||
expect(toggle).toBeChecked()
|
||||
expect(toggle).not.toBeDisabled()
|
||||
expect(screen.getByText('KVM is not available on this host')).toBeInTheDocument()
|
||||
|
||||
await user.click(toggle)
|
||||
|
||||
expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: false } })
|
||||
})
|
||||
|
||||
it('disables the switch while sandbox availability has not been reported', () => {
|
||||
mockUseSettings()
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
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 useServerHealth>)
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
expect(screen.getByRole('switch')).toBeDisabled()
|
||||
expect(screen.getByText('Checking sandbox availability...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the reported msb version when present', () => {
|
||||
mockUseSettings()
|
||||
mockHealth({ available: true, enforced: false, msbVersion: '0.9.1' })
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
expect(screen.getByText('msb 0.9.1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an error toast when saving the preference fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockUseSettings({ updateSettingsAsync: vi.fn().mockRejectedValue(new Error('failed')) })
|
||||
mockHealth({ available: true, enforced: false })
|
||||
|
||||
render(<SandboxSettings />)
|
||||
|
||||
await user.click(screen.getByRole('switch'))
|
||||
|
||||
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Failed to update sandbox preference')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useState } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Box, RotateCcw } from 'lucide-react'
|
||||
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
|
||||
const enabled = preferences?.sandbox?.enabled ?? false
|
||||
|
||||
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')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card overflow-hidden">
|
||||
<div className="p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Box className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<h3 className="text-sm font-semibold truncate">Sandbox</h3>
|
||||
</div>
|
||||
{sandbox?.msbVersion && (
|
||||
<Badge variant="outline" className="text-xs shrink-0">
|
||||
msb {sandbox.msbVersion}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Run OpenCode agent commands inside microVMs for isolation.
|
||||
</p>
|
||||
{sandbox === undefined ? (
|
||||
<p className="text-xs text-muted-foreground">Checking sandbox availability...</p>
|
||||
) : !isAvailable && (
|
||||
<p className="text-xs text-destructive">
|
||||
{sandbox.reason ?? 'Sandboxing is unavailable on this host.'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Switch
|
||||
checked={enabled}
|
||||
disabled={isUpdating || (!isAvailable && !enabled)}
|
||||
onCheckedChange={handleToggle}
|
||||
aria-label="Toggle sandbox"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{needsRestart && (
|
||||
<Alert>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Restart the OpenCode server to apply sandbox changes.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ServerHealthStatus } from './ServerHealthStatus'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
vi.mock('@/hooks/useOpenCodeServerActions')
|
||||
vi.mock('@/components/settings/RestartServerDialog', () => ({
|
||||
RestartServerDialog: () => null,
|
||||
}))
|
||||
|
||||
const BLOCKED_REASON = 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
|
||||
|
||||
function mockHealth(sandbox?: { available: boolean; enforced: boolean; reason?: string; msbVersion?: string }) {
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: { opencode: 'healthy', opencodeVersion: '1.18.16', 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 },
|
||||
} as ReturnType<typeof useServerHealth>)
|
||||
}
|
||||
|
||||
function mockActions(overrides: Partial<ReturnType<typeof useOpenCodeServerActions>> = {}) {
|
||||
vi.mocked(useOpenCodeServerActions).mockReturnValue({
|
||||
restartServerMutation: { isPending: false },
|
||||
upgradeOpenCodeMutation: { isPending: false },
|
||||
confirmOpen: false,
|
||||
setConfirmOpen: vi.fn(),
|
||||
activeSessionCount: 0,
|
||||
requestRestart: vi.fn(),
|
||||
confirmRestart: vi.fn(),
|
||||
performUpgrade: vi.fn(),
|
||||
...overrides,
|
||||
} as ReturnType<typeof useOpenCodeServerActions>)
|
||||
}
|
||||
|
||||
describe('ServerHealthStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockActions()
|
||||
})
|
||||
|
||||
it('keeps Update and Versions enabled when sandboxing is off', () => {
|
||||
mockHealth({ available: true, enforced: false })
|
||||
|
||||
render(<ServerHealthStatus />)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Update/i })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: /Versions/i })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('disables Update but keeps Versions accessible when sandbox enforcement is on', () => {
|
||||
mockHealth({ available: true, enforced: true })
|
||||
|
||||
render(<ServerHealthStatus />)
|
||||
|
||||
const update = screen.getByRole('button', { name: /Update/i })
|
||||
const versions = screen.getByRole('button', { name: /Versions/i })
|
||||
expect(update).toBeDisabled()
|
||||
expect(update).toHaveAttribute('title', BLOCKED_REASON)
|
||||
expect(versions).toBeEnabled()
|
||||
expect(screen.getByText(/Agent sandboxing is on; Update is disabled and only verified versions can be installed\./)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps Update and Versions enabled while enforcement is pending but not active', () => {
|
||||
mockHealth({ available: false, enforced: false, reason: 'KVM unavailable' })
|
||||
|
||||
render(<ServerHealthStatus />)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Update/i })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: /Versions/i })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('does not invoke an upgrade while the Update button is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const performUpgrade = vi.fn()
|
||||
mockActions({ performUpgrade })
|
||||
mockHealth({ available: true, enforced: true })
|
||||
|
||||
render(<ServerHealthStatus />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Update/i }))
|
||||
|
||||
expect(performUpgrade).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the version dialog when Versions is clicked under enforcement', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onOpenVersionDialog = vi.fn()
|
||||
mockHealth({ available: true, enforced: true })
|
||||
|
||||
render(<ServerHealthStatus onOpenVersionDialog={onOpenVersionDialog} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Versions/i }))
|
||||
|
||||
expect(onOpenVersionDialog).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -37,6 +37,10 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
}
|
||||
|
||||
const isUnhealthy = health.opencode !== 'healthy'
|
||||
const sandboxEnforced = health.sandbox?.enforced === true
|
||||
const updateBlockedReason = sandboxEnforced
|
||||
? 'Updating the OpenCode version is disabled while agent sandboxing is enabled'
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
|
||||
@@ -62,13 +66,19 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
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}
|
||||
disabled={upgradeOpenCodeMutation.isPending || sandboxEnforced}
|
||||
title={updateBlockedReason}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
|
||||
@@ -6,6 +6,7 @@ import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManag
|
||||
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
|
||||
import { ManagerTokenSettings } from '@/components/settings/ManagerTokenSettings'
|
||||
import { ServerEnvVarsSettings } from '@/components/settings/ServerEnvVarsSettings'
|
||||
import { SandboxSettings } from '@/components/settings/SandboxSettings'
|
||||
import { ServerHealthStatus } from '@/components/settings/ServerHealthStatus'
|
||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||
import { AccountSettings } from '@/components/settings/AccountSettings'
|
||||
@@ -178,6 +179,7 @@ export function SettingsDialog() {
|
||||
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
</div>
|
||||
<ServerEnvVarsSettings />
|
||||
<SandboxSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
</TabsContent>
|
||||
@@ -249,6 +251,7 @@ export function SettingsDialog() {
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<ServerEnvVarsSettings />
|
||||
<SandboxSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { VersionSelectDialog } from './VersionSelectDialog'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getOpenCodeVersions: vi.fn(),
|
||||
installOpenCodeVersion: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), loading: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
vi.mock('@/lib/queryInvalidation', () => ({
|
||||
invalidateConfigCaches: vi.fn(),
|
||||
updateOpenCodeVersionCaches: vi.fn(),
|
||||
}))
|
||||
|
||||
const mockGetOpenCodeVersions = settingsApi.getOpenCodeVersions as ReturnType<typeof vi.fn>
|
||||
const mockInstallOpenCodeVersion = settingsApi.installOpenCodeVersion as ReturnType<typeof vi.fn>
|
||||
|
||||
function renderDialog(open = true) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<VersionSelectDialog open={open} onOpenChange={vi.fn()} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
function mockHealth(enforced: boolean) {
|
||||
vi.mocked(useServerHealth).mockReturnValue({
|
||||
data: { sandbox: { available: true, enforced } },
|
||||
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 useServerHealth>)
|
||||
}
|
||||
|
||||
describe('VersionSelectDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetOpenCodeVersions.mockResolvedValue({
|
||||
versions: [
|
||||
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: true },
|
||||
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z', installable: true },
|
||||
],
|
||||
currentVersion: '1.18.16',
|
||||
})
|
||||
mockInstallOpenCodeVersion.mockResolvedValue({ success: true, message: 'ok', oldVersion: null, newVersion: '1.19.0' })
|
||||
mockHealth(false)
|
||||
})
|
||||
|
||||
it('lists versions and allows selection when sandboxing is off', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
|
||||
const row = screen.getByRole('button', { name: /v1\.19\.0/ })
|
||||
expect(row).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
|
||||
|
||||
await user.click(row)
|
||||
|
||||
expect(screen.getByRole('button', { name: /^Install$/i })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('keeps verified versions installable and disables unverified versions when sandbox enforcement is on', async () => {
|
||||
mockHealth(true)
|
||||
mockGetOpenCodeVersions.mockResolvedValue({
|
||||
versions: [
|
||||
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: false },
|
||||
{ version: '1.18.16', tag: 'v1.18.16', name: '', publishedAt: '2025-12-01T00:00:00Z', installable: true },
|
||||
],
|
||||
currentVersion: '1.17.0',
|
||||
})
|
||||
|
||||
renderDialog()
|
||||
|
||||
expect(
|
||||
await screen.findByText(/only verified OpenCode versions can be installed/),
|
||||
).toBeInTheDocument()
|
||||
const unverifiedRow = screen.getByRole('button', { name: /v1\.19\.0/ })
|
||||
const verifiedRow = screen.getByRole('button', { name: /v1\.18\.16/ })
|
||||
expect(unverifiedRow).toBeDisabled()
|
||||
expect(verifiedRow).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(verifiedRow)
|
||||
|
||||
expect(screen.getByRole('button', { name: /^Install$/i })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('keeps the install button disabled when the only available row is unverified under enforcement', async () => {
|
||||
mockHealth(true)
|
||||
mockGetOpenCodeVersions.mockResolvedValue({
|
||||
versions: [
|
||||
{ version: '1.19.0', tag: 'v1.19.0', name: '', publishedAt: '2026-01-01T00:00:00Z', installable: false },
|
||||
],
|
||||
currentVersion: '1.17.0',
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
expect(await screen.findByText('v1.19.0')).toBeInTheDocument()
|
||||
const unverifiedRow = screen.getByRole('button', { name: /v1\.19\.0/ })
|
||||
expect(unverifiedRow).toBeDisabled()
|
||||
await user.click(unverifiedRow)
|
||||
|
||||
expect(screen.getByRole('button', { name: /Select version/i })).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches, updateOpenCodeVersionCaches } from '@/lib/queryInvalidation'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
|
||||
interface VersionSelectDialogProps {
|
||||
open: boolean
|
||||
@@ -14,6 +15,8 @@ interface VersionSelectDialogProps {
|
||||
|
||||
export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
const sandboxEnforced = health?.sandbox?.enforced === true
|
||||
const [selectedVersion, setSelectedVersion] = useState<string | null>(null)
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
@@ -23,6 +26,9 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
staleTime: 60000,
|
||||
})
|
||||
|
||||
const selectedRelease = data?.versions.find((release) => release.version === selectedVersion)
|
||||
const selectedInstallable = selectedRelease?.installable === true
|
||||
|
||||
const installMutation = useMutation({
|
||||
mutationFn: (version: string) => settingsApi.installOpenCodeVersion(version),
|
||||
onSuccess: (result) => {
|
||||
@@ -95,6 +101,13 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
|
||||
{data && (
|
||||
<>
|
||||
{sandboxEnforced && (
|
||||
<div className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-600 dark:text-amber-400 mb-3">
|
||||
While agent sandboxing is enabled, only verified OpenCode versions can be installed. Unverified
|
||||
versions are disabled. Disable Agent Sandboxing in Settings and restart the OpenCode server to
|
||||
install other versions.
|
||||
</div>
|
||||
)}
|
||||
<div className="h-[300px] overflow-y-auto pr-2">
|
||||
<div className="space-y-2">
|
||||
{data.versions.map((release) => {
|
||||
@@ -105,13 +118,15 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
<button
|
||||
key={release.version}
|
||||
onClick={() => setSelectedVersion(isCurrent ? null : release.version)}
|
||||
disabled={isCurrent || installMutation.isPending}
|
||||
disabled={isCurrent || installMutation.isPending || !release.installable}
|
||||
className={`w-full text-left p-3 rounded-lg border transition-colors ${
|
||||
isSelected
|
||||
? 'border-primary bg-primary/10'
|
||||
: isCurrent
|
||||
? 'border-green-500/50 bg-green-500/10 cursor-default'
|
||||
: 'border-border hover:border-primary/50 hover:bg-muted/50'
|
||||
: !release.installable
|
||||
? 'border-border opacity-50 cursor-not-allowed'
|
||||
: 'border-border hover:border-primary/50 hover:bg-muted/50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -123,6 +138,11 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
Current
|
||||
</span>
|
||||
)}
|
||||
{!release.installable && (
|
||||
<span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
|
||||
Unverified
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{formatDate(release.publishedAt)}
|
||||
@@ -146,7 +166,7 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleInstall}
|
||||
disabled={!selectedVersion || installMutation.isPending}
|
||||
disabled={!selectedVersion || installMutation.isPending || !selectedInstallable}
|
||||
className="min-w-[120px]"
|
||||
>
|
||||
{installMutation.isPending ? (
|
||||
|
||||
@@ -23,6 +23,7 @@ interface HealthResponse {
|
||||
opencodeVersionSupported: boolean
|
||||
opencodeManagerVersion: string | null
|
||||
opencodeRestartPending?: boolean
|
||||
sandbox?: { available: boolean; enabled: boolean; enforced: boolean; reason?: string; msbVersion?: string }
|
||||
error?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ nav:
|
||||
- Speech-to-Text: features/stt.md
|
||||
- Push Notifications: features/notifications.md
|
||||
- OpenCode Server Health: features/server-health.md
|
||||
- Agent Sandboxing: features/sandboxing.md
|
||||
- Mobile & PWA: features/mobile.md
|
||||
- Configuration:
|
||||
- Environment Variables: configuration/environment.md
|
||||
|
||||
@@ -7,9 +7,45 @@ export PATH="$BUN_INSTALL/bin:$HOME/.opencode/bin:/usr/local/bin:$PATH"
|
||||
|
||||
source /usr/local/lib/ocm/container-user.sh
|
||||
|
||||
grant_kvm_access() {
|
||||
local dev="${1:-/dev/kvm}"
|
||||
[ -e "$dev" ] || return 0
|
||||
|
||||
local dev_gid group_name holder
|
||||
dev_gid="$(stat -c '%g' "$dev" 2>/dev/null)" || return 0
|
||||
case "$dev_gid" in
|
||||
''|*[!0-9]*) return 0 ;;
|
||||
esac
|
||||
|
||||
holder="$(getent group "$dev_gid" 2>/dev/null | cut -d: -f1 || true)"
|
||||
if [ -n "$holder" ]; then
|
||||
group_name="$holder"
|
||||
else
|
||||
group_name="kvm"
|
||||
if ! groupadd -g "$dev_gid" "$group_name"; then
|
||||
echo "ERROR: could not create group '$group_name' (gid $dev_gid) required for $dev access" >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if ! usermod -aG "$group_name" node; then
|
||||
echo "ERROR: could not add node to group '$group_name' (gid $dev_gid) required for $dev access" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! runuser -u node -- test -r "$dev" || ! runuser -u node -- test -w "$dev"; then
|
||||
echo "ERROR: node cannot access $dev (group '$group_name', gid $dev_gid)" >&2
|
||||
echo "ERROR: grant the container group access to $dev or run the sandbox overlay (docker-compose.sandbox.yml)" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "Granted node access to $dev (group '$group_name', gid $dev_gid)"
|
||||
}
|
||||
|
||||
install_opencode() {
|
||||
echo "Installing OpenCode latest..."
|
||||
curl -fsSL "https://github.com/anomalyco/opencode/releases/latest/download/opencode-linux-$(uname -m | sed 's/x86_64/x64/; s/aarch64/arm64/').tar.gz" \
|
||||
local opencode_version="${OPENCODE_BUNDLED_VERSION:-1.18.16}"
|
||||
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
|
||||
tar -xzf /tmp/opencode.tar.gz -C /tmp
|
||||
mkdir -p "$HOME/.opencode/bin"
|
||||
@@ -62,11 +98,11 @@ 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 "Upgrading OpenCode..."
|
||||
opencode upgrade || install_opencode
|
||||
echo "Reinstalling bundled OpenCode version ${OPENCODE_BUNDLED_VERSION:-1.18.16}..."
|
||||
install_opencode
|
||||
|
||||
OPENCODE_VERSION=$(opencode --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "unknown")
|
||||
echo "OpenCode upgraded to version: $OPENCODE_VERSION"
|
||||
echo "OpenCode reinstalled as version: $OPENCODE_VERSION"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -92,9 +128,13 @@ if ! align_container_user node; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grant_kvm_access; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
warn_if_workspace_owner_differs /workspace "$OCM_TARGET_UID" "$OCM_TARGET_GID"
|
||||
|
||||
mkdir -p /app/data /workspace /home/node/.cache /home/node/.opencode
|
||||
mkdir -p /app/data /workspace /home/node/.cache /home/node/.opencode /home/node/.microsandbox
|
||||
chown -R node:node /app/data /workspace /home/node
|
||||
|
||||
exec runuser -u node -- "$@"
|
||||
@@ -31,6 +31,17 @@ export const DEFAULTS = {
|
||||
AUTH_FILE: '.opencode/state/opencode/auth.json',
|
||||
},
|
||||
|
||||
SANDBOX: {
|
||||
MSB_PATH: 'msb',
|
||||
IMAGE: 'node:24',
|
||||
MEMORY: '4G',
|
||||
CPUS: 2,
|
||||
EXEC_USER: 'node',
|
||||
NET: 'public',
|
||||
START_TIMEOUT_MS: 300000,
|
||||
EXEC_TIMEOUT_MS: 600000,
|
||||
},
|
||||
|
||||
TIMEOUTS: {
|
||||
PROCESS_START_WAIT_MS: 2000,
|
||||
PROCESS_VERIFY_WAIT_MS: 1000,
|
||||
|
||||
@@ -2,6 +2,7 @@ import path from 'path'
|
||||
import os from 'os'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { DEFAULTS } from './defaults'
|
||||
import { ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '../utils/repo'
|
||||
|
||||
try {
|
||||
const { config } = await import('dotenv')
|
||||
@@ -87,6 +88,17 @@ export const ENV = {
|
||||
AUTH_FILE: DEFAULTS.WORKSPACE.AUTH_FILE,
|
||||
},
|
||||
|
||||
SANDBOX: {
|
||||
MSB_PATH: getEnvString('MSB_PATH', DEFAULTS.SANDBOX.MSB_PATH),
|
||||
IMAGE: getEnvString('SANDBOX_IMAGE', DEFAULTS.SANDBOX.IMAGE),
|
||||
MEMORY: getEnvString('SANDBOX_MEMORY', DEFAULTS.SANDBOX.MEMORY),
|
||||
CPUS: getEnvNumber('SANDBOX_CPUS', DEFAULTS.SANDBOX.CPUS),
|
||||
EXEC_USER: getEnvString('SANDBOX_EXEC_USER', DEFAULTS.SANDBOX.EXEC_USER),
|
||||
NET: getEnvString('SANDBOX_NET', DEFAULTS.SANDBOX.NET),
|
||||
START_TIMEOUT_MS: getEnvNumber('SANDBOX_START_TIMEOUT_MS', DEFAULTS.SANDBOX.START_TIMEOUT_MS),
|
||||
EXEC_TIMEOUT_MS: getEnvNumber('SANDBOX_EXEC_TIMEOUT_MS', DEFAULTS.SANDBOX.EXEC_TIMEOUT_MS),
|
||||
},
|
||||
|
||||
TIMEOUTS: {
|
||||
PROCESS_START_WAIT_MS: getEnvNumber('PROCESS_START_WAIT_MS', DEFAULTS.TIMEOUTS.PROCESS_START_WAIT_MS),
|
||||
PROCESS_VERIFY_WAIT_MS: getEnvNumber('PROCESS_VERIFY_WAIT_MS', DEFAULTS.TIMEOUTS.PROCESS_VERIFY_WAIT_MS),
|
||||
@@ -133,6 +145,8 @@ export const getWorkspacePath = () => ENV.WORKSPACE.BASE_PATH
|
||||
export const getBrowseRootPath = () => ENV.WORKSPACE.BROWSE_ROOT
|
||||
export const getReposPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.REPOS_DIR)
|
||||
export const getScheduleWorktreesPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.SCHEDULE_WORKTREES_DIR)
|
||||
export const getAssistantModePath = () => path.join(getReposPath(), ASSISTANT_REPO_PATH)
|
||||
export const getAssistantOpenCodeDir = () => path.join(getAssistantModePath(), ASSISTANT_OPENCODE_DIR_NAME)
|
||||
export const getConfigPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR)
|
||||
export const getOpenCodeConfigFilePath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR, 'opencode.json')
|
||||
export const getAgentsMdPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR, 'AGENTS.md')
|
||||
|
||||
@@ -119,12 +119,34 @@ 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 = {
|
||||
@@ -132,6 +154,16 @@ export const DEFAULT_GIT_IDENTITY: GitIdentity = {
|
||||
email: '',
|
||||
};
|
||||
|
||||
export const SandboxPreferencesSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
export type SandboxPreferences = z.infer<typeof SandboxPreferencesSchema>;
|
||||
|
||||
export const DEFAULT_SANDBOX_PREFERENCES: SandboxPreferences = {
|
||||
enabled: false,
|
||||
};
|
||||
|
||||
export const UserPreferencesSchema = z.object({
|
||||
theme: z.enum(["dark", "light", "system"]),
|
||||
mode: z.enum(["plan", "build"]),
|
||||
@@ -156,6 +188,7 @@ export const UserPreferencesSchema = z.object({
|
||||
repoOrder: z.array(z.number()).optional(),
|
||||
repoSortMode: z.enum(['recent', 'manual', 'name']).optional(),
|
||||
serverEnvVars: z.array(ServerEnvVarSchema).optional(),
|
||||
sandbox: SandboxPreferencesSchema.optional(),
|
||||
disabledDefaultServerEnvVars: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
@@ -206,6 +239,7 @@ export const DEFAULT_USER_PREFERENCES = {
|
||||
notifications: DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
repoSortMode: 'recent' as const,
|
||||
serverEnvVars: [] as ServerEnvVar[],
|
||||
sandbox: DEFAULT_SANDBOX_PREFERENCES,
|
||||
disabledDefaultServerEnvVars: [] as string[],
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export const ASSISTANT_REPO_ID = 0
|
||||
export const ASSISTANT_REPO_NAME = 'Assistant'
|
||||
export const ASSISTANT_REPO_PATH = 'assistant'
|
||||
export const ASSISTANT_OPENCODE_DIR_NAME = '.opencode'
|
||||
|
||||
function trimTrailingChar(value: string, char: string): string {
|
||||
let end = value.length
|
||||
|
||||
Reference in new issue
Block a user