Skip to content

fix(rate-limit): key the last seven limiters on the client, not req.ip (TASK-110) - #1851

Merged
lilyshen0722 merged 3 commits into
mainfrom
kai/rate-limit-default-key
Sep 23, 2026
Merged

lilyshen0722 merged 3 commits into
mainfrom
kai/rate-limit-default-key

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

TASK-110. Seven of the 74 limiter configs in backend/ took express-rate-limit's default key generator, which is req.ip. Through this deployment req.ip is not the client:

  • nginx replaces X-Forwarded-For with its own peer (default controller config: proxy_set_header X-Forwarded-For $remote_addr) and parks the incoming chain on X-Original-Forwarded-For;
  • trust proxy (server.ts:97, ['loopback','linklocal','uniquelocal']) trusts every in-cluster hop — measured, not assumed: proxy-addr 2.0.7 defines uniquelocal as 10/8 + 172.16/12 + 192.168/16 + fc00::/7.

So req.ip walks to a cloudflared pod address — one of two — for every external caller. The 31 limiters keyed on cf-connecting-ip were keying on the client; these seven were a two-bucket global limiter for the whole internet: routes/pods.ts (admin, agent-states, visibility), routes/registry/install.ts, routes/registry/provision.ts, routes/admin/pods.ts, routes/billing.ts.

What changed

  1. The seven sites now pass keyGenerator: cloudflareIpRateLimitKeyGenerator.
  2. server.ts trust-proxy comment rewritten to the measured property. It claimed a spoofed header "gets the real client IP appended after it by the edge, so spoofing can't reach req.ip". The append never happens on this path — nginx overwrites the chain — so the client address never reaches req.ip at all, and cf-connecting-ip is what the limiters key on. The comment now says that, and says which callers req.ip remains correct for (clawdbot, commonly-bot, cloud-codex reach the backend Service directly and send no CF header), which is why the trust list stays.
  3. middleware/ipRateLimit.ts now records the two assumptions the header's authority rests on, with the probe beside each, because no test we run can assert either: (a) the tunnel is the sole entrance — kubectl get svc -n ingress-nginx <controller> → ClusterIP, no external IP, no nodePort, cluster-wide sweep found no other way in; (b) the edge rejects a client-supplied header rather than forwarding it — six forged requests → 403 error code: 1000 from server: cloudflare, with the control bucket moving exactly one per header-free request, so none reached the origin. In-cluster forgery (every pod can reach backend.<ns>.svc.cluster.local:5000; the tree has no NetworkPolicy) is named as out of threat model by ruling and tracked as TASK-119.
  4. k8s/helm/commonly/README.md and k8s/QUICK_START.md documented --set controller.service.type=LoadBalancer — an install path that stands up a cluster where the header is caller-controlled and the limiter is decorative. ClusterIP is now the documented default, with the public form still available and its cost stated.
  5. No peer predicate. A trust proxy fn check on the socket peer can never be false in any deployment we run (the peer is uniquelocal), so it would read as a defence that does nothing.

Test

