fix(sandbox): verify worktree back-links, fail fast on root lookup, and tidy settings saves

This commit is contained in:
Chris Scott authored and Chris Scott committed 2026-10-15 16:53:49 -04:00
1 parent 1d001bc43e
commit 2d2921a6c6
10 files changed
+290 -51

No files matched your search

+43 -2
View File
@@ -1,7 +1,7 @@
import path from 'path'
import { createHash } from 'crypto'
import { accessSync, constants, realpathSync, statSync } from 'fs'
import { realpath } from 'fs/promises'
import { readFile, readdir, realpath } from 'fs/promises'
import {
ENV,
getForgeWorktreesPath,
@@ -558,6 +558,46 @@ export async function resolveSandboxWorkDirectory(directory: string): Promise<st
return null
}
async function worktreeLinksBackToCommonDir(top: string, common: string): Promise<boolean> {
const worktreesDirectory = path.join(common, 'worktrees')
let entries: string[]
try {
entries = await readdir(worktreesDirectory)
} catch {
return false
}
let expectedTarget: string
try {
expectedTarget = path.join(await realpath(top), '.git')
} catch {
return false
}
for (const entry of entries) {
const entryDirectory = path.join(worktreesDirectory, entry)
let contents: string
try {
contents = (await readFile(path.join(entryDirectory, 'gitdir'), 'utf8')).trim()
} catch {
continue
}
if (contents === '') continue
const candidate = path.isAbsolute(contents) ? contents : path.resolve(entryDirectory, contents)
let resolvedCandidate: string
try {
resolvedCandidate = await realpath(candidate)
} catch {
continue
}
if (resolvedCandidate === expectedTarget) return true
}
return false
}
export async function resolveSessionSandboxMounts(locationDirectory: string): Promise<string[] | null> {
const work = await resolveSandboxWorkDirectory(locationDirectory)
if (work === null) return null
@@ -579,7 +619,8 @@ export async function resolveSessionSandboxMounts(locationDirectory: string): Pr
const top = await resolveSandboxWorkDirectory(lines[0]!)
const common = await resolveSandboxWorkDirectory(lines[1]!)
if (top === null || common === null) return null
return isPathWithinRoot(top, common) ? [top] : [top, common]
if (isPathWithinRoot(top, common)) return [top]
return (await worktreeLinksBackToCommonDir(top, common)) ? [top, common] : null
}
export function resolveSandboxExecUser(): string {
+1
View File
@@ -1129,6 +1129,7 @@ export class SandboxRuntimeService {
}
async removeSessionSandbox(rootSessionId: string): Promise<void> {
if (!detectSandboxCapability().available) return
await removeSandboxVmAndVolume(sessionSandboxName(rootSessionId))
}
+3 -15
View File
@@ -64,7 +64,7 @@ export class SessionSandboxService {
case 'session.deleted': {
const { sessionID } = event.data
this.ancestry.forget(sessionID)
if (getSessionSandboxMode(this.db, sessionID) !== null && this.sandboxSupported()) {
if (getSessionSandboxMode(this.db, sessionID) !== null) {
this.removeSandboxInBackground(sessionID, `deleted session ${sessionID}`)
}
deleteSessionSandboxMode(this.db, sessionID)
@@ -75,13 +75,7 @@ export class SessionSandboxService {
async getState(sessionId: string): Promise<SessionSandboxState> {
const available = this.sandboxSupported()
let rootSessionId: string
try {
rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
} catch {
return this.buildState(sessionId, sessionId, available, null, null, available)
}
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
const lockedReason = rootSessionId !== sessionId ? 'child' : null
const stored = getSessionSandboxMode(this.db, rootSessionId)
@@ -95,13 +89,7 @@ export class SessionSandboxService {
async getClaim(sessionId: string): Promise<SessionSandboxClaim> {
const available = this.sandboxSupported()
let rootSessionId: string
try {
rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
} catch {
return { sandboxed: available, source: 'default', since: 0 }
}
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
if (!available) {
return { sandboxed: false, source: 'default', since: 0 }
@@ -862,4 +862,60 @@ describe('resolveSessionSandboxMounts', () => {
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 })
}
})
})
@@ -1260,6 +1260,7 @@ describe('SandboxRuntimeService', () => {
})
it('runs a single removal when the same VM is removed concurrently', async () => {
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.6.15' })
installFakeMsb(new Map<string, FakeVm>([[VM_NAME, vm()]]))
const first = service.removeSessionSandbox(ROOT_SESSION)
@@ -1305,6 +1306,7 @@ describe('SandboxRuntimeService', () => {
})
it('tolerates a missing VM and volume when removing a session sandbox', async () => {
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.6.15' })
installFakeMsb(new Map())
const baseHandler = execHandler
execHandler = (args) => {
@@ -1317,6 +1319,7 @@ describe('SandboxRuntimeService', () => {
})
it('throws when removing a session sandbox fails for another reason', async () => {
mockDetectSandboxCapability.mockReturnValue({ available: true, msbVersion: 'msb 0.6.15' })
installFakeMsb(new Map())
const baseHandler = execHandler
execHandler = (args) => {
@@ -1327,6 +1330,17 @@ describe('SandboxRuntimeService', () => {
await expect(service.removeSessionSandbox(ROOT_SESSION)).rejects.toThrow('operation not permitted')
})
it('does not touch msb when removing a session sandbox while the capability is unavailable', async () => {
mockDetectSandboxCapability.mockReturnValue({ available: false, reason: '/dev/kvm is not available' })
const vms = new Map<string, FakeVm>([[VM_NAME, vm()]])
installFakeMsb(vms)
await expect(service.removeSessionSandbox(ROOT_SESSION)).resolves.toBeUndefined()
expect(mockExecuteCommand).not.toHaveBeenCalled()
expect(vms.has(VM_NAME)).toBe(true)
})
it('caches only the guest image on boot and never touches a VM', async () => {
enableEnforcement()
+8 -28
View File
@@ -188,34 +188,18 @@ describe('SessionSandboxService', () => {
})
})
it('fails closed to sandboxed when parent resolution fails and support is enabled', async () => {
it('rejects getState when parent resolution fails and support is enabled', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient({ failSessionGet: true }), settingsService)
await expect(service.getState('ses_root')).resolves.toEqual({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: true,
source: 'default',
resources: null,
effectiveResources: ENV_RESOURCES,
lockedReason: null,
available: true,
})
await expect(service.getState('ses_root')).rejects.toThrow('upstream unavailable')
})
it('fails closed to unsandboxed when parent resolution fails and support is disabled', async () => {
it('rejects getState when parent resolution fails and support is disabled', async () => {
const service = createService(db, createFakeSessionPermissionClient({ failSessionGet: true }), new SettingsService(db))
await expect(service.getState('ses_root')).resolves.toMatchObject({
sessionId: 'ses_root',
rootSessionId: 'ses_root',
sandboxed: false,
source: 'default',
resources: null,
available: false,
})
await expect(service.getState('ses_root')).rejects.toThrow('upstream unavailable')
})
it('copies the parent root sandbox flag, source, and resources onto a forked session', async () => {
@@ -333,7 +317,7 @@ describe('SessionSandboxService', () => {
expect(removed).toEqual([])
})
it('does not remove a sandbox microVM when server sandbox support is disabled', async () => {
it('removes the sandbox microVM when a session with a mode row is deleted even when support is disabled', async () => {
setSessionSandboxed(db, 'ses_root', true)
const removed: string[] = []
const service = createService(db, createFakeSessionPermissionClient(), new SettingsService(db), {
@@ -344,7 +328,7 @@ describe('SessionSandboxService', () => {
await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root'))
expect(removed).toEqual([])
expect(removed).toEqual(['ses_root'])
expect(getSessionSandboxMode(db, 'ses_root')).toBeNull()
})
@@ -569,16 +553,12 @@ describe('SessionSandboxService', () => {
})
})
it('fails closed on an ancestry error when reporting a claim', async () => {
it('rejects getClaim on an ancestry error', async () => {
const settingsService = new SettingsService(db)
settingsService.updateSettings({ sandbox: { enabled: true } })
const service = createService(db, createFakeSessionPermissionClient({ failSessionGet: true }), settingsService)
await expect(service.getClaim('ses_root')).resolves.toEqual({
sandboxed: true,
source: 'default',
since: 0,
})
await expect(service.getClaim('ses_root')).rejects.toThrow('upstream unavailable')
})
it('resolves the shell target to the root session and effective resources', async () => {
@@ -0,0 +1,94 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionSandboxResourcesDialog } from './SessionSandboxResourcesDialog'
import { useSetSessionSandbox } from '@/hooks/useSessionSandbox'
import type { SessionSandboxResources } from '@opencode-manager/shared/schemas'
vi.mock('@/hooks/useSessionSandbox')
function mockSetSessionSandbox() {
vi.mocked(useSetSessionSandbox).mockReturnValue({
mutate: vi.fn(),
mutateAsync: vi.fn().mockResolvedValue(undefined),
isPending: false,
} as unknown as ReturnType<typeof useSetSessionSandbox>)
}
interface DialogProps {
open: boolean
override: SessionSandboxResources | null
effective: SessionSandboxResources
}
function renderDialog(props: DialogProps) {
return render(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open={props.open}
onOpenChange={vi.fn()}
override={props.override}
effective={props.effective}
/>,
)
}
describe('SessionSandboxResourcesDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSetSessionSandbox()
})
it('keeps a typed value when the effective resources change while open', async () => {
const user = userEvent.setup()
const { rerender } = renderDialog({ open: true, override: null, effective: { cpus: 2, memoryMib: 4096 } })
const cpus = screen.getByLabelText('CPUs')
await user.clear(cpus)
await user.type(cpus, '8')
rerender(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open
onOpenChange={vi.fn()}
override={null}
effective={{ cpus: 4, memoryMib: 8192 }}
/>,
)
expect(screen.getByLabelText('CPUs')).toHaveValue(8)
})
it('re-initializes the draft from the resources when reopened', async () => {
const user = userEvent.setup()
const { rerender } = renderDialog({ open: true, override: null, effective: { cpus: 2, memoryMib: 4096 } })
const cpus = screen.getByLabelText('CPUs')
await user.clear(cpus)
await user.type(cpus, '8')
rerender(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open={false}
onOpenChange={vi.fn()}
override={null}
effective={{ cpus: 2, memoryMib: 4096 }}
/>,
)
rerender(
<SessionSandboxResourcesDialog
sessionID="ses_1"
open
onOpenChange={vi.fn()}
override={{ cpus: 4, memoryMib: 8192 }}
effective={{ cpus: 2, memoryMib: 4096 }}
/>,
)
expect(screen.getByLabelText('CPUs')).toHaveValue(4)
expect(screen.getByLabelText('Memory (GiB)')).toHaveValue(8)
})
})
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
@@ -27,13 +27,16 @@ export function SessionSandboxResourcesDialog({
const [cpus, setCpus] = useState('')
const [memoryGib, setMemoryGib] = useState('')
const [error, setError] = useState<string | null>(null)
const wasOpen = useRef(false)
useEffect(() => {
if (!open) return
const source = override ?? effective
setCpus(String(source.cpus))
setMemoryGib(formatSandboxMemory(source.memoryMib))
setError(null)
if (open && !wasOpen.current) {
const source = override ?? effective
setCpus(String(source.cpus))
setMemoryGib(formatSandboxMemory(source.memoryMib))
setError(null)
}
wasOpen.current = open
}, [open, override, effective])
const submit = async (resources: SessionSandboxResources | null) => {
@@ -380,4 +380,60 @@ describe('SandboxSettings', () => {
expect(vi.mocked(showToast.error)).toHaveBeenCalledWith('Default memory exceeds the host memory')
})
it('does not save CPUs when blurred without a change', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true, cpus: 4 } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const cpus = screen.getByLabelText('Default CPUs')
await user.click(cpus)
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
expect(vi.mocked(showToast.error)).not.toHaveBeenCalled()
})
it('does not save CPUs when a blank value already uses the server default', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const cpus = screen.getByLabelText('Default CPUs')
await user.click(cpus)
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
})
it('does not save memory when blurred without a change', async () => {
const { updateSettingsAsync } = mockUseSettings({
preferences: { sandbox: { enabled: true, memoryMib: 4096 } },
})
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
const memory = screen.getByLabelText('Default memory (GiB)')
await user.click(memory)
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
})
it('does not save idle stop or max running VMs when blurred at the defaults', async () => {
const { updateSettingsAsync } = mockUseSettings({ preferences: { sandbox: { enabled: true } } })
mockHealth({ available: true, enforced: false })
const user = await renderSandbox()
await user.click(screen.getByLabelText('Remove idle sandbox VMs after (minutes)'))
await user.tab()
await user.click(screen.getByLabelText('Max running sandbox VMs'))
await user.tab()
expect(updateSettingsAsync).not.toHaveBeenCalled()
expect(vi.mocked(showToast.success)).not.toHaveBeenCalled()
})
})
@@ -96,6 +96,7 @@ export function SandboxSettings() {
const commitCpus = () => {
const trimmed = draft.cpus.trim()
if (trimmed === '') {
if (sandboxPreferences?.cpus === undefined) return
void saveSandbox({ cpus: undefined }, 'Default CPUs reset to the server default')
return
}
@@ -108,12 +109,14 @@ export function SandboxSettings() {
}))
return
}
if (value === sandboxPreferences?.cpus) return
void saveSandbox({ cpus: value }, 'Default CPUs saved')
}
const commitMemory = () => {
const trimmed = draft.memoryGib.trim()
if (trimmed === '') {
if (sandboxPreferences?.memoryMib === undefined) return
void saveSandbox({ memoryMib: undefined }, 'Default memory reset to the server default')
return
}
@@ -129,6 +132,7 @@ export function SandboxSettings() {
}))
return
}
if (memoryMib === sandboxPreferences?.memoryMib) return
void saveSandbox({ memoryMib }, 'Default memory saved')
}
@@ -144,6 +148,7 @@ export function SandboxSettings() {
}))
return
}
if (value === (sandboxPreferences?.idleStopMinutes ?? DEFAULT_SANDBOX_IDLE_STOP_MINUTES)) return
void saveSandbox({ idleStopMinutes: value }, 'Idle removal timeout saved')
}
@@ -159,6 +164,7 @@ export function SandboxSettings() {
}))
return
}
if (value === (sandboxPreferences?.maxRunningVms ?? DEFAULT_SANDBOX_MAX_RUNNING_VMS)) return
void saveSandbox({ maxRunningVms: value }, 'Max running sandbox VMs saved')
}