diff --git a/src/content/changelog/containers/2026-03-11-outbound-workers.mdx b/src/content/changelog/containers/2026-03-11-outbound-workers.mdx new file mode 100644 index 000000000000000..25889546a34bf12 --- /dev/null +++ b/src/content/changelog/containers/2026-03-11-outbound-workers.mdx @@ -0,0 +1,90 @@ +--- +title: Egress control and improved Workers integration for Containers and Sandboxes +description: Intercept and control outbound HTTP from containers using Workers as programmable egress proxies. +products: + - containers +date: 2026-03-11 +--- + +[Containers](/containers/) and [Sandboxes](/sandbox/) now support outbound Workers — programmable egress proxies that intercept HTTP requests leaving your container. Use them to inject credentials, restrict traffic, add networking observability, or route requests to other Workers bindings, all without modifying code running inside a container. + +## Networking controls + +Allow or deny traffic based on domain, IP, HTTP method, or more. The outbound Worker always runs on the same machine as the container with minimal added latency. + +```js +export class MyApp extends Sandbox { + static outbound = (request, env, ctx) => { + if (request.method !== "GET") { + return new Response("Method Not Allowed", { status: 405 }); + } + return fetch(request); + }; +} +``` + +## Secure auth + +Inject credentials at the egress layer. The untrusted workload never sees the secret. This is especially useful for agentic workloads where you need to give a sandbox access to services without exposing keys to an untrusted workload. + +```js +export class MyApp extends Sandbox { + static outboundByHost = { + "api.internal.example.com": async (request, env, ctx) => { + const headers = new Headers(request.headers); + headers.set("x-auth-token", env.SECRET); + return fetch(new Request(request, { headers })); + }, + }; +} +``` + +## Improved integrations + +Access [Workers bindings](/workers/runtime-apis/bindings/) on hostnames from within a Sandbox or Container. You can now easily +make calls to KV, R2, or other services without manually managing access tokens. + +```js +export class MyApp extends Sandbox { + static outboundByHost = { + "my.kv": async (request, env, ctx) => { + const key = new URL(request.url).pathname.slice(1); + const value = await env.KV.get(key); + return new Response(value ?? "", { status: value ? 200 : 404 }); + }, + }; +} +``` + +## Dynamic proxies + +Use `outboundHandlers` with `setOutboundHandler()` to swap egress policies at runtime. This lets you open the network for setup, then lock it down before running untrusted code. + +```js +export class MyApp extends Sandbox { + static outboundHandlers = { + allowHosts: async (request, env, ctx) => { + const { hostname } = new URL(request.url); + return ctx.params.allowedHostnames.includes(hostname) + ? fetch(request) + : new Response("Forbidden", { status: 403 }); + }, + blockAll: async () => new Response("Forbidden", { status: 403 }), + }; +} + +// In your Worker +const sandbox = await env.SANDBOX.getByName("agent-session"); +await sandbox.setOutboundHandler("allowHosts", { + allowedHostnames: ["registry.npmjs.org", "github.com"], +}); +await sandbox.exec("npm install"); +await sandbox.setOutboundHandler("blockAll"); +``` + +:::note[TLS support coming soon] +Outbound Workers currently intercept HTTP traffic only. HTTPS interception requires a platform-managed certificate authority to decrypt and re-encrypt traffic. This is in progress and will be documented when available. Until then, to force all traffic through an outbound Worker, you can set `enableInternet: false` and use `outbound` +to intercept all traffic, and optionally upgrade to TLS from inside the Worker. +::: + +Refer to [Outbound Workers](/containers/platform-details/outbound-workers/) for full documentation and examples. diff --git a/src/content/docs/containers/platform-details/outbound-workers.mdx b/src/content/docs/containers/platform-details/outbound-workers.mdx new file mode 100644 index 000000000000000..203a6f0a5c9d78b --- /dev/null +++ b/src/content/docs/containers/platform-details/outbound-workers.mdx @@ -0,0 +1,205 @@ +--- +title: Outbound Workers +pcx_content_type: concept +sidebar: + order: 50 +description: Intercept and control outbound HTTP from containers using Workers. +--- + +import { TypeScriptExample, Render } from "~/components"; + +Outbound Workers are Workers that intercept HTTP requests made by your container. They act as programmable egress proxies, running on the same machine as the container with access to all Workers bindings. + +Use outbound Workers to: + +- Inject credentials or headers without exposing secrets to untrusted code +- Log or audit outbound requests +- Restrict which methods or domains are allowed +- Route requests to internal Workers bindings (KV, R2, Durable Objects, etc.) +- Swap egress policies at runtime + +:::note[TLS support coming soon] +Outbound Workers currently intercept HTTP traffic only. HTTPS interception requires a platform-managed certificate authority to decrypt and re-encrypt traffic. This is in progress and will be documented when available. Until then, to force all traffic through an outbound Worker, you can set `enableInternet: false` and use `outbound` +to intercept all traffic, and optionally upgrade to TLS from inside the Worker. +::: + +## Define an outbound handler + +Use `outbound` to intercept all outbound HTTP traffic regardless of destination: + +```js +import { Container } from "@cloudflare/containers"; + +export class MyContainer extends Container { + static outbound = (request, env, ctx) => { + if (request.method !== "GET") { + console.log(`Blocked ${request.method} to ${request.url}`); + return new Response("Method Not Allowed", { status: 405 }); + } + return fetch(request); + }; +} +``` + +Use `outboundByHost` to map specific domain names or IP addresses to handler functions: + +```js +import { Container } from "@cloudflare/containers"; + +export class MyContainer extends Container { + static outboundByHost = { + "api.internal.example.com": async (request, env, ctx) => { + const headers = new Headers(request.headers); + headers.set("x-auth-token", env.SECRET); + return fetch(new Request(request, { headers })); + }, + }; +} +``` + +Any HTTP request from the container to `api.internal.example.com` is routed through the handler. The secret is injected by the Worker — the container code never has access to it. + + + +If you define both, `outboundByHost` handlers take precedence over the catch-all `outbound` handler. + +## Use Workers bindings in handlers + +Outbound Workers have full access to your Worker's bindings. This lets you route container traffic to internal platform resources without managing API credentials. + +```js +export class MyContainer extends Container { + static outboundByHost = { + "my.kv": async (request, env, ctx) => { + const url = new URL(request.url); + const key = url.pathname.slice(1); + const value = await env.KV.get(key); + return new Response(value); + }, + "my.r2": async (request, env, ctx) => { + const url = new URL(request.url); + // Scope access to this container's ID + const path = `${ctx.containerId}${url.pathname}`; + const object = await env.R2.get(path); + return new Response(object?.body ?? null, { status: object ? 200 : 404 }); + }, + }; +} +``` + +The container calls `http://my.kv/some-key` and the outbound handler resolves it using the KV binding. No credentials leave the Worker. + +## Apply per-instance rules + +The `ctx` argument exposes `containerId`, which lets you apply different rules per sandbox or container instance. + +```js +"api.internal.example.com": async (request, env, ctx) => { + const authKey = await env.KEYS.get(ctx.containerId); + if (!authKey) { + return new Response("Forbidden", { status: 403 }); + } + const headers = new Headers(request.headers); + headers.set("x-auth-token", authKey); + return fetch(new Request(request, { headers })); +}, +``` + +## Change policies at runtime + +Use `outboundHandlers` to define named egress policies, then swap them at runtime using `setOutboundHandler()`. Each policy accepts a `params` object so you can configure behavior from code. + +```js +export class MyContainer extends Container { + static outboundHandlers = { + allowHosts: async (request, env, ctx) => { + const url = new URL(request.url); + if (ctx.params.allowedHostnames.includes(url.hostname)) { + return fetch(request); + } + return new Response("Forbidden", { status: 403 }); + }, + + blockAll: async () => { + return new Response("Forbidden", { status: 403 }); + }, + }; +} +``` + +Apply policies programmatically from your Worker: + +```js +async setUpContainer(req, env) { + const container = await env.MY_CONTAINER.getByName("my-instance"); + + // Allow package registries during setup + await container.setOutboundHandler("allowHosts", { + allowedHostnames: ["registry.npmjs.org", "github.com"], + }); + + await container.exec("npm install"); + + // Lock down egress once dependencies are installed + await container.setOutboundHandler("blockAll"); +} +``` + +You can also manage `outboundByHost` rules on a running instance: + +```js +// Set a handler for a specific host +await container.setOutboundByHost("api.example.com", "myHandler"); + +// Set handlers for multiple hosts at once +await container.setOutboundByHosts({ + "api.example.com": "myHandler", + "cdn.example.com": "allowAll", +}); + +// Remove a host-specific handler (falls back to outbound catch-all, if set) +await container.removeOutboundByHost("api.example.com"); +``` + +## Low-level API + +To configure outbound interception directly on `ctx.container`, use `interceptOutboundHttp` for a specific IP or CIDR range, or `interceptAllOutboundHttp` for all traffic. Both accept a `WorkerEntrypoint`. + +```js +import { WorkerEntrypoint } from "cloudflare:workers"; + +export class MyOutboundWorker extends WorkerEntrypoint { + fetch(request) { + // Inspect, modify, or deny the request + return fetch(request); + } +} + +// Inside your Container DurableObject +this.ctx.container.start({ enableInternet: false }); +const worker = this.ctx.exports.MyOutboundWorker(); +await this.ctx.container.interceptAllOutboundHttp(worker); +``` + +You can call these methods before or after starting the container, and even while connections are open. In-flight TCP connections pick up the new handler automatically — no connections are dropped. + +```js +// Intercept a specific CIDR range +await this.ctx.container.interceptOutboundHttp("203.0.113.0/24", worker); + +// Update the handler while the container is running +const updated = this.ctx.exports.MyOutboundWorker({ + props: { phase: "post-install" }, +}); +await this.ctx.container.interceptOutboundHttp("203.0.113.0/24", updated); +``` + +## Local development + +`wrangler dev` supports outbound interception. A sidecar process ([`proxy-everything`](https://github.com/cloudflare/proxy-everything)) is spawned inside the container's network namespace. It applies `TPROXY` rules to route matching traffic to the local Workerd instance, mirroring production behavior. + +## Related resources + +- [Outbound Workers for Sandboxes](/sandbox/guides/outbound-workers/) — Sandbox SDK API for outbound handlers +- [Environment variables and secrets](/containers/platform-details/environment-variables/) — Store credentials for use in handlers +- [Durable Object interface](/durable-objects/api/container/) — Full `ctx.container` API reference diff --git a/src/content/docs/durable-objects/api/container.mdx b/src/content/docs/durable-objects/api/container.mdx index 5ccfe2410386b68..bfa6684e9d18999 100644 --- a/src/content/docs/durable-objects/api/container.mdx +++ b/src/content/docs/durable-objects/api/container.mdx @@ -39,7 +39,7 @@ export class MyDurableObject extends DurableObject { } -``` +```` @@ -51,7 +51,7 @@ export class MyDurableObject extends DurableObject { ```js this.ctx.container.running; -``` +```` ## Methods @@ -127,17 +127,17 @@ const res = await port.fetch("http://container/set-state", { ``` ```js -const conn = this.ctx.container.getTcpPort(8080).connect('10.0.0.1:8080'); +const conn = this.ctx.container.getTcpPort(8080).connect("10.0.0.1:8080"); await conn.opened; try { - if (request.body) { - await request.body.pipeTo(conn.writable); - } - return new Response(conn.readable); + if (request.body) { + await request.body.pipeTo(conn.writable); + } + return new Response(conn.readable); } catch (err) { - console.error("Request body piping failed:", err); - return new Response("Failed to proxy request body", { status: 502 }); + console.error("Request body piping failed:", err); + return new Response("Failed to proxy request body", { status: 502 }); } ``` @@ -181,7 +181,66 @@ class MyContainer extends DurableObject { - A promise that resolves when the container exits. +### `interceptOutboundHttp` + +`interceptOutboundHttp` routes outbound HTTP requests matching an IP address, IP:port, or CIDR range through a `WorkerEntrypoint`. Can be called before or after starting the container. Open connections pick up the new handler without being dropped. + +```js +const worker = this.ctx.exports.MyWorker({ props: { message: "hello" } }); +await this.ctx.container.interceptOutboundHttp("15.0.0.1:80", worker); + +// CIDRs are also supported (IPv4 and IPv6) +await this.ctx.container.interceptOutboundHttp("123.123.123.123/23", worker); +``` + +#### Parameters + +- `target` (string): An IP address, IP:port, or CIDR range to match. +- `worker` (WorkerEntrypoint): A `WorkerEntrypoint` instance to handle matching requests. + +#### Return values + +- None. + +### `interceptAllOutboundHttp` + +`interceptAllOutboundHttp` routes all outbound HTTP requests from the container through a `WorkerEntrypoint`, regardless of destination. + +```js +const worker = this.ctx.exports.MyWorker(); +await this.ctx.container.interceptAllOutboundHttp(worker); +``` + +#### Parameters + +- `worker` (WorkerEntrypoint): A `WorkerEntrypoint` instance to handle all outbound HTTP requests. + +#### Return values + +- None. + +### `interceptAllOutboundHttp` + +`interceptAllOutboundHttp` routes all outbound HTTP requests from the container through a `WorkerEntrypoint`, regardless of destination. Use this when you want a single handler for all egress traffic. + +```js +const outboundWorker = this.ctx.exports.MyWorker({ + props: { message: "hello" }, +}); +await this.ctx.container.interceptAllOutboundHttp(outboundWorker); +``` + +Like `interceptOutboundHttp`, this method can be called at any time and updates in-flight connections without dropping them. + +#### Parameters + +- `worker` (WorkerEntrypoint): A `WorkerEntrypoint` instance to handle all outbound HTTP requests. + +#### Return values + +- A promise that resolves once the intercept rule is installed. + ## Related resources - [Containers](/containers) -- [Get Started With Containers](/containers/get-started) \ No newline at end of file +- [Get Started With Containers](/containers/get-started) diff --git a/src/content/docs/sandbox/guides/outbound-workers.mdx b/src/content/docs/sandbox/guides/outbound-workers.mdx new file mode 100644 index 000000000000000..dc0c4134bce1293 --- /dev/null +++ b/src/content/docs/sandbox/guides/outbound-workers.mdx @@ -0,0 +1,179 @@ +--- +title: Control outbound traffic +pcx_content_type: how-to +sidebar: + order: 16 +description: Intercept, modify, and restrict outbound HTTP from sandboxes using Workers. +--- + +import { TypeScriptExample, Render } from "~/components"; + +Outbound Workers intercept HTTP requests made by code running inside a sandbox. They run on the same machine as the sandbox and have full access to your Worker's bindings. + +Use outbound Workers to: + +- Inject credentials without exposing secrets to untrusted code or the LLM +- Log or audit every outbound request +- Restrict which domains or HTTP methods are allowed +- Route sandbox requests to internal Workers bindings (KV, R2, other Workers) +- Swap egress policies at runtime + +:::note[HTTP only] +Outbound Workers currently intercept HTTP traffic only. HTTPS interception is not yet supported. Set `enableInternet: false` and allow only proxied HTTP traffic until TLS support is available. +::: + +## Define an outbound handler + +Use `outbound` to intercept all outbound HTTP traffic regardless of destination: + + +```ts +import { Sandbox } from "@cloudflare/sandbox"; + +export class MySandbox extends Sandbox { + static outbound = (request: Request, env: Env, ctx: OutboundHandlerContext) => { + if (request.method !== "GET") { + console.log(`Blocked ${request.method} to ${request.url}`); + return new Response("Method Not Allowed", { status: 405 }); + } + return fetch(request); + }; +} +``` + + +Use `outboundByHost` to map specific domain names or IP addresses to handler functions. Each handler receives the outbound `Request`, the Worker `env`, and a `ctx` object with `containerId`. + + +```ts +import { Sandbox } from "@cloudflare/sandbox"; + +export class MySandbox extends Sandbox { + static outboundByHost = { + "api.internal.example.com": async (request: Request, env: Env, ctx: OutboundHandlerContext) => { + const headers = new Headers(request.headers); + headers.set("x-auth-token", env.SECRET); + return fetch(new Request(request, { headers })); + }, + }; +} +``` + + +Any HTTP request from the sandbox to `api.internal.example.com` is routed through the handler. The secret is injected by the Worker — the sandbox code never has access to it. + + + +If you define both, `outboundByHost` handlers take precedence over the catch-all `outbound` handler. + +## Inject credentials per sandbox instance + +The `ctx` argument exposes `containerId`, which lets you apply different credentials per sandbox. This is useful when each user or agent session should have distinct access. + + +```ts +export class MySandbox extends Sandbox { + static outboundByHost = { + "api.internal.example.com": async (request: Request, env: Env, ctx: { containerId: string }) => { + // Look up per-instance credentials (KV is encrypted at rest and in transit) + const authKey = await env.KEYS.get(ctx.containerId); + if (!authKey) { + return new Response("Forbidden", { status: 403 }); + } + const headers = new Headers(request.headers); + headers.set("x-auth-token", authKey); + return fetch(new Request(request, { headers })); + }, + }; +} +``` + + +## Route traffic to Workers bindings + +Outbound Workers have full access to your Worker's bindings. Route sandbox traffic to internal platform resources without exposing credentials to the sandbox. + + +```ts +export class MySandbox extends Sandbox { + static outboundByHost = { + // Handle requests to http://my.kv/ + "my.kv": async (request: Request, env: Env, ctx: OutboundHandlerContext) => { + const url = new URL(request.url); + const key = url.pathname.slice(1); + const value = await env.KV.get(key); + return new Response(value ?? "", { status: value ? 200 : 404 }); + }, + // Handle requests to http://my.r2/, scoped to this instance + "my.r2": async (request: Request, env: Env, ctx: { containerId: string }) => { + const url = new URL(request.url); + const path = `${ctx.containerId}${url.pathname}`; + const object = await env.R2.get(path); + return new Response(object?.body ?? null, { status: object ? 200 : 404 }); + }, + }; +} +``` + + +The sandbox calls `http://my.kv/config-key` and the outbound handler resolves it using the KV binding. No API credentials ever reach the untrusted sandbox. + +## Change policies at runtime + +Use `outboundHandlers` to define named egress policies. Call `setOutboundHandler()` to swap policies at any point in the sandbox lifecycle — for example, allow package registries during setup, then lock down egress once dependencies are installed. + + +```ts +import { Sandbox, getSandbox } from "@cloudflare/sandbox"; + +export class MySandbox extends Sandbox { + static outboundHandlers = { + allowHosts: async (request: Request, env: Env, ctx: { allowedHostnames: string[] }) => { + const url = new URL(request.url); + if (ctx.params.allowedHostnames.includes(url.hostname)) { + return fetch(request); + } + return new Response("Forbidden", { status: 403 }); + }, + + blockAll: async () => { + return new Response("Forbidden", { status: 403 }); + }, + +}; +} + +export default { + async fetch(request: Request, env: Env) { + const sandbox = getSandbox(env.Sandbox, "agent-session"); + + // Open package registries during dependency installation + await sandbox.setOutboundHandler("allowHosts", { + allowedHostnames: ["registry.npmjs.org", "github.com"], + }); + await sandbox.exec("npm install"); + + // Lock down egress before running untrusted code + await sandbox.setOutboundHandler("blockAll"); + await sandbox.exec("node user-script.js"); + + return new Response("Done"); + +}, +}; + +``` + + +## How it works + +All outbound Workers run on the same machine as the sandbox VM, so additional latency is minimal. Workers logs and observability apply to outbound handler traffic, and handlers can be swapped at runtime without dropping open TCP connections. + +In local development, `wrangler dev` mirrors this behavior using a sidecar process ([`proxy-everything`](https://github.com/cloudflare/proxy-everything)) that runs inside the container's network namespace and applies `TPROXY` rules to steer matching traffic to the local Workerd instance. + +## Related resources + +- [Outbound Workers for Containers](/containers/platform-details/outbound-workers/) — Low-level `ctx.container` API +- [Sandbox options](/sandbox/configuration/sandbox-options/) — Configure sandbox behavior +- [Environment variables](/sandbox/configuration/environment-variables/) — Store secrets for use in handlers +``` diff --git a/src/content/partials/containers/outbound-by-host-dns-note.mdx b/src/content/partials/containers/outbound-by-host-dns-note.mdx new file mode 100644 index 000000000000000..034b041ef7de240 --- /dev/null +++ b/src/content/partials/containers/outbound-by-host-dns-note.mdx @@ -0,0 +1,5 @@ +:::note[DNS not available with enableInternet: false] +When `enableInternet` is set to `false`, DNS is not available inside the container. To make outbound requests by domain name via `outboundByHost`, add the domain to `/etc/hosts` with the target IP, or make requests directly to the IP and set a `Host` header instead. + +DNS-only egress (without full internet access) is coming soon, which will remove this requirement. +:::