AWS  

Sandboxing AI-Generated Code with AWS Lambda MicroVMs

Introduction

AI coding agents can now generate significantly more than a code snippet.

An agent can create files, install packages, execute shell commands, run tests, compile applications, inspect logs, and modify an entire project. That makes AI agents more useful, but it also creates a security problem.

The code generated by an AI model should not automatically receive the same environment, credentials, filesystem, or network access as the application that requested it.

A generated program can be incorrect by accident. It can contain a malicious dependency. It can be manipulated through prompt injection. It can execute destructive commands or attempt to access resources that were never intended to be available.

This creates a fundamental architectural requirement:

AI Agent
   ↓
Generated Code
   ↓
Isolated Execution Environment
   ↓
Result

AWS Lambda MicroVMs introduce a serverless execution model specifically designed for isolated, stateful workloads such as AI-generated code, coding assistants, vulnerability scanning, and interactive development environments. Lambda MicroVMs use Firecracker virtualization and provide a separate kernel, memory space, and disk state for each MicroVM.

The important engineering question is not simply whether an AI-generated program can execute.

The question is whether it can execute without becoming a security boundary failure for the rest of the system.

Why AI-Generated Code Needs Isolation

Consider an AI agent that receives this request:

Create a .NET application that reads uploaded CSV files,
calculates statistics, and produces a report.

The agent may generate:

Program
 ├── Source files
 ├── NuGet packages
 ├── Build commands
 ├── Test commands
 └── Runtime process

If this code executes directly inside the application's main environment, the generated program potentially shares resources with trusted application code.

That is dangerous.

A safer architecture is:

                 ┌──────────────────┐
                 │ AI Agent         │
                 └────────┬─────────┘
                          │
                    Generated Code
                          │
                          ▼
                 ┌──────────────────┐
                 │ Sandbox          │
                 │                  │
                 │ .NET Runtime     │
                 │ Filesystem       │
                 │ Processes        │
                 │ Network Policy   │
                 └────────┬─────────┘
                          │
                       Result

The sandbox becomes the execution boundary.

What Makes a Good Code Sandbox?

A useful sandbox should provide several properties.

Isolation

Generated code should not be able to access unrelated workloads.

Resource Limits

CPU, memory, disk, and execution duration should be constrained.

Network Control

The sandbox should have explicitly controlled network access.

Ephemeral Execution

A session should be disposable when the job completes.

State Management

If an interactive coding session requires persistence, state should be preserved without sharing it with other users.

Auditing

Commands, inputs, outputs, and lifecycle events should be observable.

No single control is sufficient.

A secure design combines multiple boundaries.

Why MicroVMs Are Interesting

Traditional sandbox architectures often use processes or containers.

Those approaches can be useful, but they should not automatically be treated as equivalent security boundaries for mutually untrusted workloads.

AWS Lambda's standard execution environments already use Firecracker virtualization for workload isolation. Lambda MicroVMs expose that isolation model as a dedicated compute primitive for workloads that need isolated execution environments.

AWS describes Lambda MicroVMs as providing VM-level isolation with a separate kernel, memory space, and disk state for each environment. They are designed for use cases including AI coding assistants, vulnerability scanning, data analytics, and CI/CD workloads.

Conceptually:

User A
  ↓
MicroVM A
  ├── Kernel
  ├── Memory
  └── Filesystem

User B
  ↓
MicroVM B
  ├── Kernel
  ├── Memory
  └── Filesystem

The objective is to avoid making different untrusted execution sessions share the same security boundary.

A Secure AI Code Execution Architecture

A production architecture can separate the system into four layers:

┌───────────────────────────────┐
│ AI Agent / Control Plane      │
└───────────────┬───────────────┘
                │
                │ Generated Code
                ▼
┌───────────────────────────────┐
│ Sandbox Launcher              │
└───────────────┬───────────────┘
                │
                ▼
┌───────────────────────────────┐
│ Lambda MicroVM                │
│                               │
│ Source Code                   │
│ Build Tools                   │
│ Runtime                       │
│ Tests                         │
└───────────────┬───────────────┘
                │
                ▼
┌───────────────────────────────┐
│ Result / Logs / Artifacts     │
└───────────────────────────────┘

The control plane should not execute generated code itself.

