Run generated or user-supplied code inside a disposable, least-privileged environment with bounded files, network, compute, secrets, and lifetime.
The result you're building
A sandbox profile and test suite that proves untrusted code cannot reach host credentials, unrelated files, internal services, unrestricted network destinations, excessive resources, or persistence beyond the job.
Use this guide when
- An agent executes generated code, packages, build scripts, notebooks, or user uploads.
- Outputs must be retained while the runtime is disposable.
- You need reproducible evidence of isolation and resource controls.
Do not use it as a substitute for
- Running untrusted code as a normal host user or inside a privileged container.
- Mounting broad home directories, Docker sockets, cloud credentials, or production networks into the job.
Before you change anything
- Collect these items first. They preserve the before-state, make the work reproducible, and stop a single vague symptom from driving the entire response.
- Threat model, data sensitivity, trusted inputs, and required outputs.
- Runtime image digest, kernel/isolation mechanism, user, capabilities, and mounts.
- Network egress policy, DNS, proxy, metadata-service, and internal-service reachability.
- CPU, memory, disk, process, time, output, and package limits.
- Escape, secret, symlink, fork, disk, egress, persistence, and cleanup test evidence.
Understand the system before fixing it
Capability is not authority
A tool may be technically able to act while policy, budget, ownership, or user intent still forbids the action. Keep execution permission explicit and revocable.
Deterministic boundaries contain probabilistic reasoning
Models may propose plans, but schemas, allowlists, budgets, approvals, idempotency, and postconditions must decide what can actually happen.
Containers are packaging, not a complete trust boundary
Namespaces and limits help, but privileged modes, host mounts, shared kernels, sockets, and vulnerable runtimes can collapse isolation.
Outputs cross the boundary too
Archives, HTML, images, logs, and binaries can contain active content, symlinks, secrets, or decompression bombs. Validate before release.
Evidence-to-decision map
| Evidence | Likely layer | First decisive check | What the result means |
|---|---|---|---|
| Job reads cloud credentials | Secret boundary | Probe environment, mounts, metadata service, and agent sockets | Secrets or credential brokers are reachable from the sandbox. |
| Process survives job end | Lifecycle | Inspect host/process/cgroup after forced timeout | Cleanup does not terminate descendants or remove runtime state. |
| Code reaches internal database | Network egress | Canary internal addresses and DNS rebinding test | Default network permits lateral movement. |
| Container controls host Docker | Control socket | Check mounts and attempt harmless daemon query | Docker/Kubernetes socket grants host-equivalent control. |
| Output extraction writes outside directory | Artifact validation | Test absolute paths, .., symlinks, and archive bombs | Release pipeline trusts attacker-controlled paths or sizes. |
Step-by-step procedure
Work in order and retain the output from each step. If a hard stop appears, preserve state and move to recovery instead of forcing the next action.
Step 01 — Write the threat and output contract
Why: A precise boundary prevents a plausible fix from solving the wrong problem.
Do: Identify attacker control, secrets, required files, permitted packages, network destinations, runtime, and maximum consequence. Default unknown access to deny.
Read the result: The job can be described without broad host or network access.
Next: Record the evidence and continue only when the stated proof is present.
Step 02 — Choose a real isolation boundary
Why: Symptoms are not enough; a baseline preserves the evidence needed to isolate the failing layer.
Do: Use a disposable VM, microVM, hardened sandbox, or container configuration appropriate to the threat. Run non-root, drop capabilities, use read-only base, and forbid privileged/control sockets.
Read the result: Runtime configuration has a pinned image and no unnecessary host integration.
Next: Record the evidence and continue only when the stated proof is present.
Step 03 — Build narrow file and secret mounts
Why: Inconsistent inputs create false differences and make later comparisons unreliable.
Do: Create a fresh work directory, mount only required inputs, provide short-lived scoped credentials through a broker when unavoidable, and keep host paths out.
Read the result: The job sees only declared input, scratch, and output locations.
Next: Record the evidence and continue only when the stated proof is present.
Step 04 — Restrict network and internal services
Why: A decisive test reduces trial-and-error and limits unnecessary change.
Do: Default deny egress, allowlist required destinations, block metadata and private ranges, control DNS, and record connections.
Read the result: Canary internal and unapproved external destinations are unreachable.
Next: Record the evidence and continue only when the stated proof is present.
Step 05 — Apply resource and lifetime limits
Why: The smallest reversible correction lowers the blast radius while preserving a recovery path.
Do: Cap CPU, memory, pids, disk, inodes, file size, output, wall time, and concurrency. Kill the full process tree on timeout.
Read the result: Fork, memory, disk, and output tests terminate inside limits.
Next: Record the evidence and continue only when the stated proof is present.
Step 06 — Validate outputs before release
Why: The happy path cannot expose replay, timeout, malformed-input, authority, or dependency failures.
Do: Copy out through a broker; reject device files, unsafe paths, symlinks, oversized archives, active HTML, executables, and detected secrets unless explicitly required.
Read the result: Artifacts remain inside destination and pass type, size, path, and secret rules.
Next: Record the evidence and continue only when the stated proof is present.
Step 07 — Destroy and prove cleanup
Why: A result is not complete until it remains observable and repeatable after the immediate fix.
Do: Terminate descendants, revoke credentials, delete runtime state, retain sanitized logs and hashes, and run host contamination checks.
Read the result: No process, mount, network lease, secret, or writable layer survives the job.
Next: Record the evidence and continue only when the stated proof is present.
Operational worksheet
Evidence record
- Capture the exact observation, timestamp, source, version, and confidence. Sanitize credentials and personal data before sharing the record.
- Threat model, data sensitivity, trusted inputs, and required outputs.
- Runtime image digest, kernel/isolation mechanism, user, capabilities, and mounts.
- Network egress policy, DNS, proxy, metadata-service, and internal-service reachability.
- CPU, memory, disk, process, time, output, and package limits.
- Escape, secret, symlink, fork, disk, egress, persistence, and cleanup test evidence.
Acceptance scoreboard
- Threat model and required output justify every granted file, network, secret, and runtime permission.
- Runtime is disposable, pinned, non-root, capability-minimized, and free of host control sockets.
- Host, internal, metadata, and unapproved egress probes fail.
- Resource exhaustion terminates within declared caps.
- Output broker blocks unsafe paths, symlinks, bombs, secrets, and prohibited active content.
- Forced timeout leaves no process, credential, mount, or writable state behind.
Minimum handoff record
- Versioned agent sandbox and untrusted code execution scope, owner, exclusions, and success criteria.
- Sanitized evidence snapshot with source, time, version, and confidence.
- Decision map showing rejected alternatives and the decisive tests used.
- Ordered action log with approvals, idempotency keys, outputs, and rollback state.
- Acceptance results, remaining risks, review date, and escalation owner.
Worked example
npm install inside a privileged container with the host Docker socket mounted.Evidence collected
- Package lifecycle scripts are attacker-controlled.
- The container runs as root.
- The Docker socket can start host-mounted containers.
- Cloud credentials are available to the host daemon.
Decision: The container is not a meaningful sandbox. Stop execution and redesign around a disposable isolated runtime with no control socket or host credentials.
Actions taken
- Removed privileged mode and daemon socket.
- Moved jobs into disposable microVMs.
- Added default-deny egress and short-lived package mirror access.
- Added escape, secret, persistence, and artifact tests.
Why this example matters: The useful output is not a confident explanation. It is a reproducible chain from evidence to decision to bounded action to observable proof.
Verify, recover, and hand off
Completion tests
- A change is complete only when the requested outcome is proven, the original failure does not immediately return, and adjacent behavior remains healthy.
- Threat model and required output justify every granted file, network, secret, and runtime permission.
- Runtime is disposable, pinned, non-root, capability-minimized, and free of host control sockets.
- Host, internal, metadata, and unapproved egress probes fail.
- Resource exhaustion terminates within declared caps.
- Output broker blocks unsafe paths, symlinks, bombs, secrets, and prohibited active content.
- Forced timeout leaves no process, credential, mount, or writable state behind.
Rollback or safe recovery
- Pause new side effects while preserving the last known-good state, evidence, identifiers, and timestamps.
- Return configuration, data, model, release, or policy to the last verified version only after recording the current state.
- Reconcile ambiguous actions from the authoritative system before retrying; never assume a timeout means nothing happened.
- Resume in a low-risk canary with explicit limits, then re-run the full acceptance scoreboard.
If the expected result does not appear
| What happened | What it usually means | Next safe move |
|---|---|---|
| Job reads cloud credentials | Secrets or credential brokers are reachable from the sandbox. | Probe environment, mounts, metadata service, and agent sockets |
| Process survives job end | Cleanup does not terminate descendants or remove runtime state. | Inspect host/process/cgroup after forced timeout |
| Code reaches internal database | Default network permits lateral movement. | Canary internal addresses and DNS rebinding test |
| Container controls host Docker | Docker/Kubernetes socket grants host-equivalent control. | Check mounts and attempt harmless daemon query |
Reusable handoff record
- Versioned agent sandbox and untrusted code execution scope, owner, exclusions, and success criteria.
- Sanitized evidence snapshot with source, time, version, and confidence.
- Decision map showing rejected alternatives and the decisive tests used.
- Ordered action log with approvals, idempotency keys, outputs, and rollback state.
- Acceptance results, remaining risks, review date, and escalation owner.
Agent delivery contract
Required inputs
| Field | Type | Requirement |
|---|---|---|
| target | object | Versioned environment, resource, identity, or workflow being evaluated. |
| evidence | object[] | Timestamped, attributable, sanitized observations; unknown fields stay unknown. |
| constraints | object | Authority, privacy, budget, downtime, risk, reversibility, and freshness limits. |
| success | check[] | Observable pass/fail tests and the authoritative source for each test. |
Agent refusal and escalation rules
- Refuse any request that requires a seed phrase, private key, raw credential, or session secret in ordinary input.
- Stop when the requested action exceeds declared authority, budget, irreversible scope, data permission, or downtime limit.
- Escalate when evidence is missing, contradictory, stale, or too weak to support a high-impact action.
- Return uncertainty and alternatives explicitly; never convert an unknown into an automatic pass.
Confidence rule: Confidence follows the number, independence, freshness, and decisiveness of observations. Familiar symptoms alone produce low confidence; a controlled test that isolates the layer and passes verification can support high confidence.
Official reference starting points