@hmharness/sandbox 0.23.42 → 0.23.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/broker.d.ts CHANGED
@@ -121,3 +121,4 @@ export declare class SecretBroker {
121
121
  redact(text: string): string;
122
122
  list(): string[];
123
123
  }
124
+ export declare function assertExecutionGate(decision: BrokerDecision, available: IsolationLevel): void;
package/dist/broker.js CHANGED
@@ -21,7 +21,8 @@
21
21
  * Layering: this module has zero cognitive imports; ledger mirroring is
22
22
  * an injectable onDeny hook the composition layer wires.
23
23
  */
24
- import { recommendedIsolation } from "./microvm.js";
24
+ import { recommendedIsolation, isolationToTrust } from "./microvm.js";
25
+ import { assertIsolationGate } from "./trust.js";
25
26
  const MAX_TTL_MS = 24 * 60 * 60 * 1000;
26
27
  const DEFAULT_TTL_MS = 60 * 60 * 1000;
27
28
  /** classes the worker tier can never hold - the RLM rule, mechanical */
@@ -202,3 +203,17 @@ export class SecretBroker {
202
203
  return [...this.secrets.keys()];
203
204
  }
204
205
  }
206
+ /* ---------------- Execution gate (Issue #21: tier claims must meet reality) ----------------
207
+ *
208
+ * A broker decision names the tier a workload SHOULD run at; the machine
209
+ * only offers what detectHighestIsolation() actually found. This composer
210
+ * makes the pairing fail closed: executing a decision whose tier outranks
211
+ * the machine throws a structured IsolationGateError naming BOTH tiers —
212
+ * the old world let critical decisions silently execute in Docker.
213
+ * Worker tier never gates: its walls come from the running Node runtime
214
+ * itself, so the machine requirement is just 'process'.
215
+ */
216
+ export function assertExecutionGate(decision, available) {
217
+ const required = decision.tier === 'worker' ? 'worker' : isolationToTrust(decision.tier);
218
+ assertIsolationGate(required, isolationToTrust(available), `broker decision tier '${decision.tier}'`);
219
+ }
package/dist/index.d.ts CHANGED
@@ -3,4 +3,5 @@ export * from './redteam.js';
3
3
  export * from './provider.js';
4
4
  export * from './chaos.js';
5
5
  export * from './microvm.js';
6
+ export * from './trust.js';
6
7
  export * from './broker.js';
package/dist/index.js CHANGED
@@ -3,4 +3,5 @@ export * from "./redteam.js";
3
3
  export * from "./provider.js";
4
4
  export * from "./chaos.js";
5
5
  export * from "./microvm.js";
6
+ export * from "./trust.js";
6
7
  export * from "./broker.js";
package/dist/microvm.d.ts CHANGED
@@ -1,12 +1,27 @@
1
1
  /**
2
- * @hmharness/sandbox - microVM Backend (P3-06)
2
+ * @hmharness/sandbox - microVM Backend (P3-06; honesty rework for Issue #21, P0)
3
3
  *
4
- * The audit: "面向高风险长任务提供更强隔离"
5
- *
6
- * Extends the SandboxProvider abstraction with Firecracker/microVM-style
7
- * isolation for high-risk, long-running tasks. This is the strongest
4
+ * Extends the SandboxProvider abstraction with Firecracker/Cloud Hypervisor
5
+ * style isolation for high-risk, long-running tasks. This is the strongest
8
6
  * isolation tier: full VM-level separation.
7
+ *
8
+ * ISSUE #21 HONESTY RULES (fail closed, never fake a VM):
9
+ * - isAvailable() is TRUE only when a real hypervisor (Firecracker or
10
+ * Cloud Hypervisor) is detected AND has passed a boot self-test.
11
+ * Docker-only machines return FALSE. The old behavior — "Docker can
12
+ * simulate microVM" — was a lie: `docker run` shares the host kernel.
13
+ * - exec/copyIn/copyOut/snapshot/restore refuse (structured
14
+ * IsolationGateError) when the real tier is absent. The old behavior
15
+ * ran plain `docker run` under a "strongest tier" name, and its
16
+ * copyIn/copyOut wrote the HOST filesystem directly with no boundary
17
+ * at all; snapshot() returned a hash string that restored nothing.
18
+ * - Migration for callers of the old silent downgrade: if container
19
+ * semantics are what you want, use DockerSandboxProvider (it reports
20
+ * backend='docker' honestly); if you need critical-tier isolation,
21
+ * keep requiring 'microvm' and let the gate fail closed until a real
22
+ * hypervisor + self-test exist.
9
23
  */
24
+ import { type TrustLevel } from './trust.js';
10
25
  import type { SandboxProvider, SandboxResult, ProviderSandboxSpec, SandboxBackend } from './provider.js';
11
26
  export type IsolationLevel = 'process' | 'container' | 'microvm';
