Skip to content

fix(rate-limit): wrap IP fallback with ipKeyGenerator for IPv6 safety#3452

Merged
PierreBrisorgueil merged 2 commits intomasterfrom
fix/rate-limit-ipv6-key-generator
Apr 10, 2026
Merged

fix(rate-limit): wrap IP fallback with ipKeyGenerator for IPv6 safety#3452
PierreBrisorgueil merged 2 commits intomasterfrom
fix/rate-limit-ipv6-key-generator

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Apr 10, 2026

Summary

  • Fixes Node startup crash ERR_ERL_KEY_GEN_IPV6 thrown by express-rate-limit v7+ when loading auth routes (login/register).
  • Imports ipKeyGenerator helper and wraps only the IP fallback in the centralized limiter's custom keyGenerator. User-id keying stays prioritized.
  • Updates the unit test mock to export ipKeyGenerator and adjusts the two IP-fallback assertions.

Why

On unauthenticated routes (/auth/login, /auth/register) there is no req.user, so the limiter always fell back to raw req.ip. express-rate-limit v7 refuses this because raw IPv6 addresses need normalization via ipKeyGenerator — otherwise an IPv6 user can rotate their /64 prefix to bypass the limit.

Changes

  • lib/middlewares/rateLimiter.js — import ipKeyGenerator, wrap req.ip fallback.
  • lib/middlewares/tests/rateLimiter.unit.tests.js — mock exports ipKeyGenerator, updated two fallback tests.

Test plan

  • npm run lint clean
  • npm run test:coverage — 751/751 passing, thresholds held
  • Targeted unit suite rateLimiter.unit.tests.js — 7/7 passing

Closes #3450

Ref: https://express-rate-limit.github.io/ERR_ERL_KEY_GEN_IPV6/

Summary by CodeRabbit

Bug Fixes

  • Improved IP address detection in rate limiting middleware to properly handle various network configurations and proxy scenarios.

Node startup was crashing with ERR_ERL_KEY_GEN_IPV6 on auth routes
because the custom keyGenerator used req.ip directly. express-rate-limit
v7+ refuses raw IPs in custom key generators to prevent IPv6 users from
bypassing limits by rotating through their /64 prefix.

Import the ipKeyGenerator helper and wrap only the IP fallback; userId
keying stays prioritized for authenticated requests.

Refs #3450
Copilot AI review requested due to automatic review settings April 10, 2026 12:19
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 10, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 22 minutes and 43 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 22 minutes and 43 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d1ebc0dd-03ef-4cce-a184-348b04fc85ce

📥 Commits

Reviewing files that changed from the base of the PR and between 3b051ba and 2e80763.

📒 Files selected for processing (1)
  • lib/middlewares/rateLimiter.js

Walkthrough

Updated the rate limiter middleware to import and use the ipKeyGenerator helper function from express-rate-limit when deriving IP-based rate-limit keys. The fallback now normalizes IP addresses via ipKeyGenerator(req.ip) instead of using raw IP values, while preserving user-based keying when available. Corresponding unit test mock and expectations were updated.

Changes

Cohort / File(s) Summary
Rate Limiter IPv6 Fix
lib/middlewares/rateLimiter.js, lib/middlewares/tests/rateLimiter.unit.tests.js
Imported ipKeyGenerator from express-rate-limit and applied it to the IP fallback in the key generator function. Updated mock and test assertions to expect the formatted IP key (ipkg:${ip}) instead of raw IP strings.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: wrapping the IP fallback with ipKeyGenerator for IPv6 safety in the rate limiter.
Description check ✅ Passed The description includes all required sections: summary of what changed and why, files impacted, test validation results, and linked issue reference. The author thoroughly documented the fix and its rationale.
Linked Issues check ✅ Passed The code changes fully satisfy issue #3450 requirements: ipKeyGenerator is imported and properly wraps the IP fallback in the keyGenerator, user-id keying remains primary, and tests are updated to reflect the change.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the ERR_ERL_KEY_GEN_IPV6 error: updates to rateLimiter.js and its unit tests only, with no extraneous modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/rate-limit-ipv6-key-generator

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.58%. Comparing base (46e7534) to head (2e80763).
⚠️ Report is 7 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #3452   +/-   ##
=======================================
  Coverage   85.58%   85.58%           
=======================================
  Files         113      113           
  Lines        2878     2879    +1     
  Branches      796      797    +1     
=======================================
+ Hits         2463     2464    +1     
  Misses        329      329           
  Partials       86       86           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/middlewares/rateLimiter.js`:
- Line 31: Add a JSDoc header for the fallback inline key generator assigned to
keyGenerator (or extract it as a named function like fallbackKeyGenerator) that
documents the parameter and return type: include a one-line description, `@param`
{Request} req (or appropriate type) describing the request object, and `@returns`
{string} describing the returned key string; update the assignment to use the
named function or leave the inline function but place the JSDoc immediately
above it, and reference ipKeyGenerator(req.ip) inside the implementation as
currently used.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a055254d-031b-482d-a125-4962824543c1

📥 Commits

Reviewing files that changed from the base of the PR and between c5aae01 and 3b051ba.

📒 Files selected for processing (2)
  • lib/middlewares/rateLimiter.js
  • lib/middlewares/tests/rateLimiter.unit.tests.js

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the centralized rate-limiter middleware to normalize the IP-based fallback key using express-rate-limit’s ipKeyGenerator, addressing IPv6 safety requirements introduced in newer express-rate-limit versions and preventing startup validation failures on unauthenticated auth routes.

Changes:

  • Updated the default limiter keyGenerator to prefer req.user._id and otherwise use ipKeyGenerator(req.ip).
  • Updated unit tests to mock ipKeyGenerator and assert the normalized IP fallback behavior.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
lib/middlewares/rateLimiter.js Imports ipKeyGenerator and wraps the IP fallback in the default keyGenerator to satisfy IPv6-safe keying expectations.
lib/middlewares/tests/rateLimiter.unit.tests.js Extends the express-rate-limit mock with ipKeyGenerator and updates assertions for the new fallback key format.

Extract inline fallback key-generator into a named defaultKeyGenerator
function with a full JSDoc header (description, @param, @returns) per
coding guidelines. Addresses CodeRabbit review feedback.
@PierreBrisorgueil PierreBrisorgueil merged commit c882495 into master Apr 10, 2026
5 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/rate-limit-ipv6-key-generator branch April 10, 2026 13:44
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.

fix(rate-limit): wrap IP fallback with ipKeyGenerator for IPv6 safety

2 participants