Files
cloudflare-os/docs/integration-testing.md
Maximo Guk f32eb12fd7 Let admins open a user's account read-only, audited (#1066)
Builds on #1026. Lets a deployment admin open a user's account
read-only, next to `inspectWorkspace`, with every call recorded in the
audit log and shown in the Audit tab. It answers the questions a
workspace can't: which accounts a user connected and whether their
credentials expired, their model settings, sessions and blueprints.

**Kernel**
- `AdminApi.inspectUser(userId, reason, { lifetimeSeconds })` mints an
`AdminUserView`: `describe`, `listWorkspaces`, `listConnectedAccounts`,
`listModels`, `listSessions`, `listBlueprints`, `getDiagnostics`. It
uses the same level setting (`off` or `metadata`), env cap and lifetime
as a workspace view, and the same call discipline, which now lives in
one place (`admin-view.ts`) and is shared by both views.
- Read-only by construction. The view gets the account's stored values
through a type that leaves out the collections holding gatekeeper stubs,
never calls a gatekeeper, and writes nothing to the account: no session,
no directory sync, no alarm. A user that doesn't exist is refused
without being created.
- What never leaves: session tokens and their hashes, the password hash,
model API tokens, headers and URLs, push subscriptions, pending tickets.
A connected account's name and description and a blueprint's id are
withheld too, so a connected account shows as its id, its vendor and
whether its credentials expired. Those two come back with content reads,
behind a grant; the version that returned them at `full` is kept on
`maximo/admin-user-view-full`.
- A new audit record kind, `user`, with the target user.
`AdminAuditQuery.owner` matches it. The audit table's `CHECK` on `kind`
can't be altered, so the log's constructor rebuilds the table once.
- One caveat, documented: opening a view wakes the account's Durable
Object, and any wake delivers notifications already queued and re-arms a
missing alarm.

**UI**: the Audit tab shows user records as a third kind, User access,
and the Target user column and filter cover them. The access card is
renamed Inspection access, since the one level bounds both views.

Design record: `docs/admin-access.md`.
2026-11-17 01:28:02 -06:00

13 KiB

Integration testing

This is how the integration test suites work, and why they are shaped the way they are.

There are two kinds of suite:

