Files
opencode-manager/backend/test/routes/internal-sandbox.test.ts
Chris Scott 4862d9c5cb fix(sandbox): wait for guest agent, verify exec user provisioning, pin rebuilt image (#343)
* fix(sandbox): wait for the guest agent before provisioning the exec user

A freshly created microVM does not accept msb exec until its guest agent is
up, so provisioning raced the boot and died on three 15s timeouts, which then
failed the whole enforcement-enable path. Gate provisioning on msb ping
bounded by SANDBOX_START_TIMEOUT_MS, give the exec a 30s budget, and downgrade
a provisioning failure to a warning so a missing sudo entry never blocks
sandboxed commands.

* fix(sandbox): align canonical shell spec with msb and pin the rebuilt guest image

- pass --shell /bin/sh explicitly at create and derive the canonical
  spec from the create args so msb 0.6.15 recordings match attestation
- bump the SANDBOX_IMAGE pin to the rebuilt guest image digest
- verify the provisioned exec user inside the guest and give the
  provisioning exec the full start timeout, bounded by a deadline

* docs(sandbox): sync the image digest pin into the docker and environment docs

* fix(sandbox): verify the guest image as an unknown uid and pin the rebuild

The build verification ran as uid 1000, which is the base image's node user,
so it exercised the known-user path and would have passed even if the numeric
exec uid the runtime actually uses were broken. Verify the toolchain as uid
4242 instead and keep the sudo check on the known user, since sudo refuses
unknown uids by design. Also only write the shadow entry when the passwd entry
is created, so a uid that already exists leaves no orphan record.

* fix(sandbox): close spawned command stdin so msb exec completes

msb exec reads its stdin during session setup and waits for EOF, so
every child spawned through executeCommand with an open stdin pipe hung
until its timeout while identical CLI execs finished instantly. Spawn
children with stdin ignored.

Also verify the provisioned exec user from a fresh guest exec after
each provisioning attempt and move failed provisioning to a logged
background retry bounded by five attempts so a slow guest no longer
blocks enforcement or leaves sudo silently missing.

* test(sandbox): derive expected inspect spec from canonical builders

* fix(sandbox): cancel provisioning retries on stop and serialize attempts

Advance the provisioning retry generation and drop the pending retry at the
start of every managed-sandbox stop, so a retry scheduled before a toggle-off
no longer pings and provisions a stopped sandbox. Clearing the promise as well
keeps later retries schedulable, since the generation guard would otherwise
strand it and short-circuit scheduling.

Route every provisioning caller through a single in-flight promise so the
boot-path attempt and the background retry cannot run the check-then-append
passwd and shadow script concurrently and append duplicate account entries.
2026-08-28 19:23:40 -04:00

182 lines
6.6 KiB
TypeScript

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 {
buildCanonicalSandboxSpec,
resolveExpectedSandboxNetworkPolicy,
resolveSandboxRuntimeTmpfsSizeMib,
WORKSPACE_SANDBOX_NAME,
} from '../../src/services/sandbox/command'
import { executeCommand } from '../../src/utils/process'
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
import { forceProcessAttestation } from '../../src/services/opencode/process-identity'
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
function trustedRunningInspect(): { exitCode: number; stdout: string; stderr: string } {
const canonical = buildCanonicalSandboxSpec()
const { memory_mib: memoryMib } = canonical.resources as { memory_mib: number }
const config = {
...canonical,
mounts: [
...(canonical.mounts as unknown[]),
{
type: 'Tmpfs',
guest: '/tmp',
size_mib: resolveSandboxRuntimeTmpfsSizeMib(memoryMib),
options: { readonly: false, noexec: false, nosuid: false, nodev: false },
},
],
network: {
enabled: true,
ports: [],
policy: resolveExpectedSandboxNetworkPolicy(ENV.SANDBOX.NET),
},
}
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' })
forceProcessAttestation(true)
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(() => {
forceProcessAttestation(null)
db.close()
rmSync(repoDir, { recursive: true, force: true })
})
function postShell(body: unknown, auth = true) {
return app.request('/api/internal/sandbox/shell', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'content-type': 'application/json',
...(auth ? { authorization: `Bearer ${token}` } : {}),
},
})
}
it('POST /shell returns 401 without bearer token', async () => {
const res = await postShell({ directory: repoDir }, false)
expect(res.status).toBe(401)
})
it('POST /shell returns host mode when the sandbox preference is off', async () => {
const res = await postShell({ directory: repoDir })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ mode: 'host' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
})
it('POST /shell returns the mapped sandbox working directory when enforcement is on', async () => {
settingsService.updateSettings({ sandbox: { enabled: true } })
const res = await postShell({ directory: repoDir })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
mode: 'sandbox',
workdir: repoDir,
})
})
it('POST /shell returns 400 for a malformed body', async () => {
const res = await postShell({ directory: '' })
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Invalid request' })
})
it('POST /shell 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 postShell({ directory: repoDir })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ mode: 'blocked', reason: '/dev/kvm is not available' })
expect(mockExecuteCommand).not.toHaveBeenCalled()
})
it('POST /shell never returns host mode for an enforced request even when the preference is off', async () => {
const res = await postShell({ directory: repoDir, enforced: true })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
mode: 'sandbox',
workdir: repoDir,
})
})
it('POST /shell blocks an enforced request for a directory outside the project roots', async () => {
const res = await postShell({ directory: '/etc', 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')
})
})