Skip to content

fix(auth): add rate limiting to login and register#53

Open
Flashl3opard wants to merge 3 commits intoalphaonelabs:mainfrom
Flashl3opard:fix/auth-rate-limit
Open

fix(auth): add rate limiting to login and register#53
Flashl3opard wants to merge 3 commits intoalphaonelabs:mainfrom
Flashl3opard:fix/auth-rate-limit

Conversation

@Flashl3opard
Copy link
Copy Markdown
Contributor

@Flashl3opard Flashl3opard commented Apr 23, 2026

fix(auth): add rate limiting to login and register

Summary

  • Add per-IP rate limiting to /api/login and /api/register
  • Return 429 Too Many Requests with Retry-After when the limit is exceeded
  • Add tests for auth rate limiting and window reset behavior

Validation

  • pytest tests/test_api_auth.py -q

Notes

  • Default limit: 5 attempts per 60 seconds
  • Test env overrides are supported via AUTH_RATE_LIMIT_MAX_ATTEMPTS and AUTH_RATE_LIMIT_WINDOW_SECONDS

Purpose

Adds rate limiting protection to the /api/login and /api/register endpoints to prevent brute-force attacks and credential stuffing attempts.

Key Modifications

Authentication Rate Limiter (src/worker.py)

  • Implements an in-memory, per-client-IP rate limiter with a fixed 60-second window and 5 maximum attempts by default
  • Configuration via environment variables: AUTH_RATE_LIMIT_WINDOW_SECONDS and AUTH_RATE_LIMIT_MAX_ATTEMPTS
  • Rate limit checks are performed early in the request flow, before request body parsing or database operations
  • Exceeding the limit returns HTTP 429 with a JSON response including Retry-After header and CORS headers

Test Infrastructure (tests/helpers.py)

  • Updated make_env() helper to include rate-limiting configuration in the mocked environment

Test Coverage (tests/test_api_auth.py)

  • Automatic cleanup of shared in-memory rate-limit state before each test
  • New tests verify rate limiting behavior for both registration and login endpoints
  • Tests confirm requests from the same IP are rate-limited (via CF-Connecting-IP header)
  • Tests validate 429 response is returned after exceeding attempt threshold
  • Tests confirm rate limit window reset after the configured duration

Impact

  • Users will now be protected against brute-force attacks on authentication endpoints
  • Legitimate users exceeding the limit will receive a clear 429 response with retry guidance
  • Rate limits are applied uniformly across all clients based on their IP address
  • Configuration is flexible for different deployment environments

Copilot AI review requested due to automatic review settings April 23, 2026 14:36
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 23, 2026

Warning

Rate limit exceeded

@Flashl3opard has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 25 minutes and 22 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 25 minutes and 22 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: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: bcc8f089-0f59-4a02-a958-f3dabb54cb6f

📥 Commits

Reviewing files that changed from the base of the PR and between 4c0c173 and 8dc7179.

📒 Files selected for processing (3)
  • src/worker.py
  • tests/helpers.py
  • tests/test_api_auth.py

Walkthrough

Introduces an in-memory, per-client-IP authentication rate limiter with configurable window and maximum attempt thresholds. Returns HTTP 429 responses with Retry-After headers when limits are exceeded. Integrates early checks into api_register and api_login endpoints before request body parsing.

Changes

Cohort / File(s) Summary
Rate Limiter Implementation
src/worker.py
Adds in-memory rate limiter tracking per-client IP with configurable AUTH_RATE_LIMIT_WINDOW_SECONDS and AUTH_RATE_LIMIT_MAX_ATTEMPTS. Returns 429 JSON responses with Retry-After and CORS headers when thresholds exceeded. Integrated as early guard in authentication endpoints.
Test Infrastructure
tests/helpers.py, tests/test_api_auth.py
Updates make_env helper to include rate-limiting configuration. Adds pytest fixtures for state cleanup, helper functions for test configuration (60s window, 2 max attempts), and behavioral test cases validating rate-limiting behavior per client IP on registration and login endpoints, including window reset scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding rate limiting to the authentication endpoints (login and register).
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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: 2

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

Inline comments:
In `@src/worker.py`:
- Around line 452-458: Replace the current multi-header fallback logic for
client_ip with a trusted-only lookup: read solely
req.headers.get("CF-Connecting-IP") into client_ip (do not use "X-Forwarded-For"
or "X-Real-IP"), and if CF-Connecting-IP is missing or empty, bail out in a
fail-closed manner (e.g., log and return an error/429) rather than deriving an
IP from untrusted headers; update the subsequent key construction (key =
f"{route}:{client_ip}") to use this trusted client_ip value.

In `@tests/test_api_auth.py`:
- Around line 145-162: After the third call in
test_register_is_rate_limited_per_ip assert the 429 response includes a
non-empty Retry-After header and that the response body matches the rate-limit
payload produced by _too_many_requests (e.g., parse the response and assert the
error/message field or text contains the expected "Too Many Requests" content);
apply the same two assertions to test_login_is_rate_limited_per_ip, and in
test_login_rate_limit_resets_after_window add an extra immediate third request
after the successful post-window call to assert the bucket re-arms and returns
429 with Retry-After and the expected rate-limit body.
🪄 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: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 60659546-7c64-4607-a400-2b2ffb68cab0

📥 Commits

Reviewing files that changed from the base of the PR and between 7f30af6 and 4c0c173.

📒 Files selected for processing (3)
  • src/worker.py
  • tests/helpers.py
  • tests/test_api_auth.py

Comment thread src/worker.py Outdated
Comment thread tests/test_api_auth.py
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

Adds in-memory, per-IP rate limiting for the auth endpoints to reduce brute-force/abuse on /api/login and /api/register, with new tests covering basic limiting behavior and window resets.

Changes:

  • Introduces a shared auth rate-limit checker and 429 response helper (with Retry-After).
  • Applies rate limiting to api_register and api_login.
  • Adds pytest coverage for per-IP limiting and login window reset; updates test env defaults for rate-limit settings.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.

File Description
src/worker.py Adds rate limiting state, config reading from env, and enforces it in login/register handlers.
tests/test_api_auth.py Adds fixtures and new tests for rate limiting + window reset behavior.
tests/helpers.py Sets default auth rate-limit env values in make_env() for tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/worker.py
Comment thread src/worker.py
Comment thread tests/test_api_auth.py Outdated
Comment thread tests/test_api_auth.py
@Flashl3opard
Copy link
Copy Markdown
Contributor Author

@A1L13N Please review the PR if you geta chance, thanks!

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