From 4ed346075904a98163396cea1b8b5531c9f7f87e Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 31 Aug 2026 18:33:11 -0400 Subject: [PATCH] fix(sandbox): mount agent tmp, tool-output, and global skills into the guest and add missing network tools - Point the OpenCode child TMPDIR at the workspace tmp home and clear the mounted agent tmp directory on spawn - Expand sandbox bind mounts to tool-output, global skills, and agent tmp while keeping only project roots as working directories - Ship the python alias and network diagnostics in the guest image, verify them at build time, and pin the rebuilt image digest --- Dockerfile.sandbox | 13 ++-- .../src/services/opencode-single-server.ts | 41 +++++++---- backend/src/services/sandbox/command.ts | 22 +++++- backend/src/services/sandbox/runtime.ts | 7 +- backend/src/services/sandbox/shell-shim.ts | 2 +- backend/src/services/skills.ts | 4 +- .../services/opencode-single-server.test.ts | 21 ++++++ backend/test/services/sandbox/command.test.ts | 51 +++++++++++--- backend/test/services/sandbox/config.test.ts | 1 + backend/test/services/sandbox/runtime.test.ts | 68 ++++++++++++++++++- docker-compose.sandbox.yml | 2 +- docs/configuration/docker.md | 2 +- docs/configuration/environment.md | 2 +- docs/features/sandboxing.md | 36 +++++++--- docs/features/skills.md | 2 + shared/src/config/defaults.ts | 2 +- shared/src/config/env.ts | 6 ++ shared/src/schemas/settings.ts | 1 + 18 files changed, 230 insertions(+), 53 deletions(-) diff --git a/Dockerfile.sandbox b/Dockerfile.sandbox index bb3a876b..ed114503 100644 --- a/Dockerfile.sandbox +++ b/Dockerfile.sandbox @@ -1,9 +1,10 @@ # Guest image for the agent sandbox microVM (SANDBOX_IMAGE). # # node:24 is buildpack-deps based, so gcc/g++/make/ld/pkg-config, glib-2.0, -# git, ssh, python3 and curl are already present. This image adds the rest of -# the Manager image toolchain (pnpm, bun, uv, jq) and the GitHub CLI and a -# Playwright-managed Chromium. +# git, ssh, python3, curl and wget are already present, but it ships no network +# diagnostics at all. This image adds the rest of the Manager image toolchain +# (pnpm, bun, uv, jq), the GitHub CLI, a Playwright-managed Chromium, the +# `python` alias, and the network tooling agents reach for. FROM node:24 ARG PLAYWRIGHT_VERSION=1.56.0 @@ -37,7 +38,9 @@ RUN echo "Installing gh and CLI tooling (cachebust=${TOOLS_CACHEBUST})" && \ apt-get update && \ apt-get install -y --no-install-recommends \ ca-certificates curl gh jq less ripgrep sudo tree file procps \ - python3-pip python3-venv && \ + python3-pip python3-venv python-is-python3 \ + iproute2 iputils-ping bind9-dnsutils bind9-host net-tools \ + netcat-openbsd traceroute lsof rsync && \ curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \ -o /usr/share/keyrings/githubcli-archive-keyring.gpg && \ chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg && \ @@ -88,7 +91,7 @@ RUN echo "Verifying guest toolchain as an unknown uid (cachebust=${TOOLS_CACHEBU rm -rf /home/ocm-agent && \ mkdir -p /home/ocm-agent && \ chmod 1777 /home/ocm-agent && \ - setpriv --reuid=4242 --regid=4242 --clear-groups sh -c "set -e; pnpm --version; bun --version; bunx --version; uv --version; uvx --version; playwright --version; gh --version; jq --version; rg --version; npm install -g --silent cowsay && cowsay -t verify-ok | head -1; git config --global user.email verify@ocm.local; uv venv /tmp/uv-check >/dev/null; uv pip install --python /tmp/uv-check/bin/python idna >/dev/null; pip3 install --user --force-reinstall --no-deps --quiet idna; rm -rf /tmp/uv-check" && \ + setpriv --reuid=4242 --regid=4242 --clear-groups sh -c "set -e; pnpm --version; bun --version; bunx --version; uv --version; uvx --version; playwright --version; gh --version; jq --version; rg --version; npm install -g --silent cowsay && cowsay -t verify-ok | head -1; git config --global user.email verify@ocm.local; uv venv /tmp/uv-check >/dev/null; uv pip install --python /tmp/uv-check/bin/python idna >/dev/null; pip3 install --user --force-reinstall --no-deps --quiet idna; rm -rf /tmp/uv-check; for tool in python python3 git curl wget ssh rsync lsof ip ss netstat ping dig host nslookup nc traceroute; do command -v \"\$tool\" >/dev/null || { echo \"missing guest tool: \$tool\"; exit 1; }; done; python --version" && \ setpriv --reuid=1000 --regid=1000 --clear-groups sh -c "set -e; sudo -n apt-get update -qq; sudo -n apt-get install -y -qq --no-install-recommends bc; bc --version | head -1" && \ rm -rf /home/ocm-agent /opt/agent-tools /var/lib/apt/lists/* && \ mkdir -p /home/ocm-agent /opt/agent-tools/bin && \ diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index efe98ee5..0f1d2abf 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -17,7 +17,15 @@ import { import { decryptSecret } from '../utils/crypto' import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@opencode-manager/shared' import { SettingsService } from './settings' -import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env' +import { + getWorkspacePath, + getOpenCodeAgentTmpPath, + getOpenCodeConfigFilePath, + getOpenCodeConfigHome, + getOpenCodeStateHome, + getOpenCodeTmpHome, + ENV, +} from '@opencode-manager/shared/config/env' import { parseJsonc } from '@opencode-manager/shared/utils' import type { Database } from 'bun:sqlite' import { compareVersions } from '../utils/version-utils' @@ -538,7 +546,7 @@ class OpenCodeServerManager { const openCodeServerDirectory = getOpenCodeServerDirectory() const openCodeConfigPath = getOpenCodeConfigPath() logger.info(`OpenCode server working directory: ${openCodeServerDirectory}`) - logger.info(`OpenCode XDG_CONFIG_HOME: ${path.join(openCodeServerDirectory, '.config')}`) + logger.info(`OpenCode XDG_CONFIG_HOME: ${getOpenCodeConfigHome()}`) logger.info(`OpenCode will use ?directory= parameter for session isolation`) const gitEnv = credentialProvider?.getGitEnv() ?? {} @@ -589,7 +597,8 @@ class OpenCodeServerManager { logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`) await this.initializeOpencodeBinDirectory() - const pluginConfigHome = path.join(openCodeServerDirectory, '.config') + await this.resetAgentTmpDirectory() + const pluginConfigHome = getOpenCodeConfigHome() try { await restoreQuarantinedOpenCodePlugins(pluginConfigHome, openCodeConfigPath) } catch (error) { @@ -645,9 +654,10 @@ class OpenCodeServerManager { OCM_SANDBOX_ENFORCED: sandboxEnforced ? 'true' : 'false', OPENCODE_PURE: 'false', GIT_SSH_COMMAND: gitSshCommand, - XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'), - XDG_STATE_HOME: path.join(openCodeServerDirectory, '.opencode/state'), - XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'), + XDG_DATA_HOME: getOpenCodeStateHome(), + XDG_STATE_HOME: getOpenCodeStateHome(), + XDG_CONFIG_HOME: getOpenCodeConfigHome(), + TMPDIR: getOpenCodeTmpHome(), ...(getOpenCodeServerPublicUrl() ? { OPENCODE_PUBLIC_URL: getOpenCodeServerPublicUrl() } : {}), ...(password ? { @@ -863,14 +873,19 @@ class OpenCodeServerManager { } } + private async resetAgentTmpDirectory(): Promise { + const tmpDir = getOpenCodeAgentTmpPath() + try { + await mkdirSafe(tmpDir) + const entries = await fs.readdir(tmpDir) + await Promise.all(entries.map((entry) => fs.rm(path.join(tmpDir, entry), { recursive: true, force: true }))) + } catch (error) { + logger.warn(`Failed to reset the agent temporary directory ${tmpDir}:`, error) + } + } + private async initializeOpencodeBinDirectory(): Promise { - const binDir = path.join( - getOpenCodeServerDirectory(), - '.opencode', - 'state', - 'opencode', - 'bin' - ) + const binDir = path.join(getOpenCodeStateHome(), 'opencode', 'bin') const packageJsonPath = path.join(binDir, 'package.json') diff --git a/backend/src/services/sandbox/command.ts b/backend/src/services/sandbox/command.ts index 6089473b..d4a839a2 100644 --- a/backend/src/services/sandbox/command.ts +++ b/backend/src/services/sandbox/command.ts @@ -1,7 +1,14 @@ import path from 'path' import { accessSync, constants, realpathSync, statSync } from 'fs' import { realpath } from 'fs/promises' -import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' +import { + ENV, + getOpenCodeAgentTmpPath, + getOpenCodeGlobalSkillsPath, + getOpenCodeToolOutputPath, + getReposPath, + getScheduleWorktreesPath, +} from '@opencode-manager/shared/config/env' export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace' @@ -145,10 +152,19 @@ export function buildSandboxVerifyProvisionArgs(): string[] { ] } -export function sandboxMountRoots(): string[] { +export function sandboxProjectRoots(): string[] { return [getReposPath(), getScheduleWorktreesPath()] } +export function sandboxMountRoots(): string[] { + return [ + ...sandboxProjectRoots(), + getOpenCodeToolOutputPath(), + getOpenCodeGlobalSkillsPath(), + getOpenCodeAgentTmpPath(), + ] +} + export function quoteForShell(value: string): string { return `'${value.replace(/'/g, `'\\''`)}'` } @@ -449,7 +465,7 @@ export async function resolveSandboxWorkDirectory(directory: string): Promise { 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`) + throw new Error(`sandbox mount root ${root} is a symbolic link; refusing to mount a redirected 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`) + throw new Error(`sandbox mount root ${root} resolves to ${canonical} instead of ${resolvedRoot}; refusing to mount a redirected root`) } } } @@ -820,7 +821,7 @@ export class SandboxRuntimeService { if (workDirectory === null) { return { mode: 'blocked', - reason: `working directory is outside the sandboxed project roots (${sandboxMountRoots().join(', ')})`, + reason: `working directory is outside the sandboxed project roots (${sandboxProjectRoots().join(', ')})`, } } try { diff --git a/backend/src/services/sandbox/shell-shim.ts b/backend/src/services/sandbox/shell-shim.ts index ae8f764b..e07bdcf9 100644 --- a/backend/src/services/sandbox/shell-shim.ts +++ b/backend/src/services/sandbox/shell-shim.ts @@ -131,7 +131,7 @@ export async function ensureSandboxShellShim(configHome: string): Promise isPathWithinRoot(root, shimPath)) if (mountRoot !== undefined) { throw new Error( - `refusing to install the sandbox shell shim at ${shimPath}: the path is inside the sandboxed project root ${mountRoot} and would be writable by agent commands`, + `refusing to install the sandbox shell shim at ${shimPath}: the path is inside the sandbox mount root ${mountRoot} and would be writable by agent commands`, ) } await writeFileAtomic(shimPath, buildSandboxShellShimScript(), { mode: 0o700 }) diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index e0257683..1385072c 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -4,7 +4,7 @@ import { promises as fs } from 'fs' import type { Database } from 'bun:sqlite' import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest, InstallSkillUploadRequest, InstallSkillFromGithubRequest, InstallSkillResponse } from '@opencode-manager/shared' import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shared' -import { getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env' +import { getOpenCodeGlobalSkillsPath, getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env' import { getRepoById, getRepoName, listRepos } from '../db/queries' import type { Repo } from '@opencode-manager/shared/types' import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations' @@ -303,7 +303,7 @@ export async function installSkillFromGithubTree( } function getGlobalSkillsPath(): string { - return path.join(getWorkspacePath(), '.config', 'opencode', 'skills') + return getOpenCodeGlobalSkillsPath() } function getOldGlobalSkillsPath(): string { diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index 5e2d1710..179311dc 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -26,6 +26,10 @@ vi.mock('bun:sqlite', () => ({ vi.mock('@opencode-manager/shared/config/env', () => ({ getWorkspacePath: vi.fn(() => '/test/workspace'), getOpenCodeConfigFilePath: vi.fn(() => '/test/workspace/.config/opencode.json'), + getOpenCodeStateHome: vi.fn(() => '/test/workspace/.opencode/state'), + getOpenCodeConfigHome: vi.fn(() => '/test/workspace/.config'), + getOpenCodeTmpHome: vi.fn(() => '/test/workspace/.opencode/tmp'), + getOpenCodeAgentTmpPath: vi.fn(() => '/test/workspace/.opencode/tmp/opencode'), getReposPath: vi.fn(() => '/test/workspace/repos'), getAgentsMdPath: vi.fn(() => '/test/workspace/AGENTS.md'), getDatabasePath: vi.fn(() => ':memory:'), @@ -138,6 +142,8 @@ vi.mock('../../src/utils/logger', () => ({ const mkdirMock = fs.mkdir as any const accessMock = fs.access as any const readFileMock = fs.readFile as any +const readdirMock = fs.readdir as any +const rmMock = fs.rm as any const execSyncMock = execSync as any const childSpawnSyncMock = spawnSync as any const readdirSyncMock = readdirSync as any @@ -510,6 +516,21 @@ describe('OpenCodeServerManager - server auth', () => { expect(env.OPENCODE_PURE).toBe('false') }) + it('points TMPDIR at the workspace temp home and clears the mounted agent temp directory before spawning', async () => { + const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server') + const manager = OpenCodeServerManager.getInstance() + manager.setDatabase(createPasswordDb(null)) + readdirMock.mockResolvedValue(['stale-run', 'leftover.txt']) + + await manager.start() + + const env = (spawnMock.mock.calls[0] as unknown as [unknown, unknown, { env: Record }])[2].env + expect(env.TMPDIR).toBe('/test/workspace/.opencode/tmp') + expect(mkdirMock).toHaveBeenCalledWith('/test/workspace/.opencode/tmp/opencode', expect.objectContaining({ recursive: true })) + expect(rmMock).toHaveBeenCalledWith('/test/workspace/.opencode/tmp/opencode/stale-run', { recursive: true, force: true }) + expect(rmMock).toHaveBeenCalledWith('/test/workspace/.opencode/tmp/opencode/leftover.txt', { recursive: true, force: true }) + }) + it('strips an inherited OPENCODE_PURE from the manager process env before spawning', async () => { const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server') const manager = OpenCodeServerManager.getInstance() diff --git a/backend/test/services/sandbox/command.test.ts b/backend/test/services/sandbox/command.test.ts index de6248c5..ec448c4f 100644 --- a/backend/test/services/sandbox/command.test.ts +++ b/backend/test/services/sandbox/command.test.ts @@ -3,7 +3,7 @@ import { spawnSync } from 'child_process' import { mkdirSync, mkdtempSync, 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 { ENV, getAssistantOpenCodeDir, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils' import { WORKSPACE_SANDBOX_NAME, @@ -18,6 +18,7 @@ import { buildSandboxStartArgs, buildSandboxStopManagedArgs, buildSandboxVersionArgs, + isPathWithinRoot, quoteForShell, resolveExpectedSandboxNetworkPolicy, resolveSandboxExecUser, @@ -70,7 +71,7 @@ describe('sandbox command builders', () => { expect(result.stdout).toBe(value) }) - it('builds create args with exactly two identical-path bind mounts and the detached flag', () => { + it('builds create args with exactly five identical-path bind mounts and the detached flag', () => { const args = buildSandboxCreateArgs() expect(args[0]).toBe('run') @@ -100,6 +101,9 @@ describe('sandbox command builders', () => { expect(mountArgs).toEqual(sandboxMountRoots().map((root) => `${root}:${root}`)) expect(mountArgs[0]).toBe(`${getReposPath()}:${getReposPath()}`) expect(mountArgs[1]).toBe(`${getScheduleWorktreesPath()}:${getScheduleWorktreesPath()}`) + expect(mountArgs[2]).toBe(`${getOpenCodeToolOutputPath()}:${getOpenCodeToolOutputPath()}`) + expect(mountArgs[3]).toBe(`${getOpenCodeGlobalSkillsPath()}:${getOpenCodeGlobalSkillsPath()}`) + expect(mountArgs[4]).toBe(`${getOpenCodeAgentTmpPath()}:${getOpenCodeAgentTmpPath()}`) }) it('never masks the assistant .opencode directory with a tmpfs overlay', () => { @@ -118,15 +122,28 @@ describe('sandbox command builders', () => { expect(args.indexOf(ENV.SANDBOX.IMAGE)).toBeGreaterThan(entrypointIndex + 1) }) - it('never mounts the SSH/config/state workspace directories', () => { - const joined = buildSandboxCreateArgs().join(' ') + it('mounts only the skills, tool-output, and agent tmp directories from outside the project roots', () => { const workspacePath = path.dirname(getReposPath()) + const roots = sandboxMountRoots() - 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') + expect(roots.filter((root) => isPathWithinRoot(path.join(workspacePath, '.config'), root))).toEqual([ + getOpenCodeGlobalSkillsPath(), + ]) + expect(roots.filter((root) => isPathWithinRoot(path.join(workspacePath, '.opencode'), root))).toEqual([ + getOpenCodeToolOutputPath(), + getOpenCodeAgentTmpPath(), + ]) + + for (const sensitive of [ + path.join(workspacePath, 'config'), + path.join(workspacePath, '.ssh-keys'), + path.join(workspacePath, '.config', 'ocm'), + path.join(workspacePath, '.config', 'opencode', 'plugin'), + path.join(workspacePath, '.opencode', 'state', 'opencode', 'auth.json'), + path.join(workspacePath, '.opencode', 'state', 'opencode', 'mcp-auth.json'), + ]) { + expect(roots.some((root) => isPathWithinRoot(root, sensitive))).toBe(false) + } }) it('derives a canonical spec from the create args matching the security configuration', () => { @@ -158,8 +175,14 @@ describe('sandbox command builders', () => { 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()]) + expect(binds).toHaveLength(5) + expect(binds.map((mount) => mount.host)).toEqual([ + getReposPath(), + getScheduleWorktreesPath(), + getOpenCodeToolOutputPath(), + getOpenCodeGlobalSkillsPath(), + getOpenCodeAgentTmpPath(), + ]) for (const mount of binds) { expect(mount.guest).toBe(mount.host) const options = mount.options as Record @@ -185,6 +208,9 @@ describe('sandbox command builders', () => { 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 }) + mkdirSync(path.join(tmp, '.opencode', 'state', 'opencode', 'tool-output'), { recursive: true }) + mkdirSync(path.join(tmp, '.opencode', 'tmp', 'opencode'), { recursive: true }) + mkdirSync(path.join(tmp, '.config', 'opencode', 'skills'), { recursive: true }) process.env.WORKSPACE_PATH = tmp const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command') @@ -197,6 +223,9 @@ describe('sandbox command builders', () => { path.join(schedules, 'job-1-run-2'), ) await expect(resolveSandboxWorkDirectory(path.join(repos, '..', '.config', 'opencode'))).resolves.toBeNull() + await expect(resolveSandboxWorkDirectory(getOpenCodeToolOutputPath())).resolves.toBeNull() + await expect(resolveSandboxWorkDirectory(getOpenCodeGlobalSkillsPath())).resolves.toBeNull() + await expect(resolveSandboxWorkDirectory(getOpenCodeAgentTmpPath())).resolves.toBeNull() await expect(resolveSandboxWorkDirectory(`${repos}-extra`)).resolves.toBeNull() await expect(resolveSandboxWorkDirectory(path.join(repos, 'missing'))).resolves.toBeNull() await expect(resolveSandboxWorkDirectory('/etc')).resolves.toBeNull() diff --git a/backend/test/services/sandbox/config.test.ts b/backend/test/services/sandbox/config.test.ts index 98892df0..8b86d6fb 100644 --- a/backend/test/services/sandbox/config.test.ts +++ b/backend/test/services/sandbox/config.test.ts @@ -22,6 +22,7 @@ describe('settings schema - BLOCKED_SERVER_ENV_KEYS', () => { expect(blocked.has('XDG_DATA_HOME')).toBe(true) expect(blocked.has('XDG_STATE_HOME')).toBe(true) expect(blocked.has('XDG_CONFIG_HOME')).toBe(true) + expect(blocked.has('TMPDIR')).toBe(true) }) }) diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index 1b7668b3..e3151e7a 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite' import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } 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 { ENV, getAssistantOpenCodeDir, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' import { migrate } from '../../../src/db/migration-runner' import { allMigrations } from '../../../src/db/migrations' import { SettingsService } from '../../../src/services/settings' @@ -40,6 +40,9 @@ process.env.WORKSPACE_PATH = suiteWorkspaceParent const reposRoot = getReposPath() const worktreesRoot = getScheduleWorktreesPath() +const toolOutputRoot = getOpenCodeToolOutputPath() +const skillsRoot = getOpenCodeGlobalSkillsPath() +const agentTmpRoot = getOpenCodeAgentTmpPath() const repoADir = path.join(reposRoot, 'repo-a') const repoBDir = path.join(reposRoot, 'repo-b') const worktreeDir = path.join(worktreesRoot, 'job-1-run-2') @@ -60,6 +63,9 @@ describe('SandboxRuntimeService', () => { mkdirSync(repoADir, { recursive: true }) mkdirSync(repoBDir, { recursive: true }) mkdirSync(worktreeDir, { recursive: true }) + mkdirSync(toolOutputRoot, { recursive: true }) + mkdirSync(skillsRoot, { recursive: true }) + mkdirSync(agentTmpRoot, { recursive: true }) }) afterEach(() => { @@ -144,6 +150,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount('/tmp', runtimeTmpfsSizeMib()), ], patches: [], @@ -617,6 +626,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), bindMount('/workspace/config'), ], }), @@ -750,6 +762,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), bindMount('/workspace/config'), ], }), @@ -786,6 +801,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount(reposRoot, 512), ], })), @@ -978,6 +996,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount(path.join(reposRoot, 'repo-a', 'src'), 512), ], })), @@ -1016,6 +1037,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), bindMount('/workspace/config'), ], }), @@ -1122,6 +1146,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), bindMount('/workspace/config'), ], }), @@ -1213,6 +1240,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount('/tmp', runtimeTmpfsSizeMib()), ], })), @@ -1900,6 +1930,9 @@ describe('SandboxRuntimeService', () => { mounts: [ { ...bindMount(reposRoot), options: { readonly: false, noexec: true, nosuid: false, nodev: false } }, bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), ], }), ), @@ -2746,6 +2779,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), { type: 'Tmpfs', guest: '/tmp', size_mib: runtimeTmpfsSizeMib(), ...mountOverrides }, ], }), @@ -2759,6 +2795,9 @@ describe('SandboxRuntimeService', () => { mounts: [ { ...bindMount(reposRoot), follow_root_symlinks: true }, bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), ], }), 'follow_root_symlinks', @@ -2771,6 +2810,9 @@ describe('SandboxRuntimeService', () => { mounts: [ { ...bindMount(reposRoot), host_permissions: 'public' }, bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), ], }), 'host_permissions', @@ -2783,6 +2825,9 @@ describe('SandboxRuntimeService', () => { mounts: [ { ...bindMount(reposRoot), stat_virtualization: 'none' }, bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), ], }), 'stat_virtualization', @@ -2795,6 +2840,9 @@ describe('SandboxRuntimeService', () => { mounts: [ { ...bindMount(reposRoot), quota_mib: 512 }, bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), ], }), 'quota_mib', @@ -2877,6 +2925,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), ], }), 'missing the runtime tmpfs mount at /tmp', @@ -2889,6 +2940,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount('/tmp', runtimeTmpfsSizeMib()), tmpfsMount('/tmp', runtimeTmpfsSizeMib()), ], @@ -2903,6 +2957,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount('/tmp', runtimeTmpfsSizeMib() + 1), ], }), @@ -2916,6 +2973,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), { type: 'Tmpfs', guest: '/tmp', size_mib: runtimeTmpfsSizeMib(), options: { readonly: true, noexec: false, nosuid: false, nodev: false } }, ], }), @@ -2972,6 +3032,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount('/dev/shm', 64), tmpfsMount('/tmp', runtimeTmpfsSizeMib()), ], @@ -2986,6 +3049,9 @@ describe('SandboxRuntimeService', () => { mounts: [ bindMount(reposRoot), bindMount(worktreesRoot), + bindMount(toolOutputRoot), + bindMount(skillsRoot), + bindMount(agentTmpRoot), tmpfsMount(getAssistantOpenCodeDir(), null), tmpfsMount('/tmp', runtimeTmpfsSizeMib()), ], diff --git a/docker-compose.sandbox.yml b/docker-compose.sandbox.yml index 3f21f3a5..c3d462f1 100644 --- a/docker-compose.sandbox.yml +++ b/docker-compose.sandbox.yml @@ -16,7 +16,7 @@ services: cap_add: - NET_ADMIN environment: - - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox@sha256:edec46ffc48bd23fdd36b732492df7c5da5acd687ba0383e66ee28bc7c78770f} + - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox@sha256:30d4c0e7cfe087d23e7387e1d0633bbbe3bb64f222263a24f3d9ca7559bea8aa} - SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G} - SANDBOX_CPUS=${SANDBOX_CPUS:-2} - SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}} diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index 0aebff14..50f55080 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -330,7 +330,7 @@ services: cap_add: - NET_ADMIN environment: - - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox@sha256:edec46ffc48bd23fdd36b732492df7c5da5acd687ba0383e66ee28bc7c78770f} + - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox@sha256:30d4c0e7cfe087d23e7387e1d0633bbbe3bb64f222263a24f3d9ca7559bea8aa} - SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G} - SANDBOX_CPUS=${SANDBOX_CPUS:-2} - SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}} diff --git a/docs/configuration/environment.md b/docs/configuration/environment.md index 3b8e08b9..6018e5ab 100644 --- a/docs/configuration/environment.md +++ b/docs/configuration/environment.md @@ -116,7 +116,7 @@ Sandboxed agent commands run inside a microVM managed by `msb` (see [Agent Sandb |----------|-------------|---------| | `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. Digest-pinned by default so a rebuilt guest image is actually adopted; see [Sandbox Guest Image](../features/sandboxing.md#sandbox-guest-image) for what the default ships and how to build your own | `docker.io/cstechdev/ocm-sandbox@sha256:edec46ff…` | +| `SANDBOX_IMAGE` | OCI image the microVM boots from. Digest-pinned by default so a rebuilt guest image is actually adopted; see [Sandbox Guest Image](../features/sandboxing.md#sandbox-guest-image) for what the default ships and how to build your own | `docker.io/cstechdev/ocm-sandbox@sha256:30d4c0e7…` | | `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` | diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index f5572ced..5338fbd1 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -67,7 +67,7 @@ The overlay exposes `/dev/kvm`, `/dev/net/tun`, and `NET_ADMIN` without enabling All projects share one microVM named `ocm-workspace`: -- It mounts `/workspace/repos` and `/workspace/schedule-worktrees` at identical guest paths. +- It mounts the two project roots plus the OpenCode directories agents are handed absolute paths to, at identical guest paths. See [Mounts and Secrets](#mounts-and-secrets). - Repositories and worktrees created after boot are visible immediately because their parent roots are mounted. - Each command supplies its own working directory through `msb exec -w`. - A session outside the mounted roots is refused rather than executed on the host. @@ -87,14 +87,25 @@ msb rm --force --label ocm.managed=true The microVM receives writable bind mounts for: -- `/workspace/repos` -- `/workspace/schedule-worktrees` +| Host path | Why it is mounted | +|-----------|-------------------| +| `/workspace/repos` | Project root | +| `/workspace/schedule-worktrees` | Project root | +| `/workspace/.opencode/state/opencode/tool-output` | Where OpenCode saves the full content of a truncated tool result before handing the agent that absolute path | +| `/workspace/.config/opencode/skills` | Global skills, including the scripts and reference files a skill bundles and refers to by absolute path | +| `/workspace/.opencode/tmp/opencode` | The temporary directory the `bash` tool description tells agents to use for work outside the workspace | + +Each is mounted at the identical guest path. That is the point: OpenCode hands the model absolute host paths, and the host-side `read`, `write`, and `glob` tools resolve them against the container. A path that is not mounted resolves for those tools but not for a sandboxed `bash` call, which is how an agent ends up searching for a file it was just told the exact location of. + +Only the two project roots are accepted as working directories. The other three mounts are readable and writable but are never a valid working directory, so `bash` calls still have to run inside a repository or a schedule worktree. No internal API token exists anywhere under the mounted roots. The token lives in the Manager's database and reaches the generated plugins only through the `OCM_INTERNAL_TOKEN` environment variable of the Manager's own OpenCode process, which is never part of the guest environment. Because `localhost` inside the microVM is the guest rather than the Manager, and because the guest has no token to present, an agent command cannot call the internal API with `curl`. Agents reach the Manager through the `ocm` tool instead, which executes in the Manager's own OpenCode process. The tool's `request` action covers settings, repos, OpenCode workspaces, and schedules through an allow-list of internal API routes, while `send_notification` covers push notifications. -The microVM also mounts a runtime-owned tmpfs at `/tmp`. It is sized to one quarter of the microVM memory, clamped to 1-512 MiB, so agent commands get writable scratch space that is not backed by a host filesystem. +The microVM also mounts a runtime-owned tmpfs at `/tmp`. It is sized to one quarter of the microVM memory, clamped to 1-512 MiB, so agent commands get guest-only scratch space that is not backed by a host filesystem. + +The agent temporary directory is separate from that tmpfs. The Manager sets `TMPDIR=/workspace/.opencode/tmp` on the OpenCode child, which puts OpenCode's own temporary directory at `/workspace/.opencode/tmp/opencode` — the path its `bash` tool description advertises — so the same files are visible to sandboxed commands and to the host-side file tools. Everything else under `TMPDIR` (temporary files from host-side `git`, `gh`, and MCP servers) stays out of the guest. The Manager empties the mounted directory each time it starts the OpenCode child, matching the lifetime it had in the container's `/tmp`; it clears the contents rather than the directory itself, because replacing the directory would detach a running microVM's bind mount. The following remain outside the microVM: @@ -102,8 +113,9 @@ The following remain outside the microVM: |-----------|----------| | `/workspace/config` | SSH configuration and known hosts | | `/workspace/.ssh-keys` | Repository SSH private keys | -| `/workspace/.config` | OpenCode configuration and generated plugins | -| `/workspace/.opencode/state` | Provider credentials | +| `/workspace/.config/opencode/plugin`, `/workspace/.config/ocm` | Generated plugins and the shell shim — the enforcement mechanism itself | +| `/workspace/.config/opencode` (except `skills`) | OpenCode configuration | +| `/workspace/.opencode/state` (except `opencode/tool-output`) | Provider and MCP credentials | OpenCode's host process still reads these paths normally. They are omitted only from the agent command environment. @@ -157,14 +169,16 @@ Understand the trade-off before enabling it. `msb exec -e` is the only injection `SANDBOX_IMAGE` defaults to a digest-pinned reference of `docker.io/cstechdev/ocm-sandbox`, built from `Dockerfile.sandbox` in this repository and published for `linux/amd64` and `linux/arm64` from a build host with `docker buildx`: ```bash -docker buildx build --platform linux/amd64,linux/arm64 \ +docker buildx build --builder \ + --platform linux/amd64,linux/arm64 \ -t docker.io/cstechdev/ocm-sandbox:latest \ --build-arg PLAYWRIGHT_VERSION=1.56.0 \ - -f Dockerfile.sandbox --load . -docker push docker.io/cstechdev/ocm-sandbox:latest + -f Dockerfile.sandbox --push . docker buildx imagetools inspect docker.io/cstechdev/ocm-sandbox:latest # copy the index digest ``` +A multi-platform build needs the `docker-container` driver and pushes the manifest list directly; `--load` cannot hold two platforms, and the default `docker` driver cannot build them. + Then update the pin in `shared/src/config/defaults.ts` (`SANDBOX.IMAGE`) and in the `docker-compose.sandbox.yml` default to the new `@sha256:` digest. That bump is what makes deployments adopt a rebuilt guest image, and it is deliberate rather than convenient: - msb caches images by reference. `msb pull docker.io/cstechdev/ocm-sandbox:latest` reports "already cached" without contacting the registry, and `pull_policy: IfMissing` never re-pulls, so a host that pulled a mutable tag once keeps that content forever. @@ -178,7 +192,9 @@ It is `node:24` (Debian 12, `buildpack-deps` based), so the compile toolchain is | --- | --- | --- | | `gcc` / `g++` / `make` / `ld` / `pkg-config` | `node:24` | GCC 12.2, GNU Make 4.3 | | `glib-2.0` | `node:24` | 2.74.6, with `pkg-config` metadata | -| `git`, `ssh`, `python3`, `curl`, `unzip` | `node:24` | git 2.39.5 | +| `git`, `ssh`, `python3`, `curl`, `wget`, `unzip` | `node:24` | git 2.39.5 | +| `python` | apt (`python-is-python3`) | The base image ships only `python3`; a skill or script invoking `python` would otherwise fail | +| `ping`, `ip`, `ss`, `netstat`, `dig`, `host`, `nslookup`, `nc`, `traceroute`, `lsof`, `rsync` | apt | `node:24` ships no network diagnostics at all. The image build fails if any of these is missing | | `pnpm` | corepack | Prewarmed into a shared, writable `COREPACK_HOME` (`/usr/local/share/corepack`), so the exec user runs the build-time version offline. A project `packageManager` pin of a different version downloads on first use | | `bun`, `bunx` | official installer | Installed to `/opt/bun`, world-readable, both symlinked onto `PATH` | | `uv`, `uvx` | Astral installer | Standalone binaries on `PATH`; `uv tool` shims land in `/opt/agent-tools/bin`, which is on `PATH` | diff --git a/docs/features/skills.md b/docs/features/skills.md index 1bf79342..6df9bbb2 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -9,6 +9,8 @@ Skills are reusable instruction sets that provide domain-specific workflows and | **Global** | `$WORKSPACE_PATH/.config/opencode/skills//SKILL.md` (defaults to `./workspace/.config/opencode/skills/`) | Available across all repositories | | **Project** | `/.opencode/skills//SKILL.md` | Scoped to a specific repository | +Both scopes are mounted into the microVM when [sandboxing](./sandboxing.md) is enforced, so a skill that bundles scripts or reference files can run them from a sandboxed `bash` call. Because the mount is writable, an agent command can also modify a global skill, which affects every later session in every repository. + ## Skill File Format Each skill is a `SKILL.md` file with YAML frontmatter and a markdown body: diff --git a/shared/src/config/defaults.ts b/shared/src/config/defaults.ts index 28bea551..cc548b76 100644 --- a/shared/src/config/defaults.ts +++ b/shared/src/config/defaults.ts @@ -33,7 +33,7 @@ export const DEFAULTS = { SANDBOX: { MSB_PATH: 'msb', - IMAGE: 'docker.io/cstechdev/ocm-sandbox@sha256:edec46ffc48bd23fdd36b732492df7c5da5acd687ba0383e66ee28bc7c78770f', + IMAGE: 'docker.io/cstechdev/ocm-sandbox@sha256:30d4c0e7cfe087d23e7387e1d0633bbbe3bb64f222263a24f3d9ca7559bea8aa', MEMORY: '4G', CPUS: 2, EXEC_USER: 'node', diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index 60f5ace5..16201b29 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -147,6 +147,12 @@ export const getReposPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPA 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 getOpenCodeConfigHome = () => path.join(ENV.WORKSPACE.BASE_PATH, '.config') +export const getOpenCodeStateHome = () => path.join(ENV.WORKSPACE.BASE_PATH, '.opencode', 'state') +export const getOpenCodeGlobalSkillsPath = () => path.join(getOpenCodeConfigHome(), 'opencode', 'skills') +export const getOpenCodeToolOutputPath = () => path.join(getOpenCodeStateHome(), 'opencode', 'tool-output') +export const getOpenCodeTmpHome = () => path.join(ENV.WORKSPACE.BASE_PATH, '.opencode', 'tmp') +export const getOpenCodeAgentTmpPath = () => path.join(getOpenCodeTmpHome(), 'opencode') 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') diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index b2fa1484..225d4b7a 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -125,6 +125,7 @@ export const BLOCKED_SERVER_ENV_KEYS = [ 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_CONFIG_HOME', + 'TMPDIR', ] as const; export const DEFAULT_GIT_IDENTITY: GitIdentity = {