Sandbox for AI-Generated Code Execution: How to Run It Safely

Sandbox for AI-Generated Code Execution: How to Run It Safely

How to isolate AI-generated code with containers, microVMs or managed services, and limit network, time and files before giving an agent execution rights.

••

Want to apply this in your company?

Book a call with Juan →

Sandbox for AI-Generated Code Execution: How to Run It Safely

To run AI-generated code safely, use a sandbox for AI-generated code execution: a disposable environment with no network by default, no secrets, and hard limits on time, memory and files. Whether you choose a container, a microVM or a managed service depends on how far you trust the source of the code and what of value sits nearby. Isolation reduces the damage, but it is the limits that keep the problem from starting.

Key takeaways

  • Code written by a model should be treated as untrusted code, because the model can be steered by malicious text or simply make a mistake.
  • A plain container is weak isolation for untrusted code, since it shares the host kernel. Hardened runtimes, microVMs and managed services give a stronger boundary.
  • Network, execution time and file system each need explicit limits, and the default should be deny.
  • Secrets never go inside the sandbox. If the code needs a credential, it should be narrowly scoped, short-lived and delivered through a controlled intermediary.
  • Logging what ran, with which input and which output, matters as much as isolating it.

Why does AI-generated code need a sandbox?

An agent that writes and runs code gains a lot of capability: analyzing spreadsheets, converting files, calculating, generating reports. At the same time, it starts running instructions that nobody has reviewed line by line. The code may contain a simple mistake, such as deleting the wrong folder, or it may be the result of a prompt injection, where text inside an email, PDF or web page convinces the model to do something the system owner never asked for.

The OWASP list of risks for applications built on language models treats this as its own category, and the same organization's prompt injection prevention guidance shows that filtering text is not enough. The realistic defense is to assume the model can be fooled and to limit what the code can do when that happens.

So the useful question is not whether the code is safe. It is this: if this code were hostile, what could it reach? If the answer includes the production database, API keys or the company's internal network, the boundary is missing.

What are the isolation options?

There are four common families, each with different trade-offs between strength of isolation, operational effort and ease of use.

  • Plain container: processes isolated by host kernel features such as namespaces and cgroups. It is fast and familiar to most teams, but every container shares the same kernel. A kernel flaw or a loose configuration can allow an escape to the host.
  • Container with a hardened runtime: tools such as gVisor intercept the code's system calls and handle them in an intermediate layer, reducing the surface exposed to the real kernel. It still looks like a container to the people operating it, with a stronger boundary.
  • MicroVM: each execution gets a minimal virtual machine with its own kernel, backed by hardware virtualization. Firecracker is a well-known example of this approach. The boundary is stronger, in exchange for more infrastructure work.
  • Managed service: a provider offers execution environments built for agents, usually through an API, and handles isolation, cleanup and scaling. You gain speed and hand off part of the operations, but you now depend on the provider's guarantees and on where it processes data.

One point that often goes unnoticed: running the code directly on the same server as your application, even as a different process or user, is not a sandbox. It is just one more process with access to everything the server can see.

How to choose: a decision guide

Use these questions, in this order, to decide the level of isolation.

  • Does the code come only from your own team, reviewed, and run on low-risk internal data? A well-configured container, unprivileged and with no network, may be enough.
  • Is the code written by a model, but the inputs are controlled by you (for example, spreadsheets you generate yourself)? Prefer a container with a hardened runtime, or a microVM.
  • Does the model read third-party content, such as customer emails, WhatsApp attachments, web pages or uploaded documents? Treat it as hostile: microVM or managed service, network denied and no secrets inside.
  • Is sensitive personal data involved? Check where the service executes and stores data. If the provider processes data outside the country, review what the LGPD requires in international data transfer when using AI providers.
  • Does your team have the capacity to run virtualization infrastructure with updates and monitoring? If not, a managed service is usually safer than a poorly maintained microVM.

The rule of thumb: the more the code depends on inputs you do not control, the stronger the boundary should be.

How do you limit network, time and files?

Isolation defines where the code runs. Limits define what it can do once it is there. The three that matter most are network, time and files.

Network. The default should be no outbound access. Most analysis and conversion tasks do not need the internet. When the code has to install packages or call an API, use an allowlist of destinations enforced outside the sandbox (in the firewall or an egress proxy), never an instruction in the prompt. Also block internal addresses and cloud metadata endpoints, which are classic targets for anyone trying to break out of an isolated environment. If the code needs outside data, let a controlled tool fetch it and hand over the result as a file.

