From 4ea3ecca9eb20fa2ba010741b12d3d49308f2d2a Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:53:07 -0500 Subject: [PATCH] Give each session VM its hidden secrets, attest them, and --- backend/src/services/sandbox/runtime.ts | 206 +++++++++-- backend/test/helpers/fake-msb.ts | 57 ++- backend/test/services/sandbox/runtime.test.ts | 346 +++++++++++++++++- 3 files changed, 567 insertions(+), 42 deletions(-) diff --git a/backend/src/services/sandbox/runtime.ts b/backend/src/services/sandbox/runtime.ts index 1ab055d8..2cfe4b12 100644 --- a/backend/src/services/sandbox/runtime.ts +++ b/backend/src/services/sandbox/runtime.ts @@ -1,6 +1,8 @@ import type { Database } from 'bun:sqlite' import path from 'path' -import { lstat, realpath } from 'fs/promises' +import { createHash } from 'crypto' +import { lstat, mkdtemp, realpath, rm, writeFile } from 'fs/promises' +import { tmpdir } from 'os' import { ENV, getOpenCodeAgentTmpPath, @@ -32,13 +34,17 @@ import { buildSandboxCreateArgs, buildSandboxInspectArgs, buildSandboxListArgs, + buildSandboxModifySecretArgs, buildSandboxPingArgs, buildSandboxProvisionArgs, buildSandboxPullArgs, buildSandboxRemoveArgs, + buildSandboxSecretConf, + buildSandboxSecretEnv, buildSandboxStartArgs, buildSandboxStopArgs, buildSandboxStopManagedArgs, + buildSandboxTrustCaArgs, buildSandboxVerifyProvisionArgs, buildSandboxVolumeRemoveArgs, resolveExpectedSandboxNetworkPolicy, @@ -49,8 +55,12 @@ import { sandboxExecutablePath, sandboxNetworkPolicyMismatch, sandboxProjectRoots, + sandboxSecretEnvName, + sandboxSecretPlaceholder, + sandboxSecretsMismatch, sandboxVmMountRoots, sessionSandboxName, + type SandboxSecretSpec, type SandboxVmSpec, } from './command' @@ -97,11 +107,14 @@ export type SandboxStatus = { type VmState = { inFlightBoot: Promise | null inFlightRemoval: Promise | null + inFlightSecretSync: Promise | null lastKnownRunningAt: number | null lastUsedAt: number inFlightProvision: Promise | null backgroundProvisionRetry: Promise | null provisionRetryGeneration: number + secretSetKey: string | null + secretFingerprints: Map } const vmStates = new Map() @@ -118,16 +131,48 @@ function vmState(name: string): VmState { const created: VmState = { inFlightBoot: null, inFlightRemoval: null, + inFlightSecretSync: null, lastKnownRunningAt: null, lastUsedAt: 0, inFlightProvision: null, backgroundProvisionRetry: null, provisionRetryGeneration: 0, + secretSetKey: null, + secretFingerprints: new Map(), } vmStates.set(name, created) return created } +function sandboxSecretFingerprint(value: string): string { + return createHash('sha256').update(value).digest('hex') +} + +function sandboxSecretSetKey(spec: SandboxVmSpec): string { + return JSON.stringify( + [...spec.secrets] + .sort((left, right) => left.envVar.localeCompare(right.envVar)) + .map((secret) => ({ + envVar: secret.envVar, + placeholder: secret.placeholder, + allowedHosts: [...secret.allowedHosts].sort(), + })), + ) +} + +function recordSandboxSecretState(spec: SandboxVmSpec): void { + const state = vmState(spec.name) + state.secretSetKey = sandboxSecretSetKey(spec) + state.secretFingerprints = new Map( + spec.secrets.map((secret) => [secret.envVar, sandboxSecretFingerprint(secret.value)]), + ) +} + +function resetSandboxSecretState(state: VmState): void { + state.secretSetKey = null + state.secretFingerprints.clear() +} + export function resetSandboxRuntimeState(): void { for (const state of vmStates.values()) { state.provisionRetryGeneration += 1 @@ -135,6 +180,8 @@ export function resetSandboxRuntimeState(): void { state.inFlightProvision = null state.inFlightBoot = null state.inFlightRemoval = null + state.inFlightSecretSync = null + resetSandboxSecretState(state) } vmStates.clear() shutdownRequested = false @@ -187,7 +234,11 @@ function ensureSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promi if (inFlightRemoval !== null) { await inFlightRemoval.catch(() => undefined) } - if (state.lastKnownRunningAt !== null && Date.now() - state.lastKnownRunningAt < SANDBOX_LS_CACHE_MS) { + if ( + state.lastKnownRunningAt !== null && + Date.now() - state.lastKnownRunningAt < SANDBOX_LS_CACHE_MS && + state.secretSetKey === sandboxSecretSetKey(spec) + ) { return } await validateSandboxVmMountRoots(spec) @@ -220,8 +271,9 @@ async function bootSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): P await removeSessionSandboxVm(spec.name) await createSessionSandbox(spec, maxRunningVms) } else { - await withStartAdmission(spec.name, maxRunningVms, () => startSessionSandbox(spec.name)) + await withStartAdmission(spec.name, maxRunningVms, () => startSessionSandbox(spec)) await provisionSandboxExecUser(spec.name) + await trustSandboxCa(spec) const runningAttestation = await attestSessionSandbox(spec, true) if (!runningAttestation.trusted) { logger.warn( @@ -229,14 +281,18 @@ async function bootSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): P ) await removeSessionSandboxVm(spec.name) await createSessionSandbox(spec, maxRunningVms) + } else { + recordSandboxSecretState(spec) } } } } state.lastKnownRunningAt = Date.now() + state.secretSetKey = sandboxSecretSetKey(spec) } catch (error) { state.lastKnownRunningAt = null + resetSandboxSecretState(state) throw error } } @@ -253,8 +309,9 @@ async function bootSessionSandboxFromListing(spec: SandboxVmSpec, maxRunningVms: await removeSessionSandboxVm(spec.name) await createSessionSandbox(spec, maxRunningVms) } else if (!entry.running) { - await withStartAdmission(spec.name, maxRunningVms, () => startSessionSandbox(spec.name)) + await withStartAdmission(spec.name, maxRunningVms, () => startSessionSandbox(spec)) await provisionSandboxExecUser(spec.name) + await trustSandboxCa(spec) const runningAttestation = await attestSessionSandbox(spec, true) if (!runningAttestation.trusted) { logger.warn( @@ -262,6 +319,8 @@ async function bootSessionSandboxFromListing(spec: SandboxVmSpec, maxRunningVms: ) await removeSessionSandboxVm(spec.name) await createSessionSandbox(spec, maxRunningVms) + } else { + recordSandboxSecretState(spec) } } } @@ -614,15 +673,9 @@ async function attestSandboxConfig(spec: SandboxVmSpec, config: JsonValue | unde return { trusted: false, reason: policyMismatch } } - const secretsConfig = network.secrets - if (secretsConfig !== undefined && secretsConfig !== null) { - const secretsRecord = parseJsonObject(secretsConfig) - if (secretsRecord === null || !Array.isArray(secretsRecord.secrets)) { - return { trusted: false, reason: 'sandbox configuration network.secrets is malformed' } - } - if (secretsRecord.secrets.length > 0) { - return { trusted: false, reason: 'sandbox configuration network.secrets must be empty' } - } + const secretsMismatch = sandboxSecretsMismatch(network.secrets, spec) + if (secretsMismatch !== null) { + return { trusted: false, reason: secretsMismatch } } const emptyMismatch = emptyArrayMismatch(inspectedSpec.patches, 'patches') @@ -751,6 +804,22 @@ async function provisionSandboxExecUser(name: string): Promise { scheduleBackgroundProvisionRetry(name) } +async function trustSandboxCa(spec: SandboxVmSpec): Promise { + if (spec.secrets.length === 0) return + try { + const result = await executeCommand([sandboxExecutablePath(), ...buildSandboxTrustCaArgs(spec.name)], { + ignoreExitCode: true, + silent: true, + timeout: SANDBOX_LS_TIMEOUT_MS, + }) + if (result.exitCode !== 0) { + logger.warn(`Sandbox CA trust setup failed for ${spec.name}: exit ${result.exitCode}: ${result.stderr || result.stdout}`) + } + } catch (error) { + logger.warn(`Sandbox CA trust setup failed for ${spec.name}: ${getErrorMessage(error)}`) + } +} + async function provisionSandboxExecUserPasswd(name: string): Promise { const provisionArgs = buildSandboxProvisionArgs(name) if (provisionArgs.length === 0) { @@ -844,14 +913,32 @@ function scheduleBackgroundProvisionRetry(name: string): void { async function createSessionSandbox(spec: SandboxVmSpec, maxRunningVms: number): Promise { await withStartAdmission(spec.name, maxRunningVms, () => runSandboxCreate(spec)) await provisionSandboxExecUser(spec.name) + await trustSandboxCa(spec) const attestation = await attestSessionSandbox(spec, true) if (!attestation.trusted) { throw new Error(`newly created sandbox ${spec.name} failed attestation: ${attestation.reason}`) } + recordSandboxSecretState(spec) } async function runSandboxCreate(spec: SandboxVmSpec): Promise { - const first = await executeSandboxCreate(buildSandboxCreateArgs(spec)) + if (spec.secrets.length === 0) { + await runSandboxCreateAttempts(spec) + return + } + const secretDir = await mkdtemp(path.join(tmpdir(), 'ocm-msb-secrets-')) + try { + const secretConfPath = path.join(secretDir, 'secrets.json') + await writeFile(secretConfPath, buildSandboxSecretConf(spec), { mode: 0o600 }) + await runSandboxCreateAttempts(spec, secretConfPath) + } finally { + await rm(secretDir, { recursive: true, force: true }) + } +} + +async function runSandboxCreateAttempts(spec: SandboxVmSpec, secretConfPath?: string): Promise { + const env = buildSandboxSecretEnv(spec) + const first = await executeSandboxCreate(buildSandboxCreateArgs(spec, { secretConfPath }), env) if (first.exitCode === 0) return if (!SANDBOX_CREATE_EXISTS_PATTERN.test(`${first.stdout}\n${first.stderr}`)) { throw new Error(`Command failed with code ${first.exitCode}: ${first.stderr || first.stdout}`) @@ -859,20 +946,25 @@ async function runSandboxCreate(spec: SandboxVmSpec): Promise { logger.warn( `Sandbox ${spec.name} already exists as an orphaned msb sandbox; recreating it with --replace: ${first.stderr || first.stdout}`, ) - const replaced = await executeSandboxCreate(buildSandboxCreateArgs(spec, { replace: true })) + const replaced = await executeSandboxCreate(buildSandboxCreateArgs(spec, { replace: true, secretConfPath }), env) if (replaced.exitCode !== 0) { throw new Error(`Command failed with code ${replaced.exitCode}: ${replaced.stderr || replaced.stdout}`) } } -async function executeSandboxCreate(args: string[]): Promise { +async function executeSandboxCreate( + args: string[], + env: Record, +): Promise { return await executeCommand([sandboxExecutablePath(), ...args], { + env, ignoreExitCode: true, timeout: ENV.SANDBOX.START_TIMEOUT_MS, }) } async function removeSessionSandboxVm(name: string): Promise { + resetSandboxSecretState(vmState(name)) await runSandboxRemoval(buildSandboxRemoveArgs(name), SANDBOX_REMOVAL_MISSING_PATTERN, 'msb rm') } @@ -948,8 +1040,9 @@ function findSessionSandboxEntry(entries: JsonValue[], name: string): { running: return null } -async function startSessionSandbox(name: string): Promise { - const result = await executeCommand([sandboxExecutablePath(), ...buildSandboxStartArgs(name)], { +async function startSessionSandbox(spec: SandboxVmSpec): Promise { + const result = await executeCommand([sandboxExecutablePath(), ...buildSandboxStartArgs(spec.name)], { + env: buildSandboxSecretEnv(spec), ignoreExitCode: true, timeout: ENV.SANDBOX.START_TIMEOUT_MS, }) @@ -957,13 +1050,47 @@ async function startSessionSandbox(name: string): Promise { return } - const entry = findSessionSandboxEntry(await listSandboxes(), name) + const entry = findSessionSandboxEntry(await listSandboxes(), spec.name) if (entry?.running) { return } throw new Error(`msb start failed with code ${result.exitCode}: ${result.stderr || result.stdout}`) } +function syncSandboxSecretValues(spec: SandboxVmSpec, maxRunningVms: number): Promise { + const state = vmState(spec.name) + if (state.inFlightSecretSync) { + return state.inFlightSecretSync + } + state.inFlightSecretSync = (async () => { + for (const secret of spec.secrets) { + const fingerprint = sandboxSecretFingerprint(secret.value) + if (state.secretFingerprints.get(secret.envVar) === fingerprint) continue + const result = await executeCommand( + [sandboxExecutablePath(), ...buildSandboxModifySecretArgs(spec.name, secret)], + { + env: buildSandboxSecretEnv(spec), + ignoreExitCode: true, + timeout: ENV.SANDBOX.START_TIMEOUT_MS, + }, + ) + if (result.exitCode === 0) { + state.secretFingerprints.set(secret.envVar, fingerprint) + continue + } + logger.warn( + `Sandbox secret ${secret.envVar} update for ${spec.name} was refused with code ${result.exitCode}: ${result.stderr || result.stdout}; recreating the sandbox`, + ) + await removeSessionSandboxVm(spec.name) + await createSessionSandbox(spec, maxRunningVms) + return + } + })().finally(() => { + state.inFlightSecretSync = null + }) + return state.inFlightSecretSync +} + async function withStartAdmission(name: string, maxRunningVms: number, run: () => Promise): Promise { const previous = startAdmission let release: () => void = () => {} @@ -1131,18 +1258,33 @@ export class SandboxRuntimeService { reason: `working directory ${directory} is outside this session's sandbox (mounted: ${projectMounts.join(', ')})`, } } - const spec: SandboxVmSpec = { - name: sessionSandboxName(target.rootSessionId), - rootSessionId: target.rootSessionId, - projectMounts, - cpus: target.resources.cpus, - memoryMib: target.resources.memoryMib, - secrets: [], - } - const state = vmState(spec.name) + const name = sessionSandboxName(target.rootSessionId) + const state = vmState(name) state.lastUsedAt = Date.now() try { - await ensureSessionSandbox(spec, sandboxMaxRunningVms(this.db)) + const sessionHiddenSecrets = this.repoEnvService + ? (await this.repoEnvService.resolveForDirectory(target.locationDirectory)).hiddenSecrets + : [] + const secrets: SandboxSecretSpec[] = sessionHiddenSecrets + .filter((binding) => binding.allowedHosts.length > 0) + .map((binding) => ({ + name: binding.name, + envVar: sandboxSecretEnvName(binding.name), + placeholder: sandboxSecretPlaceholder(name, binding.name), + allowedHosts: binding.allowedHosts, + value: binding.value, + })) + const spec: SandboxVmSpec = { + name, + rootSessionId: target.rootSessionId, + projectMounts, + cpus: target.resources.cpus, + memoryMib: target.resources.memoryMib, + secrets, + } + const maxRunningVms = sandboxMaxRunningVms(this.db) + await ensureSessionSandbox(spec, maxRunningVms) + await syncSandboxSecretValues(spec, maxRunningVms) ensureIdleSweepStarted(this.db) state.lastUsedAt = Date.now() const env = { @@ -1151,7 +1293,11 @@ export class SandboxRuntimeService { } let mask: string[] = [] if (this.repoEnvService) { - const repoEnv = await this.repoEnvService.resolveForDirectory(directory) + const placeholders = new Map(secrets.map((secret) => [secret.name, secret.placeholder])) + const repoEnv = await this.repoEnvService.resolveForDirectory(directory, { + kind: 'placeholder', + placeholderFor: (secretName) => placeholders.get(secretName) ?? '', + }) Object.assign(env, repoEnv.env) mask = repoEnv.maskValues } diff --git a/backend/test/helpers/fake-msb.ts b/backend/test/helpers/fake-msb.ts index 6ce5a84e..6d07cbdf 100644 --- a/backend/test/helpers/fake-msb.ts +++ b/backend/test/helpers/fake-msb.ts @@ -79,9 +79,13 @@ function waitGate(kind) { if (!stateDir) stderrExit('missing ${FAKE_MSB_STATE_ENV}', 2) fs.mkdirSync(stateDir, { recursive: true }) +const loggedEnv = {} +for (const [key, value] of Object.entries(process.env)) { + if (key.startsWith('OCM_SECRET_') && typeof value === 'string') loggedEnv[key] = value +} fs.appendFileSync( path.join(stateDir, 'calls.jsonl'), - JSON.stringify({ argv: [process.argv[1]].concat(args) }) + '\\n', + JSON.stringify({ argv: [process.argv[1]].concat(args), env: loggedEnv }) + '\\n', ) const spec = readJson(path.join(stateDir, 'spec.json'), {}) @@ -90,6 +94,24 @@ const state = readJson(statePath, { vms: {} }) state.vms = state.vms || {} const saveState = () => writeJson(statePath, state) +function secretEntries(name) { + const conf = readJson(path.join(stateDir, 'vms', name, 'secrets.json'), {}) + return Object.keys(conf).map((envVar) => { + const entry = conf[envVar] || {} + const allow = Array.isArray(entry.allow) ? entry.allow : [] + return { + env_var: envVar, + value: '', + source: { kind: 'env', var: envVar }, + placeholder: entry.placeholder, + allowed_hosts: allow.map((host) => host.startsWith('*.') ? { wildcard: host.slice(2) } : { exact: host }), + substitution: { headers: true, query: false, body: false }, + passthrough_hosts: [], + require_tls_identity: true, + } + }) +} + function tmpfsSize(memoryMib) { return Math.min(512, Math.max(1, Math.floor(memoryMib / 4))) } @@ -126,6 +148,17 @@ function synthesize(vm, name) { follow_root_symlinks: false, }) mounts.push({ type: 'Tmpfs', guest: '/tmp', size_mib: tmpfsSize(vm.memoryMib), options: mountOptions() }) + const network = { + enabled: true, + ports: [], + policy: spec.policy, + max_connections: null, + trust_host_cas: false, + } + const secrets = secretEntries(name) + if (secrets.length > 0) { + network.secrets = { secrets, violation_action: 'block' } + } return { name, image: { Oci: { reference: spec.image } }, @@ -152,13 +185,7 @@ function synthesize(vm, name) { rlimits: [], mounts, patches: [], - network: { - enabled: true, - ports: [], - policy: spec.policy, - max_connections: null, - trust_host_cas: false, - }, + network, init: null, pull_policy: 'IfMissing', security_profile: 'default', @@ -210,6 +237,13 @@ switch (command) { const memory = valueAfter('-m') || '0M' const sessionLabel = valuesAfter('--label').find((label) => label.startsWith('ocm.session=')) clearInspect(name) + const secretConfPath = valueAfter('--secret-conf') + const secretsPath = path.join(stateDir, 'vms', name, 'secrets.json') + if (secretConfPath) { + writeJson(secretsPath, readJson(secretConfPath, {})) + } else { + fs.rmSync(secretsPath, { force: true }) + } const sharedRoots = new Set(spec.sharedMountRoots || []) state.vms[name] = { projectMounts: valuesAfter('--mount-dir').map((mount) => mount.split(':')[0]).filter((host) => !sharedRoots.has(host)), @@ -243,12 +277,19 @@ switch (command) { const name = args[args.length - 1] if (name) fail('rm-' + name) if (name) clearInspect(name) + if (name) fs.rmSync(path.join(stateDir, 'vms', name, 'secrets.json'), { force: true }) if (name && state.vms[name]) { delete state.vms[name] saveState() } break } + case 'modify': { + fail('modify') + const name = args[1] || '' + if (name) fail('modify-' + name) + break + } case 'volume': fail('volume') break diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index 01df3665..7be92f49 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -7,6 +7,7 @@ import { ENV, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeT import { SettingsService } from '../../../src/services/settings' import { SANDBOX_DOCKER_DATA_GUEST_PATH, + buildSandboxSecretConf, buildSandboxStopArgs, buildSandboxStopManagedArgs, parseMemoryMib, @@ -16,6 +17,8 @@ import { sandboxDockerDataVolumeName, sandboxExecutablePath, sandboxProjectRoots, + sandboxSecretEnvName, + sandboxSecretPlaceholder, sessionSandboxName, } from '../../../src/services/sandbox/command' import { @@ -28,7 +31,7 @@ import { } from '../../../src/services/sandbox/runtime' import type { JsonValue } from '@opencode-manager/shared/utils' import { sandboxCapabilityProbes, resetSandboxCapabilityCache } from '../../../src/services/sandbox/capability' -import type { RepoEnvService } from '../../../src/services/repo-env' +import type { RepoEnvService, HiddenSecretPolicy } from '../../../src/services/repo-env' import { overrideSandboxExecutableTrustValidator } from '../../../src/services/sandbox/command' import { forceProcessAttestation } from '../../../src/services/opencode/process-identity' import { z } from 'zod' @@ -79,7 +82,12 @@ const FakeVmStateSchema = z.object({ type FakeVmState = z.infer -const FakeCallSchema = z.object({ argv: z.array(z.string()) }) +const FakeCallSchema = z.object({ + argv: z.array(z.string()), + env: z.record(z.string(), z.string()).optional(), +}) + +type FakeCall = z.infer interface FakeMountOptions { readonly: boolean @@ -193,13 +201,17 @@ function fakeMsbStatePath(): string { return path.join(fakeMsbStateDir, 'state.json') } -function fakeMsbInvocations(): string[][] { +function fakeMsbCallRecords(): FakeCall[] { const logPath = path.join(fakeMsbStateDir, 'calls.jsonl') if (!existsSync(logPath)) return [] return readFileSync(logPath, 'utf8') .split('\n') .filter((line) => line.length > 0) - .map((line) => FakeCallSchema.parse(JSON.parse(line)).argv) + .map((line) => FakeCallSchema.parse(JSON.parse(line))) +} + +function fakeMsbInvocations(): string[][] { + return fakeMsbCallRecords().map((call) => call.argv) } function fakeVms(): Record { @@ -329,6 +341,54 @@ function shellTarget(locationDirectory: string, resources = defaultResources()): return { rootSessionId: ROOT_SESSION, locationDirectory, resources } } +type TestHiddenSecret = { name: string; value: string; allowedHosts: string[] } + +function hiddenRepoEnv(secrets: TestHiddenSecret[]) { + return { + resolveForDirectory: vi.fn(async (_directory: string, policy: HiddenSecretPolicy = { kind: 'withhold' }) => { + const hiddenSecrets = secrets.map((secret) => ({ ...secret })) + const env: Record = {} + for (const secret of hiddenSecrets) { + env[secret.name] = + policy.kind === 'reveal' + ? secret.value + : policy.kind === 'placeholder' + ? policy.placeholderFor(secret.name) + : '' + } + return { env, maskValues: [], hiddenSecrets } + }), + } satisfies Pick +} + +function installFakeVmSecrets(name: string, secrets: TestHiddenSecret[]): void { + const spec = { + name, + rootSessionId: ROOT_SESSION, + projectMounts: [repoADir], + cpus: defaultResources().cpus, + memoryMib: defaultResources().memoryMib, + secrets: secrets.map((secret) => ({ + name: secret.name, + envVar: sandboxSecretEnvName(secret.name), + placeholder: sandboxSecretPlaceholder(name, secret.name), + allowedHosts: secret.allowedHosts, + value: secret.value, + })), + } + const secretPath = path.join(fakeMsbStateDir, 'vms', name, 'secrets.json') + mkdirSync(path.dirname(secretPath), { recursive: true }) + writeFileSync(secretPath, buildSandboxSecretConf(spec)) +} + +function runCalls(): FakeCall[] { + return fakeMsbCallRecords().filter((call) => call.argv[1] === 'run') +} + +function modifyCalls(): FakeCall[] { + return fakeMsbCallRecords().filter((call) => call.argv[1] === 'modify') +} + function bindMount(host: string): FakeBindMount { return { type: 'Bind', @@ -678,6 +738,284 @@ describe('SandboxRuntimeService', () => { }) }) + it('creates the VM with a secret conf and returns only the placeholder', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const withSecrets = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] }]), + ) + + const plan = await withSecrets.planShell(repoADir, shellTarget(repoADir)) + + const placeholder = sandboxSecretPlaceholder(VM_NAME, 'TOKEN') + expect(plan).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir, env: { TOKEN: placeholder } }) + const runs = runCalls() + expect(runs).toHaveLength(1) + expect(runs[0]?.argv).toContain('--secret-conf') + expect(runs[0]?.env).toEqual({ OCM_SECRET_TOKEN: 'hunter2' }) + expect(fakeMsbInvocations().flat()).not.toContain('hunter2') + expect(readFileSync(path.join(fakeMsbStateDir, 'vms', VM_NAME, 'secrets.json'), 'utf8')).toBe( + JSON.stringify({ + OCM_SECRET_TOKEN: { + value: { $msb_env: 'OCM_SECRET_TOKEN' }, + placeholder, + allow: ['api.example.com'], + substitution: { headers: true, query: false, body: false }, + }, + }), + ) + }) + + it('attests a running VM that carries the expected network secrets without recreating it', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const withSecrets = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] }]), + ) + + await withSecrets.planShell(repoADir, shellTarget(repoADir)) + const second = await withSecrets.planShell(repoADir, shellTarget(repoADir)) + + expect(second).toEqual({ + mode: 'sandbox', + name: VM_NAME, + workdir: repoADir, + env: { TOKEN: sandboxSecretPlaceholder(VM_NAME, 'TOKEN') }, + }) + expect(runCalls()).toHaveLength(1) + expect(msbCalls('rm')).toHaveLength(0) + expect(modifyCalls()).toHaveLength(0) + }) + + it('recreates the VM when a hidden secret is added', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const first = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] }]), + ) + const added = new SandboxRuntimeService( + db, + hiddenRepoEnv([ + { name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] }, + { name: 'OTHER', value: 'other-value', allowedHosts: ['api.example.com'] }, + ]), + ) + + await first.planShell(repoADir, shellTarget(repoADir)) + await added.planShell(repoADir, shellTarget(repoADir)) + + expect(msbCalls('rm')).toHaveLength(1) + expect(runCalls()).toHaveLength(2) + expect(modifyCalls()).toHaveLength(0) + }) + + it('recreates the VM when the allowed hosts of a hidden secret change', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const first = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] }]), + ) + const rehosted = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'hunter2', allowedHosts: ['api2.example.com'] }]), + ) + + await first.planShell(repoADir, shellTarget(repoADir)) + await rehosted.planShell(repoADir, shellTarget(repoADir)) + + expect(msbCalls('rm')).toHaveLength(1) + expect(runCalls()).toHaveLength(2) + expect(modifyCalls()).toHaveLength(0) + expect(readFileSync(path.join(fakeMsbStateDir, 'vms', VM_NAME, 'secrets.json'), 'utf8')).toContain( + '"allow":["api2.example.com"]', + ) + }) + + it('rotates a changed value with one modify and no recreate', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const first = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'value-one', allowedHosts: ['api.example.com'] }]), + ) + const rotated = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'value-two', allowedHosts: ['api.example.com'] }]), + ) + + await first.planShell(repoADir, shellTarget(repoADir)) + const plan = await rotated.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ + mode: 'sandbox', + name: VM_NAME, + workdir: repoADir, + env: { TOKEN: sandboxSecretPlaceholder(VM_NAME, 'TOKEN') }, + }) + const modifies = modifyCalls() + expect(modifies).toHaveLength(1) + expect(modifies[0]?.argv).toEqual([ + sandboxExecutablePath(), + 'modify', + VM_NAME, + '--secret', + 'OCM_SECRET_TOKEN@api.example.com', + ]) + expect(modifies[0]?.env).toEqual({ OCM_SECRET_TOKEN: 'value-two' }) + expect(fakeMsbInvocations().flat()).not.toContain('value-two') + expect(runCalls()).toHaveLength(1) + expect(msbCalls('rm')).toHaveLength(0) + + await rotated.planShell(repoADir, shellTarget(repoADir)) + expect(modifyCalls()).toHaveLength(1) + }) + + it('recreates the VM when a live modify is refused', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const first = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'value-one', allowedHosts: ['api.example.com'] }]), + ) + const rotated = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'TOKEN', value: 'value-two', allowedHosts: ['api.example.com'] }]), + ) + + await first.planShell(repoADir, shellTarget(repoADir)) + writeFailureFile('modify', 'secret update refused') + const plan = await rotated.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ + mode: 'sandbox', + name: VM_NAME, + workdir: repoADir, + env: { TOKEN: sandboxSecretPlaceholder(VM_NAME, 'TOKEN') }, + }) + expect(modifyCalls()).toHaveLength(1) + expect(msbCalls('rm')).toHaveLength(1) + expect(runCalls()).toHaveLength(2) + expect(runCalls().at(-1)?.env).toEqual({ OCM_SECRET_TOKEN: 'value-two' }) + expectLoggedMessage('was refused with code 1', 'warn') + }) + + it('rotates each secret once after a Manager restart and then stops modifying', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const withSecrets = new SandboxRuntimeService( + db, + hiddenRepoEnv([ + { name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] }, + { name: 'OTHER', value: 'other-value', allowedHosts: ['api2.example.com'] }, + ]), + ) + + await withSecrets.planShell(repoADir, shellTarget(repoADir)) + expect(modifyCalls()).toHaveLength(0) + + resetSandboxRuntimeState() + await withSecrets.planShell(repoADir, shellTarget(repoADir)) + + expect(modifyCalls()).toHaveLength(2) + expect(runCalls()).toHaveLength(1) + expect(msbCalls('rm')).toHaveLength(0) + + await withSecrets.planShell(repoADir, shellTarget(repoADir)) + expect(modifyCalls()).toHaveLength(2) + }) + + it('passes the secret env to msb start and trusts the CA for a stopped VM with secrets', async () => { + enableEnforcement() + installFakeMsb(new Map([[VM_NAME, vm({ running: false })]])) + const secret = { name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] } + installFakeVmSecrets(VM_NAME, [secret]) + const withSecrets = new SandboxRuntimeService(db, hiddenRepoEnv([secret])) + + const plan = await withSecrets.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ + mode: 'sandbox', + name: VM_NAME, + workdir: repoADir, + env: { TOKEN: sandboxSecretPlaceholder(VM_NAME, 'TOKEN') }, + }) + const start = fakeMsbCallRecords().find((call) => call.argv[1] === 'start') + expect(start?.env).toEqual({ OCM_SECRET_TOKEN: 'hunter2' }) + expect(fakeMsbInvocations().filter((args) => args[1] === 'exec').some((args) => args.some((arg) => arg.includes('certutil')))).toBe(true) + expect(runCalls()).toHaveLength(0) + expect(msbCalls('rm')).toHaveLength(0) + }) + + it('runs no secret conf or CA trust when the VM has no hidden secrets', async () => { + enableEnforcement() + installFakeMsb(new Map()) + + await service.planShell(repoADir, shellTarget(repoADir)) + + const runs = runCalls() + expect(runs).toHaveLength(1) + expect(runs[0]?.argv).not.toContain('--secret-conf') + expect(fakeMsbInvocations().filter((args) => args[1] === 'exec').some((args) => args.some((arg) => arg.includes('certutil')))).toBe(false) + expect(modifyCalls()).toHaveLength(0) + }) + + it('withholds a working directory hidden secret outside the session VM set', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const nested = path.join(repoADir, 'nested') + mkdirSync(nested, { recursive: true }) + const sessionSecret: TestHiddenSecret = { name: 'TOKEN', value: 'hunter2', allowedHosts: ['api.example.com'] } + const workingSecret: TestHiddenSecret = { name: 'OTHER', value: 'other-secret', allowedHosts: ['api.example.com'] } + const repoEnv = { + resolveForDirectory: vi.fn(async (dir: string, policy: HiddenSecretPolicy = { kind: 'withhold' }) => { + const bindings = dir === repoADir ? [sessionSecret] : [sessionSecret, workingSecret] + const env: Record = {} + for (const binding of bindings) { + env[binding.name] = + policy.kind === 'reveal' + ? binding.value + : policy.kind === 'placeholder' + ? policy.placeholderFor(binding.name) + : '' + } + return { env, maskValues: [], hiddenSecrets: bindings.map((binding) => ({ ...binding })) } + }), + } satisfies Pick + const withSecrets = new SandboxRuntimeService(db, repoEnv) + + const plan = await withSecrets.planShell(nested, shellTarget(repoADir)) + + expect(plan).toEqual({ + mode: 'sandbox', + name: VM_NAME, + workdir: nested, + env: { TOKEN: sandboxSecretPlaceholder(VM_NAME, 'TOKEN'), OTHER: '' }, + }) + expect(readFileSync(path.join(fakeMsbStateDir, 'vms', VM_NAME, 'secrets.json'), 'utf8')).not.toContain( + 'OCM_SECRET_OTHER', + ) + }) + + it('leaves a hidden secret with no allowed hosts out of the VM and withholds it', async () => { + enableEnforcement() + installFakeMsb(new Map()) + const withSecrets = new SandboxRuntimeService( + db, + hiddenRepoEnv([{ name: 'ORPHAN', value: 'orphan-value', allowedHosts: [] }]), + ) + + const plan = await withSecrets.planShell(repoADir, shellTarget(repoADir)) + + expect(plan).toEqual({ mode: 'sandbox', name: VM_NAME, workdir: repoADir, env: { ORPHAN: '' } }) + expect(runCalls()[0]?.argv).not.toContain('--secret-conf') + expect(existsSync(path.join(fakeMsbStateDir, 'vms', VM_NAME, 'secrets.json'))).toBe(false) + expect(fakeMsbInvocations().flat()).not.toContain('orphan-value') + }) + it('starts an existing stopped sandbox instead of recreating it', async () => { enableEnforcement() const vms = new Map([[VM_NAME, vm({ running: false })]])