Skip to content

Call the API through a service binding that names the visitor - #450

Merged
neuromechanist merged 15 commits into
stagingfrom
feature/issue-449-api-service-binding
Oct 12, 2026
Merged

neuromechanist merged 15 commits into
stagingfrom
feature/issue-449-api-service-binding

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Part of #449. Depends on nemar-cli#1710 only for the effect, not for merging.

What changes

A new apiFetch (src/lib/api-fetch.ts) is the way server-only code calls api.nemar.org.
When the Pages project declares a service binding named API, a call to the API's origin goes over it with the visitor's address (this request's CF-Connecting-IP) in X-Forwarded-For, which nemar-cli#1710 counts as that visitor's own.
When there is no binding (astro dev, previews, and every project until it is wired) it is the same fetch as before.

Call sites moved: the catalog reads (api.ts, api-cache.ts), the session lookup in the middleware, the sign-in, ORCID, news-media and /api/v1 proxies, the notices feed (/api/notices, the highest-volume server call after the catalog), and the device-authorization, docs-grant and private-grant clients.
The middleware puts the binding and the visitor into the existing request context (request-context.ts) and leaves the binding alone under astro dev, where the platform proxy's stand-in answers 503.
ADR 0026 records the decisions: only the API's origin takes the binding, redirects are followed here for a GET or HEAD (a binding sends a redirect target back to the bound Worker whatever its host), a request with a body gets its 3xx back unfollowed, and a binding failure is not retried publicly.
The /api/v1 proxy turns such a 3xx into a logged 502, since it copies no Location and the browser would otherwise see a bare redirect.

Three ways the API's counting can fail without an error are watched for, none of them with an address in the log:

  • The first call of each kind in an isolate is classified by X-RateLimit-Bucket: site-ip is logged quietly; ip, site-unattributed, and an answer with no rate-limit headers are warnings.
  • A missing or malformed visitor, and a failing binding, are logged at most once a minute with a count.
  • If the API's counter does not persist for binding-invoked calls, nothing is limited and every answer looks healthy. For one visitor, calls one to ten seconds apart are compared; three comparisons in a row in which X-RateLimit-Remaining did not fall log one error per isolate. (The API sends the reset time only on a refusal, so the check does not use it.)

Not in this PR

  • The [[services]] entries in wrangler.toml and wrangler.test.toml, and the checks that belong with them (a once-per-isolate warning when a production host has no binding, the [env.preview] restatement the non-inheritable binding needs). They go in after nemar-cli#1710 is deployed to the matching environment: wiring first would put every call in the API's shared unattributed bucket, which is worse than today.
  • Modules that also run in the browser (dashboard, account, collaborators, admin, news, users-admin) and the data and Zarr hosts, which need a look at zone-level caching first. Tracked in Call the API through a service binding and forward the visitor #449 follow-ups. test/client-bundle-guard.test.ts fails if a client <script> ever reaches api-fetch.ts or request-context.ts.

Testing

  • bun run lint, typecheck (0 errors), test (3349 pass, 7 skipped), build, in a CI-faithful worktree outside the home directory.
  • api-fetch.test.ts (80 tests): no binding, a binding, identity-header replacement for a Headers instance, tuples and mixed-case records, lookalike origins, every redirect status and verb, the 20/21 hop ceiling, binding failure not retried, first-call report, the stuck-counter detector (parallel bursts, out-of-order answers, per-visitor keying, the 200-visitor bound).
  • test/routes/api-binding-call-sites.test.ts (15 tests): every converted call site leaves over a recording binding naming the visitor, with globalThis.fetch failing the test. Reverting any one of the 16 sites to plain fetch fails a test.
  • Middleware tests: the binding and visitor reach the render, the session lookup goes over the binding, a client-set X-Forwarded-For/X-Real-IP/True-Client-IP never becomes the visitor, a non-binding API value is ignored.
  • Mutation check: 34 mutants of api-fetch.ts by the author, then 72 more (api-fetch, middleware and call sites) by a separate test-quality review. All killed except three equivalent mutants.
  • Real workerd: wrangler pages dev --service API=<stand-in worker>. A binding call carries no CF-Connecting-IP and the visitor in X-Forwarded-For (a spoofed browser header was replaced), cookies pass, an in-API redirect stays on the binding, an off-API redirect goes out publicly without the visitor or cookie, a POST redirect comes back unfollowed. The client bundle has no node:async_hooks.
  • Production keying can only be confirmed after nemar-cli#1710 is deployed and the binding is wired (the API's development Worker bypasses the limiter). The wiring PR reads the [api-fetch] first-call lines on test.nemar.org and then nemar.org.

Tested with a recording binding fixture, a mutation check (16 mutants, all killed), and under workerd with a stand-in API Worker.
Catalog reads and the sign-in, ORCID, news-media and /api/v1 proxies. Unchanged until a project declares the binding.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Five calls for one visitor in one window that leave the remaining count alone log one error per isolate. Mutation check: 24 mutants, all killed.
The count check no longer needs a reset header the API sends only on a refusal, ignores calls that race the counter, and logs binding faults, unreadable visitors and bad bucket kinds without addresses or queries. Requests with bodies get their redirect back unfollowed. Mutation check: 34 mutants, all killed.
The platform proxy supplies a stub that answers 503. A declared env.API that is not a service binding is logged once.
Notices feed, device authorization, docs and private grants. The news media proxy logs the status it turns into a 502.
@neuromechanist
neuromechanist merged commit 2d68f5a into staging Oct 12, 2026
5 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-449-api-service-binding branch October 12, 2026 16:50
neuromechanist added a commit that referenced this pull request Oct 12, 2026
Part of #449. Follows #450. nemar-cli#1710 (the API side) is merged to `dev`; this waits only for its deploy to `nemar-api-dev` before it merges to `staging`.

## What changes

- `wrangler.test.toml`: `[[services]] API -> nemar-api-dev`, the Worker behind api-test.nemar.org. `deploy-test.yml` swaps this file into `wrangler.toml`, so it applies to test.nemar.org.
- `wrangler.toml`: `[[services]] API -> nemar-api`, the Worker behind api.nemar.org. Previews are left without a binding on purpose (services are not inherited into `[env.preview]`, and a branch build runs unreviewed code that must not be able to name a visitor at the production API). Wrangler warns about the missing restatement; the comment says to leave the warning.
- `src/middleware.ts`: a production host (`nemar.org`, `www`, `ww2`, `app`) whose project has no `API` binding logs one warning per isolate, the way `EMBED_ANALYTICS` does, because the site would otherwise work and quietly stay in the API's shared pool. Staging has a binding but is not a production host, so a missing binding there is not warned about.
- `test/wrangler-bindings.test.ts`: production names `nemar-api`, staging names `nemar-api-dev`, and neither file restates `services` under `env.preview`.
- ADR 0026, the changelog, AGENTS.md (promotion gate and `wrangler pages dev` note), `.rules/astro.md` (manual staging deploys) and the handoff say all of this.

## Order

1. nemar-cli `dev` deployed to `nemar-api-dev` (the Deploy Backend run for the #1710 merge). This PR is then merged to `staging`, which deploys test.nemar.org with the binding.
2. Read the `[api-fetch]` lines on test.nemar.org. The development API bypasses its limiter and sends no rate-limit headers, so the line to expect is the warning that an answer carried none. It shows the binding applied (the watching runs only for calls over a binding) and nothing about the visitor's address.
3. nemar-cli released to `main` and deployed to `nemar-api`. Only then is the `staging` to `main` release of the website promoted (the gate is in AGENTS.md step 8 and the handoff), so production never has the binding in front of an API that does not read the visitor.
4. After the release, check on nemar.org: `X-RateLimit-Bucket: site-ip` with a falling `X-RateLimit-Remaining` across two calls, and the `[api-fetch]` first-call line in the production deployment's tail (`site-ip`, info).

## Testing

- [x] Middleware tests: each production host (`nemar.org`, `app`, `www`, `ww2`) warns on its first request; a repeat does not; test.nemar.org, a `*.pages.dev` preview and localhost say nothing; a production host with a binding says nothing. Mutants of the condition (app host only, apex only, no www or ww2, wrong host class, no once-flag) are killed.
- [x] `test/wrangler-bindings.test.ts`: three tests, each killed by swapping the Worker names or restating `services` under `env.preview`.
- [x] `bun run lint`, `typecheck` (0 errors), `test` (3365 pass).
- [x] Two Sonnet reviewers' findings (a test that did not cover every host, wording about staging, the staging expectation, the promotion gate living only in this body, the manual-deploy and `wrangler pages dev` notes, the edge-protection clause in the ADR) are fixed here.
- [ ] CI, then the checks under Order on test.nemar.org and nemar.org.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant