Skip to content

Key rate limiter on user id for admins - #467

Merged
neuromechanist merged 2 commits into
devfrom
feature/issue-275-admin-rate-limit
May 14, 2026
Merged

neuromechanist merged 2 commits into
devfrom
feature/issue-275-admin-rate-limit

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Closes #275.

What changed

The Worker rate limiter used to key every request on IP and exempt
/admin/* entirely. Exempting admin paths gave an admin running a
malformed loop unbounded access to the worker, and keying everything
else on IP meant several admins (or one admin running back-to-back
publication approves) shared one 100/60s bucket — exactly the regression
the 4 stuck datasets in #275 hit.

The middleware now picks the bucket from the request:

  • /auth/* endpoints stay IP-keyed at 10/60s (pre-auth, must resist
    password guessing).
  • Any other request that carries a syntactically-valid bearer token
    (length ≥ 32, matching what the auth middleware accepts) is keyed by
    the SHA-256 hash of that token at 500/60s. Admin orchestration
    fits comfortably (the heaviest single publish approve we've seen
    fires ~165 sequential subrequests; 500/60s gives ~3× headroom and
    allows a small queue of back-to-back operations) and a runaway loop
    still 429s.
  • Everything else stays on the legacy IP bucket at 100/60s.

The admin-path exemption is gone — admin requests are bounded, just at
the higher cap.

Why 500 (not 1000)

The user note in #275 suggested 500 or 1000. 500 covers the worst
real orchestration we observe by ~3× while still leaving a meaningful
floor on a misbehaving admin script. 1000 would push the cap past the
point where a runaway loop is bounded by the limiter and would be
bounded only by Worker CPU/subrequest budgets — at that point the
limiter is decorative. Sized to be useful, not theatrical.

What is NOT in this PR

The 4 currently-stuck datasets (on005515, on005516, nm000110 at
s3_lock; on002718 at ci_check) are not touched here — the user owns
that recovery action per the issue's scoping note. The fix lets those
resume commands actually go through once it lands.

Operator runbook — clear the stuck datasets after this lands

# Wait ~60s after the deploy for any in-flight rate-limit windows to
# clear. Then resume the three s3_lock stalls (now keyed on token, no
# more IP-pool starvation):
nemar admin publish approve on005515 --resume --yes
nemar admin publish approve on005516 --resume --yes
nemar admin publish approve nm000110 --resume --yes

# on002718 is a different failure mode — BIDS CI is failing. First
# verify CI status, fix the upstream issue, then resume:
nemar admin ci check on002718
# (fix upstream BIDS-validation failures in the dataset repo)
nemar admin publish approve on002718 --resume --yes

# If the BIDS failure turns out to be a known false positive after
# review, the admin override is available:
nemar admin publish approve on002718 --resume --skip-ci-check --yes

The CLI's retry-with-delay loop (approvePublication in src/lib/api.ts)
will automatically retry transient 5xx/429 on top of these commands.

Test plan

  • Added backend/test/rate-limit-buckets.test.ts exercising:
    • The pure __selectBucket decision logic across auth-path,
      token-bearing, and unauthenticated requests.
    • End-to-end through the real middleware against a real Hono app
      with an in-memory Cache (not a mock — a working Cache backed by
      Map): 150 authenticated requests on the same IP don't 429, 150
      unauthenticated requests 429 after the 100th, two distinct tokens
      on the same IP don't share a bucket, and an authenticated client
      still 429s past the 500 cap.
  • bun test in backend/: 49 pass, 0 fail (was 35 pre-change).
  • bun run typecheck (root + backend) clean.
  • bun run build clean.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

PR Review — #467 Rate limiter per-token bucketing

Reviewed by 5 specialized agents: security, test coverage, error handling, code quality, admin capacity.


Critical

None.


Important

[security] Short-token sends land in shared IP bucket, not their own bucket
__readBearerTokenFromHeader correctly rejects tokens <32 chars and falls them to the IP bucket. However all such requests from a given IP share one 100/60s IP bucket (rl:ip:<ip>). An attacker on a shared egress IP (corporate NAT) sending Bearer <31-char-garbage> requests will deplete the IP bucket for all unauthenticated traffic from that IP — legitimate signups, public dataset listing, etc. This is a degraded-availability vector, not a rate-limit bypass. Low exploitability in practice but worth noting. No immediate fix required; documenting the behavior in the module header would be sufficient.

[security/operational] "unknown" IP pools all headerless requests into one bucket
ip = c.req.header("CF-Connecting-IP") || c.req.header("X-Forwarded-For") || "unknown" — if both headers are absent, the cache key becomes rl:ip:unknown. All unauthenticated requests with no IP header share a single 100-request/60s global bucket. This is pre-existing behavior but is now more visible because admin requests go through the rate-limit path. During a Cloudflare header propagation anomaly all affected unauthenticated users would collectively exhaust one 100-request pool. Suggest adding a fallback that uses a random-per-request nonce when IP is unavailable (fail open gracefully rather than pool-sharing):

const ip = c.req.header("CF-Connecting-IP") 
  || c.req.header("X-Forwarded-For") 
  || crypto.randomUUID(); // don't pool unknown IPs

[code] BucketSelection exported without __ prefix
__selectBucket and __readBearerTokenFromHeader use the __ test-only convention, but the BucketSelection interface they return is exported publicly (line 99) without the prefix. A future developer importing BucketSelection in production code won't see the "test-only" signal. Either prefix it __BucketSelection or inline the return type:

export function __selectBucket(...): { keyKind: "auth-ip"|"ip"|"token"; rawKey: string; maxRequests: number }

[code] AUTH_PATHS uses startsWith — overly broad prefix matching
Line 111: AUTH_PATHS.some((p) => path.startsWith(p)) means a hypothetical future path like /auth/verification-status or /auth/signup-bonus would get the strict 10/60s cap unintentionally. The current path list is fine today, but the matching should be tightened:

AUTH_PATHS.some((p) => path === p || path.startsWith(p + "/") || path.startsWith(p + "?"))

[tests] In-memory cache never expires entries
InMemoryCache.put() stores entries but never evicts them. The real CF Cache API evicts entries after Cache-Control: max-age=60. The beforeEach(() => ourCache.clear()) between tests substitutes for this, but there is no test for window-reset behavior (requests in window N passing, then window N+1 also passing after reset). In production the fixed window resets naturally via TTL; in tests it resets manually. This is a test fidelity gap — not a bug in the middleware, but it means the window-expiry path is untested.

[code] Naming: AUTH_MAX_REQUESTS_AUTHED is confusing
AUTH_MAX_REQUESTS = 10 (auth endpoints, IP-keyed)
AUTH_MAX_REQUESTS_AUTHED = 500 (authenticated non-auth endpoints, token-keyed)
The AUTH_ prefix on both makes them look related when they're for opposite buckets. Suggest TOKEN_MAX_REQUESTS or AUTHED_MAX_REQUESTS for the 500 constant to make the distinction obvious at a glance.


Suggestions

[tests] No E2E test for /auth/* + valid token → 10/60s cap
__selectBucket unit test covers this branch, but there is no end-to-end rateLimiter test that verifies a valid Bearer token on /auth/login still gets the 10/60s cap (not the 500/60s token cap). Worth adding to prevent a future refactor from accidentally granting token-bucket quota to auth paths.

[docs] Document that the rate limit is per-PoP, not globally consistent
caches.default in CF Workers is per-edge-node (Point of Presence). A client whose requests are routed to different CF PoPs gets separate 500/60s buckets — the effective global limit is 500 × number_of_PoPs. This is pre-existing and unavoidable with the Cache API approach (KV would be globally consistent but has daily op limits). Worth a one-line note in the module header so future maintainers understand why "rate limit" isn't a hard global cap.

[docs] Explicitly state the window type is fixed (not sliding)
The current 500/60s description could be read as either. A fixed window allows up to 1000 requests across a window boundary (500 at second 59 + 500 at second 61). Adding "fixed window" to the module header prevents confusion.

[code] __limits export includes WINDOW_SIZE but tests don't use it
__limits.WINDOW_SIZE is exported but none of the 13 tests reference it. If it's not tested against, it doesn't need to be exported. Minor surface reduction.


Nice to haves

  • Consider adding a test that different paths for the same token deplete the same bucket (e.g., 250 hits to /admin/users + 250 hits to /admin/datasets with the same token = 500 total, then 429). Currently all token-bucket tests use a single path.
  • The X-Test-Bypass header path (lines 136–140) has no dedicated test — covered implicitly by the dev-env test, but an explicit test would improve isolation.

Admin capacity verdict

500/60s is sufficient for all known admin workflows:

  • Single publish approve on largest observed dataset: ~165 API calls (3× headroom). OK.
  • reindex --all: 1 API call (server loops internally). OK.
  • S3 lock pagination on 6500-object dataset: ~65 calls. OK.
  • Back-to-back publish approve on 4 large datasets (165×4=660): would 429 on the 4th. Acceptable — 60s window reset resolves it automatically.

False positives / non-issues

  • Cache fail-open for admin paths: The catch-and-log at line 205 is intentional and was pre-existing. Post-PR, admin requests now go through the cache path, so a cache outage removes rate limiting for admin too. This is noted in the comment but the increased scope isn't explicitly stated. Not a bug — the fail-open policy is correct for availability. Worth updating the comment text only.
  • Short token → IP bucket (not token bucket): Correctly routes to the IP bucket (100/60s). Does NOT give the attacker the higher 500/60s cap. The design is sound.
  • hashApiKey called before the cache try block: hashApiKey at line 150 is inside the function before the try block on line 158. If hashApiKey throws (extremely unlikely in CF Workers), the error would propagate up uncaught. But this is inside rateLimiter which is a Hono middleware — Hono's error handler would catch it. Not a silent failure.

Overall verdict: No blocking issues. The core fix (per-token bucketing to eliminate admin/IP bucket contention) is correct and well-tested. The BucketSelection export naming and AUTH_PATHS prefix-matching are the two items worth addressing before merge. The "unknown" IP pooling is a pre-existing risk made slightly more visible, and a one-line fix would eliminate it entirely.

- Rename BucketSelection -> __BucketSelection (test-only convention)
- Rename AUTH_MAX_REQUESTS_AUTHED -> TOKEN_MAX_REQUESTS_AUTHED (clearer)
- Tighten AUTH_PATHS matching: exact or /- or ?-prefixed subpath only
- Replace "unknown" IP fallback with crypto.randomUUID() to avoid pooling
- Add TTL-aware InMemoryCache and window-reset test (14th test)
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review findings addressed (commit 3ada43e)

All 5 Important findings resolved:

  1. BucketSelection export naming — renamed to __BucketSelection to match the test-only __ convention used by __selectBucket and __readBearerTokenFromHeader.

  2. AUTH_PATHS overly-broad startsWith — tightened to exact match or subpath (path === p || path.startsWith(p + "/") || path.startsWith(p + "?")). A future /auth/verification-status would no longer silently inherit the 10/60s cap.

  3. "unknown" IP pooling — replaced with crypto.randomUUID() so headerless requests each get an independent bucket rather than sharing one global 100/60s pool.

  4. Window-reset path untested — InMemoryCache now stores expiry timestamps derived from Cache-Control: max-age and exposes a getNow injection point. New test (14th) exhausts an IP bucket, advances the fake clock past WINDOW_SIZE, and confirms the client gets a fresh quota.

  5. AUTH_MAX_REQUESTS_AUTHED misleading name — renamed to TOKEN_MAX_REQUESTS_AUTHED throughout source and tests.

All 14 tests pass (bun test backend/test/rate-limit-buckets.test.ts).

Suggestions / nice-to-haves not addressed (false positives or intentional):

  • Per-PoP cache note and fixed-window doc: pre-existing and out of scope for this PR; can be a follow-up docs commit.
  • __limits.WINDOW_SIZE unused in tests: it is now used indirectly by the window-reset test via ourCache.getNow advancement. Left exported.
  • Cross-path token-depletion test and explicit X-Test-Bypass test: noted, not blocking.

@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR467

Version: 0.8.14-PR467.3ada43e
Commit: 3ada43e


🤖 Updated on each push.

@neuromechanist
neuromechanist merged commit 4588a32 into dev May 14, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-275-admin-rate-limit branch May 14, 2026 04:45

This branch was previously deployed

1 inactive deployment
npm — 3ada43ef Deployed May 14, 2026 by neuromechanist via publish #804
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