Implement login endpoint rate limiting (TASK-007)

- Add in-memory rate limiter with per-IP deque tracking of attempt timestamps
- Limit login attempts to 5 per 60 seconds per IP, return 429 on excess
- Add Retry-After header to rate limit responses
- Implement IP extraction utility with proxy trust validation (prevent X-Forwarded-For spoofing)
- Integrate rate limiter into auth router and dependencies
- Add 10-second asyncio.sleep on failed login attempts to further slow brute-force
- Add comprehensive tests for rate limiting (9 new tests, all passing)
- Update Features.md to document login rate limiting
- Update Backend-Development.md with rate limiting conventions and design patterns
- Fix test infrastructure issues: update password to meet complexity requirements
- Fix TestValidateSession tests to use Bearer token authentication
- All tests passing: 23 auth tests + full test suite coverage

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-26 12:40:52 +02:00
parent 9725714aa2
commit ea4c7c2f85
9 changed files with 414 additions and 73 deletions

View File

@@ -5,22 +5,40 @@
The session token is returned both in the JSON body (for API-first
consumers) and as an ``HttpOnly`` cookie (for the browser SPA).
Login attempts are rate-limited to 5 per minute per IP address to prevent
brute-force attacks. Requests exceeding the limit return ``429 Too Many Requests``
with a ``Retry-After`` header.
"""
from __future__ import annotations
import asyncio
import structlog
from fastapi import APIRouter, HTTPException, Request, Response, status
from app.dependencies import AuthDep, DbDep, SessionCacheDep, SessionRepoDep, SettingsDep
from app.dependencies import (
AuthDep,
DbDep,
LoginRateLimiterDep,
SessionCacheDep,
SessionRepoDep,
SettingsDep,
)
from app.models.auth import LoginRequest, LoginResponse, LogoutResponse
from app.services import auth_service
from app.utils.client_ip import get_client_ip
from app.utils.constants import SESSION_COOKIE_NAME
log: structlog.stdlib.BoundLogger = structlog.get_logger()
router = APIRouter(prefix="/api/auth", tags=["auth"])
# Trusted proxy IPs that can set X-Forwarded-For header.
# By default, none are trusted. In production behind nginx, add the nginx container IP.
_TRUSTED_PROXIES: list[str] = []
@router.post(
"/login",
@@ -30,27 +48,47 @@ router = APIRouter(prefix="/api/auth", tags=["auth"])
async def login(
body: LoginRequest,
response: Response,
request: Request,
db: DbDep,
settings: SettingsDep,
session_repo: SessionRepoDep,
rate_limiter: LoginRateLimiterDep,
) -> LoginResponse:
"""Verify the master password and return a session token.
On success the token is also set as an ``HttpOnly`` ``SameSite=Lax``
cookie so the browser SPA benefits from automatic credential handling.
Rate limiting: Up to 5 login attempts per minute per client IP.
Requests exceeding this limit return ``429 Too Many Requests`` with
a ``Retry-After`` header.
Args:
body: Login request validated by Pydantic.
response: FastAPI response object used to set the cookie.
request: The incoming HTTP request (used to extract client IP).
db: Injected aiosqlite connection.
settings: Application settings (used for session duration).
session_repo: The session repository.
rate_limiter: The login rate limiter (per IP).
Returns:
:class:`~app.models.auth.LoginResponse` containing the token.
Raises:
HTTPException: 401 if the password is incorrect.
HTTPException: 429 if the rate limit is exceeded.
"""
client_ip = get_client_ip(request, trusted_proxies=_TRUSTED_PROXIES)
if not rate_limiter.is_allowed(client_ip):
log.warning("login_rate_limit_exceeded", client_ip=client_ip)
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Too many login attempts. Please try again later.",
headers={"Retry-After": "60"},
)
try:
signed_token, expires_at = await auth_service.login(
db,
@@ -60,6 +98,11 @@ async def login(
session_repo=session_repo,
)
except ValueError as exc:
# Add delay on wrong password to slow down brute-force attacks.
# The bcrypt checkpw already takes ~100ms at cost factor 12,
# but an extra 10 seconds makes automation much less feasible.
await asyncio.sleep(10.0)
log.warning("login_failed", client_ip=client_ip, error=str(exc))
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=str(exc),
@@ -73,6 +116,7 @@ async def login(
secure=settings.session_cookie_secure,
max_age=settings.session_duration_minutes * 60,
)
log.info("login_success", client_ip=client_ip)
return LoginResponse(token=signed_token, expires_at=expires_at)