Skip to content

fix(auth): never answer a user-key 429 with Retry-After: 0 - #11082

Open
ayobamiseun wants to merge 1 commit into
koala73:mainfrom
ayobamiseun:fix/user-key-retry-after-floor
Open

ayobamiseun wants to merge 1 commit into
koala73:mainfrom
ayobamiseun:fix/user-key-retry-after-floor

Conversation

@ayobamiseun

@ayobamiseun ayobamiseun commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

checkBootstrapUserApiKeyRateLimit built the refusal header straight from the Redis TTL:

headers: noStoreHeaders({ 'Retry-After': String(Math.ceil(ttl)) }),

A TTL of 0 is not an error on this path. The guard twelve lines above accepts it deliberately, with a comment calling it "the normal sub-second tail of an active fixed window (counter still exists, about to reset), so accept it rather than fail-closing a valid under-limit request with a spurious 503", and api/_user-api-key.test.mjs pins that acceptance separately.

Combined with an over-limit counter, that produced HTTP 429 with Retry-After: 0: a client that was just refused is told to retry immediately, re-enters the same still-exhausted fixed window, and is refused again. Both /api/bootstrap and /api/oauth/authorize reach this path.

Why this one and not the others

Every other meter in the codebase floors the value:

Path Floors
rateLimitHeaders in api/_api-key-rate-limit.js Math.max(1, opts.retryAfterSec)
api/_desktop-key-meter.js reaches that builder through secondsUntilUtcMidnight / secondsUntilNextMinute, both already floored
api/_user-api-key.js no floor

So this is one line bringing an outlier in line, not a new convention.

Out of scope on purpose: api/_rate-limit.js and server/_shared/rate-limit.ts share a Math.max(0, …) that can also reach zero on a one-second window. They are mirrors of each other with a mirrored comment, so changing them is a two-file convention decision rather than fixing drift. I left them alone.

Tests

api/_user-api-key.test.mjs gains the missing combination. Both halves of the state were already pinned individually — the over-limit refusal at one case, the ttl: 0 acceptance at another — and only their intersection was uncovered.

Red proof: with api/_user-api-key.js reverted to its main version, the new case fails.

Verification

  • api/_user-api-key, bootstrap-auth, bootstrap-cors, _rate-limit, _api-key node suites — 189 pass, 0 fail
  • npm run typecheck:api, Biome, git diff --check — clean

Summary by CodeRabbit

  • Bug Fixes
    • Rate-limit responses now provide a minimum retry delay of one second, including when the remaining wait time is effectively zero. This avoids telling users to retry immediately while the rate limit is still active and makes the expected wait clearer. The response continues to indicate that the request was rate-limited and should not be cached.

checkBootstrapUserApiKeyRateLimit built Retry-After straight from the
Redis TTL with no floor. A TTL of 0 is not an error here — the guard
twelve lines above accepts it deliberately as "the normal sub-second
tail of an active fixed window", rather than fail-closing a valid
under-limit request, and api/_user-api-key.test.mjs pins that
acceptance. Combined with an over-limit counter it produced
Retry-After: 0 on the refusal, telling a caller that was just rejected
to come straight back into the same exhausted window.

Both /api/bootstrap and /api/oauth/authorize reach this path.

Every other meter floors the value: rateLimitHeaders in
api/_api-key-rate-limit.js uses Math.max(1, ...), and the desktop-key
meter reaches it through helpers that are themselves floored. This one
was the outlier.

Red proof: with the handler reverted, the new case fails.
@vercel

vercel Bot commented Nov 21, 2026

Copy link
Copy Markdown

@ayobamiseun is attempting to deploy a commit to the World Monitor Team on Vercel.

A member of the Team first needs to authorize it.

@strix-security

strix-security Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Strix Security Review

✅ No open security findings.

PR summary: This PR floors the `Retry-After` header on the bootstrap user-key rate-limit refusal at one second, so a caller refused while the fixed window is in its sub-second tail is no longer told to retry immediately, and adds a test for the over-limit plus zero-TTL combination.

Review summary

Reviewed the one production hunk (api/_user-api-key.js) and the added test case. The change replaces Math.ceil(ttl) with Math.max(1, Math.ceil(ttl)) in the refusal headers of checkBootstrapUserApiKeyRateLimit, and the value it formats is already constrained upstream: the guard above rejects non-finite, negative, -1 and -2 TTLs with a 503 and only lets a finite TTL >= 0 reach the refusal, so the header is always a plain positive integer with no injection surface. Admission is unaffected — the over-limit test reads the counter, not the TTL, so a zero TTL with an exhausted counter still returns 429 and now carries a one-second floor, which strictly reduces retry pressure. The meter's identity key comes from the edge-proven client IP (IPv6 collapsed to /64) with no caller-supplied input, the increment/expire/TTL sequence cannot be used to reset or extend a window, and pipeline failures fail closed to a 503 rather than admitting unlimited requests; both /api/bootstrap and /api/oauth/authorize propagate the refusal and its headers. No security issue found in the changed code.

Review 1 on this PR · c66e86a · requested Nov 21 09:28 UTC when the PR was opened


Reviewed by Strix
Re-run review · Configure security review settings · Try a deeper review with @strix-security /deep

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Over-limit requests now receive a Retry-After value of at least one second when the remaining Redis TTL is zero. A regression test checks the 429 response and its Cache-Control: no-store header.

