microsandbox secret commands, attestation check and Chromium

This commit is contained in:
Chris Scott committed 2026-12-03 19:40:01 -05:00
1 parent 32be89316d
commit a58dcc96d4
6 files changed
+435 -3

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ RUN echo "Installing gh and CLI tooling (cachebust=${TOOLS_CACHEBUST})" && \
apt-get update && \
apt-get install -y --no-install-recommends \
ca-certificates curl jq less ripgrep sudo tree file procps \
libnss3-tools \
python3-pip python3-venv python-is-python3 \
iproute2 iputils-ping bind9-dnsutils bind9-host net-tools \
netcat-openbsd traceroute lsof rsync && \
+188 -2
View File
@@ -1,5 +1,5 @@
import path from 'path'
import { createHash } from 'crypto'
import { createHash, createHmac } from 'crypto'
import { accessSync, constants, realpathSync, statSync } from 'fs'
import { lstat, readFile, realpath } from 'fs/promises'
import {
@@ -32,12 +32,54 @@ export function sandboxDockerDataVolumeName(name: string): string {
return `${name}-docker-data`
}
export type SandboxSecretSpec = {
name: string
envVar: string
placeholder: string
allowedHosts: string[]
value: string
}
export type SandboxVmSpec = {
name: string
rootSessionId: string
projectMounts: string[]
cpus: number
memoryMib: number
secrets: SandboxSecretSpec[]
}
export function sandboxSecretEnvName(name: string): string {
return `OCM_SECRET_${name}`
}
export function sandboxSecretPlaceholder(vmName: string, name: string): string {
const secret = ENV.AUTH.SECRET
if (secret.trim() === '') {
throw new Error('AUTH_SECRET is required to derive sandbox secret placeholders')
}
return `ocm-secret-${createHmac('sha256', secret).update(vmName).update('\u0000').update(name).digest('hex').slice(0, 32)}`
}
function sortedSandboxSecrets(spec: SandboxVmSpec): SandboxSecretSpec[] {
return [...spec.secrets].sort((left, right) => left.envVar.localeCompare(right.envVar))
}
export function buildSandboxSecretConf(spec: SandboxVmSpec): string {
const conf: Record<string, JsonValue> = {}
for (const secret of sortedSandboxSecrets(spec)) {
conf[secret.envVar] = {
value: { $msb_env: secret.envVar },
placeholder: secret.placeholder,
allow: [...secret.allowedHosts],
substitution: { headers: true, query: false, body: false },
}
}
return JSON.stringify(conf)
}
export function buildSandboxSecretEnv(spec: SandboxVmSpec) {
return Object.fromEntries(spec.secrets.map((secret) => [secret.envVar, secret.value]))
}
export const SANDBOX_UNAVAILABLE_PREFIX = 'Sandbox enforcement is on but the sandbox is unavailable: '
@@ -224,7 +266,10 @@ function parseSandboxNamedMountSpec(spec: string) {
return { name, guest }
}
export function buildSandboxCreateArgs(spec: SandboxVmSpec, options: { replace?: boolean } = {}): string[] {
export function buildSandboxCreateArgs(
spec: SandboxVmSpec,
options: { replace?: boolean; secretConfPath?: string } = {},
): string[] {
const tmpfsSizeMib = resolveSandboxRuntimeTmpfsSizeMib(spec.memoryMib)
if (tmpfsSizeMib === null) throw new Error('sandbox memory must be positive to size the runtime tmpfs')
const workdir = spec.projectMounts[0]
@@ -260,6 +305,7 @@ export function buildSandboxCreateArgs(spec: SandboxVmSpec, options: { replace?:
'/usr/bin/env',
'--shell',
'/bin/sh',
...(options.secretConfPath !== undefined ? ['--secret-conf', options.secretConfPath] : []),
ENV.SANDBOX.IMAGE,
'--',
'sleep',
@@ -295,6 +341,10 @@ export function buildSandboxStopManagedArgs(): string[] {
return ['stop', '--label', 'ocm.managed=true']
}
export function buildSandboxModifySecretArgs(name: string, secret: SandboxSecretSpec): string[] {
return ['modify', name, '--secret', `${secret.envVar}@${secret.allowedHosts.join(',')}`]
}
export type SandboxNetworkPolicyRule = {
direction: string
destination: JsonValue
@@ -406,6 +456,130 @@ export function sandboxNetworkPolicyMismatch(inspected: JsonValue | undefined, e
return null
}
function canonicalExpectedAllowedHost(host: string): string {
return host.startsWith('*.') ? `wildcard|${host.slice(2)}` : `exact|${host}`
}
function canonicalInspectedAllowedHost(entry: JsonValue): string | null | undefined {
if (entry === 'any') return null
const record = parseJsonObject(entry)
if (record === null) return undefined
const exact = parseJsonString(record.exact) ?? parseJsonString(record.Exact)
if (exact !== null) {
return `exact|${exact.toLowerCase()}`
}
const wildcardValue = record.wildcard ?? record.Wildcard
const wildcardString = parseJsonString(wildcardValue)
const wildcardRecord = parseJsonObject(wildcardValue)
const wildcard =
wildcardString ??
(wildcardRecord === null
? null
: parseJsonString(wildcardRecord.domain) ?? parseJsonString(wildcardRecord.suffix))
if (wildcard !== null) {
return `wildcard|${wildcard.toLowerCase().replace(/^\*\./, '')}`
}
return undefined
}
function sandboxSecretEntryMismatch(entry: JsonValue, secret: SandboxSecretSpec): string | null {
const record = parseJsonObject(entry)
if (record === null) return `sandbox secret ${secret.envVar} is malformed`
const value = record.value
if (value !== undefined && value !== null && parseJsonString(value) !== '') {
return `sandbox secret ${secret.envVar} must not carry a value`
}
const source = parseJsonObject(record.source)
if (source === null || parseJsonString(source.kind) !== 'env' || parseJsonString(source.var) !== secret.envVar) {
return `sandbox secret ${secret.envVar} must come from the ${secret.envVar} environment variable`
}
if (parseJsonString(record.placeholder) !== secret.placeholder) {
return `sandbox secret ${secret.envVar} does not match the expected placeholder`
}
if (!Array.isArray(record.allowed_hosts)) {
return `sandbox secret ${secret.envVar} has malformed allowed hosts`
}
const inspectedHosts: string[] = []
for (const hostEntry of record.allowed_hosts) {
const canonical = canonicalInspectedAllowedHost(hostEntry)
if (canonical === null) {
return `sandbox secret ${secret.envVar} must not allow any host`
}
if (canonical === undefined) {
return `sandbox secret ${secret.envVar} has malformed allowed hosts`
}
inspectedHosts.push(canonical)
}
const expectedHosts = secret.allowedHosts.map(canonicalExpectedAllowedHost)
if (
inspectedHosts.length !== expectedHosts.length ||
[...inspectedHosts].sort().join('\n') !== [...expectedHosts].sort().join('\n')
) {
return `sandbox secret ${secret.envVar} allowed hosts do not match the expected hosts`
}
const substitution = parseJsonObject(record.substitution)
if (
substitution === null ||
substitution.headers !== true ||
substitution.query === true ||
substitution.body === true
) {
return `sandbox secret ${secret.envVar} must substitute only HTTPS request headers`
}
if (record.passthrough_hosts !== undefined && record.passthrough_hosts !== null) {
if (!Array.isArray(record.passthrough_hosts) || record.passthrough_hosts.length > 0) {
return `sandbox secret ${secret.envVar} must not pass through any host`
}
}
if (record.require_tls_identity === false) {
return `sandbox secret ${secret.envVar} must require the TLS identity`
}
return null
}
export function sandboxSecretsMismatch(inspected: JsonValue | undefined, spec: SandboxVmSpec): string | null {
const expected = sortedSandboxSecrets(spec)
if (expected.length === 0) {
if (inspected === undefined || inspected === null) return null
const record = parseJsonObject(inspected)
if (record === null || !Array.isArray(record.secrets)) {
return 'sandbox configuration network.secrets is malformed'
}
if (record.secrets.length > 0) {
return 'sandbox configuration network.secrets must be empty'
}
return null
}
const record = parseJsonObject(inspected)
if (record === null || !Array.isArray(record.secrets)) {
return 'sandbox configuration network.secrets is malformed'
}
const entries = new Map<string, JsonValue>()
for (const entry of record.secrets) {
const entryRecord = parseJsonObject(entry)
const envVar = entryRecord === null ? null : parseJsonString(entryRecord.env_var)
if (entryRecord === null || envVar === null) {
return 'sandbox configuration network.secrets contains a malformed entry'
}
if (entries.has(envVar)) {
return `sandbox secret ${envVar} is duplicated`
}
entries.set(envVar, entry)
}
if (entries.size !== expected.length) {
return `sandbox network secrets do not match the expected set (expected ${expected.length}, found ${entries.size})`
}
for (const secret of expected) {
const entry = entries.get(secret.envVar)
if (entry === undefined) {
return `sandbox secret ${secret.envVar} is missing`
}
const mismatch = sandboxSecretEntryMismatch(entry, secret)
if (mismatch !== null) return mismatch
}
return null
}
export function parseMemoryMib(value: string): number | null {
const match = /^(\d+(?:\.\d+)?)([gGmM])?$/.exec(value.trim())
if (match === null) return null
@@ -540,6 +714,7 @@ function parseSandboxCreateArgs(args: string[]): SandboxCreateArgs {
case '-w': workdir = value ?? ''; i += 1; break
case '--entrypoint': if (value !== undefined) entrypoint = [value]; i += 1; break
case '--shell': if (value !== undefined) shell = value; i += 1; break
case '--secret-conf': i += 1; break
case '-d': break
default:
if (image === '' && !token.startsWith('-')) image = token
@@ -748,3 +923,14 @@ export function buildSandboxProvisionArgs(name: string): string[] {
`fi`,
]
}
export function buildSandboxTrustCaArgs(name: string): string[] {
const script = [
'ca=/.msb/tls/ca.pem',
'if [ ! -f "$ca" ] || ! command -v certutil >/dev/null 2>&1; then exit 0; fi',
'mkdir -p "$HOME/.pki/nssdb" || exit 1',
'if [ ! -f "$HOME/.pki/nssdb/cert9.db" ]; then certutil -N -d sql:"$HOME/.pki/nssdb" --empty-password || exit 1; fi',
'certutil -A -d sql:"$HOME/.pki/nssdb" -n microsandbox-interception -t C,, -i "$ca"',
].join('; ')
return ['exec', name, '--no-tty', '-q', '-u', resolveSandboxExecUser(), '--', '/bin/sh', '-c', script]
}
+1
View File
@@ -1137,6 +1137,7 @@ export class SandboxRuntimeService {
projectMounts,
cpus: target.resources.cpus,
memoryMib: target.resources.memoryMib,
secrets: [],
}
const state = vmState(spec.name)
state.lastUsedAt = Date.now()
@@ -74,6 +74,7 @@ describe('internal sandbox routes', () => {
projectMounts: [repoDirectory],
cpus: ENV.SANDBOX.CPUS,
memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0,
secrets: [],
}
}
@@ -303,6 +303,10 @@ describe('sandbox guest image', () => {
expect(sandboxDockerfile).not.toContain('corepack')
})
it('installs libnss3-tools so chromium can trust the microsandbox interception CA', () => {
expect(sandboxDockerfile).toMatch(/apt-get install -y --no-install-recommends[\s\S]*libnss3-tools/)
})
it('pins bun through the installer tag and asserts the installed version', () => {
expect(sandboxDockerfile).toMatch(/ARG BUN_VERSION=1\.4\.2/)
expect(sandboxDockerfile).toContain('bash -s "bun-v${BUN_VERSION}"')
+240 -1
View File
@@ -1,10 +1,11 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { spawnSync } from 'child_process'
import { createHmac } from 'crypto'
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 { unwrapSandboxExecCommand, type JsonValue } from '@opencode-manager/shared/utils'
import {
SESSION_SANDBOX_NAME_PATTERN,
SANDBOX_UNAVAILABLE_PREFIX,
@@ -18,12 +19,16 @@ import {
buildSandboxProvisionArgs,
buildSandboxPullArgs,
buildSandboxRemoveArgs,
buildSandboxSecretConf,
buildSandboxSecretEnv,
buildSandboxStartArgs,
buildSandboxStopArgs,
buildSandboxStopManagedArgs,
buildSandboxTrustCaArgs,
buildSandboxVerifyProvisionArgs,
buildSandboxVersionArgs,
buildSandboxVolumeRemoveArgs,
buildSandboxModifySecretArgs,
parseMemoryMib,
quoteForShell,
resolveExpectedSandboxNetworkPolicy,
@@ -35,8 +40,12 @@ import {
sandboxDockerDataVolumeName,
sandboxMountRoots,
sandboxNetworkPolicyMismatch,
sandboxSecretEnvName,
sandboxSecretPlaceholder,
sandboxSecretsMismatch,
sandboxVmMountRoots,
sessionSandboxName,
type SandboxSecretSpec,
type SandboxVmSpec,
} from '../../../src/services/sandbox/command'
import { isPathWithinRoot } from '../../../src/utils/fs-safe'
@@ -52,6 +61,7 @@ function vmSpec(overrides: Partial<SandboxVmSpec> = {}): SandboxVmSpec {
projectMounts: [getReposPath()],
cpus: ENV.SANDBOX.CPUS,
memoryMib: parseMemoryMib(ENV.SANDBOX.MEMORY) ?? 0,
secrets: [],
...overrides,
}
}
@@ -643,6 +653,235 @@ describe('sandbox command builders', () => {
})
})
describe('sandbox secret specs', () => {
const SECRET_NAME = 'API_TOKEN'
const ENV_VAR = sandboxSecretEnvName(SECRET_NAME)
const ALLOWED_HOSTS = ['api.example.com', '*.example.org']
function secret(overrides: Partial<SandboxSecretSpec> = {}): SandboxSecretSpec {
return {
name: SECRET_NAME,
envVar: ENV_VAR,
placeholder: sandboxSecretPlaceholder(VM_NAME, SECRET_NAME),
allowedHosts: [...ALLOWED_HOSTS],
value: 'real-secret-value',
...overrides,
}
}
type InspectedSecretEntry = {
env_var: JsonValue
value?: JsonValue
source?: JsonValue
placeholder: JsonValue
allowed_hosts: JsonValue
substitution: JsonValue
passthrough_hosts?: JsonValue
require_tls_identity?: JsonValue
}
function inspectedEntry(overrides: Partial<InspectedSecretEntry> = {}): InspectedSecretEntry {
return {
env_var: ENV_VAR,
value: '',
source: { kind: 'env', var: ENV_VAR },
placeholder: sandboxSecretPlaceholder(VM_NAME, SECRET_NAME),
allowed_hosts: [{ exact: 'api.example.com' }, { wildcard: 'example.org' }],
substitution: { headers: true, query: false, body: false },
passthrough_hosts: [],
require_tls_identity: true,
...overrides,
}
}
function inspected(entry: JsonValue = inspectedEntry()): JsonValue {
return { secrets: [entry] }
}
it('derives a stable, per-VM placeholder with 32 hex characters', () => {
const placeholder = sandboxSecretPlaceholder(VM_NAME, SECRET_NAME)
const expected = `ocm-secret-${createHmac('sha256', ENV.AUTH.SECRET)
.update(`${VM_NAME}\u0000${SECRET_NAME}`)
.digest('hex')
.slice(0, 32)}`
expect(placeholder).toBe(expected)
expect(placeholder).toMatch(/^ocm-secret-[0-9a-f]{32}$/)
expect(sandboxSecretPlaceholder(VM_NAME, SECRET_NAME)).toBe(placeholder)
expect(sandboxSecretPlaceholder(sessionSandboxName('ses_other'), SECRET_NAME)).not.toBe(placeholder)
expect(sandboxSecretPlaceholder(VM_NAME, 'OTHER_SECRET')).not.toBe(placeholder)
})
it('refuses to derive a placeholder without an AUTH_SECRET', async () => {
process.env.AUTH_SECRET = ''
try {
vi.resetModules()
const { sandboxSecretPlaceholder: placeholderForEmptySecret } = await import(
'../../../src/services/sandbox/command'
)
expect(() => placeholderForEmptySecret(VM_NAME, SECRET_NAME)).toThrow('AUTH_SECRET')
} finally {
delete process.env.AUTH_SECRET
}
})
it('derives the OCM_SECRET_ env var name for a secret', () => {
expect(ENV_VAR).toBe('OCM_SECRET_API_TOKEN')
expect(sandboxSecretEnvName('OTHER')).toBe('OCM_SECRET_OTHER')
})
it('builds a value-free secret conf keyed and sorted by env var with headers-only substitution', () => {
const spec = vmSpec({
secrets: [
secret({ name: 'ZED', envVar: sandboxSecretEnvName('ZED'), placeholder: sandboxSecretPlaceholder(VM_NAME, 'ZED') }),
secret(),
],
})
const conf = JSON.parse(buildSandboxSecretConf(spec))
expect(Object.keys(conf)).toEqual([ENV_VAR, sandboxSecretEnvName('ZED')])
expect(conf[ENV_VAR]).toEqual({
value: { $msb_env: ENV_VAR },
placeholder: sandboxSecretPlaceholder(VM_NAME, SECRET_NAME),
allow: ALLOWED_HOSTS,
substitution: { headers: true, query: false, body: false },
})
expect(buildSandboxSecretConf(spec)).not.toContain('real-secret-value')
})
it('returns secret values only through the child-process environment map', () => {
expect(buildSandboxSecretEnv(vmSpec({ secrets: [secret()] }))).toEqual({ [ENV_VAR]: 'real-secret-value' })
expect(buildSandboxSecretEnv(vmSpec())).toEqual({})
})
it('adds --secret-conf only when a path is supplied and keeps it before the image', () => {
const spec = vmSpec({ secrets: [secret()] })
expect(buildSandboxCreateArgs(spec)).not.toContain('--secret-conf')
const args = buildSandboxCreateArgs(spec, { secretConfPath: '/run/ocm/secrets.json' })
const confIndex = args.indexOf('--secret-conf')
expect(confIndex).toBeGreaterThan(-1)
expect(args[confIndex + 1]).toBe('/run/ocm/secrets.json')
expect(confIndex).toBeLessThan(args.indexOf(ENV.SANDBOX.IMAGE))
expect(buildCanonicalSandboxSpec(spec)).toEqual(buildCanonicalSandboxSpec(vmSpec()))
})
it('builds modify args that name the env var and allowed hosts without the value', () => {
expect(buildSandboxModifySecretArgs(VM_NAME, secret())).toEqual([
'modify',
VM_NAME,
'--secret',
`${ENV_VAR}@api.example.com,*.example.org`,
])
expect(buildSandboxModifySecretArgs(VM_NAME, secret()).join(' ')).not.toContain('real-secret-value')
})
it('accepts the exact expected secret set and ignores an absent or empty block when no secrets are expected', () => {
const spec = vmSpec({ secrets: [secret()] })
expect(sandboxSecretsMismatch(inspected(), spec)).toBeNull()
expect(sandboxSecretsMismatch(undefined, vmSpec())).toBeNull()
expect(sandboxSecretsMismatch(null, vmSpec())).toBeNull()
expect(sandboxSecretsMismatch({ secrets: [] }, vmSpec())).toBeNull()
})
it('accepts an absent value and wildcard hosts written with a leading star', () => {
const spec = vmSpec({ secrets: [secret()] })
const entry = inspectedEntry()
delete entry.value
entry.allowed_hosts = [{ exact: 'api.example.com' }, { wildcard: '*.example.org' }]
expect(sandboxSecretsMismatch(inspected(entry), spec)).toBeNull()
})
it('rejects a non-empty value, a literal source, and a changed placeholder', () => {
const spec = vmSpec({ secrets: [secret()] })
expect(sandboxSecretsMismatch(inspected(inspectedEntry({ value: 'leaked' })), spec)).toContain(
`${ENV_VAR} must not carry a value`,
)
const literal = inspectedEntry()
delete literal.source
expect(sandboxSecretsMismatch(inspected(literal), spec)).toContain(ENV_VAR)
expect(
sandboxSecretsMismatch(inspected(inspectedEntry({ placeholder: `ocm-secret-${'0'.repeat(32)}` })), spec),
).toContain(`${ENV_VAR} does not match the expected placeholder`)
})
it('rejects an extra, missing, or renamed secret', () => {
const spec = vmSpec({ secrets: [secret()] })
const extra = inspectedEntry({
env_var: sandboxSecretEnvName('EXTRA'),
source: { kind: 'env', var: sandboxSecretEnvName('EXTRA') },
})
expect(sandboxSecretsMismatch({ secrets: [inspectedEntry(), extra] }, spec)).toContain('expected 1, found 2')
expect(sandboxSecretsMismatch({ secrets: [] }, spec)).toContain('expected 1, found 0')
expect(
sandboxSecretsMismatch(inspected(inspectedEntry({ env_var: sandboxSecretEnvName('RENAMED') })), spec),
).toContain(`${ENV_VAR} is missing`)
})
it('rejects an any, changed, or malformed allowed host set', () => {
const spec = vmSpec({ secrets: [secret()] })
expect(sandboxSecretsMismatch(inspected(inspectedEntry({ allowed_hosts: ['any'] })), spec)).toContain(
'must not allow any host',
)
expect(
sandboxSecretsMismatch(inspected(inspectedEntry({ allowed_hosts: [{ exact: 'evil.example.com' }] })), spec),
).toContain('allowed hosts do not match')
expect(sandboxSecretsMismatch(inspected(inspectedEntry({ allowed_hosts: 'api.example.com' })), spec)).toContain(
'malformed allowed hosts',
)
})
it('rejects query or body substitution and any passthrough host', () => {
const spec = vmSpec({ secrets: [secret()] })
expect(
sandboxSecretsMismatch(
inspected(inspectedEntry({ substitution: { headers: true, query: true, body: false } })),
spec,
),
).toContain('must substitute only HTTPS request headers')
expect(
sandboxSecretsMismatch(
inspected(inspectedEntry({ substitution: { headers: true, query: false, body: true } })),
spec,
),
).toContain('must substitute only HTTPS request headers')
expect(
sandboxSecretsMismatch(inspected(inspectedEntry({ passthrough_hosts: ['api.example.com'] })), spec),
).toContain('must not pass through any host')
expect(sandboxSecretsMismatch(inspected(inspectedEntry({ require_tls_identity: false })), spec)).toContain(
'must require the TLS identity',
)
})
it('rejects a malformed block and a non-empty block when no secrets are expected', () => {
expect(sandboxSecretsMismatch('nope', vmSpec())).toBe('sandbox configuration network.secrets is malformed')
expect(sandboxSecretsMismatch({ secrets: 'nope' }, vmSpec())).toBe(
'sandbox configuration network.secrets is malformed',
)
expect(sandboxSecretsMismatch(inspected(), vmSpec())).toBe(
'sandbox configuration network.secrets must be empty',
)
})
it('builds CA trust args that import the interception certificate into the Chromium NSS database', () => {
const args = buildSandboxTrustCaArgs(VM_NAME)
expect(args.slice(0, 6)).toEqual(['exec', VM_NAME, '--no-tty', '-q', '-u', resolveSandboxExecUser()])
expect(args.slice(6, 9)).toEqual(['--', '/bin/sh', '-c'])
const script = args[9]
expect(script).toContain('/.msb/tls/ca.pem')
expect(script).toContain('command -v certutil')
expect(script).toContain('mkdir -p "$HOME/.pki/nssdb"')
expect(script).toContain('certutil -N -d sql:"$HOME/.pki/nssdb" --empty-password')
expect(script).toContain('certutil -A -d sql:"$HOME/.pki/nssdb" -n microsandbox-interception -t C,, -i "$ca"')
})
})
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)}`