import { describe, expect, it, vi, afterEach } from 'vitest' 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, getForgeWorktreesPath, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getOpenCodeWorktreesPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils' import { SESSION_SANDBOX_NAME_PATTERN, SANDBOX_UNAVAILABLE_PREFIX, SANDBOX_DOCKER_DATA_GUEST_PATH, SANDBOX_DOCKER_DATA_SIZE, buildCanonicalSandboxSpec, buildSandboxCreateArgs, buildSandboxInspectArgs, buildSandboxListArgs, buildSandboxPingArgs, buildSandboxProvisionArgs, buildSandboxPullArgs, buildSandboxRemoveArgs, buildSandboxStartArgs, buildSandboxStopArgs, buildSandboxStopManagedArgs, buildSandboxVerifyProvisionArgs, buildSandboxVersionArgs, buildSandboxVolumeRemoveArgs, parseMemoryMib, quoteForShell, resolveExpectedSandboxNetworkPolicy, resolveSandboxExecUser, resolveSandboxExecUserGid, resolveSandboxExecUserUid, resolveSandboxRuntimeTmpfsSizeMib, resolveSessionSandboxMounts, sandboxDockerDataVolumeName, sandboxMountRoots, sandboxNetworkPolicyMismatch, sandboxVmMountRoots, sessionSandboxName, type SandboxVmSpec, } from '../../../src/services/sandbox/command' import { isPathWithinRoot } from '../../../src/utils/fs-safe' const ROOT_SESSION_ID = 'ses_root' const VM_NAME = sessionSandboxName(ROOT_SESSION_ID) const DOCKER_DATA_VOLUME = sandboxDockerDataVolumeName(VM_NAME) function vmSpec(overrides: Partial = {}): SandboxVmSpec { return { name: VM_NAME, rootSessionId: ROOT_SESSION_ID, projectMounts: [getReposPath()], cpus: ENV.SANDBOX.CPUS, memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0, ...overrides, } } function withProcessIds(uid: () => number | undefined, gid: () => number | undefined, action: () => void): void { const originalUid = Object.getOwnPropertyDescriptor(process, 'getuid') const originalGid = Object.getOwnPropertyDescriptor(process, 'getgid') Object.defineProperty(process, 'getuid', { value: uid, configurable: true }) Object.defineProperty(process, 'getgid', { value: gid, configurable: true }) try { action() } finally { if (originalUid) Object.defineProperty(process, 'getuid', originalUid) if (originalGid) Object.defineProperty(process, 'getgid', originalGid) } } afterEach(() => { vi.restoreAllMocks() }) describe('sandbox command builders', () => { it('builds the version probe as exactly --version', () => { expect(buildSandboxVersionArgs()).toEqual(['--version']) }) it('builds pull args for the configured guest image', () => { expect(buildSandboxPullArgs()).toEqual(['pull', ENV.SANDBOX.IMAGE]) }) it('derives a stable, pattern-matching sandbox name from a root session id', () => { expect(VM_NAME).toMatch(SESSION_SANDBOX_NAME_PATTERN) expect(sessionSandboxName(ROOT_SESSION_ID)).toBe(VM_NAME) expect(sessionSandboxName('ses_other')).not.toBe(VM_NAME) expect(sessionSandboxName('ses_other')).toMatch(SESSION_SANDBOX_NAME_PATTERN) expect(SESSION_SANDBOX_NAME_PATTERN.test('ocm-workspace')).toBe(false) expect(SESSION_SANDBOX_NAME_PATTERN.test(`ocm-session-${'a'.repeat(11)}`)).toBe(false) expect(SESSION_SANDBOX_NAME_PATTERN.test(`ocm-session-${'a'.repeat(13)}`)).toBe(false) expect(SESSION_SANDBOX_NAME_PATTERN.test(`ocm-session-${'g'.repeat(12)}`)).toBe(false) expect(sandboxDockerDataVolumeName(VM_NAME)).toBe(`${VM_NAME}-docker-data`) }) it('builds ping args targeting the named sandbox with quiet output', () => { expect(buildSandboxPingArgs(VM_NAME)).toEqual(['ping', VM_NAME, '-q']) }) it('builds inspect args targeting the named sandbox with JSON output', () => { expect(buildSandboxInspectArgs(VM_NAME)).toEqual(['inspect', VM_NAME, '--format', 'json']) }) it('builds remove args that force-remove the named sandbox', () => { expect(buildSandboxRemoveArgs(VM_NAME)).toEqual(['rm', '--force', VM_NAME]) }) it('builds list args that emit machine-readable JSON for all sandboxes', () => { expect(buildSandboxListArgs()).toEqual(['ls', '--format', 'json']) }) it('builds start args targeting the named sandbox', () => { expect(buildSandboxStartArgs(VM_NAME)).toEqual(['start', VM_NAME]) }) it('builds stop args targeting the named sandbox', () => { expect(buildSandboxStopArgs(VM_NAME)).toEqual(['stop', VM_NAME]) }) it('builds volume removal args for the named Docker data volume', () => { expect(buildSandboxVolumeRemoveArgs(DOCKER_DATA_VOLUME)).toEqual(['volume', 'rm', DOCKER_DATA_VOLUME]) }) it('builds managed-stop args that filter by the ocm.managed label', () => { expect(buildSandboxStopManagedArgs()).toEqual(['stop', '--label', 'ocm.managed=true']) }) it('escapes embedded single quotes so values survive a shell round-trip', () => { const value = "echo 'a'b'" expect(quoteForShell(value)).toBe(`'echo '\\''a'\\''b'\\'''`) const result = spawnSync('sh', ['-c', `printf '%s' ${quoteForShell(value)}`], { encoding: 'utf8' }) expect(result.status).toBe(0) expect(result.stdout).toBe(value) }) it('builds create args for the VM spec with named mounts, resources, labels, and the project workdir', () => { const args = buildSandboxCreateArgs(vmSpec()) expect(args[0]).toBe('run') expect(args).toContain('-d') expect(args).toContain('--name') expect(args[args.indexOf('--name') + 1]).toBe(VM_NAME) expect(args[args.indexOf('-w') + 1]).toBe(getReposPath()) expect(args[args.indexOf('-u') + 1]).toBe(resolveSandboxExecUser()) expect(args[args.indexOf('-m') + 1]).toBe(`${parseMemoryMib(ENV.SANDBOX.MEMORY)}M`) expect(args[args.indexOf('-c') + 1]).toBe(String(ENV.SANDBOX.CPUS)) const labelArgs: string[] = [] for (let i = 0; i < args.length; i++) { const value = args[i + 1] if (args[i] === '--label' && value !== undefined) { labelArgs.push(value) } } expect(labelArgs).toContain('ocm.managed=true') expect(labelArgs).toContain(`ocm.net=${ENV.SANDBOX.NET}`) expect(labelArgs).toContain(`ocm.session=${ROOT_SESSION_ID}`) const mountArgs: string[] = [] for (let i = 0; i < args.length; i++) { const value = args[i + 1] if (args[i] === '--mount-dir' && value !== undefined) { mountArgs.push(value) } } expect(mountArgs).toEqual(sandboxVmMountRoots(vmSpec()).map((root) => `${root}:${root}`)) expect(mountArgs[0]).toBe(`${getReposPath()}:${getReposPath()}`) expect(mountArgs).toEqual([ `${getReposPath()}:${getReposPath()}`, `${getOpenCodeToolOutputPath()}:${getOpenCodeToolOutputPath()}`, `${getOpenCodeGlobalSkillsPath()}:${getOpenCodeGlobalSkillsPath()}`, `${getOpenCodeAgentTmpPath()}:${getOpenCodeAgentTmpPath()}`, ]) }) it('mounts an explicit project mount list without duplicating the shared directories', () => { const spec = vmSpec({ projectMounts: [getScheduleWorktreesPath(), getOpenCodeToolOutputPath()] }) expect(sandboxVmMountRoots(spec)).toEqual([ getScheduleWorktreesPath(), getOpenCodeToolOutputPath(), getOpenCodeGlobalSkillsPath(), getOpenCodeAgentTmpPath(), ]) expect(buildSandboxCreateArgs(spec)[buildSandboxCreateArgs(spec).indexOf('-w') + 1]).toBe(getScheduleWorktreesPath()) }) it('sizes the runtime tmpfs from the spec memory and creates the Docker data disk for the VM', () => { const spec = vmSpec() const args = buildSandboxCreateArgs(spec) const canonical = buildCanonicalSandboxSpec(spec) expect(args[args.indexOf('--tmpfs') + 1]).toBe(`/tmp:${resolveSandboxRuntimeTmpfsSizeMib(canonical.resources.memory_mib)}M`) const mountNamedIndex = args.indexOf('--mount-named') expect(mountNamedIndex).toBeGreaterThan(-1) expect(args[mountNamedIndex + 1]).toBe( `${DOCKER_DATA_VOLUME}:${SANDBOX_DOCKER_DATA_GUEST_PATH}:kind=disk,size=${SANDBOX_DOCKER_DATA_SIZE}`, ) }) it('sizes the runtime tmpfs from the VM memory rather than the environment default', () => { const args = buildSandboxCreateArgs(vmSpec({ memoryMib: 2048 })) expect(args[args.indexOf('--tmpfs') + 1]).toBe('/tmp:512M') }) it('rejects a VM spec without a project mount', () => { expect(() => buildSandboxCreateArgs(vmSpec({ projectMounts: [] }))).toThrow('at least one project mount') }) it('inserts --replace immediately after -d before the image and never after --', () => { const plain = buildSandboxCreateArgs(vmSpec()) const replace = buildSandboxCreateArgs(vmSpec(), { replace: true }) expect(plain).not.toContain('--replace') expect(plain.slice(0, 3)).toEqual(['run', '-d', '--name']) expect(replace.slice(0, 4)).toEqual(['run', '-d', '--replace', '--name']) expect(replace.filter((token) => token === '--replace')).toHaveLength(1) const imageIndex = replace.indexOf(ENV.SANDBOX.IMAGE) const separatorIndex = replace.indexOf('--') const replaceIndex = replace.indexOf('--replace') expect(replaceIndex).toBeLessThan(imageIndex) expect(replaceIndex).toBeLessThan(separatorIndex) expect(replace.slice(replaceIndex + 1)).toEqual(plain.slice(2)) }) it('keeps the canonical spec free of the --replace flag', () => { const canonical = buildCanonicalSandboxSpec(vmSpec()) expect(JSON.stringify(canonical)).not.toContain('--replace') expect(canonical.name).toBe(VM_NAME) expect(canonical.image.Oci.reference).toBe(ENV.SANDBOX.IMAGE) expect(canonical.runtime.cmd).toEqual(['sleep', 'infinity']) expect(canonical.runtime.workdir).toBe(getReposPath()) expect(canonical.labels).toEqual({ 'ocm.managed': 'true', 'ocm.net': ENV.SANDBOX.NET, 'ocm.session': ROOT_SESSION_ID }) }) it('never masks the assistant .opencode directory with a tmpfs overlay', () => { const args = buildSandboxCreateArgs(vmSpec()) const tmpfsMounts = args.flatMap((arg, index) => arg === '--tmpfs' ? [args[index + 1]] : []) expect(tmpfsMounts).toHaveLength(1) expect(tmpfsMounts[0]).toMatch(/^\/tmp:\d+M$/) expect(args).not.toContain(getAssistantOpenCodeDir()) }) it('pins --entrypoint to /usr/bin/env before the image so msb never inherits the OCI entrypoint', () => { const args = buildSandboxCreateArgs(vmSpec()) const entrypointIndex = args.indexOf('--entrypoint') expect(entrypointIndex).toBeGreaterThan(-1) expect(args[entrypointIndex + 1]).toBe('/usr/bin/env') expect(args.indexOf(ENV.SANDBOX.IMAGE)).toBeGreaterThan(entrypointIndex + 1) }) it('mounts only the worktree, skills, tool-output, and agent tmp directories from outside the repo roots', () => { const workspacePath = path.dirname(getReposPath()) const roots = sandboxMountRoots() expect(roots.filter((root) => isPathWithinRoot(path.join(workspacePath, '.config'), root))).toEqual([ getOpenCodeGlobalSkillsPath(), ]) expect(roots.filter((root) => isPathWithinRoot(path.join(workspacePath, '.opencode'), root))).toEqual([ getOpenCodeWorktreesPath(), getForgeWorktreesPath(), 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', () => { const spec = buildCanonicalSandboxSpec(vmSpec()) const labels = spec.labels const resources = spec.resources const runtime = spec.runtime const mounts = spec.mounts const network = spec.network const lifecycle = spec.lifecycle expect(spec.name).toBe(VM_NAME) expect(spec.image.Oci.reference).toBe(ENV.SANDBOX.IMAGE) expect(labels['ocm.managed']).toBe('true') expect(labels['ocm.net']).toBe(ENV.SANDBOX.NET) expect(labels['ocm.session']).toBe(ROOT_SESSION_ID) expect(resources.cpus).toBe(ENV.SANDBOX.CPUS) expect(resources.memory_mib).toBe(parseMemoryMib(ENV.SANDBOX.MEMORY)) expect(runtime.workdir).toBe(getReposPath()) expect(runtime.user).toBe(resolveSandboxExecUser()) expect(runtime.cmd).toEqual(['sleep', 'infinity']) expect(runtime.entrypoint).toEqual(['/usr/bin/env']) expect(runtime.shell).toBe('/bin/sh') expect(spec.patches).toEqual([]) expect(network.enabled).toBe(true) expect(network.ports).toEqual([]) expect(lifecycle.ephemeral).toBe(false) expect(lifecycle.max_duration_secs).toBeNull() expect(lifecycle.idle_timeout_secs).toBeNull() const binds = mounts.filter((mount) => mount.type === 'Bind') expect(binds).toHaveLength(4) expect(binds.map((mount) => mount.host)).toEqual([ getReposPath(), getOpenCodeToolOutputPath(), getOpenCodeGlobalSkillsPath(), getOpenCodeAgentTmpPath(), ]) for (const mount of binds) { expect(mount.guest).toBe(mount.host) expect(mount.options.readonly).toBe(false) expect(mount.options.noexec).toBe(false) expect(mount.options.nosuid).toBe(false) expect(mount.options.nodev).toBe(false) expect(mount.stat_virtualization).toBe('strict') expect(mount.host_permissions).toBe('private') expect(mount.follow_root_symlinks).toBe(false) expect(mount.quota_mib).toBeNull() } const named = mounts.filter((mount) => mount.type === 'Named') expect(named).toHaveLength(1) expect(named[0]).toEqual({ type: 'Named', name: DOCKER_DATA_VOLUME, guest: SANDBOX_DOCKER_DATA_GUEST_PATH, options: { readonly: false, noexec: false, nosuid: false, nodev: false }, stat_virtualization: 'strict', host_permissions: 'private', follow_root_symlinks: false, }) expect(JSON.stringify(mounts)).not.toContain('Tmpfs') }) it('accepts real repo dirs, schedule, OpenCode, and forge worktrees while rejecting config, missing, and unrelated paths', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-roots-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const schedules = path.join(tmp, 'schedule-worktrees') const openCodeWorktrees = path.join(tmp, '.opencode', 'state', 'opencode', 'worktree') const forgeWorktrees = path.join(tmp, '.opencode', 'state', 'opencode', 'forge', 'worktrees') mkdirSync(path.join(repos, 'org', 'repo', 'subdir'), { recursive: true }) mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true }) mkdirSync(path.join(openCodeWorktrees, 'project-id', 'feature'), { recursive: true }) mkdirSync(path.join(forgeWorktrees, 'loop-slug'), { 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') await expect(resolveSandboxWorkDirectory(repos)).resolves.toBe(repos) await expect(resolveSandboxWorkDirectory(path.join(repos, 'org', 'repo', 'subdir'))).resolves.toBe( path.join(repos, 'org', 'repo', 'subdir'), ) await expect(resolveSandboxWorkDirectory(path.join(schedules, 'job-1-run-2'))).resolves.toBe( path.join(schedules, 'job-1-run-2'), ) await expect(resolveSandboxWorkDirectory(path.join(openCodeWorktrees, 'project-id', 'feature'))).resolves.toBe( path.join(openCodeWorktrees, 'project-id', 'feature'), ) await expect(resolveSandboxWorkDirectory(path.join(forgeWorktrees, 'loop-slug'))).resolves.toBe( path.join(forgeWorktrees, 'loop-slug'), ) await expect(resolveSandboxWorkDirectory(path.join(tmp, '.opencode', 'state', 'opencode'))).resolves.toBeNull() await expect(resolveSandboxWorkDirectory(path.join(tmp, '.opencode', 'state', 'opencode', 'forge'))).resolves.toBeNull() 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() } finally { if (originalWorkspacePath === undefined) { delete process.env.WORKSPACE_PATH } else { process.env.WORKSPACE_PATH = originalWorkspacePath } rmSync(tmp, { recursive: true, force: true }) } }) it('returns canonical guest paths for symlinks inside the roots and null for escapes', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-sandbox-escape-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const schedules = path.join(tmp, 'schedule-worktrees') mkdirSync(path.join(tmp, 'outside'), { recursive: true }) mkdirSync(path.join(repos, 'repo'), { recursive: true }) mkdirSync(path.join(repos, 'other-repo'), { recursive: true }) mkdirSync(path.join(schedules, 'job-1-run-2'), { recursive: true }) symlinkSync(path.join(tmp, 'outside'), path.join(repos, 'repo', 'escape')) symlinkSync(path.join(repos, 'other-repo'), path.join(repos, 'repo', 'inside-link')) symlinkSync(path.join(schedules, 'job-1-run-2'), path.join(repos, 'repo', 'cross-root-link')) process.env.WORKSPACE_PATH = tmp const { resolveSandboxWorkDirectory } = await import('../../../src/services/sandbox/command') await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo'))).resolves.toBe(path.join(repos, 'repo')) await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape'))).resolves.toBeNull() await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'escape', 'nested'))).resolves.toBeNull() await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'inside-link'))).resolves.toBe( path.join(repos, 'other-repo'), ) await expect(resolveSandboxWorkDirectory(path.join(repos, 'repo', 'cross-root-link'))).resolves.toBe( path.join(schedules, 'job-1-run-2'), ) } finally { if (originalWorkspacePath === undefined) { delete process.env.WORKSPACE_PATH } else { process.env.WORKSPACE_PATH = originalWorkspacePath } rmSync(tmp, { recursive: true, force: true }) } }) it('resolves the named exec user default to the manager uid:gid', () => { withProcessIds(() => 1001, () => 1002, () => { 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 args: string[] = [] withProcessIds(() => 1001, () => 1002, () => { args.push(...buildSandboxProvisionArgs(VM_NAME)) }) expect(args[0]).toBe('exec') expect(args).toContain(VM_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; grep -q '^ocm-exec:' /etc/shadow || echo 'ocm-exec:*:19000:0:99999:7:::' >> /etc/shadow; }", ) expect(script).toContain('getent passwd 1001 >/dev/null || exit 1') expect(script).toContain('if getent group docker >/dev/null 2>&1; then') expect(script).toContain('usermod -aG docker "$(getent passwd 1001 | cut -d: -f1)" || exit 1') }) it('returns no provisioning args when the exec user does not resolve to numeric uid and gid', () => { withProcessIds(() => undefined, () => undefined, () => { expect(buildSandboxProvisionArgs(VM_NAME)).toEqual([]) expect(buildSandboxVerifyProvisionArgs(VM_NAME)).toEqual([]) }) }) it('builds verify-provision args that assert the exec user passwd entry as root', () => { const args: string[] = [] withProcessIds(() => 1001, () => 1002, () => { args.push(...buildSandboxVerifyProvisionArgs(VM_NAME)) }) expect(args).toEqual([ 'exec', VM_NAME, '--no-tty', '-q', '-u', '0:0', '--', '/bin/sh', '-c', 'getent passwd 1001 >/dev/null', ]) }) it('aligns a numeric exec user with the manager gid', async () => { process.env.SANDBOX_EXEC_USER = '1001' try { vi.resetModules() const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command') withProcessIds(() => 1001, () => 1002, () => { expect(resolveSandboxExecUser()).toBe('1001:1002') }) } finally { delete process.env.SANDBOX_EXEC_USER } }) it('keeps an explicit uid:gid exec user verbatim', async () => { process.env.SANDBOX_EXEC_USER = '1000:1000' try { vi.resetModules() const { resolveSandboxExecUser } = await import('../../../src/services/sandbox/command') expect(resolveSandboxExecUser()).toBe('1000:1000') } finally { delete process.env.SANDBOX_EXEC_USER } }) it('exposes the sandbox-unavailable message prefix', () => { expect(SANDBOX_UNAVAILABLE_PREFIX).toBe('Sandbox enforcement is on but the sandbox is unavailable: ') }) it('resolves a relative MSB_PATH to one absolute executable found on PATH', async () => { const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-resolve-')) writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }) const originalPath = process.env.PATH process.env.PATH = fakeBin try { vi.resetModules() const mod = await import('../../../src/services/sandbox/command') mod.overrideSandboxExecutableTrustValidator(() => true) const { resolveSandboxExecutable, sandboxExecutablePath } = mod expect(resolveSandboxExecutable()).toBe(path.join(fakeBin, 'msb')) expect(sandboxExecutablePath()).toBe(path.join(fakeBin, 'msb')) } finally { process.env.PATH = originalPath rmSync(fakeBin, { recursive: true, force: true }) } }) it('returns null when a relative MSB_PATH has no executable candidate on PATH', async () => { const originalPath = process.env.PATH process.env.PATH = '/nonexistent-ocm-bin' try { vi.resetModules() const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command') expect(resolveSandboxExecutable()).toBeNull() expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH) } finally { process.env.PATH = originalPath } }) it('returns an absolute MSB_PATH verbatim without consulting PATH', async () => { const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-abs-')) const msbPath = path.join(fakeBin, 'my msb') writeFileSync(msbPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 }) process.env.MSB_PATH = msbPath try { vi.resetModules() const mod = await import('../../../src/services/sandbox/command') mod.overrideSandboxExecutableTrustValidator(() => true) const { resolveSandboxExecutable, sandboxExecutablePath } = mod expect(resolveSandboxExecutable()).toBe(msbPath) expect(sandboxExecutablePath()).toBe(msbPath) } finally { delete process.env.MSB_PATH rmSync(fakeBin, { recursive: true, force: true }) } }) it('rejects an msb executable located inside a mounted project root', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-mount-')) const originalWorkspacePath = process.env.WORKSPACE_PATH const originalPath = process.env.PATH try { const repos = path.join(tmp, 'workspace', 'repos') mkdirSync(path.join(repos, 'bin'), { recursive: true }) writeFileSync(path.join(repos, 'bin', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }) process.env.WORKSPACE_PATH = path.join(tmp, 'workspace') process.env.PATH = path.join(repos, 'bin') vi.resetModules() const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command') expect(resolveSandboxExecutable()).toBeNull() expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH) } finally { if (originalWorkspacePath === undefined) { delete process.env.WORKSPACE_PATH } else { process.env.WORKSPACE_PATH = originalWorkspacePath } process.env.PATH = originalPath rmSync(tmp, { recursive: true, force: true }) } }) it('rejects an msb executable whose symlink resolves into a mounted project root', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-msb-symlink-')) const originalWorkspacePath = process.env.WORKSPACE_PATH const originalPath = process.env.PATH try { const repos = path.join(tmp, 'workspace', 'repos') const bin = path.join(tmp, 'bin') mkdirSync(path.join(repos, 'evil'), { recursive: true }) mkdirSync(bin) writeFileSync(path.join(repos, 'evil', 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }) symlinkSync(path.join(repos, 'evil', 'msb'), path.join(bin, 'msb')) process.env.WORKSPACE_PATH = path.join(tmp, 'workspace') process.env.PATH = bin vi.resetModules() const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command') expect(resolveSandboxExecutable()).toBeNull() expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH) } finally { if (originalWorkspacePath === undefined) { delete process.env.WORKSPACE_PATH } else { process.env.WORKSPACE_PATH = originalWorkspacePath } process.env.PATH = originalPath rmSync(tmp, { recursive: true, force: true }) } }) it('rejects an msb executable writable by the manager user or a parent directory', async () => { const fakeBin = mkdtempSync(path.join(tmpdir(), 'ocm-msb-writable-')) writeFileSync(path.join(fakeBin, 'msb'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }) const originalPath = process.env.PATH process.env.PATH = fakeBin try { vi.resetModules() const { resolveSandboxExecutable, sandboxExecutablePath } = await import('../../../src/services/sandbox/command') expect(resolveSandboxExecutable()).toBeNull() expect(sandboxExecutablePath()).toBe(ENV.SANDBOX.MSB_PATH) } finally { process.env.PATH = originalPath rmSync(fakeBin, { recursive: true, force: true }) } }) }) describe('unwrapSandboxExecCommand recovers commands from the legacy recorded wrapper format', () => { const legacyWrapped = (directory: string, command: string) => `${quoteForShell('/usr/local/bin/msb')} exec ocm-workspace --no-tty -q -u '1001:1001' -w ${quoteForShell(directory)} --timeout 600s -- sh -c ${quoteForShell(command)}` it('recovers the original command from a legacy sandbox exec wrapper', () => { const directory = '/workspace/repos/ai-test' for (const command of [ 'git status', "echo 'hi there'", "echo 'x' -- sh -c 'y'", 'git status\ngit diff\necho done', ]) { expect(unwrapSandboxExecCommand(legacyWrapped(directory, command))).toBe(command) } }) it('passes through plain, blocked, empty, and near-miss commands unchanged', () => { const blocked = "printf '%s\n' 'Sandbox enforcement is on but the sandbox is unavailable: KVM is unavailable' >&2; exit 1" const nearMiss = legacyWrapped('/workspace/repos/ai-test', 'git status').replace(' --no-tty -q ', ' --no-tty ') expect(unwrapSandboxExecCommand('git status')).toBe('git status') expect(unwrapSandboxExecCommand(blocked)).toBe(blocked) expect(unwrapSandboxExecCommand('')).toBe('') expect(unwrapSandboxExecCommand(nearMiss)).toBe(nearMiss) }) }) describe('resolveSandboxRuntimeTmpfsSizeMib', () => { it('clamps the quarter-memory floor to the 1-512 MiB range', () => { expect(resolveSandboxRuntimeTmpfsSizeMib(1)).toBe(1) expect(resolveSandboxRuntimeTmpfsSizeMib(3)).toBe(1) expect(resolveSandboxRuntimeTmpfsSizeMib(4)).toBe(1) expect(resolveSandboxRuntimeTmpfsSizeMib(2047)).toBe(511) expect(resolveSandboxRuntimeTmpfsSizeMib(2048)).toBe(512) expect(resolveSandboxRuntimeTmpfsSizeMib(2049)).toBe(512) expect(resolveSandboxRuntimeTmpfsSizeMib(4096)).toBe(512) }) it('floors fractional positive memory to whole MiB', () => { expect(resolveSandboxRuntimeTmpfsSizeMib(5.5)).toBe(1) expect(resolveSandboxRuntimeTmpfsSizeMib(10.5)).toBe(2) expect(resolveSandboxRuntimeTmpfsSizeMib(0.5)).toBe(1) }) it('rejects zero, negative, non-finite, and non-number memory values', () => { expect(resolveSandboxRuntimeTmpfsSizeMib(0)).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib(-1)).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib(Number.NaN)).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib(Number.POSITIVE_INFINITY)).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib(Number.NEGATIVE_INFINITY)).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib('512')).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib(null)).toBeNull() expect(resolveSandboxRuntimeTmpfsSizeMib(undefined)).toBeNull() }) }) describe('sandbox network policy attestation helpers', () => { const publicPolicy = { default_egress: 'deny', default_ingress: 'allow', rules: [ { direction: 'egress', destination: { group: 'host' }, protocols: ['udp', 'tcp'], ports: [{ start: 53, end: 53 }], action: 'allow' }, { direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' }, ], } it('resolves the public profile to the deny-by-default fixture policy', () => { expect(resolveExpectedSandboxNetworkPolicy('public')).toEqual(publicPolicy) }) it('composes comma-separated profiles with a single DNS rule in profile order', () => { expect(resolveExpectedSandboxNetworkPolicy('public,private,host')).toEqual({ default_egress: 'deny', default_ingress: 'allow', rules: [ { direction: 'egress', destination: { group: 'host' }, protocols: ['udp', 'tcp'], ports: [{ start: 53, end: 53 }], action: 'allow' }, { direction: 'egress', destination: { group: 'public' }, protocols: [], ports: [], action: 'allow' }, { direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' }, { direction: 'egress', destination: { group: 'host' }, protocols: [], ports: [], action: 'allow' }, ], }) }) it('deduplicates repeated profiles', () => { expect(resolveExpectedSandboxNetworkPolicy('public, public')).toEqual(publicPolicy) }) it('returns null for terminal, unknown, or empty profiles', () => { expect(resolveExpectedSandboxNetworkPolicy('all')).toBeNull() expect(resolveExpectedSandboxNetworkPolicy('none')).toBeNull() expect(resolveExpectedSandboxNetworkPolicy('public,unknown')).toBeNull() expect(resolveExpectedSandboxNetworkPolicy('')).toBeNull() expect(resolveExpectedSandboxNetworkPolicy(' ')).toBeNull() }) it('accepts the source-faithful public policy fixture', () => { expect(sandboxNetworkPolicyMismatch(publicPolicy, resolveExpectedSandboxNetworkPolicy('public')!)).toBeNull() }) it('rejects a policy with an allow-all wildcard rule', () => { const inspected = { ...publicPolicy, rules: [ publicPolicy.rules[0]!, { direction: 'egress', destination: { any: true }, protocols: [], ports: [], action: 'allow' }, ], } expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy') }) it('rejects a policy whose profile rule is broadened to specific protocols and ports', () => { const inspected = { ...publicPolicy, rules: [ publicPolicy.rules[0]!, { direction: 'egress', destination: { group: 'public' }, protocols: ['tcp'], ports: [443], action: 'allow' }, ], } expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy') }) it('rejects a policy carrying stale rules from another profile', () => { const inspected = { ...publicPolicy, rules: [ ...publicPolicy.rules, { direction: 'egress', destination: { group: 'private' }, protocols: [], ports: [], action: 'allow' }, ], } expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy') }) it('rejects a policy missing a required rule', () => { const inspected = { ...publicPolicy, rules: [publicPolicy.rules[0]!], } expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('network policy') }) it('rejects an allow egress default with an unrestricted-egress reason', () => { const inspected = { default_egress: 'allow', default_ingress: 'allow', rules: [] } const mismatch = sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!) expect(mismatch).toContain('unrestricted egress') }) it('rejects an altered ingress default', () => { const inspected = { ...publicPolicy, default_ingress: 'deny' } expect(sandboxNetworkPolicyMismatch(inspected, resolveExpectedSandboxNetworkPolicy('public')!)).toContain('default_ingress') }) it('rejects a missing or malformed policy', () => { const expected = resolveExpectedSandboxNetworkPolicy('public')! expect(sandboxNetworkPolicyMismatch(undefined, expected)).toContain('missing or malformed') expect(sandboxNetworkPolicyMismatch({ default_egress: 'deny' }, expected)).toContain('missing or malformed') expect(sandboxNetworkPolicyMismatch({ ...publicPolicy, rules: 'not-an-array' }, expected)).toContain('missing or malformed') expect(sandboxNetworkPolicyMismatch( { ...publicPolicy, rules: [{ direction: 'egress', destination: { group: 'host' }, action: 'allow' }] }, expected, )).toContain('network policy') }) }) describe('resolveSessionSandboxMounts', () => { function runGit(args: string[], cwd?: string): void { const result = spawnSync('git', args, { cwd, encoding: 'utf8' }) if (result.status !== 0) { throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`) } } function restoreWorkspacePath(original: string | undefined): void { if (original === undefined) { delete process.env.WORKSPACE_PATH } else { process.env.WORKSPACE_PATH = original } } it('returns the single project mount for a plain repository and a non-repository directory, and null outside the roots', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-mounts-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const repo = path.join(repos, 'repo') const plain = path.join(repos, 'plain') mkdirSync(repo, { recursive: true }) mkdirSync(plain, { recursive: true }) runGit(['init', '-q'], repo) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(repo)).resolves.toEqual([repo]) await expect(resolveSessionSandboxMounts(plain)).resolves.toEqual([plain]) await expect(resolveSessionSandboxMounts('/etc')).resolves.toBeNull() await expect(resolveSessionSandboxMounts(path.join(repos, 'missing'))).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('adds the main repository git common dir for a linked worktree', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-worktree-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const main = path.join(repos, 'main') const worktree = path.join(tmp, 'schedule-worktrees', 'job-1-run-2') mkdirSync(main, { recursive: true }) mkdirSync(path.dirname(worktree), { recursive: true }) runGit(['init', '-q'], main) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], main, ) runGit(['worktree', 'add', '-q', '-b', 'feature', worktree], main) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(worktree)).resolves.toEqual([worktree, path.join(main, '.git')]) } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('blocks a forged git dir that has no worktree back-link to the sandbox worktree', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-forged-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const main = path.join(repos, 'main') const unrelatedWorktree = path.join(tmp, 'schedule-worktrees', 'job-9-run-1') const victim = path.join(repos, 'victim') mkdirSync(main, { recursive: true }) mkdirSync(path.dirname(unrelatedWorktree), { recursive: true }) mkdirSync(victim, { recursive: true }) runGit(['init', '-q'], main) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], main, ) runGit(['worktree', 'add', '-q', '-b', 'feature', unrelatedWorktree], main) writeFileSync(path.join(victim, '.git'), `gitdir: ${path.join(main, '.git')}\n`) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(victim)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('blocks a symlinked git dir that points at another repo worktree back-link', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-gitsym-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const other = path.join(repos, 'other') const otherWorktree = path.join(tmp, 'schedule-worktrees', 'other-wt') const victim = path.join(repos, 'victim') mkdirSync(other, { recursive: true }) mkdirSync(path.dirname(otherWorktree), { recursive: true }) mkdirSync(victim, { recursive: true }) runGit(['init', '-q'], other) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], other, ) runGit(['worktree', 'add', '-q', '-b', 'feature', otherWorktree], other) symlinkSync(path.join(otherWorktree, '.git'), path.join(victim, '.git')) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(victim)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('rejects a main repository whose core.worktree points at the repos root', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-core-worktree-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const repo = path.join(repos, 'repo') mkdirSync(repo, { recursive: true }) runGit(['init', '-q'], repo) runGit(['config', 'core.worktree', repos], repo) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(repo)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('rejects a core.worktree escape that plants a matching worktree back-link', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-core-worktree-link-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const mine = path.join(repos, 'mine') const other = path.join(repos, 'other') mkdirSync(mine, { recursive: true }) mkdirSync(other, { recursive: true }) runGit(['init', '-q'], mine) runGit(['init', '-q'], other) runGit(['config', 'core.worktree', other], mine) const planted = path.join(mine, '.git', 'worktrees', 'x') mkdirSync(planted, { recursive: true }) writeFileSync(path.join(planted, 'gitdir'), `${path.join(other, '.git')}\n`) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(mine)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('rejects a main repository whose git dir is a symlink to another repository git dir', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-symlink-main-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const repo = path.join(repos, 'repo') const other = path.join(repos, 'other') mkdirSync(repo, { recursive: true }) mkdirSync(other, { recursive: true }) runGit(['init', '-q'], repo) runGit(['init', '-q'], other) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], repo, ) rmSync(path.join(repo, '.git'), { recursive: true, force: true }) symlinkSync(path.join(other, '.git'), path.join(repo, '.git'), 'dir') process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(repo)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('rejects a worktree whose git file is a symlink to another repository linked worktree git file', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-symlink-worktree-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const main = path.join(repos, 'main') const other = path.join(repos, 'other') const otherWorktree = path.join(repos, 'other-linked') const worktree = path.join(tmp, 'schedule-worktrees', 'job-1-run-2') mkdirSync(main, { recursive: true }) mkdirSync(other, { recursive: true }) mkdirSync(path.dirname(worktree), { recursive: true }) runGit(['init', '-q'], main) runGit(['init', '-q'], other) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], main, ) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], other, ) runGit(['worktree', 'add', '-q', '-b', 'feature', worktree], main) runGit(['worktree', 'add', '-q', '-b', 'linked', otherWorktree], other) rmSync(path.join(worktree, '.git'), { force: true }) symlinkSync(path.join(otherWorktree, '.git'), path.join(worktree, '.git')) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(worktree)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) it('rejects a worktree whose git file points at another repository linked worktree', async () => { const tmp = mkdtempSync(path.join(tmpdir(), 'ocm-session-cross-linked-')) const originalWorkspacePath = process.env.WORKSPACE_PATH try { const repos = path.join(tmp, 'repos') const main = path.join(repos, 'main') const other = path.join(repos, 'other') const otherWorktree = path.join(repos, 'other-linked') const worktree = path.join(tmp, 'schedule-worktrees', 'job-1-run-2') mkdirSync(main, { recursive: true }) mkdirSync(other, { recursive: true }) mkdirSync(path.dirname(worktree), { recursive: true }) runGit(['init', '-q'], main) runGit(['init', '-q'], other) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], main, ) runGit( ['-c', 'user.email=ocm@example.com', '-c', 'user.name=OCM', 'commit', '--allow-empty', '-q', '-m', 'init'], other, ) runGit(['worktree', 'add', '-q', '-b', 'feature', worktree], main) runGit(['worktree', 'add', '-q', '-b', 'linked', otherWorktree], other) const otherGitDir = path.join(other, '.git', 'worktrees', path.basename(otherWorktree)) writeFileSync(path.join(worktree, '.git'), `gitdir: ${otherGitDir}\n`) process.env.WORKSPACE_PATH = tmp await expect(resolveSessionSandboxMounts(worktree)).resolves.toBeNull() } finally { restoreWorkspacePath(originalWorkspacePath) rmSync(tmp, { recursive: true, force: true }) } }) })