Changes: Rate-limit rejection header

Layer / File(s) Summary
Set and test the minimum Retry-After value
api/_user-api-key.js, api/_user-api-key.test.mjs
The over-limit response uses the ceiling of the remaining TTL, with a minimum of one second. The regression test checks TTL zero, the 429 status, Retry-After: 1, and Cache-Control: no-store.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Possibly related PRs

  • koala73/worldmonitor#10279: Adds a one-second Retry-After floor to 429 responses from api/oauth/authorize.js, whose route can reach the user-key rate-limit rejection.

Suggested reviewers: koala73

Merge Risk: Minimal · up to c66e8

Over-limit responses now always tell clients to wait at least one second instead of returning Retry-After: 0. The change is small and covered by a test, and no merge-blocking risk is apparent.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: an over-limit user-key 429 no longer returns Retry-After: 0. The raw summary confirms the fix sets Retry-After to at least 1 second in api/_user-api-key.js, with a mat…
Description check Passed The description covers the problem, root cause, why the fix is scoped to one file, out-of-scope items, tests, and verification. It follows the repository template's Summary section, but it omits the t…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: an over-limit user-key 429 no longer returns Retry-After: 0. The raw summary confirms the fix sets Retry-After to at least 1 second in api/_user-api-key.js, with a matching test. The title uses the conventional fix(auth) prefix and is specific.

Full details: Description check

Explanation

The description covers the problem, root cause, why the fix is scoped to one file, out-of-scope items, tests, and verification. It follows the repository template's Summary section, but it omits the template's Type of change, Affected areas, and Checklist sections. Those are needed for a complete template match. The Bundle budget section is not applicable here and can be marked N/A.

Resolution

Consider adding the template sections the author skipped: mark Type of change as Bug fix, mark Affected areas (API endpoints /api/* and any others that apply), and complete or mark N/A the Checklist items (for example, typecheck run and the Bundle budget N/A). This is non-blocking because the core content is complete.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ddac5332-80bb-4bd6-94fd-08aee0079663
Commits

Reviewing files that changed from the base of the PR and between f762da2 and c66e86a.

Files selected for processing: 2

  • api/_user-api-key.js
  • api/_user-api-key.test.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

Floors Retry-After at one second when the user-key rate limit refuses a request.

  • User-key rate-limit refusals always give callers at least one second to wait.

Reviews (1) · Last reviewed commit: "fix(auth): never answer a user-key 429 w..." · Reviewed by Greptile

@auditbenchaibot auditbenchaibot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open in Audit Bench Ai

🤖 Automated review by Audit Bench Ai, not a personal review. It was posted through the GitHub account connected to Audit Bench Ai. Install the Audit Bench Ai GitHub App to have reviews posted by a separate bot account.

No actionable comments were generated in this review. 🎉

Merge risk: ⚪ Minimal · up to c66e86a

The change is a small, well-tested floor adjustment that prevents immediate retry loops and matches existing conventions elsewhere in the codebase.

Merge readiness: ⛔ Not ready to merge

Pre-merge checks: ✅ 9 · ❌ 1

❌ Failed checks: 1 error

Check name Status Explanation Resolution
CI checks ❌ 1 of 59 failing: Vercel. Open the failing runs on GitHub and fix them before merging.
✅ Passed checks: 9 passed
Check name Status Explanation
Merge conflicts ✅ Merges cleanly into main.
Secrets ✅ No keys, passwords or tokens in the changed code.
Blocking issues ✅ No critical or high-severity issues in the changed lines.
Tests ✅ Tests were changed alongside the code.
PR size ✅ 26 lines changed.
Title check ✅ The title clearly states the bug fix and its specific target.
Description check ✅ The description provides comprehensive context, rationale, and verification details.
Linked issues check ✅ No issue links were referenced in the pull request description.
Out of scope changes check ✅ All changes are strictly limited to fixing the Retry-After header floor and adding corresponding test coverage.
📝 Walkthrough

This pull request ensures that HTTP 429 rate limit responses in user API key validation always include a minimum Retry-After header value of 1 second rather than 0. Previously, when the Redis TTL fell into a sub-second tail, callers over the limit were told to retry immediately into the same exhausted window. The change aligns this endpoint with other rate meters across the codebase and adds a targeted unit test.

File Changes
api/_user-api-key.js Floors the Retry-After header value to at least 1 second when returning a 429 response.
api/_user-api-key.test.mjs Adds a unit test verifying that a 0 TTL over-limit state produces a Retry-After header of 1.
ℹ️ Review info
  • Commit: c66e86a
  • Verdict: ✅ Pass
  • Findings: none
  • Review: local checks plus AI review of the changed lines
  • Scope: Reviewed 2/2 selected files (of 2 total): 2 reviewed by AI, 0 from cache, 0 passed local checks with nothing risky enough to send to AI. Found 0 finding(s), No secrets found.

💬 Reply to any inline comment and Audit Bench Ai will recheck that code and answer in the thread. Mention @auditbench in the conversation to ask about the whole PR.

🛠️ Open the full report and fix with AI

Thanks for using Audit Bench Ai! Free pull request reviews for open source: paste any public PR at auditbenchai.com/scan.

Reviewed by Audit Bench Ai · Build fast. Check what ships. · Review any public PR free

This branch has not been deployed

No deployments
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.

2 participants