Rate limiter miscounts concurrent requests: KV read-modify-write lets a burst of N count as 1

Open
#1,123 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
typescript
Domain
backend, security

Research direction

Start with packages/core/src/middleware/rate-limit.ts and packages/core/src/plugins/core-plugins/security-audit-plugin/services/brute-force-detector.ts, then compare the KV read-modify-write flows described in the issue. Evaluate the suggested Cloudflare Rate Limiting binding and Durable Object approaches, including their effect on both counters and graceful degradation. Done means concurrent requests are counted reliably and the limiter remains safe across locations; the issue names no tests to run.

Written by the indexing model from the issue text.

Description

area: auth bug priority: P1 security triage: needs-validation

Summary

rateLimit() counts requests with a read-modify-write against KV. Concurrent requests all read the same counter before any of them writes, so a burst of N simultaneous requests is recorded as 1, not N. The limit is only enforced against serial traffic — which is the opposite of the threat model, since an attacker controls their own concurrency.

BruteForceDetector.incrementCounter() has the identical shape and the same defect.

Evidence

Measured against a live preview deployment (/auth/register, limit max: 30, windowMs: 60_000):

probe result
35 serial POSTs X-RateLimit-Remaining counts down correctly, 429s fire as expected
40 concurrent POSTs zero 429s, every response reports a near-identical X-RateLimit-Remaining

So the limiter is not broken in general — it is specifically blind to concurrency.

Affected code

packages/core/src/middleware/rate-limit.ts:62-88 — the window between the read and the write is one full KV round trip, which is where every concurrent request lands:

const stored = await kv.get(key, 'json') as RateLimitEntry | null   // L62  all racers read here
// …
entry.count++                                                        // L71
// …
await kv.put(key, JSON.stringify(entry), { expirationTtl: … })      // L88  last writer wins

packages/core/src/plugins/core-plugins/security-audit-plugin/services/brute-force-detector.ts:144-168 — same pattern (kv.get → filter/push → kv.put), so lockout thresholds undercount bursts too.

Why this matters

Every caller is an auth endpoint, and the tightest limit is the most exposed:

route limit file
password reset 3 / 15 min routes/auth.ts:1179
login (×2) 30 / min routes/auth.ts:277, :712
register (×2) 30 / min routes/auth.ts:138, :515
seed-admin 10 / min routes/auth.ts:838
token refresh 60 / min routes/auth.ts:460

A burst of N concurrent requests can exceed any of these by up to N. The password-reset limiter is the sharpest case: its whole purpose is to cap reset-email sends, and 3 / 15 min offers no protection at all against 200 requests fired at once.

Second, independent mechanism: KV is eventually consistent

Even with the race fixed, Cloudflare KV propagates writes globally with eventual consistency — a read in a different colo can return a value up to ~60s stale. For a 60s window that means the counter can be effectively per-colo rather than global, so a distributed caller gets roughly (number of colos) × the limit. KV is structurally the wrong primitive for a rate limiter, not merely used incorrectly here.

Suggested fix

In rough order of effort:

  1. Cloudflare's native Rate Limiting binding — purpose-built, atomic, no storage to manage. Simplest option if the fixed-window semantics fit.
  2. A Durable Object keyed by ${keyPrefix}:${ip} — single-threaded per key, so the increment is genuinely atomic and globally consistent. More code, but exact, and reusable for the brute-force counter.

Keep the existing graceful-degradation behaviour either way: no binding → next(), and errors → next() (rate-limit.ts:52-55, :95-99), so a limiter outage can't take the app down.

Not worth doing: a KV compare-and-swap retry loop. KV has no CAS primitive, and the consistency problem above would survive it.

Notes

  • Found while investigating unrelated CI E2E flakiness; this is not a cause of any test failure — checked.
  • rateLimitClientKey() (rate-limit.ts:29-41) is correct and should be kept as-is in any rewrite — it deliberately takes the rightmost x-forwarded-for hop, which is the only entry a remote caller cannot forge.
Dominant language
TypeScript
Stars
1.8k
Forks
219
Avg merge
2d 21h
Merged PRs (30d)
67

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from SonicJs-Org/sonicjs

All issues in SonicJs-Org/sonicjs

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.