Sandboxing and Permissions for Coding Agents
A coding agent can read files, run commands, install packages, call APIs, and change a repository.
Those capabilities make it useful. They also mean a mistaken or manipulated tool call can:
- delete data
- expose credentials
- modify files outside the project
- contact an untrusted server
- deploy an unreviewed change
- trigger a paid or externally visible action
Prompt instructions are not enough to prevent these outcomes.
Security comes from limiting what the agent can reach and what its tools are allowed to do, even when the model makes the wrong decision.
Guidance And Enforcement Are Different
Section titled “Guidance And Enforcement Are Different”This is guidance:
Do not read secret files.Do not deploy without approval.Do not run destructive commands.It can improve the model’s behavior, but the model may:
- misunderstand the instruction
- lose it during context compaction
- follow conflicting untrusted content
- choose a command whose side effects it does not recognize
This is enforcement:
- secret files are outside the readable filesystem boundary
- deployment credentials are unavailable to the agent
- production deployment requires a separate authorization service
- destructive commands are denied by policy
- network access is restricted to approved destinations
A secure design assumes prompts can fail.
The Security Layers
Section titled “The Security Layers”flowchart TD
I["Instructions<br/>desired behavior"] --> M["Model requests a tool action"]
M --> P["Permission and policy layer"]
P -->|"Denied"| D["Block, explain, or request approval"]
P -->|"Allowed"| S["Sandbox or isolated runtime"]
S --> T["Tool executes with scoped identity"]
T --> R["Resource policy and authorization"]
R -->|"Allowed"| O["Operation and audit record"]
R -->|"Denied"| E["Safe error returned to agent"]
Each layer has a different job.
| Layer | Purpose | Example |
|---|---|---|
| Instructions | Guide model behavior | ”Run focused tests before finishing” |
| Tool permissions | Control which tools may be requested | Deny deployment tool |
| Sandbox | Restrict process filesystem and network reach | Write only inside workspace |
| Identity and authorization | Limit what an allowed tool can do | Read-only database role |
| Approval | Require human confirmation for a commitment | Approve production release |
| Audit and monitoring | Make actions inspectable | Record tool, arguments, actor, result |
Removing one layer increases reliance on the others.
Threat Model
Section titled “Threat Model”Design for more than deliberate misuse by the user.
Model error
Section titled “Model error”The agent may:
- misunderstand a path
- run a broad command
- retry an unsafe operation
- edit generated output instead of its source
- mistake staging for production
Prompt injection
Section titled “Prompt injection”Untrusted content can contain instructions intended for the agent:
- repository files
- issue descriptions
- web pages
- package metadata
- logs
- emails
- tool output
An instruction inside retrieved data must not gain the authority of the user or system prompt.
Malicious or compromised code
Section titled “Malicious or compromised code”Package installation and test execution can run:
- install scripts
- build hooks
- test fixtures
- repository scripts
- downloaded binaries
Even if the model behaves correctly, the code it executes may be hostile.
Excessive agency
Section titled “Excessive agency”The tool may have more capability than the task requires:
- database administrator instead of read-only user
- cloud owner instead of one project role
- full home-directory access instead of one repository
- unrestricted internet access instead of a small allowlist
The safest response is to reduce the capability, not add another warning sentence.
Permissions And Sandboxing Are Complementary
Section titled “Permissions And Sandboxing Are Complementary”Permissions answer:
May the agent request this tool or action?
Sandboxing answers:
What can the resulting process actually access?
Consider a rule that denies a built-in file-reading tool access to .env.
If Bash remains unrestricted, the agent may still run:
cat .envA filesystem sandbox can block the Bash process too.
The reverse is also true. A sandbox may restrict Bash but not a separate file-edit, browser, MCP, or computer-use tool. Those tools need their own permission and authorization controls.
Bound The Filesystem
Section titled “Bound The Filesystem”Start with the smallest required filesystem view.
Typical policy:
- read and write the current workspace
- read language runtimes and dependencies where needed
- deny credential directories
- deny shell configuration
- deny unrelated repositories and personal files
- use a separate temporary directory
- mount the root filesystem read-only in unattended containers
For parallel agents, give each worker:
- a separate worktree, checkout, or workspace
- an explicit writable path
- no write access to other workers’ directories
- no direct access to the integration branch
Filesystem isolation protects against accidental edits and reduces the impact of malicious scripts.
Bound The Network
Section titled “Bound The Network”Filesystem-only isolation is incomplete.
An agent that can read files and reach any network destination may exfiltrate data. An agent that cannot read host secrets but can download arbitrary code may introduce a supply-chain risk.
Network policy should define:
- whether outbound access is needed
- approved domains or services
- DNS and proxy behavior
- whether local network and metadata endpoints are blocked
- whether package registries are permitted
- whether TLS traffic is inspected by organizational infrastructure
- whether inbound ports are allowed
Avoid broad entries such as “allow all GitHub” when a narrower repository or proxy-mediated workflow is possible. Domain allowlists reduce risk but do not prove that every path or account on the domain is trusted.
Keep Credentials Outside The Agent Boundary
Section titled “Keep Credentials Outside The Agent Boundary”Do not place long-lived credentials in:
- prompts
- project instructions
- skills
- repository files
- model-readable environment dumps
- tool results
- agent memory
Prefer:
- short-lived credentials
- workload identity
- narrowly scoped service accounts
- server-side credential injection inside trusted tools
- secret managers
- separate credentials per environment
- rapid revocation and rotation
The agent can request:
deploy_preview(commit_sha)The trusted deployment service can authenticate, authorize, and execute without revealing the credential to the model.
Scope Identity To The Task
Section titled “Scope Identity To The Task”An isolated process is still dangerous if its identity has broad authority.
Use least privilege for:
- repository access
- cloud roles
- databases
- issue trackers
- artifact registries
- deployment environments
- messaging and email
- MCP servers
Examples:
| Task | Appropriate identity |
|---|---|
| Review a pull request | Read repository and CI results |
| Create a patch | Write one branch, no merge permission |
| Inspect production logs | Read selected log stream, no infrastructure changes |
| Query analytics | Read approved views, no raw customer table |
| Deploy preview | Create preview only, no production target |
Do not rely on the model to voluntarily avoid capabilities it should never have received.
Make Sensitive Tools Narrow
Section titled “Make Sensitive Tools Narrow”Broad:
run_cloud_command(command)Narrow:
get_service_status(service_id)create_preview_deployment(commit_sha)request_production_approval(release_id)Narrow tools can enforce:
- typed arguments
- allowed resources
- authorization
- rate and spend limits
- idempotency
- approval state
- audit logging
- bounded output
The model retains semantic choice while the tool owns security-critical mechanics.
Human Approval Is A Commitment Boundary
Section titled “Human Approval Is A Commitment Boundary”Ask for approval before:
- deleting or overwriting important data
- sending external communications
- purchasing or refunding
- publishing content
- changing production infrastructure
- exposing private data
- merging or deploying code
- widening permissions
An approval should show:
- the exact action
- target resource and environment
- relevant diff or preview
- expected effect
- important risk
- whether it can be reversed
Weak:
Claude wants to run a command. Allow?Better:
Deploy commit 8a71c2f to production service billing-api.This replaces the currently running image and may restart 4 instances.Rollback image: billing-api:2026-07-23. Approve?Approval cannot repair an unclear interface. If users approve dozens of vague prompts, approval fatigue turns the dialog into a weak control.
Create A Safe Autonomy Zone
Section titled “Create A Safe Autonomy Zone”The goal is not to ask for every harmless command. It is to define a boundary inside which the agent can work freely.
flowchart LR
A["Autonomous zone"] --> B["Read project files"]
A --> C["Edit isolated branch"]
A --> D["Run local tests"]
A --> E["Use approved package cache"]
F["Approval boundary"] --> G["Network expansion"]
F --> H["Secret access"]
F --> I["External communication"]
F --> J["Merge or production deploy"]
This improves both safety and usability:
- routine operations do not interrupt the user
- unusual requests remain visible
- the agent can iterate quickly inside the workspace
- permissions match the cost of being wrong
Fail Closed
Section titled “Fail Closed”An unattended run should stop when a required security control is unavailable.
Fail-closed examples:
- sandbox cannot initialize
- identity cannot be verified
- policy service is unreachable
- approval record is missing or expired
- target environment cannot be confirmed
- requested network destination is not allowlisted
Failing open turns an infrastructure problem into expanded authority.
Current Claude Code sandboxing has a failIfUnavailable setting for managed environments that need startup to fail when the sandbox cannot run. It also supports disabling unsandboxed fallback. Other agent runtimes need equivalent controls at the container, VM, policy, or orchestration layer.
Separate Environments By Risk
Section titled “Separate Environments By Risk”Use different boundaries for:
| Environment | Typical policy |
|---|---|
| Local interactive development | Project write access, prompts for unusual commands |
| CI evaluation | Ephemeral container, no secrets, limited network |
| Pull-request automation | One repository/branch, bot identity, no merge |
| Production investigation | Read-only logs and metrics, no shell on hosts |
| Production change | Separate approved workflow with narrow deployment identity |
Do not reuse a powerful local developer identity for unattended automation.
Treat Internet And Repository Content As Untrusted
Section titled “Treat Internet And Repository Content As Untrusted”When the agent reads a web page or repository file, separate data from authority.
Practical controls:
- label retrieved content as untrusted
- do not let retrieved instructions override system policy
- use separate contexts for risky browsing where supported
- restrict web access to needed sources
- scan and review downloaded code before execution
- run dependencies and tests inside isolation
- prevent network access while processing sensitive files
- require approval before crossing from research to action
Prompt injection cannot be solved only by detecting suspicious sentences. Assume some malicious instructions will reach the model and keep the blast radius limited.
Side Effects Need Application Semantics
Section titled “Side Effects Need Application Semantics”Sandboxing does not prevent every logical error.
An agent can make an allowed API call twice or send the correct request to the wrong customer.
Side-effecting tools still need:
- authorization
- validation
- idempotency keys
- transaction boundaries
- concurrency control
- rate limits
- preview or dry-run modes
- compensation or rollback where possible
- audit records
Infrastructure isolation limits technical reach. Business logic limits valid actions.
Current Claude Code Example
Section titled “Current Claude Code Example”As of July 2026, official Claude Code documentation describes two complementary layers:
- permissions apply to tools such as Bash, Read, Edit, WebFetch, and MCP
- the Bash sandbox applies OS-level filesystem and network restrictions to Bash and its child processes
The current sandbox uses:
- Seatbelt on macOS
- bubblewrap on Linux and WSL2
- a proxy for network restrictions
Important limitations:
- the Bash sandbox does not automatically isolate built-in file tools
- computer-use actions operate on the actual desktop and require separate controls
- broad filesystem, network, or Unix-socket exceptions can weaken isolation
- an unsandboxed fallback must be disabled when the environment must fail closed
These are product details, not universal agent guarantees. Verify the boundaries of the runtime you actually deploy.
Test The Security Boundary
Section titled “Test The Security Boundary”Security configuration needs tests.
Test that the agent or its subprocess cannot:
- read denied secret files
- write outside the workspace
- access cloud metadata endpoints
- contact an unapproved domain
- use blocked Unix sockets
- run as root
- access another worker’s files
- deploy with a read-only identity
- reuse an expired approval
- execute the same side effect twice
Also test normal tasks. A sandbox that blocks every build command may cause users to bypass it entirely.
Logging And Incident Response
Section titled “Logging And Incident Response”Record:
- task and user identity
- model and harness version
- tool name and arguments, with secret redaction
- permission decision
- approval actor and timestamp
- sandbox violations
- external resource affected
- result and error
- changed files and commit
Logs should support:
- reconstructing an incident
- identifying exposed credentials
- revoking affected identities
- finding similar runs
- determining whether a side effect completed
Do not log raw secrets or unnecessary model context.
Common Failure Modes
Section titled “Common Failure Modes”| Failure | Why it is unsafe | Better control |
|---|---|---|
| ”Never read secrets” only in prompt | Prompt is not enforcement | Deny filesystem and secret access |
| Full host shell for convenience | One command can affect everything | Isolated workspace and OS sandbox |
| Sandbox without network restrictions | Read data can be exfiltrated | Restrict egress |
| Network sandbox without filesystem restrictions | Malicious code can alter host files | Restrict both layers |
| Broad cloud credential in environment | Allowed process has excessive authority | Short-lived scoped identity |
| One generic admin tool | Model constructs high-risk operations | Narrow typed tools |
| Approval for every command | Users stop reviewing carefully | Autonomous low-risk zone |
| Security control fails open | Outage expands capability | Stop the run |
| Shared writable workspace | Parallel agents interfere | Per-agent isolation |
| Tests run on host | Repository code gains host access | Run in container or VM |
Deployment Checklist
Section titled “Deployment Checklist”Identity and access:
- The agent has a dedicated identity.
- Credentials are short-lived and narrowly scoped.
- Production authority is separate from development authority.
- Secrets remain outside model-readable context.
Isolation:
- Writable filesystem paths are explicit.
- Sensitive paths are denied at the process level.
- Network egress is restricted.
- Processes run as non-root.
- Parallel workers have isolated workspaces.
- Sandbox startup failure stops unattended runs.
Tools:
- Sensitive tools use typed, bounded operations.
- Authorization is checked inside trusted infrastructure.
- Side effects are idempotent where possible.
- Outputs are bounded and secrets are redacted.
Approvals and operations:
- Approval prompts describe the exact commitment.
- Expired or reused approvals are rejected.
- Destructive operations have rollback or recovery plans.
- Tool calls, permission decisions, and affected resources are logged.
- Boundary tests run in CI or deployment validation.
Key Takeaways
Section titled “Key Takeaways”- Prompt instructions guide behavior; they do not enforce security.
- Permissions control requested tools, while sandboxes restrict what processes can actually reach.
- Filesystem and network isolation must be designed together.
- Keep credentials outside the agent boundary and use narrowly scoped identities.
- Put sensitive side effects behind typed tools with authorization and idempotency.
- Define a low-risk autonomy zone and reserve approvals for real commitments.
- Fail closed when isolation, identity, policy, or approval checks are unavailable.
- Treat repository, web, and tool content as untrusted.
- Test the security boundary as rigorously as application behavior.