diff --git a/.env.example b/.env.example index fae2206c..8f0658c6 100644 --- a/.env.example +++ b/.env.example @@ -137,8 +137,10 @@ PASSKEY_ORIGIN=http://localhost:5003 # 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 +# OCI image the microVM boots from. The default ships gh, a Playwright Chromium, +# and the node:24 toolchain; any image you point this at must contain every tool +# the agent expects to run and a shell at /bin/sh. +# SANDBOX_IMAGE=docker.io/cstechdev/ocm-sandbox:latest # MicroVM memory (e.g. 4G) # SANDBOX_MEMORY=4G # MicroVM CPU count @@ -149,7 +151,8 @@ PASSKEY_ORIGIN=http://localhost:5003 # 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) +# Network mode for the microVM: public, private, or host, or a comma-separated +# composition (for example public,host) # SANDBOX_NET=public # Timeout for microVM startup, in milliseconds # SANDBOX_START_TIMEOUT_MS=300000 diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 175ab029..9c26e7a2 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -217,12 +217,12 @@ function needsOpenCodeRestart( return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field)) } -function sandboxPreferenceChanged( +function sandboxEnforcementChanged( previous: SandboxPreferences | undefined, next: SandboxPreferences | undefined, ): boolean { if (next === undefined) return false - return JSON.stringify(previous ?? {}) !== JSON.stringify(next) + return (previous?.enabled ?? false) !== next.enabled } function parseOptionalRepoId(value: string | undefined): number | undefined { @@ -396,7 +396,7 @@ 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) + const sandboxChanged = sandboxEnforcementChanged(currentSettings.preferences.sandbox, validated.preferences.sandbox) const credentialsChanged = validated.preferences.gitCredentials !== undefined && JSON.stringify(currentSettings.preferences.gitCredentials || []) !== JSON.stringify(validated.preferences.gitCredentials) @@ -435,9 +435,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const currentSettings = settingsService.getSettings(userId) const settings = settingsService.resetSettings(userId) - const sandboxChanged = sandboxPreferenceChanged(currentSettings.preferences.sandbox, settings.preferences.sandbox) + const sandboxChanged = sandboxEnforcementChanged(currentSettings.preferences.sandbox, settings.preferences.sandbox) if (sandboxChanged) { - logger.info('Sandbox preference changed, marking OpenCode server restart as pending') + logger.info('Sandbox enforcement changed, marking OpenCode server restart as pending') opencodeServerManager.markRestartPending() } diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 763a295b..ee526ae0 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -1733,6 +1733,27 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(opencodeServerManager.markRestartPending).not.toHaveBeenCalled() }) + it('does not mark the OpenCode server restart pending when only sandbox.gitCredentials changes', async () => { + mockGetSettings.mockReturnValue({ + preferences: { sandbox: { enabled: true, gitCredentials: false } }, + updatedAt: 1, + }) + mockUpdateSettings.mockReturnValue({ + preferences: { sandbox: { enabled: true, gitCredentials: true } }, + updatedAt: 2, + }) + + const req = new Request('http://localhost/', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: { sandbox: { enabled: true, gitCredentials: true } } }), + }) + const res = await settingsApp.fetch(req) + + expect(res.status).toBe(200) + expect(opencodeServerManager.markRestartPending).not.toHaveBeenCalled() + }) + it('does not mark the OpenCode server restart pending when sandbox is absent from the patch', async () => { mockGetSettings.mockReturnValue({ preferences: { sandbox: { enabled: true } }, diff --git a/backend/test/scripts/docker-config.test.ts b/backend/test/scripts/docker-config.test.ts index 2da7ada7..cb611664 100644 --- a/backend/test/scripts/docker-config.test.ts +++ b/backend/test/scripts/docker-config.test.ts @@ -227,6 +227,9 @@ describe('docker lifecycle scripts', () => { describe('sandbox compose overlay', () => { const overlayPath = join(repoRoot, 'docker-compose.sandbox.yml') const overlay = read(overlayPath) + const overlayDirectives = overlay + .split('\n') + .filter((line) => line.trim() !== '' && !line.trimStart().startsWith('#')) 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}}') @@ -239,11 +242,30 @@ describe('sandbox compose overlay', () => { }) 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('"/dev/net/tun:/dev/net/tun"') + expect(overlay).toContain('- NET_ADMIN') expect(overlay).toContain('microsandbox-data:/home/node/.microsandbox') expect(overlay).toMatch(/^volumes:\n(?:.*\n)*?\s+microsandbox-data:/m) }) + + it('grants only the devices and capability msb needs, never full container privilege', () => { + expect(overlayDirectives.join('\n')).not.toContain('privileged') + }) + + it('keeps the sandbox overlay docs snippet in sync with docker-compose.sandbox.yml', () => { + const docs = read(dockerDocsPath) + const docsOverlay = [...docs.matchAll(/```yaml\n([\s\S]*?)\n```/g)] + .map((match) => match[1]!) + .find((block) => block.includes('microsandbox-data')) + + expect(docsOverlay, 'docs must contain the sandbox overlay yaml block').toBeDefined() + + const significantLines = (source: string[]) => + source.filter((line) => line.trim() !== '').map((line) => line.replace(/\s+$/, '')).join('\n') + + expect(significantLines(docsOverlay!.split('\n'))).toBe(significantLines(overlayDirectives)) + }) }) describe('named-volume migration recipe', () => { diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index bce015e4..4f97e384 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -319,14 +319,16 @@ With a fresh Docker volume, first startup imports the host OpenCode config and s ## 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: +Optional KVM-backed agent sandboxing (see [Agent Sandboxing](../features/sandboxing.md)). The sandbox overlay (`docker-compose.sandbox.yml`) grants the container KVM and guest-networking access, passes sandbox tuning through from `.env`, and persists microsandbox state. It deliberately avoids `privileged: true`, granting only the specific devices and capability `msb` needs: ```yaml services: app: - privileged: true devices: - "/dev/kvm:/dev/kvm" + - "/dev/net/tun:/dev/net/tun" + cap_add: + - NET_ADMIN environment: - SANDBOX_IMAGE=${SANDBOX_IMAGE:-docker.io/cstechdev/ocm-sandbox:latest} - SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G} @@ -349,7 +351,7 @@ Start the Manager with the overlay: 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. +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. `/dev/net/tun` and `NET_ADMIN` provide guest networking for `SANDBOX_NET=public`; if `msb` reports a missing device or capability on a particular host, add that specific entry rather than enabling full privilege. `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. diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index 13ea4845..7821183d 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -139,7 +139,7 @@ Forwarding is opt-in, off by default: | Scope | Where | Effect | | --- | --- | --- | | Global | Settings → Sandbox → *Git credentials in sandbox* (`preferences.sandbox.gitCredentials`) | Default for every repo | -| Per repo | `repo_settings.sandboxGitCredentials` | Overrides the global default in either direction | +| Per repo | `repo_settings.sandboxGitCredentials` | Overrides the global default in either direction. The planner honours it when resolving credentials, but nothing writes it yet — there is no UI or API for the per-repo override | When enabled, the planner resolves credentials on the host and the shim forwards them into the microVM with `msb exec -e`: @@ -148,9 +148,9 @@ When enabled, the planner resolves credentials on the host and the shim forwards - `GIT_AUTHOR_*` / `GIT_COMMITTER_*` so `git commit` has an identity, and `GH_TOKEN` / `GITHUB_TOKEN` for `gh`. - At most 16 hosts. Beyond that the Manager logs a warning and forwards the first 16 rather than emitting a `GIT_CONFIG_COUNT` that git would reject. -Credentials are resolved per command, so changing a credential takes effect on the next sandboxed command without restarting the OpenCode server. +Both the switch and the credentials themselves are resolved per command, so turning forwarding on or off, or changing a credential, takes effect on the next sandboxed command without restarting the OpenCode server. Only the sandbox enable toggle requires a restart. -Understand the trade-off before enabling it. `msb exec -e` is the only injection mechanism microsandbox offers, so the token is visible in the `msb` process arguments on the host and in the guest environment for that command's lifetime. A prompt-injected agent inside the microVM can read and exfiltrate any credential you forward. Leave it off for repos where the agent handles untrusted input, and prefer per-repo opt-in over the global switch. +Understand the trade-off before enabling it. `msb exec -e` is the only injection mechanism microsandbox offers, so the token is visible in the `msb` process arguments on the host and in the guest environment for that command's lifetime. A prompt-injected agent inside the microVM can read and exfiltrate any credential you forward. The global switch is the only exposed control today, so enabling it applies to every repo; leave it off while any agent handles untrusted input. ## Sandbox Guest Image diff --git a/frontend/src/components/settings/SandboxSettings.test.tsx b/frontend/src/components/settings/SandboxSettings.test.tsx index c95daf37..4c93b12b 100644 --- a/frontend/src/components/settings/SandboxSettings.test.tsx +++ b/frontend/src/components/settings/SandboxSettings.test.tsx @@ -51,7 +51,7 @@ describe('SandboxSettings', () => { render() - expect(screen.getByRole('switch')).toBeChecked() + expect(screen.getByRole('switch', { name: 'Toggle sandbox' })).toBeChecked() }) it('writes only the sandbox preference when toggled and shows the restart notice', async () => { @@ -61,9 +61,9 @@ describe('SandboxSettings', () => { render() - await user.click(screen.getByRole('switch')) + await user.click(screen.getByRole('switch', { name: 'Toggle sandbox' })) - expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true } }) + expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, gitCredentials: false } }) expect(screen.getByText('Restart the OpenCode server to apply sandbox changes.')).toBeInTheDocument() }) @@ -73,7 +73,7 @@ describe('SandboxSettings', () => { render() - expect(screen.getByRole('switch')).toBeDisabled() + expect(screen.getByRole('switch', { name: 'Toggle sandbox' })).toBeDisabled() expect(screen.getByText('KVM is not available on this host')).toBeInTheDocument() }) @@ -84,14 +84,14 @@ describe('SandboxSettings', () => { render() - const toggle = screen.getByRole('switch') + const toggle = screen.getByRole('switch', { name: 'Toggle sandbox' }) 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 } }) + expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: false, gitCredentials: false } }) }) it('disables the switch while sandbox availability has not been reported', () => { @@ -107,7 +107,7 @@ describe('SandboxSettings', () => { render() - expect(screen.getByRole('switch')).toBeDisabled() + expect(screen.getByRole('switch', { name: 'Toggle sandbox' })).toBeDisabled() expect(screen.getByText('Checking sandbox availability...')).toBeInTheDocument() }) @@ -127,8 +127,43 @@ describe('SandboxSettings', () => { render() - await user.click(screen.getByRole('switch')) + await user.click(screen.getByRole('switch', { name: 'Toggle sandbox' })) expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Failed to update sandbox preference') }) + + it('preserves the git credential preference when the sandbox toggle changes', async () => { + const user = userEvent.setup() + const { updateSettingsAsync } = mockUseSettings({ + preferences: { sandbox: { enabled: false, gitCredentials: true } }, + }) + mockHealth({ available: true, enforced: false }) + + render() + + await user.click(screen.getByRole('switch', { name: 'Toggle sandbox' })) + + expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, gitCredentials: true } }) + }) + + it('enables git credential forwarding without changing the sandbox preference', async () => { + const user = userEvent.setup() + const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } }) + mockHealth({ available: true, enforced: false }) + + render() + + await user.click(screen.getByRole('switch', { name: 'Toggle git credentials in sandbox' })) + + expect(updateSettingsAsync).toHaveBeenCalledWith({ sandbox: { enabled: true, gitCredentials: true } }) + }) + + it('disables the git credential switch while sandboxing is off', () => { + mockUseSettings() + mockHealth({ available: true, enforced: false }) + + render() + + expect(screen.getByRole('switch', { name: 'Toggle git credentials in sandbox' })).toBeDisabled() + }) }) diff --git a/frontend/src/components/settings/SandboxSettings.tsx b/frontend/src/components/settings/SandboxSettings.tsx index d77b3931..f6c5c7d5 100644 --- a/frontend/src/components/settings/SandboxSettings.tsx +++ b/frontend/src/components/settings/SandboxSettings.tsx @@ -13,16 +13,26 @@ export function SandboxSettings() { const sandbox = health?.sandbox const isAvailable = sandbox?.available === true const enabled = preferences?.sandbox?.enabled ?? false + const gitCredentials = preferences?.sandbox?.gitCredentials ?? false - const handleToggle = async (next: boolean) => { + const saveSandbox = async (next: { enabled: boolean; gitCredentials: boolean }, message: string) => { try { - await updateSettingsAsync({ sandbox: { enabled: next } }) - showToast.success(next ? 'Sandboxing enabled' : 'Sandboxing disabled') + await updateSettingsAsync({ sandbox: next }) + showToast.success(message) } catch { showToast.error('Failed to update sandbox preference') } } + const handleToggle = (next: boolean) => + saveSandbox({ enabled: next, gitCredentials }, next ? 'Sandboxing enabled' : 'Sandboxing disabled') + + const handleGitCredentialsToggle = (next: boolean) => + saveSandbox( + { enabled, gitCredentials: next }, + next ? 'Git credentials will be forwarded into the sandbox' : 'Git credential forwarding disabled', + ) + return (
@@ -59,6 +69,22 @@ export function SandboxSettings() { />
+
+
+

Git credentials in sandbox

+

+ Forward git credentials into the microVM so sandboxed git and gh commands can authenticate. A + prompt-injected agent can exfiltrate any credential you forward. +

+
+ +
+ {health?.opencodeRestartPending && (