Its job is to:

  1. Accept the task.

  2. Create or select an isolated environment.

  3. Transfer the required code and inputs.

  4. Execute the requested workload.

  5. Collect results.

  6. Destroy or suspend the environment according to the workflow.

  7. Record security and operational telemetry.

Package the Sandbox as an Image

Lambda MicroVMs can be created from a container-based image. AWS documents support for applications packaged for Amazon Linux 2023, with MicroVM configurations supporting up to 32 GB of memory and 16 vCPUs.

For a .NET sandbox, the image might contain:

Amazon Linux
   ↓
.NET Runtime / SDK
   ↓
Build Tools
   ↓
Test Tools
   ↓
Sandbox Application

The image should contain only the tools required by the workload.

Avoid turning the sandbox image into a general-purpose development environment containing unnecessary credentials, utilities, or network clients.

Do Not Put Secrets in the Sandbox

One of the most important rules is simple:

Generated code should not automatically receive production credentials.

Avoid placing credentials in:

Environment Variables
Configuration Files
Source Code
Container Images
Local Files

Instead, use explicit authorization boundaries.

If generated code needs to access a service, provide only the capability required for that operation.

For example:

AI Agent
   ↓
Needs database metadata
   ↓
Controlled API
   ↓
Database

is safer than:

AI Agent
   ↓
Full Database Credentials

Least privilege is particularly important because generated code cannot be assumed to understand the security implications of every action it performs.

Control Network Access

Network access deserves special attention.

An unrestricted sandbox could potentially execute:

HTTP requests
DNS lookups
Package downloads
Cloud API calls
Internal service requests

That creates an opportunity for data exfiltration or unauthorized access.

A safer architecture starts with:

Default
   ↓
No Network

and enables only the connections required by the workload.

For workloads that need access to internal resources, AWS documents VPC egress options for Lambda MicroVMs.

For example:

MicroVM
   │
   ├── Public Internet: DENY
   │
   ├── Internal API: ALLOW
   │
   └── Database: ALLOW

Network policy should be part of the sandbox design rather than an afterthought.

Control Authentication to the MicroVM

The sandbox itself should not become an unauthenticated execution endpoint.

AWS Lambda MicroVMs use authentication tokens for inbound access, and those tokens can be scoped to specific ports. AWS recommends short-lived tokens and limiting token scope to the ports actually required by the application.

Conceptually:

Client
   ↓
Short-Lived Token
   ↓
Specific MicroVM
   ↓
Specific Port

This is substantially better than exposing a sandbox endpoint without authentication.

Treat AI Output as Untrusted Input

An important architectural mistake is assuming that code generated by a trusted AI model is trusted code.

It is not.

AI-generated code can contain:

Unexpected shell commands
Unsafe dependencies
Credential access
Network requests
Destructive filesystem operations
Infinite loops
Resource-intensive operations

The model may also be influenced by malicious instructions contained in files, repositories, documentation, or external content.

Therefore:

AI Output
   ↓
UNTRUSTED
   ↓
Sandbox

should be the default security model.

Limit CPU and Memory

Generated code can accidentally consume excessive resources.

For example:

while (true)
{
    var data = new byte[1024 * 1024];
}

could consume significant resources.

A sandbox should therefore be sized deliberately.

AWS recommends right-sizing MicroVM resources and notes that bandwidth scales with configured memory.

A practical policy might look like:

Small Task
CPU:    Low
Memory: 1–2 GB
Disk:   Limited
Time:   Short

Large Build
CPU:    Higher
Memory: Larger
Disk:   Larger
Time:   Controlled

The exact limits should be determined from workload testing.

Enforce Execution Time Limits

Resource limits should include time.

Without a timeout, generated code could execute indefinitely:

Agent
 ↓
Generated Program
 ↓
Infinite Loop
 ↓
Sandbox Never Completes

A control plane should define a maximum execution duration:

Job Started
    ↓
Execute
    ↓
Timeout?
 ┌──Yes──→ Terminate
 │
 No
 ↓
Complete

For interactive sessions, the lifecycle can instead use suspension and resume where appropriate.

AWS states that Lambda MicroVM environments can preserve state across interactions for up to eight hours.

Use Ephemeral Filesystems Carefully

Generated applications frequently need a workspace:

/workspace
 ├── src
 ├── tests
 ├── packages
 └── artifacts

That workspace should belong to the isolated execution environment.

Do not assume that temporary execution state should be shared between users.

A strong model is:

User A → MicroVM A → Workspace A
User B → MicroVM B → Workspace B

When the session ends, terminate the environment when persistent state is no longer required.

Snapshot State Requires Care

One of the interesting capabilities of Lambda MicroVMs is snapshot-based startup and state preservation.

A snapshot can capture memory, disk state, and other initialized execution state.

This creates a security consideration.

Suppose a snapshot contains:

Temporary Token
Session ID
Random Identifier
Cached Credential
Network Connection

That state may be reproduced when the snapshot is reused.

AWS recommends generating unique values such as UUIDs, secrets, and random values at runtime rather than baking them into the image snapshot, and using lifecycle hooks appropriately.

The principle is:

Build-Time State
      ≠
Runtime-Unique State

Generate secrets and unique identifiers after the environment starts.

Lifecycle Hooks Matter

A sandbox has more lifecycle events than simply:

Start
Stop

A practical model is:

Run
 ↓
Suspend
 ↓
Resume
 ↓
Terminate

Applications should account for these transitions.

AWS recommends using lifecycle hooks such as /run, /suspend, /resume, and /terminate for initialization, cleanup, connection re-establishment, and data flushing.

For example, after resume:

Resume
  ↓
Validate Network Connections
  ↓
Refresh Temporary State
  ↓
Continue Work

This is especially important for long-lived interactive AI coding sessions.

Give Agents a Capability-Based Interface

Instead of allowing an agent to directly control the infrastructure, expose a small execution API:

POST /sandbox
POST /sandbox/{id}/execute
GET  /sandbox/{id}/status
GET  /sandbox/{id}/logs
POST /sandbox/{id}/terminate

The control plane can validate each operation.

For example:

Agent
  ↓
Execute Command
  ↓
Policy Check
  ↓
MicroVM

The policy layer can reject operations that violate the application's security model.

Example .NET Control-Plane Model

A simple request model could look like:

public sealed record SandboxRequest(
    string SessionId,
    string Code,
    int TimeoutSeconds);

The control plane should validate:

if (request.TimeoutSeconds <= 0 ||
    request.TimeoutSeconds > 300)
{
    throw new ArgumentOutOfRangeException(
        nameof(request.TimeoutSeconds));
}

The important part is that the application should not blindly pass every AI-generated instruction to the sandbox.

Validate the execution request before provisioning resources.

Capture Execution Logs

Every sandbox execution should produce useful telemetry.

Record:

Session ID
Sandbox ID
Request ID
Start Time
End Time
Exit Code
CPU Usage
Memory Usage
Network Activity
Files Created
Execution Result

For example:

Session:     agent-83f1
Sandbox:     vm-2918
Duration:    8.4 s
Exit Code:   0
Memory:      620 MB
Network:     Restricted
Result:      Tests Passed

This makes security investigations and performance troubleshooting substantially easier.

Separate Logs from User-Controlled Output

Generated applications can print arbitrary content.

Do not treat application output as trusted operational logs.

For example:

Application Output
      ↓
Untrusted
      ↓
Sanitize / Structure
      ↓
Operational Logging

Structured logging should preserve important metadata independently from arbitrary generated output.

Protect Against Dependency Risks

AI-generated projects frequently install dependencies automatically.

That creates another attack surface.

A generated application might request:

dotnet add package SomePackage

The sandbox should not assume every package is trustworthy.

Possible controls include:

  • Approved package sources

  • Dependency scanning

  • Package allowlists

  • Version pinning

  • Network restrictions

  • Build-time inspection

For security-sensitive workloads, dependency acquisition should be treated as an explicit policy decision.

Do Not Confuse Isolation With Complete Security

A MicroVM provides a strong execution boundary, but it does not eliminate every security problem.

You still need:

Identity
+
Authorization
+
Network Controls
+
Resource Limits
+
Input Validation
+
Logging
+
Dependency Controls

For example, a perfectly isolated sandbox can still leak information if the control plane sends sensitive data into it.

Security must therefore be designed across the entire pipeline.

A Practical Security Boundary