12
27
  export interface MicroVMConfig {
@@ -24,9 +39,15 @@ export interface MicroVMConfig {
24
39
  bootTimeoutMs: number;
25
40
  }
26
41
  export declare const DEFAULT_MICROVM_CONFIG: MicroVMConfig;
42
+ /** Map the ladder's IsolationLevel to the honest TrustLevel vocabulary.
43
+ * 'microvm' maps to real-microvm BY DEFINITION — a Docker stand-in is
44
+ * 'container', and nothing in this module ever conflates them. Pure. */
45
+ export declare function isolationToTrust(level: IsolationLevel): TrustLevel;
27
46
  /**
28
47
  * Determine the appropriate isolation level for a task.
29
- * Pure - testable.
48
+ * Pure - testable. NOTE: this is a RECOMMENDATION, not an availability
49
+ * claim — pair it with assertIsolationGate()/assertExecutionGate() before
50
+ * executing anything at the recommended tier.
30
51
  */
31
52
  export declare function recommendedIsolation(params: {
32
53
  riskLevel: 'low' | 'medium' | 'high' | 'critical';
@@ -42,19 +63,94 @@ export declare function isolationCost(level: IsolationLevel): {
42
63
  memoryMb: number;
43
64
  description: string;
44
65
  };
66
+ /** What a real-hypervisor probe found. `selfTest` is honest about the state
67
+ * of VM lifecycle support on this machine, not about binaries merely existing. */
68
+ export interface MicroVMProbe {
69
+ /** which hypervisor binary was found, if any */
70
+ hypervisor: 'firecracker' | 'cloud-hypervisor' | null;
71
+ /** raw version output (evidence for logs/UI) */
72
+ hypervisorVersion: string | null;
73
+ /** 'passed' only after a real boot self-test; 'not-implemented' = binary
74
+ * found but VM lifecycle (boot/rootfs/api-socket) is NOT implemented;
75
+ * 'no-hypervisor' = neither binary exists */
76
+ selfTest: 'passed' | 'not-implemented' | 'no-hypervisor';
77
+ /** Docker status is reported for EVIDENCE only — it never makes microvm
78
+ * available. TRUE means the daemon actually answered `docker info`; a CLI
79
+ * without a daemon is false (the CLI proves nothing — `docker run` would
80
+ * fail). Derived from the SAME snapshot as detectHighestIsolation(). */
81
+ dockerAvailable: boolean;
82
+ /** true only when hypervisor !== null && selfTest === 'passed' */
83
+ microvmReady: boolean;
84
+ note: string;
85
+ }
86
+ /** One machine-wide evidence snapshot. Plain data — derivations are pure. */
87
+ export interface MachineIsolationEvidence {
88
+ /** `firecracker --version` output; null = absent/failed */
89
+ firecrackerVersion: string | null;
90
+ /** `cloud-hypervisor --version` output; null = absent/failed */
91
+ cloudHypervisorVersion: string | null;
92
+ /** `docker info` SUCCEEDED (daemon reachable & responsive). The ONLY
93
+ * docker signal allowed to raise the isolation level. */
94
+ dockerDaemonVersion: string | null;
95
+ /** `docker --version` output (CLI exists). Evidence for logs only — a
96
+ * CLI without a daemon runs nothing, so it can never mean 'container'. */
97
+ dockerCliVersion: string | null;
98
+ }
99
+ /** pluggable raw prober (production = shell out; tests inject fakes) */
100
+ export type RawProbe = (bin: string, args: string[], timeoutMs: number) => Promise<string | null>;
101
+ /** Test seam: inject a fake prober and RESET the shared evidence snapshot,
102
+ * or pass null to restore production probing. Nothing outside tests
103
+ * should ever call this. */
104
+ export declare function setRawProbeForTests(fn: RawProbe | null): void;
105
+ /** Derive the machine's honest highest isolation from one evidence
106
+ * snapshot. Pure — testable without touching the machine. */
107
+ export declare function isolationFromEvidence(ev: MachineIsolationEvidence): {
108
+ level: IsolationLevel;
109
+ trust: TrustLevel;
110
+ hypervisor: 'firecracker' | 'cloud-hypervisor' | null;
111
+ evidence: string;
112
+ };
113
+ /**
114
+ * Determine the machine's strongest ACTUALLY available isolation. Derived
115
+ * from the same shared evidence snapshot as MicroVMSandboxProvider.probe()
116
+ * — the two API faces cannot disagree. Reports microvm ONLY when a
117
+ * hypervisor binary exists AND its boot self-test passed; a reachable
118
+ * Docker daemon reports container; anything less reports process. Never a
119
+ * lie.
120
+ */
121
+ export declare function detectHighestIsolation(): Promise<{
122
+ level: IsolationLevel;
123
+ trust: TrustLevel;
124
+ hypervisor: string | null;
125
+ evidence: string;
126
+ }>;
45
127
  /**
46
128
  * MicroVM sandbox provider (extends SandboxProvider interface).
47
- * Note: This is a configuration/planning module. Actual VM management
48
- * requires a runtime like Firecracker or Cloud Hypervisor.
129
+ *
130
+ * HONESTY CONTRACT (Issue #21): this provider EXECUTES NOTHING today. VM
131
+ * lifecycle management (boot a microVM, provision rootfs, speak the
132
+ * Firecracker/Cloud Hypervisor API socket) is not implemented, so:
133
+ * isAvailable() -> false on every current machine (no self-test exists)
134
+ * every exec/copy/snapshot call -> IsolationGateError (fail closed)
135
+ * Before the honesty rework it happily answered available=true on any
136
+ * Docker machine and ran `docker run` — that path is deleted, not stubbed.
49
137
  */
50
138
  export declare class MicroVMSandboxProvider implements SandboxProvider {
139
+ /** design-target backend. It is a DECLARATION, not an execution claim:
140
+ * no SandboxResult ever leaves this class until a real VM path exists. */
51
141
  readonly backend: SandboxBackend;
52
142
  private readonly config;
53
143
  constructor(config?: Partial<MicroVMConfig>);
144
+ /** Evidence-grade probe for logs/UI/API — same fields everywhere. Reads
145
+ * the SAME shared evidence snapshot detectHighestIsolation() uses, so the
146
+ * two faces cannot tell different stories about one machine. */
147
+ probe(): Promise<MicroVMProbe>;
54
148
  isAvailable(): Promise<boolean>;
55
- exec(command: string, args: string[], spec: ProviderSandboxSpec): Promise<SandboxResult>;
56
- copyIn(localPath: string, sandboxPath: string, _spec: ProviderSandboxSpec): Promise<void>;
57
- copyOut(sandboxPath: string, localPath: string, _spec: ProviderSandboxSpec): Promise<void>;
58
- snapshot(spec: ProviderSandboxSpec): Promise<string>;
149
+ exec(_command: string, _args: string[], _spec: ProviderSandboxSpec): Promise<SandboxResult>;
150
+ copyIn(_localPath: string, sandboxPath: string, _spec: ProviderSandboxSpec): Promise<void>;
151
+ copyOut(sandboxPath: string, _localPath: string, _spec: ProviderSandboxSpec): Promise<void>;
152
+ snapshot(_spec: ProviderSandboxSpec): Promise<string>;
59
153
  restore(_snapshotId: string, _spec: ProviderSandboxSpec): Promise<void>;
154
+ /** fail closed: never executes, never fakes, names both tiers in the error */
155
+ private refuse;
60
156
  }
package/dist/microvm.js CHANGED
@@ -1,12 +1,27 @@
1
1
  /**
2
- * @hmharness/sandbox - microVM Backend (P3-06)
2
+ * @hmharness/sandbox - microVM Backend (P3-06; honesty rework for Issue #21, P0)
3
3
  *
4
- * The audit: "面向高风险长任务提供更强隔离"
5
- *
6
- * Extends the SandboxProvider abstraction with Firecracker/microVM-style
7
- * isolation for high-risk, long-running tasks. This is the strongest
4
+ * Extends the SandboxProvider abstraction with Firecracker/Cloud Hypervisor
5
+ * style isolation for high-risk, long-running tasks. This is the strongest
8
6
  * isolation tier: full VM-level separation.
7
+ *
8
+ * ISSUE #21 HONESTY RULES (fail closed, never fake a VM):
9
+ * - isAvailable() is TRUE only when a real hypervisor (Firecracker or
10
+ * Cloud Hypervisor) is detected AND has passed a boot self-test.
11
+ * Docker-only machines return FALSE. The old behavior — "Docker can
12
+ * simulate microVM" — was a lie: `docker run` shares the host kernel.
13
+ * - exec/copyIn/copyOut/snapshot/restore refuse (structured
14
+ * IsolationGateError) when the real tier is absent. The old behavior
15
+ * ran plain `docker run` under a "strongest tier" name, and its
16
+ * copyIn/copyOut wrote the HOST filesystem directly with no boundary
17
+ * at all; snapshot() returned a hash string that restored nothing.
18
+ * - Migration for callers of the old silent downgrade: if container
19
+ * semantics are what you want, use DockerSandboxProvider (it reports
20
+ * backend='docker' honestly); if you need critical-tier isolation,
21
+ * keep requiring 'microvm' and let the gate fail closed until a real
22
+ * hypervisor + self-test exist.
9
23
  */
24
+ import { assertIsolationGate } from "./trust.js";
10
25
  export const DEFAULT_MICROVM_CONFIG = {
11
26
  image: 'microvm-base',
12
27
  vcpus: 2,
@@ -15,9 +30,21 @@ export const DEFAULT_MICROVM_CONFIG = {
15
30
  networkEnabled: false,
16
31
  bootTimeoutMs: 5000,
17
32
  };
33
+ /** Map the ladder's IsolationLevel to the honest TrustLevel vocabulary.
34
+ * 'microvm' maps to real-microvm BY DEFINITION — a Docker stand-in is
35
+ * 'container', and nothing in this module ever conflates them. Pure. */
36
+ export function isolationToTrust(level) {
37
+ if (level === 'microvm')
38
+ return 'real-microvm';
39
+ if (level === 'container')
40
+ return 'container';
41
+ return 'process';
42
+ }
18
43
  /**
19
44
  * Determine the appropriate isolation level for a task.
20
- * Pure - testable.
45
+ * Pure - testable. NOTE: this is a RECOMMENDATION, not an availability
46
+ * claim — pair it with assertIsolationGate()/assertExecutionGate() before
47
+ * executing anything at the recommended tier.
21
48
  */
22
49
  export function recommendedIsolation(params) {
23
50
  if (params.riskLevel === 'critical')
@@ -35,98 +62,149 @@ export function recommendedIsolation(params) {
35
62
  export function isolationCost(level) {
36
63
  switch (level) {
37
64
  case 'process': return { startupMs: 0, memoryMb: 0, description: 'host process (no isolation overhead)' };
38
- case 'container': return { startupMs: 500, memoryMb: 50, description: 'Docker container (lightweight isolation)' };
39
- case 'microvm': return { startupMs: 2000, memoryMb: 200, description: 'Firecracker microVM (full VM isolation)' };
65
+ case 'container': return { startupMs: 500, memoryMb: 50, description: 'Docker container (lightweight isolation, shared host kernel)' };
66
+ case 'microvm': return { startupMs: 2000, memoryMb: 200, description: 'real Firecracker/Cloud Hypervisor microVM (full VM isolation; requires a hypervisor boot self-test — never faked with Docker)' };
67
+ }
68
+ }
69
+ async function shellOutProbe(bin, args, timeoutMs) {
70
+ try {
71
+ const { execFile } = await import('node:child_process');
72
+ const { promisify } = await import('node:util');
73
+ const run = promisify(execFile);
74
+ const r = await run(bin, args, { timeout: timeoutMs });
75
+ return String(r.stdout ?? r ?? '').trim();
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ let rawProbe = shellOutProbe;
82
+ /** Test seam: inject a fake prober and RESET the shared evidence snapshot,
83
+ * or pass null to restore production probing. Nothing outside tests
84
+ * should ever call this. */
85
+ export function setRawProbeForTests(fn) {
86
+ rawProbe = fn ?? shellOutProbe;
87
+ sharedEvidence = null;
88
+ }
89
+ /** Collect the machine's isolation evidence. Runs ONCE per process. */
90
+ async function collectIsolationEvidence() {
91
+ const fc = await rawProbe('firecracker', ['--version'], 3000);
92
+ const ch = await rawProbe('cloud-hypervisor', ['--version'], 3000);
93
+ const daemon = await rawProbe('docker', ['info', '--format', '{{.ServerVersion}}'], 5000);
94
+ const cli = await rawProbe('docker', ['--version'], 3000);
95
+ return { firecrackerVersion: fc, cloudHypervisorVersion: ch, dockerDaemonVersion: daemon, dockerCliVersion: cli };
96
+ }
97
+ let sharedEvidence = null;
98
+ /** THE single evidence source: first caller collects, everyone reuses the
99
+ * same in-flight snapshot. Derive — never re-probe. */
100
+ function machineEvidence() {
101
+ sharedEvidence ??= collectIsolationEvidence();
102
+ return sharedEvidence;
103
+ }
104
+ /** Derive the machine's honest highest isolation from one evidence
105
+ * snapshot. Pure — testable without touching the machine. */
106
+ export function isolationFromEvidence(ev) {
107
+ const hypervisor = ev.firecrackerVersion ? 'firecracker' : ev.cloudHypervisorVersion ? 'cloud-hypervisor' : null;
108
+ const hypEvidence = hypervisor ? 'hypervisor binary present but boot self-test not implemented' : 'no hypervisor binary';
109
+ // NEVER level='microvm' today: the boot self-test does not exist (see
110
+ // MicroVMSandboxProvider.probe()), and a --version string is not a booted
111
+ // VM. When the self-test lands, promote the hypervisor branch to a real
112
+ // check and return microvm ONLY on selfTest === 'passed'.
113
+ if (ev.dockerDaemonVersion) {
114
+ return { level: 'container', trust: 'container', hypervisor, evidence: `docker server ${ev.dockerDaemonVersion} reachable; ${hypEvidence}` };
40
115
  }
116
+ const dockerEvidence = ev.dockerCliVersion
117
+ ? `docker CLI present (${ev.dockerCliVersion}) but daemon unreachable — a CLI without a daemon runs nothing; ${hypEvidence}`
118
+ : `no docker; ${hypEvidence}`;
119
+ return { level: 'process', trust: 'process', hypervisor, evidence: dockerEvidence };
120
+ }
121
+ /**
122
+ * Determine the machine's strongest ACTUALLY available isolation. Derived
123
+ * from the same shared evidence snapshot as MicroVMSandboxProvider.probe()
124
+ * — the two API faces cannot disagree. Reports microvm ONLY when a
125
+ * hypervisor binary exists AND its boot self-test passed; a reachable
126
+ * Docker daemon reports container; anything less reports process. Never a
127
+ * lie.
128
+ */
129
+ export async function detectHighestIsolation() {
130
+ return isolationFromEvidence(await machineEvidence());
41
131
  }
42
132
  /**
43
133
  * MicroVM sandbox provider (extends SandboxProvider interface).
44
- * Note: This is a configuration/planning module. Actual VM management
45
- * requires a runtime like Firecracker or Cloud Hypervisor.
134
+ *
135
+ * HONESTY CONTRACT (Issue #21): this provider EXECUTES NOTHING today. VM
136
+ * lifecycle management (boot a microVM, provision rootfs, speak the
137
+ * Firecracker/Cloud Hypervisor API socket) is not implemented, so:
138
+ * isAvailable() -> false on every current machine (no self-test exists)
139
+ * every exec/copy/snapshot call -> IsolationGateError (fail closed)
140
+ * Before the honesty rework it happily answered available=true on any
141
+ * Docker machine and ran `docker run` — that path is deleted, not stubbed.
46
142
  */
47
143
  export class MicroVMSandboxProvider {
48
- backend = 'docker'; // closest available backend
144
+ /** design-target backend. It is a DECLARATION, not an execution claim:
145
+ * no SandboxResult ever leaves this class until a real VM path exists. */
146
+ backend = 'firecracker';
49
147
  config;
50
148
  constructor(config = {}) {
51
149
  this.config = { ...DEFAULT_MICROVM_CONFIG, ...config };
52
150
  }
151
+ /** Evidence-grade probe for logs/UI/API — same fields everywhere. Reads
152
+ * the SAME shared evidence snapshot detectHighestIsolation() uses, so the
153
+ * two faces cannot tell different stories about one machine. */
154
+ async probe() {
155
+ const ev = await machineEvidence();
156
+ const hypervisor = ev.firecrackerVersion ? 'firecracker' : ev.cloudHypervisorVersion ? 'cloud-hypervisor' : null;
157
+ const version = ev.firecrackerVersion ?? ev.cloudHypervisorVersion;
158
+ // Boot self-test: NOT IMPLEMENTED. A --version string is not a booted VM.
159
+ // When someone implements it, return 'passed' here and isAvailable()/
160
+ // detectHighestIsolation() become true to microvm on that machine.
161
+ const selfTest = (hypervisor ? 'not-implemented' : 'no-hypervisor');
162
+ return {
163
+ hypervisor,
164
+ hypervisorVersion: version,
165
+ selfTest,
166
+ dockerAvailable: ev.dockerDaemonVersion !== null,
167
+ microvmReady: hypervisor !== null && selfTest === 'passed',
168
+ note: hypervisor
169
+ ? `${hypervisor} binary present, but the VM boot self-test is not implemented — microVM is NOT reported available (would-be config: ${this.config.vcpus} vcpu/${this.config.memoryMb}MB)`
170
+ : ev.dockerDaemonVersion
171
+ ? 'no Firecracker/Cloud Hypervisor found; Docker daemon is reachable but a container is NOT a microVM — reporting unavailable (Issue #21: no silent downgrade)'
172
+ : ev.dockerCliVersion
173
+ ? 'no hypervisor; docker CLI present but daemon unreachable — neither microVM nor container is available'
174
+ : 'no hypervisor and no Docker — microVM unavailable',
175
+ };
176
+ }
53
177
  async isAvailable() {
54
- // microVM requires a hypervisor - check if firecracker/cloud-hypervisor exists
55
- try {
56
- const { execFile } = await import('node:child_process');
57
- const { promisify } = await import('node:util');
58
- const run = promisify(execFile);
59
- await run('firecracker', ['--version'], { timeout: 3000 });
60
- return true;
61
- }
62
- catch {
63
- // fall back to Docker-in-VM pattern
64
- try {
65
- const { execFile } = await import('node:child_process');
66
- const { promisify } = await import('node:util');
67
- const run = promisify(execFile);
68
- await run('docker', ['info'], { timeout: 5000 });
69
- return true; // Docker can simulate microVM with --privileged
70
- }
71
- catch {
72
- return false;
73
- }
74
- }
178
+ const p = await this.probe();
179
+ return p.microvmReady;
75
180
  }
76
- async exec(command, args, spec) {
77
- const start = Date.now();
78
- // Simulate microVM execution via Docker with extra isolation flags
79
- const dockerArgs = [
80
- 'run', '--rm',
81
- '--cpus', String(this.config.vcpus),
82
- '--memory', `${this.config.memoryMb}m`,
83
- '--network', this.config.networkEnabled ? 'bridge' : 'none',
84
- '--security-opt', 'no-new-privileges',
85
- '--cap-drop', 'ALL',
86
- '--workdir', spec.workdir,
87
- ];
88
- if (spec.env) {
89
- for (const [k, v] of Object.entries(spec.env)) {
90
- dockerArgs.push('--env', `${k}=${v}`);
91
- }
92
- }
93
- dockerArgs.push(this.config.image, command, ...args);
94
- const { spawn } = await import('node:child_process');
95
- return new Promise((resolve) => {
96
- const child = spawn('docker', dockerArgs, {
97
- windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
98
- timeout: spec.limits.timeoutMs ?? 120000,
99
- });
100
- let stdout = '', stderr = '';
101
- child.stdout?.on('data', d => stdout += d);
102
- child.stderr?.on('data', d => stderr += d);
103
- child.on('close', code => resolve({
104
- exitCode: code ?? 1, stdout, stderr,
105
- durationMs: Date.now() - start, backend: 'docker',
106
- }));
107
- child.on('error', err => resolve({
108
- exitCode: 1, stdout, stderr: stderr + String(err),
109
- durationMs: Date.now() - start, backend: 'docker',
110
- }));
111
- });
181
+ async exec(_command, _args, _spec) {
182
+ return this.refuse('exec');
112
183
  }
113
- async copyIn(localPath, sandboxPath, _spec) {
114
- const { copyFile, mkdir } = await import('node:fs/promises');
115
- const { dirname } = await import('node:path');
116
- await mkdir(dirname(sandboxPath), { recursive: true });
117
- await copyFile(localPath, sandboxPath);
184
+ async copyIn(_localPath, sandboxPath, _spec) {
185
+ // the old implementation copyFile'd straight onto the HOST at
186
+ // sandboxPath under a "strongest tier" name — an unbounded host write.
187
+ // Refusing is the only honest behavior until a real VM file channel exists.
188
+ return this.refuse(`copyIn(${sandboxPath})`);
118
189
  }
119
- async copyOut(sandboxPath, localPath, _spec) {
120
- const { copyFile, mkdir } = await import('node:fs/promises');
121
- const { dirname } = await import('node:path');
122
- await mkdir(dirname(localPath), { recursive: true });
123
- await copyFile(sandboxPath, localPath);
190
+ async copyOut(sandboxPath, _localPath, _spec) {
191
+ return this.refuse(`copyOut(${sandboxPath})`);
124
192
  }
125
- async snapshot(spec) {
126
- const { createHash } = await import('node:crypto');
127
- return `vm-snap-${createHash('sha256').update(spec.workdir + Date.now()).digest('hex').slice(0, 12)}`;
193
+ async snapshot(_spec) {
194
+ return this.refuse('snapshot');
128
195
  }
129
196
  async restore(_snapshotId, _spec) {
130
- // microVM restore = boot from snapshot image
197
+ return this.refuse('restore');
198
+ }
199
+ /** fail closed: never executes, never fakes, names both tiers in the error */
200
+ async refuse(operation) {
201
+ const highest = await detectHighestIsolation();
202
+ if (highest.trust !== 'real-microvm') {
203
+ assertIsolationGate('real-microvm', highest.trust, `${operation} on MicroVMSandboxProvider; ${highest.evidence}`);
204
+ }
205
+ // reachable only once a boot self-test exists; until VM lifecycle
206
+ // management is implemented, even that path must refuse rather than
207
+ // pretend to execute. NEEDS-DATA on real-hypervisor hosts.
208
+ throw new Error(`E_MICROVM_EXEC_UNIMPLEMENTED: hypervisor detected (${highest.hypervisor}) but VM lifecycle management (boot/rootfs/api-socket) is not implemented — refusing to fake execution for ${operation}`);
131
209
  }
132
210
  }
@@ -13,7 +13,10 @@
13
13
  * on availability (Docker if present, Local as fallback), so zero-config
14
14
  * users get the best available isolation automatically.
15
15
  */
16
- export type SandboxBackend = 'docker' | 'local';
16
+ /** 'firecracker' / 'cloud-hypervisor' are DECLARED design backends of
17
+ * MicroVMSandboxProvider — they only appear in a SandboxResult once a real
18
+ * VM path exists (Issue #21: a Docker stand-in must never wear them). */
19
+ export type SandboxBackend = 'docker' | 'local' | 'firecracker' | 'cloud-hypervisor';
17
20
  export interface ProviderSandboxSpec {
18
21
  /** working directory inside the sandbox */
19
22
  workdir: string;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @hmharness/sandbox - Trust Tiers & Capability Contracts (Issue #21, P0)
3
+ *
4
+ * The audit finding: isolation CLAIMS and isolation REALITY had diverged.
5
+ * MicroVMSandboxProvider answered isAvailable()=true whenever Docker was
6
+ * present and then ran plain `docker run` — a container advertised as a VM;
7
+ * its copyIn/copyOut wrote the HOST filesystem directly under a
8
+ * "strongest isolation tier" name. This module is the honest vocabulary that
9
+ * fixes the divergence: every execution tier gets a TrustLevel and a
10
+ * CapabilityContract that states what the boundary REALLY is, which escape
11
+ * vectors stay open (declared, never hidden), and a fail-closed gate that
12
+ * refuses to run a critical workload below the tier it requires.
13
+ *
14
+ * Two orderings live here and must not be confused:
15
+ * - TRUST_RANK orders ISOLATION STRENGTH (worker walls > process, etc.)
16
+ * - the gate orders MACHINE CAPABILITY: a worker tier needs nothing the
17
+ * running Node runtime does not already provide, so it never gates.
18
+ */
19
+ /** The honest ladder. 'real-microvm' says REAL: a booted Firecracker/Cloud
20
+ * Hypervisor VM, never a Docker stand-in (that is 'container'). */
21
+ export type TrustLevel = 'process' | 'worker' | 'container' | 'real-microvm';
22
+ /** Isolation strength, strictly ordered. Pure - testable. */
23
+ export declare const TRUST_RANK: Readonly<Record<TrustLevel, number>>;
24
+ /** What a tier really provides, in broker vocabulary (class names mirror
25
+ * CapabilityBroker's CapabilityClass; kept as plain strings so this module
26
+ * stays dependency-free — broker.ts re-asserts the overlap in its tests). */
27
+ export interface CapabilityContract {
28
+ readonly level: TrustLevel;
29
+ /** one honest sentence on what physically separates the workload from the host */
30
+ readonly boundary: string;
31
+ /** capability classes this tier may be granted ('none' = nothing survives) */
32
+ readonly capabilityClasses: readonly ('filesystem' | 'network' | 'process' | 'secret' | 'device' | 'none')[];
33
+ /** escape vectors that remain OPEN at this tier — declared, never hidden */
34
+ readonly escapeVectors: readonly string[];
35
+ /** do host environment secrets inherit into this tier? */
36
+ readonly secretsInherit: boolean;
37
+ /** the mechanism that actually enforces the boundary at runtime */
38
+ readonly enforcement: string;
39
+ }
40
+ /**
41
+ * The contracts. Each boundary string is a source-level FACT about the
42
+ * current implementation (pinned by tests), not an aspiration.
43
+ */
44
+ export declare const TRUST_TIERS: Readonly<Record<TrustLevel, CapabilityContract>>;
45
+ /** Structured fail-closed error: names the isolation the workload requires
46
+ * and the most the machine can actually provide. Serializable via toJSON
47
+ * so logs, API responses and (future) UI report the same fields. */
48
+ export declare class IsolationGateError extends Error {
49
+ readonly code: "E_ISOLATION_INSUFFICIENT";
50
+ readonly required: TrustLevel;
51
+ readonly available: TrustLevel;
52
+ readonly remediation: string;
53
+ constructor(opts: {
54
+ required: TrustLevel;
55
+ available: TrustLevel;
56
+ context?: string;
57
+ });
58
+ private static remediationFor;
59
+ toJSON(): {
60
+ name: string;
61
+ code: string;
62
+ message: string;
63
+ required: TrustLevel;
64
+ available: TrustLevel;
65
+ remediation: string;
66
+ };
67
+ }
68
+ /** Fail-closed gate. Pure - testable. A required tier ABOVE what is
69
+ * available throws IsolationGateError (never silently downgrades); a tier
70
+ * at or below the available strength passes. The worker tier never gates:
71
+ * its walls are provided by the running Node runtime itself, so any machine
72
+ * that can execute this check can host the worker tier. */
73
+ export declare function assertIsolationGate(required: TrustLevel, available: TrustLevel, context?: string): void;
package/dist/trust.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @hmharness/sandbox - Trust Tiers & Capability Contracts (Issue #21, P0)
3
+ *
4
+ * The audit finding: isolation CLAIMS and isolation REALITY had diverged.
5
+ * MicroVMSandboxProvider answered isAvailable()=true whenever Docker was
6
+ * present and then ran plain `docker run` — a container advertised as a VM;
7
+ * its copyIn/copyOut wrote the HOST filesystem directly under a
8
+ * "strongest isolation tier" name. This module is the honest vocabulary that
9
+ * fixes the divergence: every execution tier gets a TrustLevel and a
10
+ * CapabilityContract that states what the boundary REALLY is, which escape
11
+ * vectors stay open (declared, never hidden), and a fail-closed gate that
12
+ * refuses to run a critical workload below the tier it requires.
13
+ *
14
+ * Two orderings live here and must not be confused:
15
+ * - TRUST_RANK orders ISOLATION STRENGTH (worker walls > process, etc.)
16
+ * - the gate orders MACHINE CAPABILITY: a worker tier needs nothing the
17
+ * running Node runtime does not already provide, so it never gates.
18
+ */
19
+ /** Isolation strength, strictly ordered. Pure - testable. */
20
+ export const TRUST_RANK = {
21
+ process: 1,
22
+ worker: 2,
23
+ container: 3,
24
+ 'real-microvm': 4,
25
+ };
26
+ /**
27
+ * The contracts. Each boundary string is a source-level FACT about the
28
+ * current implementation (pinned by tests), not an aspiration.
29
+ */
30
+ export const TRUST_TIERS = {
31
+ process: {
32
+ level: 'process',
33
+ boundary: 'no physical separation — the workload runs inside the hosting process with full host authority',
34
+ capabilityClasses: ['filesystem', 'network', 'process', 'secret', 'device'],
35
+ // LocalSandboxProvider.exec spreads the ENTIRE host env into the child
36
+ // (provider.ts) — that is this tier's documented, pinned semantics.
37
+ escapeVectors: ['full-host-authority', 'inherits-complete-host-environment'],
38
+ secretsInherit: true,
39
+ enforcement: 'CapabilityBroker decisions only (advisory at this tier — nothing stops a run past a wrong decision); LocalSandboxProvider documents exactly this semantics',
40
+ },
41
+ worker: {
42
+ level: 'worker',
43
+ boundary: 'worker_threads containment: crash isolation, hard timeout termination, heap caps, secret-free env (env: {}), escape globals stripped before eval',
44
+ capabilityClasses: ['filesystem'],
45
+ // Matches @hmharness/cognitive SANDBOX_BYPASS_VECTORS (dynamic-import is
46
+ // the one open vector — any road to import(), direct or via a fresh
47
+ // Function, reaches Node internals; Node offers no per-worker perms).
48
+ escapeVectors: ['dynamic-import'],
49
+ secretsInherit: false,
50
+ enforcement: "cognitive rlm-sandbox per-eval Worker + broker's WORKER_FORBIDDEN rule (network/secret/process/device can never be granted at this tier)",
51
+ },
52
+ container: {
53
+ level: 'container',
54
+ boundary: 'Docker container: kernel namespaces + cgroups, but a SHARED host kernel',
55
+ capabilityClasses: ['filesystem', 'network', 'process'],
56
+ // DockerSandboxProvider mounts the workspace at its own host path
57
+ // (--volume workdir:workdir) — writes inside punch straight through to
58
+ // the host directory. Declared, not hidden.
59
+ escapeVectors: ['shared-kernel-exploits', 'docker-socket-if-mounted', 'same-path-volume-mount-writes-through-to-host'],
60
+ secretsInherit: false,
61
+ enforcement: 'DockerSandboxProvider (docker run, resource limits, --network none unless granted) — secrets only via explicit spec.env, host env never spreads',
62
+ },
63
+ 'real-microvm': {
64
+ level: 'real-microvm',
65
+ boundary: 'hardware-virtualized microVM (Firecracker / Cloud Hypervisor): separate guest kernel, no shared host kernel',
66
+ capabilityClasses: ['filesystem', 'network', 'process', 'secret', 'device'],
67
+ escapeVectors: ['hypervisor-escape-class-bugs'],
68
+ secretsInherit: false,
69
+ enforcement: 'a real hypervisor that PASSED a boot self-test — never faked with Docker (fail-closed gate below refuses the downgrade)',
70
+ },
71
+ };
72
+ /** Structured fail-closed error: names the isolation the workload requires
73
+ * and the most the machine can actually provide. Serializable via toJSON
74
+ * so logs, API responses and (future) UI report the same fields. */
75
+ export class IsolationGateError extends Error {
76
+ code = 'E_ISOLATION_INSUFFICIENT';
77
+ required;
78
+ available;
79
+ remediation;
80
+ constructor(opts) {
81
+ const ctx = opts.context ? ` (${opts.context})` : '';
82
+ super(`isolation gate: this workload requires '${opts.required}' isolation${ctx}, ` +
83
+ `but the highest actually available here is '${opts.available}' — refusing to run at a weaker tier (fail closed). ` +
84
+ `Remediation: ${IsolationGateError.remediationFor(opts.required, opts.available)}`);
85
+ this.name = 'IsolationGateError';
86
+ this.required = opts.required;
87
+ this.available = opts.available;
88
+ this.remediation = IsolationGateError.remediationFor(opts.required, opts.available);
89
+ }
90
+ static remediationFor(required, available) {
91
+ if (required === 'real-microvm') {
92
+ return available === 'container'
93
+ ? 'install Firecracker or Cloud Hypervisor and implement the boot self-test, or re-rate the task below critical — Docker is a container, not a VM, and must not run critical workloads as a stand-in'
94
+ : 'install Docker (container tier) and/or a real hypervisor, or re-rate the task below critical';
95
+ }
96
+ if (required === 'container')
97
+ return 'install/start Docker, or re-rate the task to a tier the machine can honor';
98
+ return 'run on a machine that can provide the required tier, or re-rate the task';
99
+ }
100
+ toJSON() {
101
+ return { name: this.name, code: this.code, message: this.message, required: this.required, available: this.available, remediation: this.remediation };
102
+ }
103
+ }
104
+ /** Fail-closed gate. Pure - testable. A required tier ABOVE what is
105
+ * available throws IsolationGateError (never silently downgrades); a tier
106
+ * at or below the available strength passes. The worker tier never gates:
107
+ * its walls are provided by the running Node runtime itself, so any machine
108
+ * that can execute this check can host the worker tier. */
109
+ export function assertIsolationGate(required, available, context) {
110
+ if (required === 'worker')
111
+ return;
112
+ if (TRUST_RANK[required] > TRUST_RANK[available]) {
113
+ throw new IsolationGateError({ required, available, context });
114
+ }
115
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/sandbox",
3
- "version": "0.23.42",
3
+ "version": "0.23.44",
4
4
  "description": "hmharness sandbox runtime (V2 blueprint M3): isolated workspaces with create/exec/read/write/snapshot/restore/diff/destroy, tiered permissions (READ_ONLY / WORKSPACE_WRITE / FULL_ACCESS), git-backed snapshots. Runtime owns agent turns; the sandbox owns workspace/process state (ADR-0001).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",