> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Keep API Keys Out of E2B Sandboxes

> Run the Formal Endpoint in an E2B sandbox so a Connector injects API keys outside the sandbox

## Overview

Agents in an [E2B sandbox](https://e2b.dev/docs/sandbox) often need API keys.
Prompt-injected code can read a key from the sandbox and send it anywhere.

With Formal, the API key never enters the sandbox:

1. A custom [E2B template](https://e2b.dev/docs/template/quickstart) installs
   the headless [Formal Endpoint](https://docs.formal.ai/docs/glossary/index.md#formal-endpoint) in
   Transparent Mode.
2. The Endpoint runs as `root` and logs in with a Formal machine user API key.
   The agent runs as the default `user`.
3. A [network rule](https://docs.formal.ai/docs/guides/network-rules.md) forwards requests for the API
   hostname to a [Connector](https://docs.formal.ai/docs/glossary/index.md#connector).
4. A [Native User](https://docs.formal.ai/docs/glossary/index.md#native-user) on the Connector adds the API key.
   [Policies](https://docs.formal.ai/docs/glossary/index.md#policy) and logs apply to every request.
5. E2B's [egress controls](https://e2b.dev/docs/sandbox/internet-access) allow
   only Formal and the Connector.

The agent keeps calling the real API hostname, such as `api.stripe.com`, with
no proxy settings.

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
E2B sandbox (egress allowed: api.formal.ai, <CONNECTOR_HOSTNAME>)
  agent (user): curl https://api.stripe.com/v1/customers
    -> Formal Endpoint (root, Transparent Mode, FORMAL_API_KEY)
         network rule: api.stripe.com -> forward_to_connector
      -> Formal Connector (STRIPE_API_KEY in its environment)
        -> api.stripe.com
```

This guide uses the Stripe API with a bearer key. The same setup works for any
HTTP API and every [Native User type](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#supported-credential-types).

### Machine user API key

The Endpoint logs in with `FORMAL_API_KEY`. Your orchestrator passes it only to
the Endpoint's process when it starts the sandbox. To scope it:

* Create a dedicated machine user and API key for E2B.
* Never bake the key into a template.
* [Restrict the machine user's Control Plane access](https://docs.formal.ai/docs/guides/example-use-cases/formal-endpoint-cloud-agents.md#restrict-control-plane-access).
* Rotate the key on a schedule.

### E2B features used

| Feature | Role |
| - | - |
| [Templates](https://e2b.dev/docs/template/quickstart) | Bakes the Endpoint package and config into the sandbox image. |
| [Egress allow and deny lists](https://e2b.dev/docs/sandbox/internet-access) | Allows only `api.formal.ai` and the Connector. |
| [Commands](https://e2b.dev/docs/commands/background) | Starts the Endpoint in the background as `root`. |

## Steps

### 1. Store the key on the Connector

Set `STRIPE_API_KEY` in the Connector's environment. Remove the key from any
E2B template or environment variable that the agent can use.

### 2. Create the resource, Native User, and listener

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_resource" "stripe" {
  name       = "stripe"
  technology = "http"
  hostname   = "api.stripe.com"
  port       = 443
}

resource "formal_resource_tls_configuration" "stripe" {
  resource_id = formal_resource.stripe.id
  tls_config  = "verify-full"
}

resource "formal_native_user_v3" "stripe" {
  resource_id = formal_resource.stripe.id
  label       = "stripe-api-key"

  http_bearer {
    header = "Authorization"
    token {
      environment_variable = "STRIPE_API_KEY"
    }
  }
}

resource "formal_resource_native_user_selection" "stripe" {
  resource_id = formal_resource.stripe.id
  cel         = "\"${formal_native_user_v3.stripe.id}\""
}

resource "formal_connector_listener" "stripe" {
  connector_id = var.connector_id
  name         = "stripe-listener"
  port         = 443
}

resource "formal_connector_listener_rule" "stripe" {
  connector_listener_id = formal_connector_listener.stripe.id
  type                  = "resource"
  rule                  = formal_resource.stripe.id
}
```

**Verify:** `stripe` appears under the Connector's **Reachable Resources**.

### 3. Create the machine user and API key

1. Go to [Users](https://app.formal.ai/users), click **Create User**, and
   choose **Machine**. Name it `e2b-agents`.
2. Create an [API key](https://app.formal.ai/api-keys) for it. Store it in your
   orchestrator as `FORMAL_E2B_API_KEY`.

Copy the machine user's `user_...` ID for the next step.

### 4. Forward API traffic to the Connector

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_network_rule" "stripe_e2b" {
  name   = "stripe-e2b-sandboxes"
  status = "active"

  cel_expression = <<-EOT
    {
      "condition": {
        "pre_tls": hostname == "api.stripe.com" &&
          user.id == "<E2B_MACHINE_USER_ID>",
        "post_tls": true
      },
      "outputs": {
        "resource_name": "stripe",
        "forward_to_connector": true
      }
    }
  EOT
}
```

Linux Endpoints ignore `pre_tcp`, so `pre_tls` checks the hostname and user.

### 5. Build the Endpoint template

Copy the **Ubuntu/Debian (x86, headless)** package link from the Control Plane
(**Download** > **Linux**).

```python theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
from e2b import Template, default_build_logger

template = (
    Template()
    .from_base_image()
    .run_cmd(
        [
            "curl -fsSL '<FORMAL_ENDPOINT_PACKAGE_URL>' -o /tmp/formal.deb",
            "apt-get update && apt-get install -y /tmp/formal.deb",
            "mkdir -p /root/.formal && printf '[transparent_proxy]\\nenable = true\\nenforce = true\\nfail = \"closed\"\\n' > /root/.formal/config.toml",
        ],
        user="root",
    )
)

Template.build(template, "formal-endpoint", on_build_logs=default_build_logger())
```

**Verify:** `formal-endpoint` appears under **Templates** in the E2B dashboard.

### 6. Run an agent

```python theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
import os

from e2b import Sandbox

CONNECTOR_HOSTNAME = "<CONNECTOR_HOSTNAME>"
CA = "/var/lib/formal/ca/localca-cert.pem"

sandbox = Sandbox.create(
    "formal-endpoint",
    network={
        "allow_out": ["api.formal.ai", CONNECTOR_HOSTNAME],
        "deny_out": lambda ctx: [ctx.all_traffic],
    },
)

sandbox.commands.run(
    "test -s /etc/machine-id || tr -d - < /proc/sys/kernel/random/uuid > /etc/machine-id; "
    "formal agent --headless > /var/log/formal.log 2>&1",
    background=True,
    timeout=0,
    user="root",
    envs={"FORMAL_API_KEY": os.environ["FORMAL_E2B_API_KEY"]},
)
sandbox.commands.run(
    f"until test -s {CA}; do sleep 1; done; formal ca trust",
    user="root",
)

result = sandbox.commands.run(
    "curl -s 'https://api.stripe.com/v1/customers?limit=1' | head -c 200",
    envs={"NODE_EXTRA_CA_CERTS": "/etc/ssl/certs/ca-certificates.crt"},
)
print(result.stdout)
```

`formal ca trust` adds the Endpoint's certificate authority to the system
trust store. `NODE_EXTRA_CA_CERTS` points Node.js at the same bundle. Run your
agent as the default `user` with the same `envs`.

**Verify:** the script prints a Stripe JSON response.

### 7. Verify the key stays out

Run these as the default `user`:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
env | grep -ci -E 'stripe|formal'
# Expected: 0

curl -s -m 5 https://example.com || echo blocked
# Expected: blocked
```

In [Logs](https://app.formal.ai/logs), each request shows the `e2b-agents`
machine user and the `stripe` resource.

## Next Steps

> [card] [Modal](https://docs.formal.ai/docs/guides/example-use-cases/sandbox-credential-injection/modal.md)
>
> The same pattern with a Modal Sidecar and OIDC

> [card] [Daytona](https://docs.formal.ai/docs/guides/example-use-cases/sandbox-credential-injection/daytona.md)
>
> The same pattern with linked Daytona sandboxes


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.