A robust AI code execution system can be modeled as:

                 AI Agent
                    │
                    ▼
            ┌───────────────┐
            │ Policy Layer  │
            └───────┬───────┘
                    │
              Approved Task
                    │
                    ▼
            ┌───────────────┐
            │ MicroVM       │
            │               │
            │ Code          │
            │ Runtime       │
            │ Filesystem    │
            └───────┬───────┘
                    │
          ┌─────────┴─────────┐
          ▼                   ▼
      Controlled           Logs /
       Network             Results

Each layer has a different responsibility.

Benchmark Sandbox Performance

Security is the primary objective, but performance still matters.

Measure:

  • Sandbox startup latency

  • Resume latency

  • Code execution time

  • Build time

  • Memory consumption

  • Disk usage

  • Network latency

  • Concurrent sandbox capacity

  • Termination time

For example:

Test A
Start → Execute → Terminate

Test B
Start → Execute → Suspend → Resume → Execute

Test C
100 concurrent sandboxes

Test D
Large .NET build

This reveals whether the sandbox architecture is practical for interactive workloads.

Common Mistakes

Executing AI Code in the Main Application

This removes the most important security boundary.

Giving the Sandbox Production Credentials

Generated code should receive only explicitly required capabilities.

Allowing Unlimited Network Access

Network access can become an exfiltration and lateral-movement path.

Using Containers as the Only Security Boundary

Containers are useful for packaging and isolation, but untrusted workloads require a carefully chosen security boundary.

Sharing Workspaces Between Users

One user's generated files should never become another user's execution context.

Baking Secrets Into Snapshots

Runtime-unique credentials and identifiers should be generated after startup.

Ignoring Resource Exhaustion

Malicious or buggy code can consume CPU, memory, disk, or network capacity.

Logging Everything Without Classification

Generated output may contain secrets or sensitive information.

Best Practices

  1. Treat every AI-generated program as untrusted.

  2. Execute generated code outside the trusted application process.

  3. Give each untrusted workload its own isolated execution environment.

  4. Use least-privilege IAM permissions.

  5. Restrict network access by default.

  6. Use short-lived authentication tokens.

  7. Scope inbound access to required ports.

  8. Apply CPU, memory, disk, and execution-time limits.

  9. Keep production credentials out of the sandbox.

  10. Generate runtime-unique secrets and identifiers after snapshot initialization.

  11. Design explicitly for suspend and resume.

  12. Scan or control third-party dependencies.

  13. Record structured security and execution telemetry.

  14. Test malicious, malformed, and resource-intensive generated programs.

  15. Terminate environments when persistent state is no longer required.

Frequently Asked Questions

Is running AI-generated code in a container enough?

Not necessarily. Containers are excellent packaging and isolation tools, but the appropriate security boundary depends on the trust model. For mutually untrusted workloads, stronger isolation should be evaluated.

Can AI-generated code access the internet?

It can if the sandbox is configured to permit network access. A safer default is to deny unnecessary outbound connectivity and explicitly allow required destinations.

Should every user receive a separate MicroVM?

For strongly isolated multi-tenant execution, a dedicated MicroVM per user or session provides a clear isolation model. The correct lifecycle depends on whether the workload needs persistent state.

Can a MicroVM preserve state?

Yes. AWS Lambda MicroVMs support state preservation across interactions, including suspend and resume behavior, with documented session limits.

What should happen when generated code fails?

Capture the exit status and logs, classify the failure, and terminate or reset the environment according to the workflow's security policy.

Should generated code receive AWS credentials?

Only when absolutely necessary, and then only through narrowly scoped permissions. In most code-execution scenarios, generated code should have no direct access to production AWS credentials.

Conclusion

AI agents are changing the definition of application security.

When an AI system can generate and execute code, the execution environment becomes part of the security architecture.

The safer model is:

Generate
   ↓
Validate
   ↓
Isolate
   ↓
Execute
   ↓
Observe
   ↓
Destroy or Suspend

AWS Lambda MicroVMs provide a serverless approach to this problem by combining Firecracker-based VM-level isolation with lifecycle management and state preservation. AWS specifically positions the technology for workloads such as AI coding assistants, vulnerability scanning, data analytics, CI/CD, and other applications that need isolated execution environments for user- or AI-generated code.

But the MicroVM itself should not be treated as the entire security strategy.

A production AI code execution platform still needs least-privilege identity, controlled networking, resource limits, dependency controls, short-lived authentication, secure state management, observability, and rigorous failure testing.