Time and resources. Set a maximum run time per execution, plus ceilings for memory, CPU and number of processes. This protects against infinite loops, memory bombs and unwanted crypto mining. The same reasoning applies to the agent as a whole, which needs step and spending limits, as we explain in AI agent infinite loops and step, time and budget caps. When a limit is hit, the execution should be terminated and logged, not silently retried.

Files. Mount only the files the task needs, read-only where possible, plus a separate, small output folder. Use a disposable file system: when the run ends, everything disappears, and only what is in the output folder is collected and checked. Set a maximum size for input and output. Do not mount personal folders, whole repositories or directories that hold configuration files.

Secrets. No environment variables with keys, no credential files. If a step needs access to a system, perform it outside the sandbox through a tool with minimal permissions, and require human approval for irreversible actions. The input, output and action controls described in guardrails for AI agents complement this design.

Step by step: building your first sandbox

This outline works for a first pilot, whatever technology you pick.

  • Describe the task in one sentence and list the expected inputs and outputs. If it does not fit in one sentence, split it.
  • Classify where the inputs come from: internal and controlled, or external and untrusted.
  • Choose the isolation level using the decision guide above.
  • Set network denied, a maximum run time, memory and CPU ceilings, and a maximum file size.
  • Mount only the necessary inputs, read-only, and a single output folder.
  • Make sure no secret is present in the environment and that the environment is discarded after every run.
  • Log the code that ran, the input, the output, the time spent and the reason for any failure.
  • Validate the output before using it: expected format, size, file types, and human review when there is external impact.
  • Test on purpose with bad code: attempts to reach the network, read files outside the folder, consume memory without stopping. Confirm that each attempt fails and is logged.

The last item is the one most often forgotten and the one that builds the most confidence. A sandbox that has never been tested against hostile behavior is only an assumption.

Illustrative scenario: an agent that analyzes spreadsheets sent by customers

Imagine a services company that receives spreadsheets from customers by email and uses an agent to produce a summary. This is an illustrative scenario, unrelated to any real case.

The agent writes a script to read the spreadsheet and calculate totals. Without a sandbox, the script would run on the same server that holds the credentials for the company's management system. A cell containing malicious text could push the model to add a call to the script that sends files out.

With a sandbox, the design changes: the spreadsheet is copied into a disposable environment in a microVM or managed service, with network denied and no sensitive environment variables. The script has a short maximum run time and writes only to an output folder. The result comes back as a small file in a known format, which goes through validation. If the script tries to open a connection, the attempt fails and shows up in the log. The worst case stops being a data leak and becomes a failed run.

How to apply the method: map, limit, pilot, hand over

In consulting practice, the work follows four stages. Map: understand which tasks truly require code execution and which can be solved by a deterministic workflow, which is cheaper and more predictable. Limit: define data, tools, network, time and permissions before switching on any execution. Pilot: run a real workflow with logs and an agreed success metric, including abuse tests. Hand over: give the team the documentation, the logs and the criteria to expand, adjust or stop.

Teams that work with AI coding tools can see the same principle in Claude Code security: permissions, sandbox and secrets for teams. For broader agent environments, the idea of evidence before exposure appears in the OpenClaw Gateway security checklist. For a general view of how agents should be built, Anthropic's material on building effective agents is worth reading, since it recommends starting simple and testing in a controlled environment.

Frequently asked questions

Is a Docker container enough as a sandbox for AI code? It depends on where the code and the inputs come from. For reviewed code and internal data, an unprivileged container with no network and with resource limits can be acceptable. For model-written code that reads third-party content, prefer a hardened runtime, a microVM or a managed service, because a plain container shares the host kernel.

Does a sandbox eliminate the risk of prompt injection? No. Prompt injection affects what the model decides to do, and the sandbox limits the damage of what it executes. That is why the full setup also needs input and output validation, minimal permissions on tools, and human approval for actions with external effects.

Can I use a managed service with customer data? You can, as long as you know where the service executes and stores data, how long it keeps it and who has access. If personal data is involved, define the legal basis, minimize what enters the environment and assess processing outside Brazil. The ANPD website is the official starting point for following guidance.

What should I log for each execution? Keep the code that ran, the inputs used, the output produced, the time and resources consumed, and any error or block. Avoid writing unnecessary personal data to the logs and define how long they are kept. This record lets you investigate incidents and decide, with evidence, whether the pilot should grow.

Sources

AI sandboxAI agentscode executionmicroVMAI security