From da88528c252f9f9c3436c0a1a015510bf9692c6a Mon Sep 17 00:00:00 2001 From: aron <263346377+aron-cf@users.noreply.github.com> Date: Wed, 3 Jun 2026 14:10:25 +0100 Subject: [PATCH 1/4] [Sandbox] Add guide to document tunnel auth --- .../docs/sandbox/guides/expose-services.mdx | 2 +- .../guides/protect-tunnels-with-access.mdx | 149 ++++++++++++++++++ 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx diff --git a/src/content/docs/sandbox/guides/expose-services.mdx b/src/content/docs/sandbox/guides/expose-services.mdx index db3032671d4..7f8c66c60d8 100644 --- a/src/content/docs/sandbox/guides/expose-services.mdx +++ b/src/content/docs/sandbox/guides/expose-services.mdx @@ -15,7 +15,7 @@ Preview URLs require a custom domain with wildcard DNS routing in production. Se ::: :::note[Alternative: quick tunnels] -If you only need a public URL for development or a `.workers.dev` deployment, [`sandbox.tunnels`](/sandbox/api/tunnels/) returns a `*.trycloudflare.com` URL without DNS setup. For production, follow this guide and use `exposePort()` with a custom domain. +If you only need a public URL for development or a `.workers.dev` deployment, [`sandbox.tunnels`](/sandbox/api/tunnels/) returns a `*.trycloudflare.com` URL without DNS setup. For production, follow this guide and use `exposePort()` with a custom domain. To require authentication on a tunnel before requests reach the sandbox, see [Protect tunnels with Cloudflare Access](/sandbox/guides/protect-tunnels-with-access/). ::: This guide shows you how to expose services running in your sandbox to the internet via preview URLs. diff --git a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx new file mode 100644 index 00000000000..2d2d608f8f5 --- /dev/null +++ b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx @@ -0,0 +1,149 @@ +--- +title: Protect tunnels with Cloudflare Access +pcx_content_type: how-to +sidebar: + order: 8 +description: Lock down a named tunnel created with the Sandbox SDK behind a Cloudflare Access service token. +products: + - sandbox + - cloudflare-one +--- + +import { Render, TypeScriptExample } from "~/components"; + +A [named tunnel](/sandbox/api/tunnels/) created with `sandbox.tunnels.get(port, { name })` resolves to a hostname on a zone in your Cloudflare account (for example, `my-agent-api.example.com`). By default, that hostname is reachable by anyone on the internet. + +This guide shows how to put [Cloudflare Access](/cloudflare-one/access-controls/applications/) in front of that hostname and require callers to present a [service token](/cloudflare-one/access-controls/service-credentials/service-tokens/). After the policy is in place, only clients that send a valid Client ID and Client Secret (or a `CF_Authorization` cookie obtained from them) can reach the sandboxed service. + +:::note[Quick tunnels are out of scope] +Quick tunnels (`*.trycloudflare.com`) cannot be protected with Access because the hostname is not on a zone in your account. To require authentication, use a named tunnel on one of your zones. +::: + +## Before you begin + +You need: + +- A zone in your Cloudflare account that the Worker can create tunnel hostnames under. +- `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`, and `CLOUDFLARE_ZONE_ID` configured as Worker secrets or variables. The API token needs `Account:Cloudflare Tunnel:Edit`, `Zone:DNS:Edit`, and `Zone:Zone:Read` permissions on the zone. +- Cloudflare Access enabled on your account. If this is your first Access application, complete the [Access onboarding](/cloudflare-one/setup/). + +## 1. Create a named tunnel + +Pass a `name` option to `sandbox.tunnels.get()`. The SDK provisions a Cloudflare Tunnel and CNAMEs `.` at it. + + +```ts +import { getSandbox } from "@cloudflare/sandbox"; + +export { Sandbox } from "@cloudflare/sandbox"; + +export default { + async fetch(request: Request, env: Env): Promise { + const sandbox = getSandbox(env.Sandbox, "my-sandbox"); + + await sandbox.startProcess("python -m http.server 8080"); + + const tunnel = await sandbox.tunnels.get(8080, { name: "my-agent-api" }); + // → https://my-agent-api.example.com + + return Response.json({ url: tunnel.url }); + }, +}; +``` + + +`startProcess` resolves when the process starts, not when it is listening. In real code, wait for the port to be ready before calling `tunnels.get()` — see [Expose services](/sandbox/guides/expose-services/) for an example. + +At this point the hostname is live but public. Anyone with the URL can reach the service. Continue to step 2 to lock it down. For production hostnames, create the Access application (steps 2–3) before deploying the Worker that calls `tunnels.get()` so the SDK CNAMEs onto an already-protected hostname. + +## 2. Create a service token + +A service token is a Client ID / Client Secret pair that automated clients send instead of going through an identity provider login. + + + +Store the Client ID and Client Secret as secrets on whichever system will call the tunnel (your CI job, agent runtime, or another Worker). + +## 3. Add a self-hosted Access application + +Create a [self-hosted Access application](/cloudflare-one/access-controls/applications/http-apps/self-hosted-public-app/) for the tunnel hostname, then attach a Service Auth policy that references the token from step 2. + +**Application domain.** You have two options: + +- **Single hostname** — `my-agent-api.example.com`. Protects exactly the one tunnel. +- **Wildcard subdomain** — `*.example.com`. Protects every named tunnel under the zone with a single application. Use this when your Worker creates many tunnels (for example, one per sandbox or per agent session) on the same zone. + +**Policy.** Add a policy with: + +- **Action**: `Service Auth` (see [policy actions](/cloudflare-one/access-controls/policies/#service-auth)). If you use `Allow` here, Access will redirect unauthenticated requests to an identity provider login page instead of returning an error, which is rarely what an automation client wants. +- **Include**: `Service Token` → the token created in step 2. + +Optional: add a second `Allow` policy (for example, `Emails ending in @your-company.com`) so engineers can hit the URL in a browser via the identity provider flow for debugging. + +## 4. Call the tunnel from a client + +Once the policy is in place, requests must carry the service token. Access supports three patterns. + +### Header pair (default) + +Send both headers on every request: + +```sh +curl https://my-agent-api.example.com \ + --header "CF-Access-Client-Id: " \ + --header "CF-Access-Client-Secret: " +``` + +From a Worker or any `fetch`-capable runtime: + + +```ts +const response = await fetch("https://my-agent-api.example.com", { + headers: { + "CF-Access-Client-Id": env.ACCESS_CLIENT_ID, + "CF-Access-Client-Secret": env.ACCESS_CLIENT_SECRET, + }, +}); +``` + + +### Single custom header + +If the calling system can only set one header (for example, a SaaS integration that exposes a single `Authorization` field), configure the Access application to read both values from one header. See [Authenticate with a single header](/cloudflare-one/access-controls/service-credentials/service-tokens/#authenticate-with-a-single-header). + +### Session cookie reuse + +If your Access application has at least one `Allow` policy in addition to Service Auth (see step 3), Access returns a `CF_Authorization` cookie on the first authenticated request, and subsequent requests on the same hostname can send the cookie instead of the headers. Service-Auth-only applications do not honor the cookie — every request must carry the headers. See [Authorization cookie](/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/) and [Subsequent requests](/cloudflare-one/access-controls/service-credentials/service-tokens/#subsequent-requests). + +## 5. Verify + +If the hostname is brand-new, allow a few seconds for DNS and edge TLS provisioning before the first request — a `curl: (6)` or TLS error here means the hostname isn't live yet, not that the Access policy is wrong. + +From a machine without the token: + +```sh +curl --include https://my-agent-api.example.com +``` + +Expect an HTTP `302` redirecting to the Access login page (or `401` if managed OAuth is enabled on the application). + +With the token: + +```sh +curl https://my-agent-api.example.com \ + --header "CF-Access-Client-Id: " \ + --header "CF-Access-Client-Secret: " +``` + +Expect the response from the service running inside the sandbox. + +## Rotation and tear-down + +- **Rotate the service token** — follow [Renew service tokens](/cloudflare-one/access-controls/service-credentials/service-tokens/#renew-service-tokens) and update the secret on every client. +- **Revoke a single client** — a service token is shared by every client that holds it. To revoke one caller individually, issue a separate service token per client and delete only that token. +- **Remove the tunnel** — call `sandbox.tunnels.destroy(port)` from the Worker. Delete the Access application from the dashboard if the hostname is gone for good. If your Access application uses a wildcard subdomain (`*.`), deleting it removes protection from every other named tunnel under that zone — delete only when you are tearing down the wildcard pattern entirely. + +## Caveats + +- Named tunnel hostnames are stable per `{ name }`. The `cloudflared` process inside the container is restarted with the container, but the SDK reuses the existing Cloudflare tunnel and DNS record by name, so the Access application keyed on the hostname is unaffected. +- A service token is a bearer credential. Anyone who holds the Client Secret can reach the application. Store it like any other production secret and rotate it on suspicion of compromise. From d94eaa36b0dfacd73deeaf447ce1cd616811ddc7 Mon Sep 17 00:00:00 2001 From: aron <263346377+aron-cf@users.noreply.github.com> Date: Thu, 4 Jun 2026 09:11:54 +0000 Subject: [PATCH 2/4] [Sandbox] Make tunnel guide startProcess example idempotent Use getProcess() with a stable processId before startProcess() so the Worker fetch handler does not spawn a duplicate server on every request. Also wait for the port to be ready before creating the tunnel. --- .../sandbox/guides/protect-tunnels-with-access.mdx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx index 2d2d608f8f5..10723e601e6 100644 --- a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx +++ b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx @@ -41,7 +41,17 @@ export default { async fetch(request: Request, env: Env): Promise { const sandbox = getSandbox(env.Sandbox, "my-sandbox"); - await sandbox.startProcess("python -m http.server 8080"); + // Start the server only if it is not already running. The Worker's + // fetch handler runs on every request, so guard against spawning + // duplicate processes by checking for an existing one first. + const processId = "http-server"; + let server = await sandbox.getProcess(processId); + if (!server) { + server = await sandbox.startProcess("python -m http.server 8080", { + processId, + }); + } + await server.waitForPort(8080); const tunnel = await sandbox.tunnels.get(8080, { name: "my-agent-api" }); // → https://my-agent-api.example.com @@ -52,7 +62,7 @@ export default { ``` -`startProcess` resolves when the process starts, not when it is listening. In real code, wait for the port to be ready before calling `tunnels.get()` — see [Expose services](/sandbox/guides/expose-services/) for an example. +The `getProcess` check makes the handler idempotent across requests, and `waitForPort` ensures the server is actually listening before the tunnel is created. See [Expose services](/sandbox/guides/expose-services/) for more patterns. At this point the hostname is live but public. Anyone with the URL can reach the service. Continue to step 2 to lock it down. For production hostnames, create the Access application (steps 2–3) before deploying the Worker that calls `tunnels.get()` so the SDK CNAMEs onto an already-protected hostname. From 8042f9f382948a46659a2cc40888ce942871b839 Mon Sep 17 00:00:00 2001 From: aron <263346377+aron-cf@users.noreply.github.com> Date: Thu, 4 Jun 2026 09:18:46 +0000 Subject: [PATCH 3/4] [Sandbox] Address review feedback on Access tunnel guide - Simplify env var bullet to CLOUDFLARE_API_TOKEN and link to Tunnels. - Reorder steps so Access auth (service token, application) is set up before the tunnel is created. - Drop the public-hostname interim paragraph and the editorialising ', which is rarely what an automation client wants' clause. - Reframe Application domain as: create the policy first, then add more domains to the same application. --- .../guides/protect-tunnels-with-access.mdx | 62 +++++++++---------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx index 10723e601e6..c10b7da5867 100644 --- a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx +++ b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx @@ -24,12 +24,38 @@ Quick tunnels (`*.trycloudflare.com`) cannot be protected with Access because th You need: - A zone in your Cloudflare account that the Worker can create tunnel hostnames under. -- `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`, and `CLOUDFLARE_ZONE_ID` configured as Worker secrets or variables. The API token needs `Account:Cloudflare Tunnel:Edit`, `Zone:DNS:Edit`, and `Zone:Zone:Read` permissions on the zone. +- `CLOUDFLARE_API_TOKEN` configured as a Worker secret. See [Tunnels](/sandbox/api/tunnels/) for the required token permissions and other configuration. - Cloudflare Access enabled on your account. If this is your first Access application, complete the [Access onboarding](/cloudflare-one/setup/). -## 1. Create a named tunnel +## 1. Create a service token -Pass a `name` option to `sandbox.tunnels.get()`. The SDK provisions a Cloudflare Tunnel and CNAMEs `.` at it. +A service token is a Client ID / Client Secret pair that automated clients send instead of going through an identity provider login. + + + +Store the Client ID and Client Secret as secrets on whichever system will call the tunnel (your CI job, agent runtime, or another Worker). + +## 2. Add a self-hosted Access application + +Create a [self-hosted Access application](/cloudflare-one/access-controls/applications/http-apps/self-hosted-public-app/) for the tunnel hostname, then attach a Service Auth policy that references the token from step 1. + +**Policy.** Add a policy with: + +- **Action**: `Service Auth` (see [policy actions](/cloudflare-one/access-controls/policies/#service-auth)). If you use `Allow` here, Access will redirect unauthenticated requests to an identity provider login page instead of returning an error. +- **Include**: `Service Token` → the token created in step 1. + +Optional: add a second `Allow` policy (for example, `Emails ending in @your-company.com`) so engineers can hit the URL in a browser via the identity provider flow for debugging. + +**Application domain.** Start with a single hostname, then add more domains to the same application as you create additional tunnels: + +- **Single hostname** — `my-agent-api.example.com`. Protects exactly the one tunnel. +- **Wildcard subdomain** — `*.example.com`. Protects every named tunnel under the zone with a single application. Use this when your Worker creates many tunnels (for example, one per sandbox or per agent session) on the same zone. + +Create the Access application before deploying the Worker that calls `tunnels.get()` so the SDK CNAMEs onto an already-protected hostname. + +## 3. Create a named tunnel + +With the Access application in place, pass a `name` option to `sandbox.tunnels.get()`. The SDK provisions a Cloudflare Tunnel and CNAMEs `.` at it, and the hostname is protected by Access from the first request. ```ts @@ -62,34 +88,6 @@ export default { ``` -The `getProcess` check makes the handler idempotent across requests, and `waitForPort` ensures the server is actually listening before the tunnel is created. See [Expose services](/sandbox/guides/expose-services/) for more patterns. - -At this point the hostname is live but public. Anyone with the URL can reach the service. Continue to step 2 to lock it down. For production hostnames, create the Access application (steps 2–3) before deploying the Worker that calls `tunnels.get()` so the SDK CNAMEs onto an already-protected hostname. - -## 2. Create a service token - -A service token is a Client ID / Client Secret pair that automated clients send instead of going through an identity provider login. - - - -Store the Client ID and Client Secret as secrets on whichever system will call the tunnel (your CI job, agent runtime, or another Worker). - -## 3. Add a self-hosted Access application - -Create a [self-hosted Access application](/cloudflare-one/access-controls/applications/http-apps/self-hosted-public-app/) for the tunnel hostname, then attach a Service Auth policy that references the token from step 2. - -**Application domain.** You have two options: - -- **Single hostname** — `my-agent-api.example.com`. Protects exactly the one tunnel. -- **Wildcard subdomain** — `*.example.com`. Protects every named tunnel under the zone with a single application. Use this when your Worker creates many tunnels (for example, one per sandbox or per agent session) on the same zone. - -**Policy.** Add a policy with: - -- **Action**: `Service Auth` (see [policy actions](/cloudflare-one/access-controls/policies/#service-auth)). If you use `Allow` here, Access will redirect unauthenticated requests to an identity provider login page instead of returning an error, which is rarely what an automation client wants. -- **Include**: `Service Token` → the token created in step 2. - -Optional: add a second `Allow` policy (for example, `Emails ending in @your-company.com`) so engineers can hit the URL in a browser via the identity provider flow for debugging. - ## 4. Call the tunnel from a client Once the policy is in place, requests must carry the service token. Access supports three patterns. @@ -123,7 +121,7 @@ If the calling system can only set one header (for example, a SaaS integration t ### Session cookie reuse -If your Access application has at least one `Allow` policy in addition to Service Auth (see step 3), Access returns a `CF_Authorization` cookie on the first authenticated request, and subsequent requests on the same hostname can send the cookie instead of the headers. Service-Auth-only applications do not honor the cookie — every request must carry the headers. See [Authorization cookie](/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/) and [Subsequent requests](/cloudflare-one/access-controls/service-credentials/service-tokens/#subsequent-requests). +If your Access application has at least one `Allow` policy in addition to Service Auth (see step 2), Access returns a `CF_Authorization` cookie on the first authenticated request, and subsequent requests on the same hostname can send the cookie instead of the headers. Service-Auth-only applications do not honor the cookie — every request must carry the headers. See [Authorization cookie](/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/) and [Subsequent requests](/cloudflare-one/access-controls/service-credentials/service-tokens/#subsequent-requests). ## 5. Verify From 138b6162d49e550c052440d2239a683a6ab8ea19 Mon Sep 17 00:00:00 2001 From: aron <263346377+aron-cf@users.noreply.github.com> Date: Thu, 4 Jun 2026 09:26:06 +0000 Subject: [PATCH 4/4] [Sandbox] Add API example for adding hostnames; use CURL component - Add an APIRequest example showing how to PUT the Access application with an updated destinations array to add a hostname programmatically. - Wrap the verify and header-pair curl snippets in the CURL component to match the convention used elsewhere in the docs. --- .../guides/protect-tunnels-with-access.mdx | 49 +++++++++++++------ 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx index c10b7da5867..d512eb0c451 100644 --- a/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx +++ b/src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx @@ -9,7 +9,7 @@ products: - cloudflare-one --- -import { Render, TypeScriptExample } from "~/components"; +import { APIRequest, CURL, Render, TypeScriptExample } from "~/components"; A [named tunnel](/sandbox/api/tunnels/) created with `sandbox.tunnels.get(port, { name })` resolves to a hostname on a zone in your Cloudflare account (for example, `my-agent-api.example.com`). By default, that hostname is reachable by anyone on the internet. @@ -51,6 +51,23 @@ Optional: add a second `Allow` policy (for example, `Emails ending in @your-comp - **Single hostname** — `my-agent-api.example.com`. Protects exactly the one tunnel. - **Wildcard subdomain** — `*.example.com`. Protects every named tunnel under the zone with a single application. Use this when your Worker creates many tunnels (for example, one per sandbox or per agent session) on the same zone. +To add another hostname to an existing application programmatically, [`GET` the application](/api/resources/zero_trust/subresources/access/subresources/applications/methods/get/) to read its current `destinations`, then `PUT` the full configuration back with the new destination appended: + + + +The request body must include every field returned by the previous `GET` request — fields you omit are reset to their defaults. + Create the Access application before deploying the Worker that calls `tunnels.get()` so the SDK CNAMEs onto an already-protected hostname. ## 3. Create a named tunnel @@ -96,11 +113,13 @@ Once the policy is in place, requests must carry the service token. Access suppo Send both headers on every request: -```sh -curl https://my-agent-api.example.com \ - --header "CF-Access-Client-Id: " \ - --header "CF-Access-Client-Secret: " -``` + From a Worker or any `fetch`-capable runtime: @@ -129,19 +148,19 @@ If the hostname is brand-new, allow a few seconds for DNS and edge TLS provision From a machine without the token: -```sh -curl --include https://my-agent-api.example.com -``` + -Expect an HTTP `302` redirecting to the Access login page (or `401` if managed OAuth is enabled on the application). +Expect an HTTP `302` redirecting to the Access login page (or `401` if managed OAuth is enabled on the application). Add `--include` to see the response headers. With the token: -```sh -curl https://my-agent-api.example.com \ - --header "CF-Access-Client-Id: " \ - --header "CF-Access-Client-Secret: " -``` + Expect the response from the service running inside the sandbox.