Files
Kenton VardaandClaude Fable 5.2 88f6190d7a Let gadgets, executeCode and gatekeepers fetch under one policy (#1211)
Agents can fetch web pages with the `webFetch` tool, but `fetch()` in
gadget server code and in `executeCode` was blocked outright. A
gatekeeper that hosts untrusted code somewhere else, such as a
container, also had no way to apply the workspace's rules to that code's
egress. This PR lets all three reach the web under the policy `webFetch`
already enforced, and puts that policy in one place so it can grow (a
list of hosts known to be safe, for example) without its callers
changing.

## Design

**One `Fetcher` holds the policy.** A new loopback entrypoint,
`FetchLoopback`, is the only thing that sends these requests. The
`webFetch` tool goes through it, gadget and `executeCode` sandboxes get
it as their `globalOutbound`, and gatekeepers get one from
`ApprovalQueue.getFetcher()`. Callers never see the policy's shape.

**The policy is what `webFetch` had.** An unrestricted workspace may
fetch any public `https:` host. One that has observed restricted data
may fetch only the admin's trusted hosts, with no query string and no
`/cdn-cgi/` path. Where the admin allows approvals, an agent's refused
URL posts the existing `webFetchRequest` card and ends its turn.

**Two modes, because of who can go stale.**
- A gatekeeper's `Fetcher` carries a snapshot of the policy and decides
locally, so a container on another machine filters its egress with no
round trip to the workspace. The snapshot never updates or expires.
Restricted data can reach what the `Fetcher` filters only through a call
to the gatekeeper, so the contract is that the gatekeeper takes a fresh
one before new workspace data flows in. A long-running container that
has received nothing new has nothing new to leak.
- The kernel's own sandboxes cannot work that way. Code in one
`executeCode` call can read restricted data through a binding and call
`fetch()` on the next line, and a gadget's worker is cached across
calls. Their `Fetcher` carries no snapshot and asks the workspace on
every request.

**Requests are GET and HEAD only, with no credentials.** The `Fetcher`
builds a new request from the method, the URL and a short allowlist of
headers, which also rules out WebSocket upgrades. In a restricted
workspace it forwards none of the caller's headers: a header's value is
a channel for the data the policy is holding back, and a user's approval
names a URL, not what travels with it.

**Refusals are responses, not exceptions.** A refusal is a 403 (405 for
the method) with the reason in the body and a
`Cloudflare-OS-Fetch-Refused` header, so a container's HTTP client and
JS code see the same thing.

**Redirects are checked hop by hop.** The `Fetcher` returns a 3xx to its
caller, whose next hop comes back through it. The exception is a URL a
user approved, whose redirects the `Fetcher` follows itself, because an
approval covers them.

## Behaviour changes to `webFetch`

- A redirect to a host the policy refuses now asks for approval, where
approvals are on. It used to fail.
- The audit record is written when each hop is allowed, so it no longer
carries the status, content type or body length. It means "allowed", not
"succeeded".
- The `user-agent` is `Cloudflare-OS/1.0`, replacing
`GadgetsWebFetch/1.0`.
- A turn now ends whenever a step captured a decision request, decided
in `finishTurn`. That replaces the separate latches in the `webFetch`
tool and `requestConnection`, and is what makes an `executeCode` fetch
that asks for approval end the turn.

## Reviewing

The commits are ordered so each kernel diff reads on its own: the
entrypoint and `authorizeFetch()` with `webFetch` moved onto them, then
the sandboxes and agent prompts, then `getFetcher()` and snapshots, then
the test gatekeeper fixture, then docs. `docs/unified-fetch.md`
describes the design as built, `plans/unified-fetch.md` records the
decisions and where the implementation departed from the plan, and the
`write-gatekeeper` skill has the contract for gatekeeper authors.

Limits worth knowing: there is no rate limit on sandbox fetches;
requests a snapshot allows are not recorded by the workspace, so a
gatekeeper audits its own calls; and a caller with no agent turn to end
(a mainline gadget, a hook firing) is refused where an agent would be
asked.

The internal repository's gatekeepers and fake queues will need
`getFetcher()` once this lands there.

## Manual check

Beyond the test suites, one agent turn was run through `pnpm cf-os api`
against `pnpm dev-server`: its `executeCode` call fetched
`https://example.com/` (200), its POST came back 405, and the fetch
appeared in the action log.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 11:39:51 -06:00

6.4 KiB

Running tests

Use this guide when running cold-checkout tests or investigating a slow or hung suite. For the cross-Worker harness and its isolation rules, see integration testing.

Entry points

  • pnpm --filter <package> test:run: the direct route, useful while iterating: Vitest, or node --test for packages/api-cli.
  • pnpm exec vp run -F <package> test: cached task route; unchanged results may replay.
  • pnpm test: workspace verification, including the scripts/ and packages/api-cli suites, which run under node --test rather than Vitest.
  • pnpm lint: lint, script types, generated-config checks, and workspace build/type-checks.

A direct test:run script does not execute a task's dependsOn. When tests import generated files, both entrypoints must request codegen; verify without a root prebuild or prepared snapshot.

Backend unit tests use inline Miniflare bindings, not the full deployment configuration. Tests that read admin settings, including fetchPolicy() in a restricted workspace (through authorizeFetch() or getFetcher()), must provide a BLUEPRINTS.get fixture; returning null selects the default configuration. Assert async refusals with an awaited .rejects.toThrow(...), not a synchronous .toThrow(...).

Workspace-restart integration tests must accept either a pending-restart refusal or an already-broken RPC session. Match the pending-restart code or the same failure reported by that stub's onRpcBroken(), not error wording or an arbitrary rejection. Assert that old capabilities return no data and a replacement session re-verifies; do not race the transient error code against the scheduled abort.

For tests that advance time within a daily budget, pin the fake clock to a fixed UTC time before seeding credentials and counters. Advancing from the wall clock can cross midnight and legitimately reset the budget; test that rollover separately from cache expiry or limit enforcement.

Workshop's browser tests need Chromium installed once with pnpm --filter @gadgets/workshop-frontend exec playwright install chromium (CI adds --with-deps for the system libraries). Run them separately with pnpm --filter @gadgets/workshop-frontend test:run:browser. The workshop-evals unit tests run views in that Chromium too, through Playwright, so they need the same install. So does gatekeeper-kit's connect-form test (connect-form-browser.test.ts), which submits the pasted-key form from a real page, because what a browser sends as Origin depends on the page's Referrer-Policy.

Watchdog policy

Shared test tasks use scripts/with-timeout.ts: 60 seconds without output and 900 seconds (15 minutes) total. The total allowance supports healthy runs on slower machines, including cloud containers, without requiring a special invocation. Idle detection remains unchanged; a hung command that continues printing output can take five minutes longer to terminate than with the previous ten-minute cap.

Import-heavy backend unit tests use a 120-second idle allowance, and the workshop-evals unit tests a 240-second one: evals/chat-views.test.ts reports only when it ends, and took 114 seconds on CI on 2026-11-09. These process-level watchdogs are separate from Vitest's per-test limits and Linux Container execution deadlines. Google test projects allow 15 seconds per test.

For a run that needs more time than these defaults, explicitly override the relevant bounds:

TESTS_WITH_TIMEOUT_IDLE_SECONDS=1800 TESTS_WITH_TIMEOUT_MAX_SECONDS=1800 pnpm test

Each override accepts positive, finite seconds and supersedes its corresponding command-line threshold. An omitted override retains that command's default; malformed values fail before the command starts. Cached tasks forward and fingerprint the overrides, so results from a different policy are not reused. The direct Vitest route does not use this shared watchdog.

TESTS_WITH_TIMEOUT_DISABLE=1 retains its existing meaning: disable both watchdogs, not process cleanup. Prefer bounded overrides; disable only when an outer job or operator supplies the bound. A timeout exits 124 and names the idle/total limit, command, and surviving process tree. Exit 137 alone does not prove OOM; inspect the primary failure and available memory diagnostics.

Workerd and resource pressure

The root test launcher computes task concurrency and a Vitest worker budget in scripts/vp/concurrency.ts. Workerd fleets can dominate memory usage; avoid simultaneously running independent workspace-wide test launchers. Set VITEST_MAX_WORKERS for direct Vitest runs when needed; cached tasks forward it without changing the result fingerprint.

Do not remove scripts/assert-workerd.ts from suites that require workerd: it prevents a failed pool from appearing to pass under Node. On a Mac, prevent idle sleep for the duration of a benchmark (caffeinate -is <command>) before interpreting wall-clock timeout results.

Local instances

  • pnpm run-local --port <n> serves the built frontend from the backend's own origin, so it runs beside another checkout's servers with nothing on :3000, and connect handoffs follow the port. It builds the frontend first and has no hot reload. For UI work, run PUBLIC_BASE_URL=http://localhost:<m> pnpm dev-server --port <n> and VITE_BACKEND_HOST=localhost:<n> pnpm --filter @gadgets/workshop-frontend exec vite --port <m> --strictPort.
  • Point pnpm cf-os api at it with CFOS_API_URL=http://localhost:<n>; it defaults to :8787.
  • A repo-root .dev.vars is loaded automatically; values already in the shell win.
  • AI Gateway mode needs CF_AI_GATEWAY, CF_AI_GATEWAY_ACCOUNT_ID, CF_AI_GATEWAY_PROVIDERS (cloudflare for @cf/* models) and a transport: --use-workers-ai-binding, which needs a Wrangler login (set CLOUDFLARE_ACCOUNT_ID if it has several accounts), or CF_AI_GATEWAY_API_TOKEN with CF_AI_GATEWAY_USE_BINDING=false. Listing models and changing admin model settings send nothing to the gateway, so placeholder values are enough for them.
  • workshop-backend's test:run runs Vitest twice, unit then integration, so a file argument only reaches the integration run. For one unit file, run the script's two build steps, then pnpm exec vitest run <file> in packages/workshop-backend.
  • To see what a request sent to a model, read the AI Gateway logs, or add a temporary log in the payload hook (onPayload in ai-models.ts) and revert it before committing.