this repo's packages/integration-tests a consumer repo's per-vendor suite
Runs pnpm test (part of CI's normal test job) its own CI step
Gatekeeper a fixture Worker whose verification outcome the tests set a real vendor gatekeeper, unmodified
Covers the overseer's observer logic a genuinely expired credential, end to end
Owns the harness, interceptor, and RPC client that vendor's handlers and token minting

A consumer repo is one that vendors this repo as a public/ submodule and consumes the toolkit as a workspace dependency (public/packages/integration-tests in its pnpm-workspace.yaml).

The second column is what the toolkit is parameterised for: the harness takes a list of gatekeepers and the interceptor takes pluggable handler modules precisely so a suite can be added outside this repo without forking either. One such suite does live here, for GitHub's event hooks (see "A real gatekeeper for its hooks" below): __tests__/github-hooks*.test.ts boot the real gatekeeper-github, unmodified, against the GitHub that __tests__/github-fake.ts answers.

What these tests are

wrangler's createTestHarness() boots workshop-backend and one or more gatekeepers as real Workers in workerd, with their checked-in wrangler.jsonc patched in memory. Tests speak Cap'n Web over a WebSocket to /api — the same transport the browser uses — and serve an ObserverConfigCallback the overseer calls back into.

Nothing is stubbed except outbound HTTP. The consequence worth internalising: the code under test is in another process. Most of what follows falls out of that.

Findings that shape the design

Fake timers cannot work here

vi.useFakeTimers() patches the test process's clock. The code under test reads workerd's clock, out of process, so a faked clock is invisible to it. isTokenExpired()'s 30-second skew is inside gatekeeper-shared and evaluated inside the Worker.

(Fake timers do work for in-isolate unit tests under @cloudflare/vitest-plugin, where the test runs inside the same isolate)

A fixture gatekeeper, not a real one, for the overseer's own logic

The overseer cases need a gatekeeper that refuses an observer on command. Every shipping public gatekeeper can do that only at a cost that would dominate the test:

  • OAuth gatekeepers need a whole vendor auth surface mocked before an account exists at all.
  • The Context Library only refuses once an observation has been recorded, which takes a gadget read session (so a Worker Loader), a slash-command invocation, or an AI-chat catalog snapshot. It is also a singleton, so it can never produce the two simultaneously-failing bindings one of these cases needs.

Adding a test hook to those workers was considered and rejected. A "mark observed" hook would stub the very state the tracker maintains, making the test circular.

So fixtures/gatekeeper-test/ is a real Worker speaking the real protocol, whose verification outcome the tests set over an HTTP control route. It is scoped to overseer logic, not a long-term substitute for per-vendor coverage. Testing actual gatekeepers is the expected trajectory, which is why the harness takes a list of gatekeepers and the interceptor takes pluggable handler modules: a future gatekeeper-google suite is "add google-handlers.ts, point the harness at the package" — the same shape a consumer repo's per-vendor suite takes, with production code unmodified.

A real gatekeeper for its hooks

A gatekeeper's event hooks run through the whole system — a gadget subscribes, the Workshop records the hook and enables it, the gatekeeper adds a webhook, a signed delivery runs the gadget, its write waits for approval, and removing the connection has to clean all of it up — so they are tested with the real gatekeeper-github rather than the fixture. Only GitHub is faked: its OAuth token endpoint, the REST calls the gatekeeper makes, and webhooks that deliver back through the gatekeeper's own route, signed with the secret it configured.

It is booted from a validated tree built before the test files start, as the Workshop's is: @gadgets/github-gatekeeper#build:integration-worker writes it into that package's .wrangler/validate, the test task depends on it, and githubGatekeeper() deletes the config's build so no file rebuilds it under its siblings. It is not in src/worker-inputs.ts, because that table also keys the eval cache, which this gatekeeper doesn't reach: watch mode reruns a hook suite on an edit there only once something else triggers the rerun, which rebuilds it.

Real Context collections for sharing

__tests__/context-sharing.test.ts boots the real gatekeeper-context beside the Workshop and drives both through the public RPC API. Each case creates separate owner and collaborator accounts and an owner-private collection. Listing the collection's discovery metadata must still let the collaborator open the workspace; listing or reading its contents must refuse that open without naming the inaccessible collection. No Context storage, verifier, or observation authorizer is faked.

Both test entrypoints build @gadgets/gatekeeper-context#build:integration-worker (including its management SPA) before files start. The suite disables per-boot rebuilding, and src/worker-inputs.ts tracks Context source/config edits for watch reruns while excluding its generated outputs.

Run just these cases with pnpm --filter @gadgets/integration-tests test:run __tests__/context-sharing.test.ts.

Storage isolation is by convention, because the alternative is worse

server.reset() exists, and measuring it settles the question: ~3 s per call, which is more than an entire suite run. It also restarts the server — server.url becomes undefined and every open WebSocket RPC session dies with "WebSocket connection failed". It is not a storage wipe you can use between tests; it is a teardown.

So storage persists for the harness's lifetime and no test may assume a clean slate. Tests stay independent by taking fresh identities: nextUsernames() from the toolkit, per-test resource URLs, and account labels allocated by the connect/provision helper rather than chosen by the caller.

One corollary that is easy to get wrong: the "nothing escaped to the internet" assertion belongs in afterAll, not afterEach. With it.concurrent, an afterEach fires while siblings are still running, so it would inspect and clear state they are still using — and could discard an escape a sibling was about to be blamed for.

Reconnection helpers must retain the reopened workspace and its child capabilities until the caller finishes using them. Return an owned DisposableStack with stack.move() rather than letting using dispose the workspace before returning a child read session; that workspace owns the native RPC session the child needs. See observer-exclusion.test.ts's reopenAfterRestart().

Reaching a Durable Object's storage from a test

await harness.server.getWorker(name).getDurableObjectStorage(className, { id } | { name }) returns a handle on one Durable Object's SQLite storage, whose exec() resolves to the result rows. { name: "" } addresses the object a Worker reaches with getByName(""). Three uses shape the admin suites:

  • Faulting a store. To show that a call fails when its audit record cannot be written, the suite installs a trigger on admin_audit, the deployment-wide audit log's table (CREATE TRIGGER ... BEFORE INSERT ON admin_audit BEGIN SELECT RAISE(ABORT, ...); END), and drops it afterwards. The insert then fails exactly as a real storage failure would, inside the real Worker, and production code carries no test hook, which would be a switch that disables the audit shipped in every deployment.
  • Proving an object was never written. listDurableObjectIds() cannot tell: it lists every object with a storage file, and any visit creates one (miniflare records the object's name in it) that a deletion leaves behind. What can tell is sqlite_master with miniflare's own __miniflare* tables left out. The Overseer keeps its records in typed storage over the KV API, whose _cf_KV table the first write creates and deleteAll() drops, so whether that table exists says whether anything has been written. _cf_KV itself is unreadable (SQLITE_AUTH), hence sqlite_master. A test client cannot mint an unused workspace id (creating a workspace opens it), so the suite uses a deleted one.
  • Proving a call wrote nothing. SELECT total_changes() through the handle counts every row the object has written since it started, the KV API's records and the alarm included, so equal counts around one call show that the call wrote nothing. The count restarts with the object, so both reads bracket a single call, and the suite checks that an ordinary write moves it. A workspace reports to its owner's account after the call that caused the report has returned, so the user view's suite closes what it opened to seed an account, and waits for the account's count to settle, before its first read.

A redeploy keeps storage, so an upgrade can be tested

server.update() is the opposite of reset(): it reloads the Workers from new configs and keeps every Durable Object, the KV namespaces, the R2 bucket and the server URL. That makes it a deployment of a new version over an old one, which is what Harness.redeployWorkshop() uses it for. It costs about 1.5 s, and it does break every open RPC session, so a test that redeploys starts a harness of its own rather than doing it under its siblings.

What changes between the two builds has to be something a config can express, because the Workshop is built once, before any test file runs. A build-time input qualifies if wrangler's bundler can swap it: bundleBlueprints() points the alias for the Workshop's generated bundled-blueprints module at fixtures/bundled-blueprints.ts, and hands that fixture its list through a define. The installer, and the check that decides whether to run it, are the Workshop's own.

A gatekeeper's main is such an input too, so a gatekeeper can be upgraded from an older release: build:upgrade-base bundles gatekeeper-google as an earlier revision of the repo had it, the Google hooks suite boots that bundle, and upgradeGoogle() (__tests__/google-fake.ts) swaps in this tree's build with deploy(harness.server, current => …), replacing only that Worker's config.

update() resolves at the first reload, not the last. It hands each Worker its new config in turn, and each rebuilds and reloads on its own, so the reload it waited for can be running one Worker's new build beside the other's old one, with a second reload still to come. That second restart breaks the sessions and the requests the test has opened since. So deploy() (src/harness.ts), which Harness.redeployWorkshop() and upgradeGoogle() both go through, gives every Worker's config a mark unique to the update, and waits until each reports it through getWorker(name).getEnv(), the one state no reload can leave half-applied.

wrangler and miniflare versions are coupled

Nothing pins workerd directly: wrangler and miniflare each depend on an exact workerd. The catalog in pnpm-workspace.yaml pins miniflare exactly, to the prerelease the catalog wrangler depends on, and its overrides point @cloudflare/vitest-plugin at those same catalog versions, so the lockfile resolves one Wrangler/Miniflare/workerd stack. Bump wrangler and miniflare together; letting them drift installs a second stack.

A consumer in another repo can end up with two copies of capnweb

A consumer repo installs its own workspace and the public/ submodule's, as two separate pnpm stores. So capnweb resolves to two different copies: the toolkit's rpc-client gets the submodule's, while anything importing capnweb from one of the consumer's own packages gets the other. A stub is only serialisable by the instance that owns the session, so mixing them fails:

TypeError: Cannot serialize value: [object RpcStub]

The trap is that a dev machine where a single pnpm install deduped both will not show this. It first appeared in CI, which runs pnpm install and pnpm --dir public install separately. To reproduce locally, do the same.

The toolkit therefore owns the capnweb boundary: mint callback stubs with stubFor() from rpc-client, never with an imported RpcStub. Importing RpcStub as a type is fine. This is enforced structurally in this repo — the lint rules in vite.config.ts restrict capnweb value imports within this package to rpc-client.ts (allowTypeImports leaves type imports alone). A consumer repo without a linter should treat the rule as a convention its test files follow via stubFor().

Worker entry modules may export only classes and the default handler

workerd treats every named export of the entry module as an entrypoint. Exporting a plain string constant from the fixture produced:

Incorrect type for map entry 'THING_URL_PATTERN': the provided value is not of
type 'function or ExportedHandler'.

Type-only exports are fine (they erase). Anything else has to stay module-private.