-
Notifications
You must be signed in to change notification settings - Fork 14.9k
[Sandbox] Add guide to document tunnel auth #31229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
aron-cf
wants to merge
4
commits into
production
Choose a base branch
from
sandbox-tunnel-auth
base: production
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
da88528
[Sandbox] Add guide to document tunnel auth
aron-cf d94eaa3
[Sandbox] Make tunnel guide startProcess example idempotent
aron-cf 8042f9f
[Sandbox] Address review feedback on Access tunnel guide
aron-cf 138b616
[Sandbox] Add API example for adding hostnames; use CURL component
aron-cf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
176 changes: 176 additions & 0 deletions
176
src/content/docs/sandbox/guides/protect-tunnels-with-access.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,176 @@ | ||||||
| --- | ||||||
| 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 { 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. | ||||||
|
|
||||||
| 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` 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 service token | ||||||
|
|
||||||
| A service token is a Client ID / Client Secret pair that automated clients send instead of going through an identity provider login. | ||||||
|
|
||||||
| <Render file="access/create-service-token" product="cloudflare-one" /> | ||||||
|
|
||||||
| 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. | ||||||
|
|
||||||
| 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: | ||||||
|
|
||||||
| <APIRequest | ||||||
| path="/accounts/{account_id}/access/apps/{app_id}" | ||||||
| method="PUT" | ||||||
| json={{ | ||||||
| name: "Sandbox tunnels", | ||||||
| type: "self_hosted", | ||||||
| destinations: [ | ||||||
| { type: "public", uri: "my-agent-api.example.com" }, | ||||||
| { type: "public", uri: "another-tunnel.example.com" }, | ||||||
| ], | ||||||
| }} | ||||||
| /> | ||||||
|
|
||||||
| 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 | ||||||
|
|
||||||
| With the Access application in place, pass a `name` option to `sandbox.tunnels.get()`. The SDK provisions a Cloudflare Tunnel and CNAMEs `<name>.<your-zone>` at it, and the hostname is protected by Access from the first request. | ||||||
|
|
||||||
| <TypeScriptExample> | ||||||
| ```ts | ||||||
| import { getSandbox } from "@cloudflare/sandbox"; | ||||||
|
|
||||||
| export { Sandbox } from "@cloudflare/sandbox"; | ||||||
|
|
||||||
| export default { | ||||||
| async fetch(request: Request, env: Env): Promise<Response> { | ||||||
| const sandbox = getSandbox(env.Sandbox, "my-sandbox"); | ||||||
|
|
||||||
| // 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 | ||||||
|
|
||||||
| return Response.json({ url: tunnel.url }); | ||||||
| }, | ||||||
| }; | ||||||
| ``` | ||||||
| </TypeScriptExample> | ||||||
|
|
||||||
| ## 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: | ||||||
|
|
||||||
| <CURL | ||||||
| url="https://my-agent-api.example.com" | ||||||
| headers={{ | ||||||
| "CF-Access-Client-Id": "$CF_ACCESS_CLIENT_ID", | ||||||
| "CF-Access-Client-Secret": "$CF_ACCESS_CLIENT_SECRET", | ||||||
| }} | ||||||
| /> | ||||||
|
|
||||||
| From a Worker or any `fetch`-capable runtime: | ||||||
|
|
||||||
| <TypeScriptExample> | ||||||
| ```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, | ||||||
| }, | ||||||
| }); | ||||||
| ``` | ||||||
| </TypeScriptExample> | ||||||
|
|
||||||
| ### 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). | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use 'Refer to' instead of 'See':
Suggested change
|
||||||
|
|
||||||
| ### Session cookie reuse | ||||||
|
|
||||||
| 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 | ||||||
|
|
||||||
| 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: | ||||||
|
|
||||||
| <CURL url="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). Add `--include` to see the response headers. | ||||||
|
|
||||||
| With the token: | ||||||
|
|
||||||
| <CURL | ||||||
| url="https://my-agent-api.example.com" | ||||||
| headers={{ | ||||||
| "CF-Access-Client-Id": "$CF_ACCESS_CLIENT_ID", | ||||||
| "CF-Access-Client-Secret": "$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 (`*.<your-zone>`), 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. | ||||||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use 'refer to' instead of 'see':