mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(sandbox): make the guest toolchain and sudo usable by the exec user
Set a writable guest HOME and shared COREPACK_HOME, expose bunx, redirect npm/pnpm global installs to a PATH dir, lift Debian's externally-managed pip guard, and verify the toolchain as an unprivileged uid at build time. Provision passwd/group/shadow entries for the numeric exec uid at sandbox create, start, and Manager boot so passwordless sudo works in the guest.
This commit is contained in:
1 parent
c5f0964988
commit
78702da2e4
8 files changed
+271
-22
No files matched your search
+43
-10
@@ -7,8 +7,8 @@
|
||||
FROM node:24
|
||||
|
||||
ARG PLAYWRIGHT_VERSION=1.56.0
|
||||
# Bump TOOLS_CACHEBUST (e.g. via --build-arg) to force a fresh gh/Playwright
|
||||
# install without invalidating the rest of the build cache.
|
||||
# Bump TOOLS_CACHEBUST (e.g. via --build-arg) to force a fresh tool install
|
||||
# without invalidating the rest of the build cache.
|
||||
ARG TOOLS_CACHEBUST=0
|
||||
|
||||
# Shared browser location so the sandbox exec user (SANDBOX_EXEC_USER, default
|
||||
@@ -17,11 +17,21 @@ ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
# Lets agent code `require("playwright")` from any working directory without a
|
||||
# project-local install. Only a resolution fallback; local node_modules wins.
|
||||
ENV NODE_PATH=/usr/local/lib/node_modules
|
||||
# msb exec runs commands as a numeric host uid with no /etc/passwd entry, so
|
||||
# the guest defaults to HOME=/ and every tool that writes per-user state (uv
|
||||
# and pip caches, git config, gh config, the pnpm store) fails with EACCES.
|
||||
# Point HOME at a sticky world-writable directory and give corepack a shared
|
||||
# prewarmed cache so the preinstalled pnpm resolves without network or root.
|
||||
ENV HOME=/home/ocm-agent
|
||||
ENV COREPACK_HOME=/usr/local/share/corepack
|
||||
ENV UV_TOOL_BIN_DIR=/opt/agent-tools/bin
|
||||
ENV PNPM_HOME=/opt/agent-tools
|
||||
ENV PATH=/opt/agent-tools/bin:$PATH
|
||||
|
||||
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 tree file procps \
|
||||
ca-certificates curl gh jq less ripgrep sudo tree file procps \
|
||||
python3-pip python3-venv && \
|
||||
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
|
||||
-o /usr/share/keyrings/githubcli-archive-keyring.gpg && \
|
||||
@@ -31,19 +41,24 @@ RUN echo "Installing gh and CLI tooling (cachebust=${TOOLS_CACHEBUST})" && \
|
||||
apt-get update && \
|
||||
apt-get install -y --no-install-recommends gh && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
rm -f /usr/lib/python3*/EXTERNALLY-MANAGED && \
|
||||
printf 'Defaults env_keep += "npm_config_prefix"\nALL ALL=(ALL:ALL) NOPASSWD:ALL\n' \
|
||||
> /etc/sudoers.d/ocm-guest && \
|
||||
chmod 440 /etc/sudoers.d/ocm-guest && \
|
||||
visudo -c && \
|
||||
gh --version
|
||||
|
||||
RUN echo "Installing pnpm, bun and uv (cachebust=${TOOLS_CACHEBUST})" && \
|
||||
mkdir -p /home/ocm-agent /opt/agent-tools/bin /usr/local/share/corepack && \
|
||||
chmod 1777 /home/ocm-agent /opt/agent-tools /opt/agent-tools/bin /usr/local/share/corepack && \
|
||||
corepack enable && corepack prepare pnpm@latest --activate && \
|
||||
curl -fsSL https://bun.sh/install | bash && \
|
||||
mv /root/.bun /opt/bun && \
|
||||
curl -fsSL https://bun.sh/install | BUN_INSTALL=/opt/bun bash && \
|
||||
chmod -R a+rX /opt/bun && \
|
||||
ln -sf /opt/bun/bin/bun /opt/bun/bin/bunx && \
|
||||
ln -s /opt/bun/bin/bun /usr/local/bin/bun && \
|
||||
curl -LsSf https://astral.sh/uv/install.sh | UV_NO_MODIFY_PATH=1 sh && \
|
||||
mv /root/.local/bin/uv /usr/local/bin/uv && \
|
||||
mv /root/.local/bin/uvx /usr/local/bin/uvx && \
|
||||
chmod +x /usr/local/bin/uv /usr/local/bin/uvx && \
|
||||
rm -rf /root/.npm /root/.cache/uv && \
|
||||
ln -s /opt/bun/bin/bun /usr/local/bin/bunx && \
|
||||
curl -LsSf https://astral.sh/uv/install.sh | UV_INSTALL_DIR=/usr/local/bin UV_NO_MODIFY_PATH=1 sh && \
|
||||
rm -rf /root/.npm /root/.cache/uv /home/ocm-agent/.cache && \
|
||||
pnpm --version && bun --version && uv --version
|
||||
|
||||
RUN echo "Installing playwright=${PLAYWRIGHT_VERSION} chromium (cachebust=${TOOLS_CACHEBUST})" && \
|
||||
@@ -52,3 +67,21 @@ RUN echo "Installing playwright=${PLAYWRIGHT_VERSION} chromium (cachebust=${TOOL
|
||||
chmod -R a+rX "${PLAYWRIGHT_BROWSERS_PATH}" && \
|
||||
rm -rf /var/lib/apt/lists/* /root/.npm && \
|
||||
npx --yes "playwright@${PLAYWRIGHT_VERSION}" --version
|
||||
|
||||
# Declared after the Playwright layer on purpose: npm_config_prefix must not
|
||||
# affect the root-run `npm install -g playwright`, which has to land in
|
||||
# /usr/local/lib/node_modules for the NODE_PATH fallback above to work.
|
||||
ENV npm_config_prefix=/opt/agent-tools
|
||||
|
||||
# The exec user is an unknown numeric uid, so verify as uid 1000 (also absent
|
||||
# from /etc/passwd) instead of root. A root-only check would not catch the
|
||||
# EACCES failures this image exists to prevent.
|
||||
RUN echo "Verifying guest toolchain as an unprivileged uid (cachebust=${TOOLS_CACHEBUST})" && \
|
||||
rm -rf /home/ocm-agent && \
|
||||
mkdir -p /home/ocm-agent && \
|
||||
chmod 1777 /home/ocm-agent && \
|
||||
setpriv --reuid=1000 --regid=1000 --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; sudo -n apt-get update -qq && sudo -n apt-get install -y -qq --no-install-recommends bc && bc --version | head -1; 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" && \
|
||||
npm uninstall -g --silent cowsay && \
|
||||
rm -rf /home/ocm-agent /opt/agent-tools /var/lib/apt/lists/* && \
|
||||
mkdir -p /home/ocm-agent /opt/agent-tools/bin && \
|
||||
chmod 1777 /home/ocm-agent /opt/agent-tools /opt/agent-tools/bin
|
||||
@@ -52,7 +52,7 @@ import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { detectSandboxCapability } from './services/sandbox/capability'
|
||||
import { stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
|
||||
import { SandboxRuntimeService, 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'
|
||||
@@ -296,6 +296,11 @@ try {
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
detectSandboxCapability()
|
||||
try {
|
||||
await new SandboxRuntimeService(db).provisionWorkspaceSandboxOnBoot()
|
||||
} catch (error) {
|
||||
logger.warn('Workspace sandbox provisioning skipped:', error)
|
||||
}
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
|
||||
@@ -455,3 +455,29 @@ export function resolveSandboxExecUserUid(): number | null {
|
||||
return Number(uid)
|
||||
}
|
||||
|
||||
export function resolveSandboxExecUserGid(): number | null {
|
||||
const gid = resolveSandboxExecUser().split(':')[1]
|
||||
if (gid === undefined || !/^\d+$/.test(gid)) return null
|
||||
return Number(gid)
|
||||
}
|
||||
|
||||
export function buildSandboxProvisionArgs(): string[] {
|
||||
const uid = resolveSandboxExecUserUid()
|
||||
const gid = resolveSandboxExecUserGid()
|
||||
if (uid === null || gid === null) return []
|
||||
return [
|
||||
'exec',
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
'--no-tty',
|
||||
'-q',
|
||||
'-u',
|
||||
'0:0',
|
||||
'--',
|
||||
'/bin/sh',
|
||||
'-c',
|
||||
`getent group ${gid} >/dev/null 2>&1 || echo 'ocm-exec:x:${gid}:' >> /etc/group; ` +
|
||||
`getent passwd ${uid} >/dev/null 2>&1 || echo 'ocm-exec:x:${uid}:${gid}:Manager sandbox exec user:/home/ocm-agent:/bin/sh' >> /etc/passwd; ` +
|
||||
`grep -q '^ocm-exec:' /etc/shadow || echo 'ocm-exec:*:19000:0:99999:7:::' >> /etc/shadow`,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
buildSandboxCreateArgs,
|
||||
buildSandboxInspectArgs,
|
||||
buildSandboxListArgs,
|
||||
buildSandboxProvisionArgs,
|
||||
buildSandboxRemoveArgs,
|
||||
buildSandboxStartArgs,
|
||||
buildSandboxStopManagedArgs,
|
||||
@@ -29,6 +30,8 @@ import {
|
||||
const SANDBOX_LS_CACHE_MS = 5000
|
||||
const SANDBOX_LS_TIMEOUT_MS = 15000
|
||||
const SANDBOX_STOP_TIMEOUT_MS = 30000
|
||||
const SANDBOX_PROVISION_ATTEMPTS = 3
|
||||
const SANDBOX_PROVISION_RETRY_DELAY_MS = 2000
|
||||
const SANDBOX_RUNTIME_TMPFS_GUEST = path.resolve('/tmp')
|
||||
|
||||
export type SandboxShellPlan =
|
||||
@@ -129,6 +132,7 @@ async function bootWorkspaceSandbox(): Promise<void> {
|
||||
await createWorkspaceSandbox()
|
||||
} else {
|
||||
await startWorkspaceSandbox()
|
||||
await provisionSandboxExecUserPasswd()
|
||||
const runningAttestation = await attestWorkspaceSandbox(true)
|
||||
if (!runningAttestation.trusted) {
|
||||
logger.warn(
|
||||
@@ -161,6 +165,7 @@ async function bootWorkspaceSandboxFromListing(): Promise<void> {
|
||||
await createWorkspaceSandbox()
|
||||
} else if (!entry.running) {
|
||||
await startWorkspaceSandbox()
|
||||
await provisionSandboxExecUserPasswd()
|
||||
const runningAttestation = await attestWorkspaceSandbox(true)
|
||||
if (!runningAttestation.trusted) {
|
||||
logger.warn(
|
||||
@@ -537,10 +542,35 @@ async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestat
|
||||
return await attestWorkspaceSandboxConfig(outcome.record.config)
|
||||
}
|
||||
|
||||
async function provisionSandboxExecUserPasswd(): Promise<void> {
|
||||
const provisionArgs = buildSandboxProvisionArgs()
|
||||
if (provisionArgs.length === 0) {
|
||||
return
|
||||
}
|
||||
let lastError: unknown = null
|
||||
for (let attempt = 0; attempt < SANDBOX_PROVISION_ATTEMPTS; attempt++) {
|
||||
if (attempt > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, SANDBOX_PROVISION_RETRY_DELAY_MS))
|
||||
}
|
||||
try {
|
||||
await executeCommand([sandboxExecutablePath(), ...provisionArgs], {
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})
|
||||
return
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`provisioning the sandbox exec user passwd entry failed: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
|
||||
)
|
||||
}
|
||||
|
||||
async function createWorkspaceSandbox(): Promise<void> {
|
||||
await executeCommand([sandboxExecutablePath(), ...buildSandboxCreateArgs()], {
|
||||
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
|
||||
})
|
||||
await provisionSandboxExecUserPasswd()
|
||||
const attestation = await attestWorkspaceSandbox(true)
|
||||
if (!attestation.trusted) {
|
||||
throw new Error(`newly created sandbox ${WORKSPACE_SANDBOX_NAME} failed attestation: ${attestation.reason}`)
|
||||
@@ -619,6 +649,18 @@ async function startWorkspaceSandbox(): Promise<void> {
|
||||
export class SandboxRuntimeService {
|
||||
constructor(private readonly db: Database) {}
|
||||
|
||||
async provisionWorkspaceSandboxOnBoot(): Promise<void> {
|
||||
if (!this.isSandboxEnabled()) return
|
||||
const capability = detectSandboxCapability()
|
||||
if (!capability.available) return
|
||||
if (getProcessIdentityAttestationError() !== null) return
|
||||
if (buildSandboxProvisionArgs().length === 0) return
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
if (entry === null || !entry.running) return
|
||||
await provisionSandboxExecUserPasswd()
|
||||
logger.info('Provisioned the workspace sandbox exec user passwd entry')
|
||||
}
|
||||
|
||||
isEnabled(): boolean {
|
||||
return this.isSandboxEnabled()
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ vi.mock('../../src/services/sandbox/capability', () => ({
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { createHealthRoutes } from '../../src/routes/health'
|
||||
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
|
||||
import { forceProcessAttestation } from '../../src/services/opencode/process-identity'
|
||||
import type { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
|
||||
const mockDetectSandboxCapability = detectSandboxCapability as ReturnType<typeof vi.fn>
|
||||
@@ -126,14 +127,18 @@ describe('Health Routes', () => {
|
||||
preferences: JSON.stringify({ sandbox: { enabled: true } }),
|
||||
updated_at: Date.now(),
|
||||
})
|
||||
forceProcessAttestation(true)
|
||||
try {
|
||||
const req = new Request('http://localhost/')
|
||||
const res = await healthApp.fetch(req)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
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' })
|
||||
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' })
|
||||
} finally {
|
||||
forceProcessAttestation(null)
|
||||
}
|
||||
})
|
||||
|
||||
it('should keep the overall status unchanged when the sandbox runtime is unavailable', async () => {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
buildSandboxCreateArgs,
|
||||
buildSandboxInspectArgs,
|
||||
buildSandboxListArgs,
|
||||
buildSandboxProvisionArgs,
|
||||
buildSandboxRemoveArgs,
|
||||
buildSandboxStartArgs,
|
||||
buildSandboxStopManagedArgs,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
quoteForShell,
|
||||
resolveExpectedSandboxNetworkPolicy,
|
||||
resolveSandboxExecUser,
|
||||
resolveSandboxExecUserGid,
|
||||
resolveSandboxExecUserUid,
|
||||
resolveSandboxRuntimeTmpfsSizeMib,
|
||||
sandboxMountRoots,
|
||||
@@ -245,6 +247,33 @@ describe('sandbox command builders', () => {
|
||||
|
||||
expect(resolveSandboxExecUser()).toBe('1001:1002')
|
||||
expect(resolveSandboxExecUserUid()).toBe(1001)
|
||||
expect(resolveSandboxExecUserGid()).toBe(1002)
|
||||
})
|
||||
|
||||
it('builds provisioning args that add the exec user passwd entry as root', () => {
|
||||
const proc = process as unknown as { getuid: () => number; getgid: () => number }
|
||||
vi.spyOn(proc, 'getuid').mockReturnValue(1001)
|
||||
vi.spyOn(proc, 'getgid').mockReturnValue(1002)
|
||||
|
||||
const args = buildSandboxProvisionArgs()
|
||||
|
||||
expect(args[0]).toBe('exec')
|
||||
expect(args).toContain(WORKSPACE_SANDBOX_NAME)
|
||||
expect(args[args.indexOf('-u') + 1]).toBe('0:0')
|
||||
const script = args[args.indexOf('-c') + 1]
|
||||
expect(script).toContain("getent group 1002 >/dev/null 2>&1 || echo 'ocm-exec:x:1002:' >> /etc/group")
|
||||
expect(script).toContain(
|
||||
"getent passwd 1001 >/dev/null 2>&1 || echo 'ocm-exec:x:1001:1002:Manager sandbox exec user:/home/ocm-agent:/bin/sh' >> /etc/passwd",
|
||||
)
|
||||
expect(script).toContain("grep -q '^ocm-exec:' /etc/shadow || echo 'ocm-exec:*:19000:0:99999:7:::' >> /etc/shadow")
|
||||
})
|
||||
|
||||
it('returns no provisioning args when the exec user does not resolve to numeric uid and gid', () => {
|
||||
const proc = process as unknown as { getuid: () => number | undefined; getgid: () => number | undefined }
|
||||
vi.spyOn(proc, 'getuid').mockReturnValue(undefined)
|
||||
vi.spyOn(proc, 'getgid').mockReturnValue(undefined)
|
||||
|
||||
expect(buildSandboxProvisionArgs()).toEqual([])
|
||||
})
|
||||
|
||||
it('aligns a numeric exec user with the manager gid', async () => {
|
||||
|
||||
@@ -52,6 +52,7 @@ describe('SandboxRuntimeService', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
resetSandboxRuntimeState()
|
||||
forceProcessAttestation(true)
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
@@ -310,6 +311,78 @@ describe('SandboxRuntimeService', () => {
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('inspect'))).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('provisions the exec user passwd entry after starting a stopped sandbox', async () => {
|
||||
enableEnforcement()
|
||||
let inspectCalls = 0
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('ls')) {
|
||||
return { exitCode: 0, stdout: stoppedListingOutput(), stderr: '' }
|
||||
}
|
||||
if (args.includes('inspect')) {
|
||||
inspectCalls += 1
|
||||
if (inspectCalls === 1) {
|
||||
return { exitCode: 0, stdout: trustedInspectOutput(), stderr: '' }
|
||||
}
|
||||
return inspectedRunningSandbox()
|
||||
}
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const plan = await service.planShell(repoADir)
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
|
||||
const provisionCall = mockExecuteCommand.mock.calls.find((call) => call[0].includes('exec'))
|
||||
expect(provisionCall).toBeDefined()
|
||||
const provisionArgs = provisionCall![0]
|
||||
expect(provisionArgs[provisionArgs.indexOf('-u') + 1]).toBe('0:0')
|
||||
expect(provisionArgs.join(' ')).toContain('getent passwd')
|
||||
})
|
||||
|
||||
it('provisions a running workspace sandbox once at boot when enforcement is on', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('ls')) {
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout: JSON.stringify([{ name: WORKSPACE_SANDBOX_NAME, status: 'running' }]),
|
||||
stderr: '',
|
||||
}
|
||||
}
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
await service.provisionWorkspaceSandboxOnBoot()
|
||||
|
||||
const provisionCall = mockExecuteCommand.mock.calls.find((call) => call[0].includes('exec'))
|
||||
expect(provisionCall).toBeDefined()
|
||||
const provisionArgs = provisionCall![0]
|
||||
expect(provisionArgs[provisionArgs.indexOf('-u') + 1]).toBe('0:0')
|
||||
})
|
||||
|
||||
it('skips boot provisioning when the sandbox preference is off', async () => {
|
||||
mockExecuteCommand.mockImplementation(async () => {
|
||||
throw new Error('msb must not be invoked when sandboxing is disabled')
|
||||
})
|
||||
|
||||
await service.provisionWorkspaceSandboxOnBoot()
|
||||
|
||||
expect(mockExecuteCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips boot provisioning when the workspace sandbox is not running', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('ls')) {
|
||||
return { exitCode: 0, stdout: stoppedListingOutput(), stderr: '' }
|
||||
}
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
await service.provisionWorkspaceSandboxOnBoot()
|
||||
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('exec'))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns blocked with the start stderr when a stopped sandbox fails to start', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
@@ -342,6 +415,7 @@ describe('SandboxRuntimeService', () => {
|
||||
stdout: JSON.stringify([{ name: WORKSPACE_SANDBOX_NAME, status: 'running' }]),
|
||||
stderr: '',
|
||||
})
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce(inspectedRunningSandbox())
|
||||
|
||||
const directory = repoADir
|
||||
@@ -394,6 +468,34 @@ describe('SandboxRuntimeService', () => {
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('failed running attestation'))
|
||||
})
|
||||
|
||||
it('provisions the exec user passwd entry over a root exec after creating the sandbox', async () => {
|
||||
enableEnforcement()
|
||||
let inspectCalls = 0
|
||||
mockExecuteCommand.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('inspect')) {
|
||||
inspectCalls += 1
|
||||
if (inspectCalls === 1) {
|
||||
return { exitCode: 1, stdout: '', stderr: 'no such sandbox' }
|
||||
}
|
||||
return { exitCode: 0, stdout: runningInspectOutput(realInspectConfig()), stderr: '' }
|
||||
}
|
||||
return { exitCode: 0, stdout: '[]', stderr: '' }
|
||||
})
|
||||
|
||||
const plan = await service.planShell(repoADir)
|
||||
|
||||
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
|
||||
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
|
||||
const provisionCall = mockExecuteCommand.mock.calls.find((call) => call[0].includes('exec'))
|
||||
expect(provisionCall).toBeDefined()
|
||||
const provisionArgs = provisionCall![0]
|
||||
expect(provisionArgs[provisionArgs.indexOf('-u') + 1]).toBe('0:0')
|
||||
const provisionScript = provisionArgs.join(' ')
|
||||
expect(provisionScript).toContain('getent group')
|
||||
expect(provisionScript).toContain('getent passwd')
|
||||
expect(provisionScript).toContain('/home/ocm-agent')
|
||||
})
|
||||
|
||||
it('blocks a signal-terminated start and never caches the sandbox as running without proof', async () => {
|
||||
enableEnforcement()
|
||||
mockExecuteCommand
|
||||
@@ -2241,6 +2343,7 @@ describe('SandboxRuntimeService', () => {
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '[]', stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '[]', stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce(inspectedRunningSandbox())
|
||||
|
||||
const failed = await service.planShell(repoADir)
|
||||
|
||||
@@ -163,16 +163,22 @@ 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 |
|
||||
| `pnpm` | corepack | Activated at build time; a project `packageManager` pin still wins |
|
||||
| `bun` | official installer | Installed to `/opt/bun`, world-readable, symlinked onto `PATH` |
|
||||
| `uv`, `uvx` | Astral installer | Standalone binaries on `PATH` |
|
||||
| `pip`, `venv` | apt | `python3-pip` and `python3-venv` on top of the base `python3` |
|
||||
| `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` |
|
||||
| `npm -g`, `pnpm -g` | npm / corepack | Global installs redirect to `/opt/agent-tools` (`npm_config_prefix`, `PNPM_HOME`), so they are writable for the exec user and their binaries are on `PATH` |
|
||||
| `sudo` | apt | Passwordless for every guest user via `/etc/sudoers.d/ocm-guest`; system-wide `apt-get install` works from the exec user |
|
||||
| `pip`, `venv` | apt | `python3-pip` and `python3-venv` on top of the base `python3`. Debian's externally-managed marker is removed, so `pip` and `uv pip --system` are not refused; system-wide writes still need `sudo`, so use `--user` or a venv |
|
||||
| `jq`, `ripgrep`, `less`, `tree`, `file`, `procps` | apt | Common CLI tools agent workflows expect |
|
||||
| `gh` | official `cli.github.com` apt repo | Current release. Debian's own package is several years stale |
|
||||
| Chromium | Playwright (`PLAYWRIGHT_VERSION`, default `1.56.0`) | Installed to `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`, world-readable so `SANDBOX_EXEC_USER` can launch it |
|
||||
|
||||
`NODE_PATH=/usr/local/lib/node_modules` is set so agent code can `require("playwright")` from any working directory. It is only a resolution fallback; a project-local `node_modules` still wins.
|
||||
|
||||
The guest runs every command as a numeric host uid that has no `/etc/passwd` entry in the image, so the uncorrected default `HOME` is `/` and anything that writes per-user state — the pnpm store, uv and pip caches, `git config`, `gh` config — dies with `EACCES` on the first run. The image therefore sets `HOME=/home/ocm-agent` (mode 1777), prewarms corepack into a world-readable `COREPACK_HOME`, and puts a world-writable `/opt/agent-tools/bin` on `PATH` for `uv tool` and global package-manager installs. Image `ENV` reaches `msb exec` commands verbatim, including for unknown uids. The image build verifies the whole toolchain as an unprivileged uid so a root-only regression fails the build instead of the agent.
|
||||
|
||||
`sudo` also needs the exec user to exist in the guest, which the image cannot know at build time. The Manager provisions the `/etc/passwd`, `/etc/group`, and `/etc/shadow` entries for the exec uid through an idempotent root exec (verified by `getent`, so repeats are no-ops) at three points: when the workspace sandbox is created, when a stopped sandbox is started, and once at Manager startup for a sandbox that is already running. Without the entries, `sudo` refuses with "you do not exist in the passwd database" or a PAM "account validation failure". Only a sandbox created before this mechanism existed and never started again slips through; remove it once with `msb rm -f ocm-workspace` to pick up sudo and the fixed toolchain.
|
||||
|
||||
Chromium launches headless as the non-root exec user without extra flags. If your host kernel restricts user namespaces so Chromium's own sandbox fails, pass `--no-sandbox` — the microVM is already the isolation boundary.
|
||||
|
||||
The image is over 3 GB against a 1.6 GB `node:24` baseline, almost entirely Chromium and its dependencies. The first pull is bounded by `SANDBOX_START_TIMEOUT_MS`; raise it on slow links.
|
||||
|
||||
Reference in new issue
Block a user