feat(sandbox): add KVM-backed agent sandboxing via microsandbox

This commit is contained in:
Chris Scott committed 2026-08-13 16:14:16 -04:00
1 parent 1d477bdee4
commit aa3fb48a62
80 files changed
+17304 -204

No files matched your search

+22 -5
View File
@@ -39,8 +39,10 @@ export interface OpenCodeClient {
authenticateMcp(serverName: string, directory?: string): Promise<Response>
}
export type OpenCodeClientHost = string | (() => string)
export interface FetchOpenCodeClientConfig {
baseUrl: string
baseUrl: OpenCodeClientHost
basicAuth: string | null
passwordResolver?: OpenCodePasswordResolver
fetchFn?: typeof fetch
@@ -53,6 +55,10 @@ export class FetchOpenCodeClient implements OpenCodeClient {
return this.config.fetchFn ?? fetch
}
private resolveBaseUrl(): string {
return typeof this.config.baseUrl === 'function' ? this.config.baseUrl() : this.config.baseUrl
}
private async getBasicAuth(): Promise<string> {
if (!this.config.passwordResolver) {
return this.config.basicAuth ?? ''
@@ -62,7 +68,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
}
private async request(req: ForwardRequest): Promise<Response> {
const url = new URL(this.config.baseUrl + req.path)
const url = new URL(this.resolveBaseUrl() + req.path)
if (req.directory) {
url.searchParams.set('directory', req.directory)
@@ -248,9 +254,20 @@ export class FetchOpenCodeClient implements OpenCodeClient {
}
}
export function createOpenCodeClient(passwordOverride?: string | OpenCodePasswordResolver): OpenCodeClient {
const host = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
const baseUrl = `http://${host}:${ENV.OPENCODE.PORT}`
function formatOpenCodeHostForUrl(host: string): string {
return host.includes(':') ? `[${host}]` : host
}
export function createOpenCodeClient(
passwordOverride?: string | OpenCodePasswordResolver,
host?: OpenCodeClientHost,
): OpenCodeClient {
const resolveConfiguredHost = typeof host === 'function' ? host : () => (host ?? ENV.OPENCODE.HOST)
const baseUrl: OpenCodeClientHost = () => {
const configuredHost = resolveConfiguredHost()
const normalized = configuredHost === '0.0.0.0' ? '127.0.0.1' : configuredHost
return `http://${formatOpenCodeHostForUrl(normalized)}:${ENV.OPENCODE.PORT}`
}
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
const basicAuth = getOpenCodeBasicAuthHeader(password)
@@ -0,0 +1,194 @@
import { logger } from '../../utils/logger'
export type EnforcementRemovedSections = Record<string, unknown>
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export function sanitizeConfigForEnforcement(
config: Record<string, unknown>,
enforced: boolean,
): Record<string, unknown> {
return sanitizeConfigForEnforcementResult(config, enforced).sanitized
}
export function sanitizeConfigForEnforcementResult(
config: Record<string, unknown>,
enforced: boolean,
): { sanitized: Record<string, unknown>; removed: EnforcementRemovedSections } {
if (!enforced) {
return { sanitized: config, removed: {} }
}
const { sanitized, removed } = sanitizeEnforcementSections(config)
if (Object.keys(removed).length === 0) {
return { sanitized: config, removed: {} }
}
if (Array.isArray(removed.plugin)) {
logger.warn(`Stripped ${removed.plugin.length} configured OpenCode plugin(s) from the live config while sandbox enforcement is active`)
}
if (isRecord(removed.mcp)) {
logger.warn(`Disabled ${Object.keys(removed.mcp).length} local MCP server(s) from the live config while sandbox enforcement is active`)
}
if (isRecord(removed.provider)) {
logger.warn(`Disabled ${Object.keys(removed.provider).length} custom provider module(s) from the live config while sandbox enforcement is active`)
}
if (removed.formatter !== undefined) {
logger.warn('Disabled formatter execution from the live config while sandbox enforcement is active')
}
if (removed.shell !== undefined) {
logger.warn('Disabled the shell configuration from the live config while sandbox enforcement is active')
}
if (removed.lsp !== undefined) {
logger.warn('Disabled LSP server configuration from the live config while sandbox enforcement is active')
}
if (removed.experimentalHook !== undefined) {
logger.warn('Disabled experimental hook commands from the live config while sandbox enforcement is active')
}
return { sanitized, removed }
}
export function isLocalMcpServerEntry(entry: unknown): boolean {
if (!isRecord(entry)) return false
return entry.type === 'local' || Array.isArray(entry.command)
}
export function isCustomProviderEntry(entry: unknown): boolean {
return isRecord(entry) && typeof entry.npm === 'string'
}
export function sanitizeEnforcementSections(config: Record<string, unknown>): {
sanitized: Record<string, unknown>
removed: EnforcementRemovedSections
} {
const sanitized: Record<string, unknown> = { ...config }
const removed: EnforcementRemovedSections = {}
if (Array.isArray(config.plugin) && config.plugin.length > 0) {
delete sanitized.plugin
removed.plugin = config.plugin
}
if (config.formatter !== undefined) {
delete sanitized.formatter
removed.formatter = config.formatter
}
if (config.shell !== undefined) {
delete sanitized.shell
removed.shell = config.shell
}
const mcp = config.mcp
if (isRecord(mcp)) {
const retained: Record<string, unknown> = {}
const removedMcp: Record<string, unknown> = {}
for (const [name, entry] of Object.entries(mcp)) {
if (isLocalMcpServerEntry(entry)) {
removedMcp[name] = entry
} else {
retained[name] = entry
}
}
if (Object.keys(removedMcp).length > 0) {
removed.mcp = removedMcp
if (Object.keys(retained).length > 0) {
sanitized.mcp = retained
} else {
delete sanitized.mcp
}
}
}
const provider = config.provider
if (isRecord(provider)) {
const retainedProvider: Record<string, unknown> = {}
const removedProvider: Record<string, unknown> = {}
for (const [name, entry] of Object.entries(provider)) {
if (isCustomProviderEntry(entry)) {
removedProvider[name] = entry
} else {
retainedProvider[name] = entry
}
}
if (Object.keys(removedProvider).length > 0) {
removed.provider = removedProvider
if (Object.keys(retainedProvider).length > 0) {
sanitized.provider = retainedProvider
} else {
delete sanitized.provider
}
}
}
const lsp = config.lsp
if (lsp !== undefined && lsp !== false) {
delete sanitized.lsp
removed.lsp = lsp
}
const experimental = config.experimental
if (isRecord(experimental) && experimental.hook !== undefined) {
const retainedExperimental: Record<string, unknown> = { ...experimental }
delete retainedExperimental.hook
removed.experimentalHook = experimental.hook
if (Object.keys(retainedExperimental).length > 0) {
sanitized.experimental = retainedExperimental
} else {
delete sanitized.experimental
}
}
return { sanitized, removed }
}
export function restoreEnforcementSections(
config: Record<string, unknown>,
removed: EnforcementRemovedSections,
): Record<string, unknown> {
const restored: Record<string, unknown> = { ...config }
for (const [key, value] of Object.entries(removed)) {
if (key === 'plugin') {
if (Array.isArray(value) && value.length > 0 && restored.plugin === undefined) {
restored.plugin = value
}
continue
}
if (key === 'mcp' && isRecord(value)) {
const currentMcp = isRecord(restored.mcp) ? { ...(restored.mcp as Record<string, unknown>) } : {}
for (const [name, entry] of Object.entries(value)) {
if (currentMcp[name] === undefined) {
currentMcp[name] = entry
}
}
restored.mcp = currentMcp
continue
}
if (key === 'provider' && isRecord(value)) {
const currentProvider = isRecord(restored.provider) ? { ...(restored.provider as Record<string, unknown>) } : {}
for (const [name, entry] of Object.entries(value)) {
if (currentProvider[name] === undefined) {
currentProvider[name] = entry
}
}
restored.provider = currentProvider
continue
}
if (key === 'experimentalHook') {
const experimental = isRecord(restored.experimental)
? { ...(restored.experimental as Record<string, unknown>) }
: {}
if (experimental.hook === undefined) {
experimental.hook = value
restored.experimental = experimental
}
continue
}
if (restored[key] === undefined) {
restored[key] = value
}
}
return restored
}
@@ -0,0 +1,87 @@
import { readFileSync, readdirSync } from 'fs'
export type ProcessStat = {
pgrp: number
startToken: string
}
export type ProcessGroupMember = {
pid: number
startToken: string
}
export type ProcessIdentityProvider = {
attested: boolean
readProcessStat(pid: number): ProcessStat | null
readProcessGroupMembers(pgid: number): ProcessGroupMember[]
}
function parseProcessStat(stat: string): ProcessStat | null {
const commEnd = stat.lastIndexOf(')')
if (commEnd === -1) return null
const fields = stat.slice(commEnd + 2).split(' ')
const pgrp = Number(fields[2])
const startToken = fields[19]
if (!Number.isInteger(pgrp) || pgrp <= 0) return null
if (startToken === undefined || startToken === '') return null
return { pgrp, startToken }
}
const LINUX_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
attested: true,
readProcessStat(pid) {
try {
return parseProcessStat(readFileSync(`/proc/${pid}/stat`, 'utf-8'))
} catch {
return null
}
},
readProcessGroupMembers(pgid) {
const members: ProcessGroupMember[] = []
let entries: string[]
try {
entries = readdirSync('/proc')
} catch {
return members
}
if (!Array.isArray(entries)) return members
for (const entry of entries) {
if (!/^\d+$/.test(entry)) continue
const pid = Number(entry)
const stat = this.readProcessStat(pid)
if (stat !== null && stat.pgrp === pgid) {
members.push({ pid, startToken: stat.startToken })
}
}
return members
},
}
const DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
attested: false,
readProcessStat() {
return null
},
readProcessGroupMembers() {
return []
},
}
let cachedProvider: ProcessIdentityProvider | null = null
let forcedProvider: ProcessIdentityProvider | null = null
export function resolveProcessIdentityProvider(): ProcessIdentityProvider {
if (cachedProvider !== null) return cachedProvider
cachedProvider = forcedProvider ??
(process.platform === 'linux' ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER)
return cachedProvider
}
export function resetProcessIdentityProvider(): void {
cachedProvider = null
}
export function forceProcessAttestation(attested: boolean | null): void {
forcedProvider = attested === null ? null : attested ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER
cachedProvider = null
}
@@ -0,0 +1,228 @@
import { isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
export type SandboxProxyDecision = { blocked: true; reason: string } | { blocked: false }
export const SANDBOX_BLOCKED_REASON_PREFIX = 'Sandbox enforcement is on; host-process shell execution is disabled: '
export const SANDBOX_CONFIG_MUTATION_REASON_PREFIX =
'Sandbox enforcement is on; config mutations that could re-enable host-process execution are disabled: '
const ENCODED_PATH_HAZARD =
/%(?:2f|5c|25|00|01|02|03|04|05|06|07|08|09|0a|0b|0c|0d|0e|0f|10|11|12|13|14|15|16|17|18|19|1a|1b|1c|1d|1e|1f|7f)/i
function stripSandboxProxyApiPrefix(pathname: string): string {
if (pathname === '/api' || pathname.startsWith('/api/')) {
return pathname.slice(4) || '/'
}
return pathname
}
function canonicalizeSandboxProxyPath(pathname: string): string | null {
if (!pathname.includes('%')) return stripSandboxProxyApiPrefix(pathname)
if (ENCODED_PATH_HAZARD.test(pathname)) return null
try {
return stripSandboxProxyApiPrefix(decodeURIComponent(pathname))
} catch {
return null
}
}
const BLOCKED_ENFORCED_ROUTES: ReadonlyArray<{
methods: readonly string[]
pathPattern: RegExp
reason: string
}> = [
{
methods: ['POST'],
pathPattern: /^\/session\/[^/]+\/shell$/,
reason: 'the session shell endpoint (`!command`) runs in the OpenCode host process',
},
{
methods: ['POST'],
pathPattern: /^\/session\/[^/]+\/command$/,
reason: 'custom slash commands can run shell templates in the OpenCode host process',
},
{
methods: ['POST'],
pathPattern: /^\/pty$/,
reason: 'PTY creation runs commands in the OpenCode host process',
},
{
methods: ['GET', 'POST'],
pathPattern: /^\/pty\/[^/]+\/connect$/,
reason: 'PTY connections drive processes in the OpenCode host process',
},
]
export function decideSandboxProxyBlock(enforced: boolean, method: string, pathname: string): SandboxProxyDecision {
if (!enforced) {
return { blocked: false }
}
const normalizedMethod = method.toUpperCase()
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
if (canonicalPath === null) {
return {
blocked: true,
reason: `${SANDBOX_BLOCKED_REASON_PREFIX}the request path could not be safely canonicalized`,
}
}
for (const route of BLOCKED_ENFORCED_ROUTES) {
if (route.methods.includes(normalizedMethod) && route.pathPattern.test(canonicalPath)) {
return { blocked: true, reason: `${SANDBOX_BLOCKED_REASON_PREFIX}${route.reason}` }
}
}
return { blocked: false }
}
export function isSandboxConfigMutation(enforced: boolean, method: string, pathname: string): boolean {
if (!enforced) {
return false
}
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
if (canonicalPath === null) {
return false
}
return method.toUpperCase() === 'PATCH' && canonicalPath === '/config'
}
export function isSandboxMcpAdd(enforced: boolean, method: string, pathname: string): boolean {
if (!enforced) {
return false
}
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
if (canonicalPath === null) {
return false
}
return method.toUpperCase() === 'POST' && canonicalPath === '/mcp'
}
export function isSandboxAuthWrite(enforced: boolean, method: string, pathname: string): boolean {
if (!enforced) {
return false
}
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
if (canonicalPath === null) {
return false
}
return method.toUpperCase() === 'PUT' && /^\/auth\/[^/]+$/.test(canonicalPath)
}
export type SandboxConfigBodyDecision =
| { kind: 'passthrough' }
| { kind: 'sanitized'; body: string }
| { kind: 'reject'; reason: string }
export function decideSandboxConfigBody(
enforced: boolean,
method: string,
pathname: string,
rawBody: string,
): SandboxConfigBodyDecision {
if (!isSandboxConfigMutation(enforced, method, pathname)) {
return { kind: 'passthrough' }
}
let parsed: unknown
try {
parsed = JSON.parse(rawBody)
} catch {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the config mutation body is not valid JSON`,
}
}
if (!isRecord(parsed)) {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the config mutation body must be a JSON object`,
}
}
return { kind: 'sanitized', body: JSON.stringify(sanitizeConfigForEnforcement(parsed, true)) }
}
export function decideSandboxMcpAddBody(
enforced: boolean,
method: string,
pathname: string,
rawBody: string,
): SandboxConfigBodyDecision {
if (!isSandboxMcpAdd(enforced, method, pathname)) {
return { kind: 'passthrough' }
}
let parsed: unknown
try {
parsed = JSON.parse(rawBody)
} catch {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body is not valid JSON`,
}
}
if (!isRecord(parsed)) {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body must be a JSON object`,
}
}
const config = parsed.config
if (
!isRecord(config) ||
config.type !== 'remote' ||
typeof config.url !== 'string' ||
config.command !== undefined ||
config.environment !== undefined
) {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}only remote MCP servers can be added while enforcement is active`,
}
}
return { kind: 'passthrough' }
}
export function decideSandboxAuthBody(
enforced: boolean,
method: string,
pathname: string,
rawBody: string,
): SandboxConfigBodyDecision {
if (!isSandboxAuthWrite(enforced, method, pathname)) {
return { kind: 'passthrough' }
}
let parsed: unknown
try {
parsed = JSON.parse(rawBody)
} catch {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the auth body is not valid JSON`,
}
}
if (!isRecord(parsed)) {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the auth body must be a JSON object`,
}
}
if (parsed.type === 'wellknown') {
return {
kind: 'reject',
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}well-known provider authentication loads remote host-executed code and cannot be added while enforcement is active`,
}
}
return { kind: 'passthrough' }
}
export function decideSandboxMutationBody(
enforced: boolean,
method: string,
pathname: string,
rawBody: string,
): SandboxConfigBodyDecision {
if (isSandboxMcpAdd(enforced, method, pathname)) {
return decideSandboxMcpAddBody(enforced, method, pathname, rawBody)
}
if (isSandboxAuthWrite(enforced, method, pathname)) {
return decideSandboxAuthBody(enforced, method, pathname, rawBody)
}
return decideSandboxConfigBody(enforced, method, pathname, rawBody)
}