Repository navigation
fix(auth): add a per-IP rate limit to magic link and forgot password - #1272
manas23sanam wants to merge 3 commits into
Conversation
Reviewer's GuideAPIAdd a per-IP rate limit to both email-sending auth endpoints, using a separate 30-request-per-10-minute bucket for each route.
DocumentationDocument the per-email and per-IP limits and the 429 response for both email-sending endpoints.
TestsVerify that each endpoint enforces the per-IP budget independently while allowing requests below the limit.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
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. |
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
Linked issuesChecked at commit b2115e5 #1271 Magic link and forgot password have no per-IP rate limit, only per email · 3 of 3 met
|
There was a problem hiding this comment.
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
|
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 |
|
Thank you @manas23sanam for adding a screencast! The |
hazelmayank
left a comment
There was a problem hiding this comment.
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?
|
@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 ( |
|
Hi @manas23sanam! 👋 It looks like this pull request currently has merge conflicts with the base branch ( Could you please rebase or merge the latest changes from How to resolve merge conflicts
Thank you for your contribution! 🚀 |
ArnavBallinCode
left a comment
There was a problem hiding this comment.
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, andtests/test_user_auth.py. - Please rebase onto
devand resolve the conflicts.
d175252 to
a57c23f
Compare
|
@ArnavBallinCode rebased onto dev and resolved the conflicts, ready for another look. |
Fixes #1271
Description
/api/auth/magic-linkand/api/auth/forgot-passwordwere 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 withRetry-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 routestests/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 routeTesting
pytest tests/test_user_auth.py tests/test_email.py tests/test_rate_limit.py tests/test_registration_protection.py: 137 passedruff check/ruff format --checkon changed filesBefore (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:
Documentation:
Tests:
Summary by CodeRabbit