Skip to content

fix(auth): add a per-IP rate limit to magic link and forgot password - #1272

Open
manas23sanam wants to merge 3 commits into
fossasia:devfrom
manas23sanam:fix/magic-link-ip-rate-limit
Open

manas23sanam wants to merge 3 commits into
fossasia:devfrom
manas23sanam:fix/magic-link-ip-rate-limit

Conversation

@manas23sanam

@manas23sanam manas23sanam commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1271

Description

/api/auth/magic-link and /api/auth/forgot-password were only limited per email, so one client could rotate addresses and make the portal send mail to all of them. Both routes now also have a per-IP limit (30 requests per 10 minutes, per route), checked before the body is read. Over the limit they return 429 with Retry-After: 600. The per-email limit is unchanged.

The client IP is taken the same way as limit_registration (request.client.host, forwarded headers are left to the trusted proxy setup from #1085). The limit is a bit loose on purpose, since attendees at an event often share one network.

Changes Made

  • portal/routers/auth.py: limit_email_requests_per_ip() helper + EMAIL_REQUESTS_PER_IP / EMAIL_REQUESTS_IP_WINDOW_SECONDS, called first in both routes
  • tests/test_user_auth.py: 30 requests with different emails from one IP pass and the 31st gets 429 (both routes), and the budget is per route

Testing

  • New tests fail on dev without the fix (3 failed) and pass with it
  • pytest tests/test_user_auth.py tests/test_email.py tests/test_rate_limit.py tests/test_registration_protection.py: 137 passed
  • ruff check / ruff format --check on changed files

Before (dev): 100 requests with rotating emails from one IP -> {200: 100} on both routes.
After: requests 1-30 -> 200, request 31 -> 429.

Summary by Sourcery

Prevent clients from bypassing email-sending limits by rotating addresses.

Bug Fixes:

  • Add a per-IP limit of 30 requests per 10 minutes to the magic-link and forgot-password email-sending routes, returning 429 with a Retry-After header when exceeded.

Documentation:

  • Document the per-email and per-IP limits for the magic-link and forgot-password routes in the route map.

Tests:

  • Test the per-IP limits on both routes and verify that each route has an independent request budget.

Summary by CodeRabbit

  • Bug Fixes
    • Magic-link sign-in and password-reset requests are limited to 30 requests per IP address every 10 minutes, in addition to the existing limit of 5 requests per email address per hour.
    • Exceeding the IP limit returns a rate-limit response with a 10-minute retry period. Limits are applied separately to each request type, so reaching the limit for one does not block the other.

@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

API

Add a per-IP rate limit to both email-sending auth endpoints, using a separate 30-request-per-10-minute bucket for each route.

  • portal/routers/auth.py L490-514, L634

Documentation

Document the per-email and per-IP limits and the 429 response for both email-sending endpoints.

  • .agents/context/ROUTE_MAP.md L342-346

Tests

Verify that each endpoint enforces the per-IP budget independently while allowing requests below the limit.

  • tests/test_user_auth.py L19, L28, L810-833

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

Copy link
Copy Markdown
Contributor

Hi @manas23sanam, thanks for your contribution!

Before we can review this PR, please add a short screencast video showing the change working (before/after where relevant).

If no video is added within 72 hours, this PR will be closed automatically. You are welcome to reopen it or submit a new PR once you have the screencast.

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The magic-link and forgot-password routes now limit requests per client IP to 30 in 600 seconds. They retain their existing per-email limits. Tests verify rejection at the limit and separate limits for each route.

Changes: Email request rate limits

Layer / File(s) Summary
Define per-IP limits
portal/routers/auth.py
Added a per-IP limit helper with separate action-specific limits. It returns HTTP 429 with Retry-After: 600 after 30 requests in 600 seconds.
Apply limits to email routes
portal/routers/auth.py, tests/test_user_auth.py, .agents/context/ROUTE_MAP.md
Both routes apply the per-IP check while retaining their per-email limits. Tests verify the limit and confirm that exhausting one route’s limit does not block the other. The route map documents both limits.

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

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to b2115

The magic-link and forgot-password routes now cap requests per client IP at 30 per 10 minutes, per route, and return 429 with Retry-After when exceeded. The existing per-email limits are unchanged. The proxy configuration resolves real client addresses, and tests cover the limit and route independence. No merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: a per-IP rate limit on the magic-link and forgot-password routes. It also uses the conventional fix(auth) prefix. The raw summary and objectives both confirm the chang…
Linked Issues check Passed [#1271] requires a per-IP limit on POST /api/auth/magic-link and POST /api/auth/forgot-password that returns 429 with Retry-After. The per-email limit must stay unchanged. The whole-PR diff against th…
Out of Scope Changes check Passed Every change in the whole-PR diff relates to #1271. portal/routers/auth.py adds the constants and helper and one call at the top of each of the two named routes. tests/test_user_auth.py adds tests for…
Full details: Title check

Explanation

The title names the main change: a per-IP rate limit on the magic-link and forgot-password routes. It also uses the conventional fix(auth) prefix. The raw summary and objectives both confirm the change adds a 30-request-per-10-minute per-IP limit to these two routes, with 429 and Retry-After. The title is specific and does not need to list every detail.

Full details: Linked Issues check

Explanation

[#1271] requires a per-IP limit on POST /api/auth/magic-link and POST /api/auth/forgot-password that returns 429 with Retry-After. The per-email limit must stay unchanged. The whole-PR diff against the merge base adds EMAIL_REQUESTS_PER_IP = 30 and EMAIL_REQUESTS_IP_WINDOW_SECONDS = 600 in portal/routers/auth.py. The helper limit_email_requests_per_ip(request, action) calls check_rate_limit with key f"{action}_ip" and request.client.host. On rejection it raises HTTPException 429 with Retry-After: 600. request_magic_link and forgot_password_request call the helper before read_json_body. Separate action keys (magic_link_ip, forgot_password_ip) give each route its own budget. The per-email code path is not modified. The current head diff for portal/routers/auth.py matches this analysis. The diff against the previous reviewed head was empty for this file, so no incremental code change affects the prior conclusion. Tests in tests/test_user_auth.py cover rotating emails reaching 429 and per-route independence. The tests were not executed in this review.

Full details: Out of Scope Changes check

Explanation

Every change in the whole-PR diff relates to #1271. portal/routers/auth.py adds the constants and helper and one call at the top of each of the two named routes. tests/test_user_auth.py adds tests for the per-IP limit, Retry-After, and per-route independence. The raw summary reports a documentation update to .agents/context/ROUTE_MAP.md that describes the new limit. This supports the same objective. No reviewed change touches other routes, the per-email limit, or unrelated behavior.

Finishing Touches

Generate unit tests (beta)

  • 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: 410c3466-195d-4e90-ac00-0ab534822b35
Commits

Reviewing files that changed from the base of the PR and between a57c23f and b2115e5.

Files selected for processing: 2

  • portal/routers/auth.py
  • tests/test_user_auth.py

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

@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit b2115e5

#1271 Magic link and forgot password have no per-IP rate limit, only per email · 3 of 3 met

# Requirement Status Notes
1 Rate-limit both magic-link and forgot-password requests per IP ✅ Met Both routes check an IP-keyed limit of 30 requests per 600 seconds before reading the request body.
2 Return 429 with a Retry-After header when the per-IP limit is exceeded ✅ Met The shared helper returns 429 with Retry-After set to 600 seconds.
3 Keep the per-email limit as it is ✅ Met Both routes retain their existing per-email limit of 5 requests per hour.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="portal/routers/auth.py" line_range="486" />
<code_context>
+def limit_email_requests_per_ip(request: Request, action: str) -> None:
+    # Same peer address as limit_registration: forwarded headers are handled by the trusted proxy setup.
+    client_ip = request.client.host if request.client else "unknown"
+    if not check_rate_limit(
+        f"{action}_ip",
+        client_ip,
</code_context>
<issue_to_address>
**Requests exceed the per-IP budget**

When requests are served by multiple workers or replicas, each worker or replica keeps its own `_rates` dictionary, so requests distributed across instances receive a separate allowance on each and the caller can send substantially more than 30 emails per route in ten minutes before seeing 429s.

Store these counters in a shared rate-limit backend, or ensure the production deployment routes these endpoints through a single rate-limit state.
</issue_to_address>

### Comment 2
<location path="portal/routers/auth.py" line_range="496" />
<code_context>
+            status_code=429,
+            detail="Too many requests",
+            headers={"Retry-After": str(EMAIL_REQUESTS_IP_WINDOW_SECONDS)},
+        )
+
+
</code_context>
<issue_to_address>
**Retry window is overstated**

When the IP's 30 allowed requests span most of the 600-second window, `limit_email_requests_per_ip` always returns `Retry-After: 600`, although `check_rate_limit` admits requests again as soon as an old timestamp expires. Clients honoring the header unnecessarily wait out the full window.

Set `Retry-After` to the time remaining until the oldest counted request expires.
</issue_to_address>

### Comment 3
<location path="portal/routers/auth.py" line_range="501" />
<code_context>
+
 @router.post("/api/auth/magic-link")
 async def request_magic_link(request: Request):
+    limit_email_requests_per_ip(request, "magic_link")
     data = await request.json()
     email = data.get("email", "").strip().lower()
</code_context>
<issue_to_address>
**Route context omits new limits**

When the route behavior changes without updating its relevant context file, the route map still omits the new per-IP limits, so maintainers consulting repository context are not told that these email routes allow 30 requests per 10 minutes per IP.

Update `.agents/context/ROUTE_MAP.md` to document both endpoints and their per-IP limits.

Also at `portal/routers/auth.py:621`.
</issue_to_address>

### Comment 4
<location path="tests/test_user_auth.py" line_range="719-720" />
<code_context>
+    @pytest.mark.parametrize("path", ["/api/auth/magic-link", "/api/auth/forgot-password"])
+    async def test_email_sending_routes_are_limited_per_ip(self, setup_db, monkeypatch, path):
+        """Rotating the email must not get around the limit on routes that send mail."""
+        import portal.rate_limit
+        from portal.routers.auth import EMAIL_REQUESTS_PER_IP
+
+        monkeypatch.setattr(portal.rate_limit, "_rates", {})
</code_context>
<issue_to_address>
**New test imports stay local**

When the new tests are run, both new tests place imports inside their function bodies, contrary to the repository’s import-placement rule.

Move these imports to the module’s import section.

Also at `tests/test_user_auth.py:735-736`.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: portal/routers/auth.py:486, portal/routers/auth.py:496


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread portal/routers/auth.py Resolved
Comment thread portal/routers/auth.py Resolved
Comment thread portal/routers/auth.py Resolved
Comment thread tests/test_user_auth.py Resolved
@manas23sanam

Copy link
Copy Markdown
Contributor Author

Screencast: before (dev), 35 requests from one IP with a different email each time all return 200 on magic-link and forgot-password. After (this PR), requests 1-30 return 200 and 31+ return 429 with Retry-After: 600. The new tests pass.

pr1272-small.mp4

@github-actions

Copy link
Copy Markdown
Contributor

Thank you @manas23sanam for adding a screencast! The needs-screencast label has been removed and this PR is ready for maintainer review.

@hazelmayank hazelmayank left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I read the diff and the existing threads, and ran tests/test_user_auth.py, tests/test_rate_limit.py and tests/test_registration_protection.py locally on d175252 (125 passed). I also put dev auth.py back in and the three new tests failed, so they do catch the missing per-IP limit. I did not try it behind a real proxy. From docker-compose.yml, FORWARDED_ALLOW_IPS is set, so request.client.host should be the real client IP there.

Looks good to me. One question, not a blocker: login allows 60 per minute per IP, while this is 30 per 10 minutes. Attendees on one venue network could hit that when a session starts and many of them ask for a magic link. Is that limit enough for that case?

@manas23sanam

Copy link
Copy Markdown
Contributor Author

@hazelmayank thanks for testing it! It's lower than login on purpose because every request here sends an email. It's per route and one constant (EMAIL_REQUESTS_PER_IP), so I'm happy to raise it if you expect bigger venues on one network.

@github-actions

Copy link
Copy Markdown
Contributor

Hi @manas23sanam! 👋

It looks like this pull request currently has merge conflicts with the base branch (dev) that prevent it from being merged.

Could you please rebase or merge the latest changes from dev and resolve the conflicts?

How to resolve merge conflicts
  1. Fetch the latest changes from upstream:
    git fetch upstream dev
    git checkout fix/magic-link-ip-rate-limit
    git merge upstream/dev
  2. Open the conflicting files in your editor, resolve the conflicts, and save.
  3. Stage and commit the resolved files:
    git add <resolved-files>
    git commit -m "Merge upstream/dev and resolve conflicts"
    git push origin fix/magic-link-ip-rate-limit

Thank you for your contribution! 🚀

@ArnavBallinCode ArnavBallinCode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The per-IP rate limiting on /api/auth/magic-link and /api/auth/forgot-password (limit_email_requests_per_ip) looks good, but this PR has merge conflicts with dev:

  • Conflicts in .agents/context/ROUTE_MAP.md, portal/routers/auth.py, and tests/test_user_auth.py.
  • Please rebase onto dev and resolve the conflicts.

@manas23sanam
manas23sanam force-pushed the fix/magic-link-ip-rate-limit branch from d175252 to a57c23f Compare December 4, 2026 11:50
@manas23sanam

Copy link
Copy Markdown
Contributor Author

@ArnavBallinCode rebased onto dev and resolved the conflicts, ready for another look.

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.

Magic link and forgot password have no per-IP rate limit, only per email

3 participants