> ## 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 Daytona Sandboxes

> Run the Formal Endpoint in a linked Daytona sandbox so a Connector injects API keys outside the agent's sandbox

## Overview

Agents in a Daytona sandbox often need API keys. Prompt-injected code can read
a key from the sandbox and send it anywhere.

With Formal, the key never enters the agent's sandbox. Each run uses two
[linked sandboxes](https://www.daytona.io/docs/en/sandboxes#linked-sandboxes):

1. An **Endpoint sandbox** runs the headless [Formal Endpoint](https://docs.formal.ai/docs/glossary/index.md#formal-endpoint).
   It logs in with a Formal machine user API key.
2. An **agent sandbox** is linked to it. Its network allow list contains only
   the Endpoint sandbox, and its HTTP clients use it as `HTTPS_PROXY`.
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.

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

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
agent sandbox (no secrets; allow list = Endpoint sandbox only)
  HTTPS_PROXY=http://<ENDPOINT_SANDBOX_IP>:3128
    -> Endpoint sandbox (FORMAL_API_KEY, Formal Endpoint)
         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`. The key lives only in the Endpoint
sandbox, which the agent cannot read. To scope it:

* Create a dedicated machine user and API key for Daytona.
* Pass the key from your orchestrator when you create the sandbox. Never bake
  it into a snapshot.
* Rotate the key on a schedule.

### Daytona features used

| Feature | Role |
| - | - |
| [Linked sandboxes](https://www.daytona.io/docs/en/sandboxes#linked-sandboxes) | Private network between the two sandboxes. Deleting the Endpoint sandbox deletes the agent sandbox. |
| [Network allow list](https://www.daytona.io/docs/en/network-limits) | Limits the agent sandbox to the Endpoint sandbox's `/32`. |
| Domain allow list | Limits the Endpoint sandbox to Formal and the Connector. |
| [Snapshots](https://www.daytona.io/docs/en/snapshots) | Bakes the Endpoint package into the Endpoint sandbox's image. |

> [!NOTE]
>
> Sandbox-level network settings are available to Daytona organizations on
> **Tier 3 or 4**.

## Steps

### 1. Store the key on the Connector

Set `STRIPE_API_KEY` in the Connector's environment. Remove the key from any
Daytona secret or snapshot 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 `daytona-agents`.
2. Create an [API key](https://app.formal.ai/api-keys) for it. Store it in your
   orchestrator as `FORMAL_DAYTONA_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_daytona" {
  name   = "stripe-daytona-sandboxes"
  status = "active"

  cel_expression = <<-EOT
    {
      "condition": {
        "pre_tls": hostname == "api.stripe.com" &&
          user.id == "<DAYTONA_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. Create the Endpoint snapshot

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 daytona import CreateSnapshotParams, Daytona, Image

daytona = Daytona()

image = Image.debian_slim("3.12").run_commands(
    "apt-get update && apt-get install -y ca-certificates curl iproute2 socat",
    "curl -fsSL '<FORMAL_ENDPOINT_PACKAGE_URL>' -o /tmp/formal.deb",
    "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",
)
daytona.snapshot.create(
    CreateSnapshotParams(name="formal-endpoint", image=image),
    on_logs=print,
)
```

**Verify:** `formal-endpoint` appears in the Daytona dashboard under
**Snapshots** with the **Active** state.

### 6. Run an agent

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

from daytona import CreateSandboxFromSnapshotParams, Daytona

daytona = Daytona()

CONNECTOR_HOSTNAME = "<CONNECTOR_HOSTNAME>"
CA = "/var/lib/formal/ca/localca-cert.pem"
START_ENDPOINT = (
    "test -s /etc/machine-id || tr -d - < /proc/sys/kernel/random/uuid > /etc/machine-id; "
    "nohup formal agent --headless --explicit-proxy=127.0.0.1:3128 > /tmp/formal.log 2>&1 &"
)
LINK_IP = (
    "for i in $(seq 60); do "
    "ip -4 -o addr show eth1 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep . && exit 0; "
    "sleep 0.5; done; exit 1"
)

endpoint = daytona.create(CreateSandboxFromSnapshotParams(
    snapshot="formal-endpoint",
    env_vars={"FORMAL_API_KEY": os.environ["FORMAL_DAYTONA_API_KEY"]},
    domain_allow_list=f"api.formal.ai,{CONNECTOR_HOSTNAME}",
))
try:
    endpoint.process.exec(START_ENDPOINT)

    agent = daytona.create(CreateSandboxFromSnapshotParams(
        linked_sandbox=endpoint.id,
        auto_delete_interval=0,
        network_block_all=True,
    ))
    ip = endpoint.process.exec(LINK_IP).result.strip()
    # Explicit Proxy mode listens on loopback; expose it on the link network.
    endpoint.process.exec(
        f"nohup socat TCP-LISTEN:3128,bind={ip},fork,reuseaddr "
        "TCP:127.0.0.1:3128 > /dev/null 2>&1 &")
    agent.update_network_settings(network_allow_list=f"{ip}/32")

    # Only the CA's public certificate leaves the Endpoint sandbox.
    pem = endpoint.process.exec(f"until test -s {CA}; do sleep 1; done; cat {CA}").result
    agent.fs.upload_file(pem.encode(), "/tmp/formal.crt")
    agent.process.exec(
        "sudo cp /tmp/formal.crt /usr/local/share/ca-certificates/formal.crt "
        "&& sudo update-ca-certificates")

    proxy = f"http://{ip}:3128"
    result = agent.process.exec(
        "curl -s 'https://api.stripe.com/v1/customers?limit=1' | head -c 200",
        env={"HTTPS_PROXY": proxy, "HTTP_PROXY": proxy,
             "NODE_EXTRA_CA_CERTS": "/tmp/formal.crt"},
    )
    print(result.result)
finally:
    # Deleting the Endpoint sandbox also deletes the linked agent sandbox.
    endpoint.delete()
```

The link network address appears on `eth1` shortly after the agent sandbox is
linked. Run your agent with the same `env` as the `curl` command.

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

### 7. Verify the key stays out

Run these in the agent sandbox, with the `env` from step 6:

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

curl -s --noproxy '*' -m 5 https://api.stripe.com || echo blocked
# Expected: blocked
```

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

## Operational notes

* Set `HTTPS_PROXY` and `HTTP_PROXY` for your agent's tools, as in step 6.
  The agent sandbox has no other route out.
* Create linked agent sandboxes with `auto_delete_interval=0`.

## 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] [E2B](https://docs.formal.ai/docs/guides/example-use-cases/sandbox-credential-injection/e2b.md)
>
> The same pattern with the Endpoint in an E2B sandbox


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