Skip to content

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.

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.

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.

LayerPurposeExample
InstructionsGuide model behavior”Run focused tests before finishing”
Tool permissionsControl which tools may be requestedDeny deployment tool
SandboxRestrict process filesystem and network reachWrite only inside workspace
Identity and authorizationLimit what an allowed tool can doRead-only database role
ApprovalRequire human confirmation for a commitmentApprove production release
Audit and monitoringMake actions inspectableRecord tool, arguments, actor, result

Removing one layer increases reliance on the others.

Design for more than deliberate misuse by the user.

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

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.

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.

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:

Terminal window
cat .env

A 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.

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.

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.

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:

TaskAppropriate identity
Review a pull requestRead repository and CI results
Create a patchWrite one branch, no merge permission
Inspect production logsRead selected log stream, no infrastructure changes
Query analyticsRead approved views, no raw customer table
Deploy previewCreate preview only, no production target

Do not rely on the model to voluntarily avoid capabilities it should never have received.

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.

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.

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

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.

Use different boundaries for:

EnvironmentTypical policy
Local interactive developmentProject write access, prompts for unusual commands
CI evaluationEphemeral container, no secrets, limited network
Pull-request automationOne repository/branch, bot identity, no merge
Production investigationRead-only logs and metrics, no shell on hosts
Production changeSeparate 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.

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.

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.

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.

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.

FailureWhy it is unsafeBetter control
”Never read secrets” only in promptPrompt is not enforcementDeny filesystem and secret access
Full host shell for convenienceOne command can affect everythingIsolated workspace and OS sandbox
Sandbox without network restrictionsRead data can be exfiltratedRestrict egress
Network sandbox without filesystem restrictionsMalicious code can alter host filesRestrict both layers
Broad cloud credential in environmentAllowed process has excessive authorityShort-lived scoped identity
One generic admin toolModel constructs high-risk operationsNarrow typed tools
Approval for every commandUsers stop reviewing carefullyAutonomous low-risk zone
Security control fails openOutage expands capabilityStop the run
Shared writable workspaceParallel agents interferePer-agent isolation
Tests run on hostRepository code gains host accessRun in container or VM

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.
  • 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.

Diagram viewer