skip to content

On Cloudflare, how do you run untrusted generated code in a Dynamic Worker or a sandbox container without exposing your Worker's credentials?

level: seniorimportance: should knowfreq 24%

answer

  1. give only what the code may use
  2. globalOutbound defaults to inherit
  3. credentials stay in your Worker
  4. enableInternet and outbound handlers
  5. one sandbox per user

basics

~20 s

Give the sandbox only what its code may use: a Dynamic Worker with globalOutbound: null and scoped methods in env, or a container with Internet off and credentials added by an outbound handler, one per user.

solid answer

~40 s

A Dynamic Worker, loaded through a `worker_loaders` binding with `env.LOADER.load()` or `get(id, callback)`, sees only the `env` you pass; it does not inherit your bindings. Its network does default to yours: omit `globalOutbound` and it inherits the parent's access, while `null` makes `fetch()` and `connect()` throw. Pass a `WorkerEntrypoint` method that holds the token and returns only results. In a container, every process has root's capabilities on the `durable_object` policy, so keep the token out: start with Internet off (the `Container` class defaults `enableInternet` to `true`), then register `interceptOutboundHttps()` with a Worker entrypoint that adds the credential to HTTPS requests. `exec()` takes an argument array with no shell. Give each user or job its own sandbox, named from the authenticated identity, and treat its output as untrusted input.

code

javascript · 36 lines
javascript
import { WorkerEntrypoint } from "cloudflare:workers";

export class Library extends WorkerEntrypoint {
  async lookup(term) {
    return `definition of ${term} for ${this.ctx.props.tenant}`;
  }
}

const GENERATED = `
export default {
  async fetch(request, env) {
    let network;
    try {
      await fetch("https://example.com/");
      network = "reachable";
    } catch (e) {
      network = e.message;
    }
    const text = await env.LIBRARY.lookup("invoice");
    return Response.json({ envKeys: Object.keys(env), text, network });
  },
};`;

export default {
  async fetch(request, env, ctx) {
    const worker = env.LOADER.load({
      compatibilityDate: "2026-10-01",
      mainModule: "task.js",
      modules: { "task.js": GENERATED },
      env: { LIBRARY: ctx.exports.Library({ props: { tenant: "acme" } }) },
      globalOutbound: null,
      limits: { cpuMs: 50, subRequests: 5 },
    });
    return worker.getEntrypoint().fetch("http://sandbox/");
  },
};

go deeper

for a junior

Recall the two sandboxes Cloudflare offers, a Dynamic Worker and a container, and that each should receive only what the code needs.

for a middle

Explain env, globalOutbound and limits for Dynamic Workers, and enableInternet, outbound handlers and exec() argument arrays for containers.

for a senior

Design the credential flow so no token enters the sandbox, scope one sandbox per user or job, and catch the inherit-by-default network setting.

for a principal

Decide which untrusted workloads get Dynamic Workers or containers, and plan around the Sandbox SDK 1.0 beta and the end of 0.x fixes.

