# Secrets in Cloudflare Sandbox

Cloudflare Sandbox is the one provider on this list where keeping the credential
out of the sandbox needs no proxy at all. A container's outbound HTTP and HTTPS
can be **intercepted into a Worker entrypoint** — code that runs in the Workers
runtime, outside the container, after the platform has terminated TLS. That is
exactly what [`seekrit-proxy`](/docs/guides/agent-proxy) does elsewhere, built
into the platform.

`@seekrit/sdk/cloudflare-sandbox` gives you that entrypoint's `fetch`. The
container gets placeholders instead of keys; the gateway swaps in the real values
for the hosts you name and refuses everything else.

## The gateway

`seekritEgress` builds the handler. Export it as a `WorkerEntrypoint` — this is
the `Outbound` class from Cloudflare's [coding-agent
tutorial](https://developers.cloudflare.com/sandbox/get-started/build-a-coding-agent-runner/),
with seekrit doing the allowing and the injecting:

```ts
// src/outbound.ts
import { WorkerEntrypoint } from 'cloudflare:workers';
import { type SeekritEgressGateway, seekritEgress } from '@seekrit/sdk/cloudflare-sandbox';

let egress: SeekritEgressGateway | undefined;

export class Outbound extends WorkerEntrypoint<Env> {
  override fetch(request: Request) {
    egress ??= seekritEgress({
      token: this.env.SEEKRIT_TOKEN,
      rules: [
        { host: 'api.anthropic.com', allow: ['ANTHROPIC_API_KEY'] },
        { host: 'api.github.com', methods: ['GET'], paths: ['/repos/acme/**'], allow: ['GITHUB_TOKEN'] },
        { host: 'registry.npmjs.org', methods: ['GET'] },
      ],
    });
    return egress.fetch(request, this.ctx);
  }
}
```

Every request is checked twice. First the operation — host, method, path, and
port — so a request no rule covers is answered `403` and never sent. Then each
`{{seekrit:NAME}}` it carries, so a name the host may not receive is refused
too. A rule with no `allow` (the npm registry above) lets the agent install
packages without letting it carry a credential there.

> **Warning:** **Build the gateway at module scope, not in a class field.** Workers
>   constructs a `WorkerEntrypoint` afresh for every call, so
>   `#egress = seekritEgress(…)` would build a new gateway — and make a new
>   metered `/v1/resolve` call — for every outbound request the agent makes. At
>   module scope it lives as long as the isolate, and resolved values are reused
>   for `ttlSeconds` (60 by default). They stay in the Worker's memory and are
>   never written into the container.
> 
> Pass `this.ctx` as the second argument. It is only used with a [signed
>   policy](#rules-from-the-dashboard), where it lets a policy refresh run in the
>   background of the request that found it due.

## Wire it to the container

Route every HTTPS host through the gateway, start the container with no other
route out, and hand the command placeholders:

```ts
// src/sandbox.ts
import { DurableObject } from 'cloudflare:workers';
import { containerTrustEnv, seekritEnv } from '@seekrit/sdk/cloudflare-sandbox';

export class AgentSandbox extends DurableObject<Env> {
  async run(task: string) {
    const container = this.ctx.container;
    if (!container) throw new Error('No container is configured');

    if (!container.running) {
      // Intercepts last until the container stops: register them on every start,
      // and before start() so the CA file exists when the entrypoint runs.
      await container.interceptOutboundHttps('*', this.ctx.exports.Outbound);
      await container.interceptAllOutboundHttp(this.ctx.exports.Outbound);
      container.start({ image: container.images.agent, enableInternet: false });
    }

    const proc = await container.exec(['claude', '-p', task], {
      cwd: '/workspace',
      env: { ...seekritEnv(['ANTHROPIC_API_KEY', 'GITHUB_TOKEN']), ...containerTrustEnv() },
    });
    const output = await proc.output();
    return new TextDecoder().decode(output.stdout);
  }
}
```

```ts
// src/index.ts
export { Outbound } from './outbound';
export { AgentSandbox } from './sandbox';
```

Inside the container, `$ANTHROPIC_API_KEY` is the literal string
`{{seekrit:ANTHROPIC_API_KEY}}`. The agent sends it as an ordinary `x-api-key`
header; the gateway replaces it on the way out to `api.anthropic.com`, and
nowhere else.

- **`'*'`, not a list of hosts.** Intercepting every HTTPS host makes the
  gateway the container's only route out, so its default-deny *is* your egress
  policy: an unlisted host gets a `403` that says which rule is missing, rather
  than a DNS failure.
- **`interceptAllOutboundHttp` is optional.** The gateway refuses cleartext
  unless a rule lists `http_ports`, so routing port 80 to it just turns a
  silent failure into a refusal with a reason.
- **`enableInternet: false`** means a request has no path that skips the
  gateway. Leave it on and anything the intercepts do not cover — another port,
  a raw TCP connection — goes straight out.

`seekritEgress` needs the usual Worker secret: `wrangler secret put
SEEKRIT_TOKEN` with a [service token](/docs/guides/service-tokens) for the
environment the agent should draw from. `ctx.exports` needs a compatibility date
of `2025-11-17` or later.

## Trust the gateway's certificate

To read an HTTPS request, the platform terminates its TLS with a per-container CA
at `/etc/cloudflare/certs/cloudflare-containers-ca.crt`. Every TLS client in the
container has to trust it, or each intercepted request fails its handshake before
the gateway sees it. `containerTrustEnv()` returns the variables that point the
common clients at it:

| Variable | Read by |
| --- | --- |
| `NODE_EXTRA_CA_CERTS` | Node, Bun — *added* to the built-in roots |
| `SSL_CERT_FILE` | OpenSSL, and most things linked against it |
| `CURL_CA_BUNDLE` | curl |
| `GIT_SSL_CAINFO` | git |
| `REQUESTS_CA_BUNDLE` | Python `requests` |

All but the first *replace* the client's trust store with that one file. That is
correct because every HTTPS host is intercepted — a host that was not would be
checked against this CA alone and fail. If you intercept only some hosts, pick
the variables you need yourself, or install the CA into the image's system store
from its entrypoint, as Cloudflare's [outbound traffic
docs](https://developers.cloudflare.com/containers/configuration/outbound-traffic/)
describe.

## Headers the agent never sends

Substitution only rewrites what the request already carries. When the
credential belongs in a header the client never sends — Cloudflare's tutorial
authenticates to AI Gateway with `cf-aig-authorization` — add the header in the
entrypoint, *as a placeholder*, before handing the request to the gateway:

```ts
export class Outbound extends WorkerEntrypoint<Env> {
  override fetch(request: Request) {
    const { hostname } = new URL(request.url);
    if (hostname === 'gateway.ai.cloudflare.com') {
      const headers = new Headers(request.headers);
      headers.delete('x-api-key');
      headers.set('cf-aig-authorization', 'Bearer {{seekrit:AI_GATEWAY_TOKEN}}');
      request = new Request(request, { headers });
    }
    egress ??= seekritEgress({
      token: this.env.SEEKRIT_TOKEN,
      rules: [
        {
          host: 'gateway.ai.cloudflare.com',
          paths: [`/v1/${this.env.AI_GATEWAY_ACCOUNT_ID}/${this.env.AI_GATEWAY_ID}/**`],
          allow: ['AI_GATEWAY_TOKEN'],
        },
      ],
    });
    return egress.fetch(request, this.ctx);
  }
}
```

The value still comes from seekrit and still exists only in the gateway, and the
rule — not the `if` — decides that `AI_GATEWAY_TOKEN` may go to your gateway's
path and nowhere else. Point the agent at
`https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic` with
`ANTHROPIC_BASE_URL`; its own `x-api-key` is dropped.

## Rules from the dashboard

The rules above live in your Worker's source, which is what makes them
trustworthy. To change them without a redeploy, publish a **signed `ap1.`
policy** from the dashboard and give the gateway `policy` instead of `rules` —
it verifies each bundle against signers pinned in your own config, so the API
serves bytes it cannot forge:

```ts
egress ??= seekritEgress({
  token: this.env.SEEKRIT_TOKEN,
  policy: {
    signers: this.env.POLICY_SIGNERS.split(','),
    agent: 'coding-agent',
    ceiling: { 'api.anthropic.com': ['ANTHROPIC_API_KEY'] },
  },
});
```

The verification, refresh layers, and the `ceiling` that bounds what a bundle
may ever say work exactly as on [Cloudflare
Computer](/docs/guides/sandboxes/cloudflare-computer#keeping-policy-current) —
it is the same gateway. See [Agent access policy](/docs/guides/agent-proxy/policy)
for publishing.

## Per-sandbox credentials

Pass [`props`](https://developers.cloudflare.com/containers/configuration/workers-connections/)
when you register the intercept, and the entrypoint reads them as
`this.ctx.props`. Keep one gateway per value at module scope, so each tenant's
container resolves its own slice of a `tenants` group — a [`with`
override](/docs/guides/environments#swapping-one-group-per-boot) — without
rebuilding a gateway per request:

```ts
const gateways = new Map<string, SeekritEgressGateway>();

export class Outbound extends WorkerEntrypoint<Env, { tenant: string }> {
  override fetch(request: Request) {
    const { tenant } = this.ctx.props;
    let egress = gateways.get(tenant);
    if (!egress) {
      egress = seekritEgress({
        token: this.env.SEEKRIT_TOKEN,
        with: { tenants: tenant },
        allow: { 'api.example.com': ['TENANT_API_KEY'] },
      });
      gateways.set(tenant, egress);
    }
    return egress.fetch(request, this.ctx);
  }
}

// In the Durable Object, for the tenant this sandbox belongs to:
await container.interceptOutboundHttps(
  '*',
  this.ctx.exports.Outbound({ props: { tenant } }),
);
```

Overrides are fail-closed: the service token has to be created with each slice
it may pull (`token create … --allow tenants=acme`), so a container cannot
reach another tenant's values by naming them.

## git over HTTPS

git sends `user:password` as an `Authorization: Basic` header, base64-encoded, so
a placeholder in the password is not in the request as written. The gateway
decodes exactly that shape — an `Authorization` or `Proxy-Authorization` value
of `Basic` followed by standard, padded base64 — substitutes inside it under the
same rules as any other placeholder, and re-encodes it. A placeholder password
is all git needs:

```ts
await container.exec(
  ['git', 'clone', 'https://x-access-token:{{seekrit:GITHUB_TOKEN}}@github.com/acme/app.git', '/workspace'],
  { env: containerTrustEnv() },
);
```

with a rule that lets the token go to the host git talks to:

```ts
{ host: 'github.com', paths: ['/acme/app.git/**'], allow: ['GITHUB_TOKEN'] },
```

The remote URL, placeholder and all, is saved to `.git/config`. That is
harmless — it is a marker, not a token — and it means a later `git fetch` or
`git push` from the agent is substituted the same way. If you would rather keep
the URL plain, a credential helper that prints the `$GITHUB_TOKEN` from
`seekritEnv` sends the identical header:

```ts
['git', '-c', 'credential.helper=!f() { echo username=x-access-token; echo "password=$GITHUB_TOKEN"; }; f', 'clone', …]
```

A name the rule does not allow, or one that did not resolve, is refused with a
`403` before anything leaves; git reports it as `The requested URL returned
error: 403`. Only a Basic credential in those two headers is decoded — a value
the client encodes any other way, under another scheme or inside a body, is not.

## What the gateway cannot inject

An egress gateway sees HTTP requests. A `psql` connection or `git push` over SSH
has no request for a placeholder to sit in. When a step like that is *yours* —
running a migration before the agent starts — resolve the value in the Worker
and pass it to that one `exec`:

```ts
import { Seekrit } from '@seekrit/sdk';
import { resolveEnv } from '@seekrit/sdk/cloudflare-sandbox';

const client = new Seekrit({ token: this.env.SEEKRIT_TOKEN });

await container.exec(['npm', 'run', 'migrate'], {
  cwd: '/workspace',
  env: await resolveEnv(client, ['DATABASE_URL']),
});
```

`exec`'s `env` is per process — later commands, including the agent, do not
inherit it. `resolveEnv` takes named secrets only and throws on a name that did
not resolve. Do not hand an `exec` the whole resolved map.

## On the 0.x SDK

Cloudflare points new apps at the Containers API above. If you are on the older
`@cloudflare/sandbox` 0.x API — a class that `extends Sandbox` with static
`outbound` / `outboundByHost` handlers — the same gateway goes in the catch-all
handler:

```ts
import { Sandbox } from '@cloudflare/sandbox';

export class AgentSandbox extends Sandbox {
  interceptHttps = true;
}

// `egress` and `rules` as in the gateway above, at module scope.
AgentSandbox.outbound = (request: Request, env: Env) => {
  egress ??= seekritEgress({ token: env.SEEKRIT_TOKEN, rules });
  return egress.fetch(request);
};
```

Use `outbound` rather than `outboundByHost`, so the gateway's default-deny
covers every host and not only the ones you listed.

## Which one, concretely

| The sandbox runs | Use |
| --- | --- |
| A coding agent, or model-generated code | `seekritEgress` as the outbound handler, `seekritEnv` placeholders |
| Your build, migration, or test step | `resolveEnv` into that one `exec` |
| Untrusted user submissions | The gateway, and nothing real in any `exec` `env` |

A useful tell: if you would be unhappy to find the value printed in the
sandbox's stdout, it belongs in the Worker.

## See also

- [Cloudflare Computer](/docs/guides/sandboxes/cloudflare-computer) — the same gateway, as a Workspace egress policy
- [Agent access policy](/docs/guides/agent-proxy/policy) — publishing signed rules this gateway can verify, instead of hard-coding them
- [Agent sandboxes](/docs/guides/sandboxes) — the two shapes and when each is right
- [Agent proxy](/docs/guides/agent-proxy) — the same boundary for every runtime without an egress hook
- [Sync to Cloudflare](/docs/guides/third-party-sync/cloudflare) — for Workers, Pages, and Secrets Store, which are the other problem
