feat(ratelimit): API rate limiting with per-IP and per-user classes (#62) #119

Merged
amiryahaya merged 10 commits from feat/62-rate-limiting into main 2026-10-28 18:53:33 +01:00
Owner

What

API-level rate limiting (#62, slice 1): in-memory token buckets per node (internal/ratelimit), a fixed 429 problem with Retry-After, a correct client IP behind trusted proxies, and six classes:

Class Key Limit (burst) Routes
auth_fail IP 20/min (20), failures only bad JWT / unknown or revoked kws_ key
purchase user 30/min (10) cart edits, checkout, wallet pay, M-Pesa pay
sensitive user 10/hour (5) org registration, org document upload, invitations create/accept, API-key create
scan user 120/min (30) check-in/out, overstay, top-up, vehicle add-on, ticket lookup
heavy user 10/min (5) PDFs, report exports and JSON reports, media upload
default IP 600/min (200) everything else (and tokenless hits on classed routes)

Exempt: /healthz, /readyz, the M-Pesa callback. The gate runs after the route is matched and before the cache; per-user limits wrap the authenticate function given to every module. 429 added to the OpenAPI contract on every classed operation. ADR 0028, CLAUDE.md section, docs/02 proxy text. No migration, no new dependency.

Verification

  • make cover: 91.3% (minimum 80%), run on the final commit (9588207). ratelimit is at 100%.
  • make lint 0 issues, make contract ok, go test -race -count=1 ./... ok, scripts/generate-clients.sh ok.
  • Dual-pass review: Pass 1 no Must fix; Pass 2 two Important (outage when the proxy setting is unset; one mobile-network client locking out everyone on a shared IP), both fixed; scoped re-review found one new Important (a blocked IP could force unlimited JWT verifications), fixed and re-checked with Pass 1: Must fix none.

Rulings made without you (owner to check, [verify] in ADR 0028)

  • KWS_TRUSTED_PROXIES is now required in API mode (proxy CIDRs or the literal none); unset = startup error. make run defaults it to none. Production (#57) must set it to the Caddy/Cloudflare ranges, and Caddy must accept only Cloudflare ranges or CF-Connecting-IP is forgeable.
  • A blocked IP's valid JWTs still pass (mobile carrier networks share IPs); invalid JWTs and every kws_ key get 429 with no key lookup. Once an IP is blocked its requests also spend the 600/min default cap.
  • Counters are per node (N nodes allow N times the rate). All numbers are my defaults, to be tuned in #61.
  • At the 50,000-bucket cap new keys are allowed (fail open, with a rate-limited Warn): a wide IPv6 range or many accounts could fill it.
  • Seat availability, media bytes and the QR image stay in the default class.

Not verified

  • No load test; real Caddy/Cloudflare header behaviour; a two-node setup.
  • Verifying JWTs from a blocked IP can make go-oidc re-fetch Zitadel's key set (no cooldown there). Bounded per IP now; a cooldown in auth.OIDCVerifier is a follow-up, also for floods spread across many IPv6 /64s.
  • A few tests pin behaviour that already worked and were not red-first (cached-hit counting, Patterns wrapped, contract 429).
  • #62 stays open: Cloudflare/Caddy rules (#57), shared limiter for more than one node, CORS/CSRF review, ASVS L2 review, dependency and image scanning.

🤖 Generated with Claude Code

## What API-level rate limiting (#62, slice 1): in-memory token buckets per node (`internal/ratelimit`), a fixed 429 problem with `Retry-After`, a correct client IP behind trusted proxies, and six classes: | Class | Key | Limit (burst) | Routes | |---|---|---|---| | `auth_fail` | IP | 20/min (20), failures only | bad JWT / unknown or revoked `kws_` key | | `purchase` | user | 30/min (10) | cart edits, checkout, wallet pay, M-Pesa pay | | `sensitive` | user | 10/hour (5) | org registration, org document upload, invitations create/accept, API-key create | | `scan` | user | 120/min (30) | check-in/out, overstay, top-up, vehicle add-on, ticket lookup | | `heavy` | user | 10/min (5) | PDFs, report exports and JSON reports, media upload | | `default` | IP | 600/min (200) | everything else (and tokenless hits on classed routes) | Exempt: `/healthz`, `/readyz`, the M-Pesa callback. The gate runs after the route is matched and before the cache; per-user limits wrap the `authenticate` function given to every module. 429 added to the OpenAPI contract on every classed operation. ADR 0028, CLAUDE.md section, docs/02 proxy text. No migration, no new dependency. ## Verification - `make cover`: **91.3%** (minimum 80%), run on the final commit (9588207). `ratelimit` is at 100%. - `make lint` 0 issues, `make contract` ok, `go test -race -count=1 ./...` ok, `scripts/generate-clients.sh` ok. - Dual-pass review: Pass 1 no Must fix; Pass 2 two Important (outage when the proxy setting is unset; one mobile-network client locking out everyone on a shared IP), both fixed; scoped re-review found one new Important (a blocked IP could force unlimited JWT verifications), fixed and re-checked with Pass 1: Must fix none. ## Rulings made without you (owner to check, [verify] in ADR 0028) - **`KWS_TRUSTED_PROXIES` is now required in API mode** (proxy CIDRs or the literal `none`); unset = startup error. `make run` defaults it to `none`. Production (#57) must set it to the Caddy/Cloudflare ranges, and Caddy must accept only Cloudflare ranges or `CF-Connecting-IP` is forgeable. - A blocked IP's valid JWTs still pass (mobile carrier networks share IPs); invalid JWTs and every `kws_` key get 429 with no key lookup. Once an IP is blocked its requests also spend the 600/min default cap. - Counters are per node (N nodes allow N times the rate). All numbers are my defaults, to be tuned in #61. - At the 50,000-bucket cap new keys are allowed (fail open, with a rate-limited Warn): a wide IPv6 range or many accounts could fill it. - Seat availability, media bytes and the QR image stay in the default class. ## Not verified - No load test; real Caddy/Cloudflare header behaviour; a two-node setup. - Verifying JWTs from a blocked IP can make go-oidc re-fetch Zitadel's key set (no cooldown there). Bounded per IP now; a cooldown in `auth.OIDCVerifier` is a follow-up, also for floods spread across many IPv6 /64s. - A few tests pin behaviour that already worked and were not red-first (cached-hit counting, Patterns wrapped, contract 429). - #62 stays open: Cloudflare/Caddy rules (#57), shared limiter for more than one node, CORS/CSRF review, ASVS L2 review, dependency and image scanning. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Per-IP default gate in problemFallback before the cache, auth_fail limiter
before key lookup and JWT verification, per-user classes inside
Authenticate, KWS_RATE_LIMIT=off, startup Warn without trusted proxies,
full-store Warn, and 0-bit trusted proxies rejected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Tokenless requests to per-user-classed routes now spend the per-IP default
bucket; a test runs the real cache with the real limiter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A blocked IP still gets valid JWTs through (bad tokens and kws_ keys get
429 without a lookup); KWS_TRUSTED_PROXIES is required in api mode (none =
direct); Store.Allow loses its unused cost; a test pins every classed route
behind the per-user limiter; the live 429 test tolerates a refill; ADR,
CLAUDE.md, docs/02 and the OpenAPI description updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
fix(ratelimit): keep blocked IPs under the default cap (#62)
All checks were successful
ci / changes (pull_request) Successful in 10s
ci / clients (pull_request) Successful in 1m11s
ci / api (pull_request) Successful in 7m18s
ci / ci-gate (pull_request) Successful in 2s
9588207c2c
A classed route sent with a token skips the per-IP default bucket only
while the IP has auth_fail budget, so a blocked IP's bad JWTs (each a
verification and possibly a key-set refetch) stop at the default cap.
The contract 429 test validates through the harness.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
primatekuntech/kws!119
No description provided.