## One rule for both sandboxes Cloudflare offers two places for code you did not write and do not trust, such as code a model generated for a customer's document template. A **Dynamic Worker** is a new isolate your Worker loads at runtime from code strings. A **container** is a Linux instance in its own microVM, started by a Durable Object. Isolation keeps that code away from your Worker's memory, but not from anything you hand it. The rule is the same for both: **put in each sandbox only what that code may use, and keep credentials in your Worker.** ## Dynamic Workers A Worker gets the loader through a binding, `"worker_loaders": [{ "binding": "LOADER" }]`, then: - `env.LOADER.load(code)` creates a fresh Dynamic Worker on every call; `env.LOADER.get(id, callback)` lets the runtime reuse a warm one for the same `id`, calling the callback only when it must load the code. - `env` holds only what you pass: structured-clonable values and service bindings, including loopback entrypoints from `ctx.exports` with per-sandbox `props`. The Dynamic Worker does not inherit your Worker's bindings, secrets or data. - `globalOutbound` controls the network. **Omitted, it inherits your Worker's network access**, which usually means the full public Internet. Set to `null`, `fetch()` and `connect()` throw: "This worker is not permitted to access the internet via global functions like fetch()." Set to a service binding, every outbound request goes through your code. - `limits: { cpuMs, subRequests }` lowers the per-invocation limits; a Dynamic Worker that hits one throws. To let generated code use a credential without reading it, pass a method instead of the token. A `WorkerEntrypoint` such as `Library.lookup()` runs in your Worker, uses the token there, checks what it is asked, and returns only the result. ## Containers as sandboxes | Concern | What to do | | --- | --- | | Internet access | Start with it off. The `Container` class defaults `enableInternet` to `true`; with `ctx.container.start(options)`, `enableInternet` is a required option | | Credentials | Keep them out of env vars, files and URLs. Register `interceptOutboundHttps("api.example.com", worker)` so a Worker entrypoint adds the token after the request leaves the container | | Other ports | With Internet on, only ports 80 and 443 pass through handlers and other ports go straight out, which is another reason to keep it off | | Commands | `exec(["converter", inputPath])` starts the executable with an argument array and no shell; a shell runs only when you pass one, such as `["sh", "-c", "..."]` | | Linux users | On the `durable_object` policy, every process has root's capabilities whatever its `user`, so file permissions do not separate code | HTTPS interception requires the container to trust the CA certificate at `/etc/cloudflare/certs/cloudflare-containers-ca.crt`, and a container holds at most 128 intercept entries. Add credentials only to HTTPS requests, since the handler fetches with the scheme the container used. ## Isolation is per sandbox, not per process Everything inside one sandbox is shared: processes read the same files and reach the same `localhost` ports, and modules in one Dynamic Worker share memory. So the sandbox is the unit of trust: 1. Give each user, or each job, its own sandbox. 2. Derive the sandbox's name, the value passed to `getByName()`, from the authenticated identity, never from a URL the caller controls. 3. Never reuse a name or a snapshot across users: a snapshot restores files, including a token written into a repository's config file. 4. Treat results, files and HTTP responses from the sandbox as untrusted input, and serve web previews on a separate hostname so a page cannot use your application's cookies. ## The Sandbox SDK `@cloudflare/sandbox` 1.0 is a small helper library, such as its `Files` class, over a container that your own Durable Object starts with `ctx.container` on the `durable_object` scheduling policy, in public beta. Your class decides lifetime, network access and retries. The 0.x line, whose `Sandbox` class and `getSandbox()` ran their own server in the container, gets bug and security fixes until 2026-12-31. Moving a class to the `durable_object` policy cannot be undone, even with `wrangler rollback`. ## Choosing between the two | | Dynamic Worker | Container | | --- | --- | --- | | Code can use | Only the modules, methods and values you pass | Everything in its Linux image | | Network by default | Inherits your Worker's | Off unless `start()` passes `enableInternet: true`; on for the `Container` class | | Start | Milliseconds, reusable through `get()` | Seconds for a cold start | | You maintain | The method surface | The image | Use a Dynamic Worker when generated JavaScript only needs methods you can define; use a container when it needs Linux tools, child processes or native binaries.

  • Why not pass the API token to a container as an environment variable and trust the code to use it carefully?
    Every process in the sandbox, including any dependency the code installs, can read environment variables, files and command arguments, then send them anywhere the sandbox can reach. Keeping Internet off and adding the token in an outbound handler means the container never holds it, and the handler decides which requests may use it.
  • When would you choose get() over load() for a Dynamic Worker?
    When the same code will run again, such as a tenant's saved plugin. `get(id, callback)` lets the runtime reuse a warm Dynamic Worker for that id and skip loading the code, and it is also cheaper, because each `load()` counts as a new Dynamic Worker for the daily-creation charge. Give each code version its own id, since a changed id or code counts as a new Dynamic Worker.

  • Assumes a Dynamic Worker has no network access unless you grant it.
  • Thinks a Dynamic Worker inherits the parent's bindings and secrets.
  • Puts the API token in the container's environment variables.
  • Relies on a non-root Linux user to keep sandboxed code away from files.
  • Lets the caller choose the sandbox name from a URL parameter.
  • Believes the Container class blocks outbound traffic by default.

Assumes Cloudflare's platform as of 2026-10-10: Dynamic Workers on Workers Paid, Sandbox SDK 1.0 built on the durable_object scheduling policy (public beta), and Sandbox SDK 0.x fixes until 2026-12-31.