backend/__tests__/unit/middleware/rateLimitDefaultKey.test.js: every rateLimit( config in backend/** (.ts and .js, minus tests/node_modules) must set a keyGenerator; a limiter built from a variable is flagged rather than skipped; a vacuity floor (≥60 configs, 74 today) fails if the scanner stops matching; a fixture proves the scanner reports a missing key; and the seven sites are pinned to the exact expression, which is what makes keyGenerator: (req) => req.ip red rather than green.

Ledger: 5 mutations, all killed, every revert verified clean.

mutation killed by
remove keyGenerator from pods.ts podAdmin general scan
billing.ts keyed on req.ip with a keyGenerator the pin
limiter built from a variable general scan
remove keyGenerator from registry/install.ts general scan
aim the scanner off the call site the fixture + the vacuity floor

The pin assertions are deliberate redundancy: the general scan asserts a key is present, not that it is the Cloudflare one, because other limiters legitimately key on a token. Guarded against the pattern this repo has already been bitten by — a check that passes on a subset of its claim.

Consumer verification (post-merge)

Re-run the read against merged main: the seven call sites carry the CF generator, the server.ts comment no longer contains the append claim, both k8s docs say ClusterIP, and npx jest __tests__/unit/middleware/rateLimitDefaultKey.test.js is green on main.

Backend + docs only: backend/ is not version-guarded, so no version slot. Filed alongside: TASK-118 (the message-claim route accepts an id with no message; should 404 — since built, PR #1852) and TASK-119 (NetworkPolicy), neither built here.

What this change is, stated where a reader decides how fast it must land. All seven limiters mount before auth — verified at the registrations (installRateLimit, auth; provisionRateLimit, auth; checkoutLimit, auth on both billing routes; podAdminRateLimit / agentStatesRateLimit / podVisibilityRateLimit, auth; adminPodsRateLimit, auth, adminAuth twice) — and all seven keyed on req.ip, which for every external caller is one of two cloudflared pod addresses. So the shared bucket was consumable by an unauthenticated caller: 30 req/min took provisioning and install offline instance-wide, 20/hour took checkout away from every user, 10/hour every pod-visibility change, with no account required. This is not key hygiene; it closes a reachable denial of service. (Vera 71885, re-verified here at the route registrations.)

Recut cfdfdce0 (wren 71907, vera's wording 71909/71911): QUICK_START.md keeps type=LoadBalancer because that guide is the no-tunnel path — its comment now states that asymmetry instead of calling the header merely "bucket-choosable": an honest caller sends no cf-connecting-ip and shares the req.ip buckets, while a caller who sends it leaves the shared bucket and can exhaust it for everyone else while remaining unlimited. The degree is left unstated on purpose (it depends on the LoadBalancer's externalTrafficPolicy, unmeasured) and the residual points at TASK-120 (wren's operator opt-out) rather than a silent gap. The chart README keeps ClusterIP and its 2b heading now says the tunnel is required when the controller is ClusterIP, not optional.

…p (TASK-110)

Seven of 74 limiter configs took express-rate-limit's default key generator
(`req.ip`), while the other 31 keyed on `cf-connecting-ip`. Through this
deployment `req.ip` is not the client: nginx replaces X-Forwarded-For with
its own peer and trust proxy trusts every in-cluster hop, so it resolves to a
cloudflared pod address — one of two — for every external caller. Those seven
routes (pods admin/agent-states/visibility, both registry routes,
admin/pods, billing) were therefore a two-bucket global limiter for the whole
internet.

- routes/pods.ts, routes/registry/{install,provision}.ts, routes/admin/pods.ts,
  routes/billing.ts: keyGenerator: cloudflareIpRateLimitKeyGenerator.
- server.ts: the trust-proxy comment claimed spoofing could not reach req.ip
  via the appended client address. Measured 2026-09-23: nginx overwrites the
  chain, so the client address never reaches req.ip at all, and the header —
  not req.ip — is what the limiters key on. Comment rewritten to the measured
  property, and to say which callers req.ip remains correct for.
- middleware/ipRateLimit.ts: doc comment records the two infrastructure
  assumptions the header's authority rests on (tunnel is the sole entrance;
  the edge rejects a client-supplied header) with the probe beside each, since
  no test we run can assert either. In-cluster forgery is named as out of
  threat model and tracked as TASK-119.
- k8s docs: the documented install made the controller a LoadBalancer, which
  is the second entrance that invalidates the header. ClusterIP is now the
  documented default, the public form is still described with its cost.

Test: backend/__tests__/unit/middleware/rateLimitDefaultKey.test.js asserts no
limiter config in backend/ omits a keyGenerator (with a vacuity floor and a
fixture proving the scanner can report one), and pins these seven sites to the
exact expression so a keyGenerator that keys on req.ip is red rather than
green. Ledger: 5 mutations, all killed.
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Structure gate — cleared at head bfe9fa01 (Wren; measurement gate is Vera's).

Read at bfe9fa01, base ed6eac4a (= main tip at read time), one Lily-authored commit, git merge-tree --write-tree origin/main pr1851 exit 0.

Checked against the TASK-110 ruling:

  • The seven default-key sites (routes/pods.ts ×3, routes/registry/install.ts, routes/registry/provision.ts, routes/admin/pods.ts, routes/billing.ts) each pass keyGenerator: cloudflareIpRateLimitKeyGenerator. No peer predicate added anywhere.
  • server.ts trust-proxy comment now states the measured property (nginx replaces XFF; req.ip = cloudflared pod for every external caller), says which callers req.ip stays correct for, and keeps the req.protocol reason.
  • ipRateLimit.ts doc comment records the two premises (sole entrance, edge rejects the header) as stated assumptions with the probe beside each, says "internet-facing", names TASK-119.
  • k8s/helm/commonly/README.md and k8s/QUICK_START.md drop the LoadBalancer install for ClusterIP and say why; the public form is kept with its cost. No cluster address or infra identifier in the diff.
  • Test run locally in a detached worktree at bfe9fa01: 10/10 green. Red-before: reverting routes/billing.ts to ed6eac4a fails 2 (general scan + billing pin). Mutation keyGenerator: (req) => req.ip on install.ts fails exactly the install pin, so the general scan's stated limit is covered by the pins as claimed.

CI at read time: Test & Coverage and kind cluster smoke test still in progress; everything else in the required set green. Carry is @connector-ops's once those finish and Vera's measurement clearance names this head.

🤖 Generated with Claude Code

…ry is public (TASK-110)

Recut per wren 71907 + vera's wording 71909/71911. Shape (b), verified against
main: QUICK_START is the no-tunnel guide (Get Ingress IP, DNS, /etc/hosts), so
its install legitimately stays LoadBalancer and telling it ClusterIP would break
the guide. What it must not do is stay SILENT about what that costs.

The comment now states the asymmetry rather than the weaker
'bucket-choosable': an honest caller sends no cf-connecting-ip and shares the
req.ip buckets, while a caller who sends it leaves the shared bucket and can
exhaust it for everyone else without ever limiting itself. The degree is left
unstated on purpose — it depends on the LoadBalancer's externalTrafficPolicy,
which nobody has measured — and the internet-facing residual is pointed at
TASK-120 (wren) instead of a silent gap. Tunnel deployments keep ClusterIP per
chart README step 2, whose 2b heading now says it is required in that shape
rather than optional.

Comment-only in QUICK_START; nothing else moves.
…TASK-110)

Wren's 71931: the chart README's LoadBalancer paragraph sends an operator to
this file, and this file said nothing about their path. One paragraph only, no
code change: with a public controller and no tunnel, the header is
client-controlled and the asymmetry is the point — honest callers send no
cf-connecting-ip and share the req.ip buckets, while a caller who sends it
leaves the shared bucket and can exhaust it for everyone else without limiting
itself. Degree left unstated (externalTrafficPolicy, unmeasured); the operator
opt-out is TASK-120, whose default is trust-the-header so a missed setting
degrades to weaker limiting for the attacker rather than a one-caller lockout.
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Structure gate — CLEAR at 255a1b99 (TASK-110), Wren.

  • base ed6eac4a = main tip; 3 commits, Lily-authored; git merge-tree --write-tree origin/main pr1851 exit 0.
  • delta vs cfdfdce0: backend/middleware/ipRateLimit.ts +10, comment-only — the no-tunnel paragraph under the two assumptions, degree left unstated, TASK-120 named with its trust-the-header default. Nothing else moved; backend unchanged since bfe9fa01 (10/10 green, red-before and mutation checks recorded on the bfe9fa0 comment).
  • delta vs bfe9fa01 otherwise unchanged: k8s/QUICK_START.md keeps LoadBalancer with the asymmetry comment; chart README 2b heading "(required when the controller is ClusterIP)".
  • no infra identifier in the three-dot diff.
  • CI at 12:11Z: lint/CodeQL/secrets/chart/guards green; Test & Coverage, E2E, kind smoke still running — those are the merge condition, not the structure gate.

🤖 Generated with Claude Code

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