Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Security: rate limit login failures and password reset requests (AUTH-05)

Omega (QA)2c20a3ce6f67
diff --git a/backend/auth_routes.py b/backend/auth_routes.py
index 1057af6..4332a7a 100644
--- a/backend/auth_routes.py
+++ b/backend/auth_routes.py
@@ -17,11 +17,17 @@ try:
from . import db_handler, notifications
from .auth_utils import generate_token, token_required, is_valid_email, is_valid_password, is_password_too_long
from .localization import SUPPORTED_LANGUAGES
+ from .rate_limit import (
+ login_limited, record_login_failure, clear_login_failures,
+ reset_request_limited, record_reset_request)
except ImportError:
# Fallback for development environment
import db_handler, notifications
from auth_utils import generate_token, token_required, is_valid_email, is_valid_password, is_password_too_long
from localization import SUPPORTED_LANGUAGES
+ from rate_limit import (
+ login_limited, record_login_failure, clear_login_failures,
+ reset_request_limited, record_reset_request)
# Import bcrypt from extensions since it's initialized with the app
try:
@@ -215,6 +221,11 @@ def login():
if is_password_too_long(password):
return jsonify({'message': 'Password must not exceed 72 characters!'}), 400
+ # AUTH-05: refuse a locked-out (IP, username) pair before the
+ # password check, so brute force cannot keep burning bcrypt.
+ if login_limited(request.remote_addr, username):
+ return jsonify({'message': 'Too many failed login attempts. Try again later!'}), 429
+
conn = db_handler.get_db_connection()
with conn.cursor() as cur:
# AUTH-12: OIDC-only mode forbids local sign-in outright. The
@@ -232,10 +243,14 @@ def login():
# would short-circuit it and restore the timing split.
password_ok = bcrypt.check_password_hash(password_hash, password)
if not user or not password_ok:
+ record_login_failure(request.remote_addr, username)
return jsonify({'message': 'Invalid username or password!'}), 401
if not user[4]: # is_active
return jsonify({'message': 'Account is inactive!'}), 401
+
+ # A successful login clears the pair's failure count.
+ clear_login_failures(request.remote_addr, username)
user_id = user[0]
@@ -418,7 +433,16 @@ def request_password_reset():
# not reveal whether the address is registered or SSO-managed.
if user[1] is not None and _oidc_only_mode_enabled(cur):
return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
-
+
+ # AUTH-05: cap reset requests per address. A limited request
+ # gets the same generic 200 as an unknown address, and no
+ # token is minted and no mail is sent, so the endpoint
+ # cannot be used as an unauthenticated mail relay.
+ if reset_request_limited(email):
+ current_app.logger.warning(
+ f"Password reset requests rate-limited for {email}.")
+ return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
+
# Generate reset token. Only its hash is stored (AUTH-08), so
# the database value alone can never complete a reset; the
# emailed link carries the raw token. Tokens live one hour.
@@ -435,6 +459,7 @@ def request_password_reset():
)
conn.commit()
+ record_reset_request(email)
# Get email base URL from settings with correct precedence
# Priority: Environment Variable > Database Setting > Hardcoded Default
diff --git a/backend/rate_limit.py b/backend/rate_limit.py
new file mode 100644
index 0000000..556c29e
--- /dev/null
+++ b/backend/rate_limit.py
@@ -0,0 +1,90 @@
+"""Conservative in-memory rate limiting for the auth surface (AUTH-05).
+
+Two narrow limiters, both best effort and per worker (the app runs
+two gunicorn workers, so a distributed attacker gets twice the
+budget; the thresholds below are set with that in mind):
+
+- Login failures: 10 failures for one (client IP, username) pair in
+ 5 minutes, then 429 for the rest of the window. A success clears
+ the pair's failures, so a legitimate user who mistypes a few times
+ is never locked out by old attempts.
+- Password reset requests: 5 requests for one email address in one
+ hour. A limited request is answered with the same generic 200 as
+ an unknown address, and no token is minted and no mail is sent, so
+ the endpoint cannot be used as an unauthenticated mail relay and
+ the limit itself does not reveal whether the address is registered.
+
+Registration is deliberately not limited here: the first-user race
+(AUTH-07) is fixed with a database lock instead, and a registration
+cap would break legitimate bulk onboarding.
+"""
+import threading
+import time
+
+LOGIN_MAX_FAILURES = 10
+LOGIN_WINDOW_SECONDS = 300
+RESET_MAX_REQUESTS = 5
+RESET_WINDOW_SECONDS = 3600
+
+
+class _AttemptTracker:
+ """Thread-safe per-key timestamp lists with window pruning."""
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._attempts = {}
+
+ def _prune(self, key, window):
+ cutoff = time.monotonic() - window
+ stamps = [t for t in self._attempts.get(key, []) if t > cutoff]
+ if stamps:
+ self._attempts[key] = stamps
+ else:
+ self._attempts.pop(key, None)
+ return stamps
+
+ def record(self, key):
+ with self._lock:
+ self._attempts.setdefault(key, []).append(time.monotonic())
+
+ def count(self, key, window):
+ with self._lock:
+ return len(self._prune(key, window))
+
+ def is_limited(self, key, limit, window):
+ return self.count(key, window) >= limit
+
+ def clear(self, key):
+ with self._lock:
+ self._attempts.pop(key, None)
+
+
+_login_tracker = _AttemptTracker()
+_reset_tracker = _AttemptTracker()
+
+
+def _login_key(ip_address, username):
+ return (ip_address or "", (username or "").lower())
+
+
+def login_limited(ip_address, username):
+ return _login_tracker.is_limited(
+ _login_key(ip_address, username),
+ LOGIN_MAX_FAILURES, LOGIN_WINDOW_SECONDS)
+
+
+def record_login_failure(ip_address, username):
+ _login_tracker.record(_login_key(ip_address, username))
+
+
+def clear_login_failures(ip_address, username):
+ _login_tracker.clear(_login_key(ip_address, username))
+
+
+def reset_request_limited(email):
+ return _reset_tracker.is_limited(
+ (email or "").lower(), RESET_MAX_REQUESTS, RESET_WINDOW_SECONDS)
+
+
+def record_reset_request(email):
+ _reset_tracker.record((email or "").lower())
diff --git a/tests/test_rate_limiting.py b/tests/test_rate_limiting.py
new file mode 100644
index 0000000..2629358
--- /dev/null
+++ b/tests/test_rate_limiting.py
@@ -0,0 +1,94 @@
+"""Rate limiting on the auth surface (AUTH-05).
+
+Login: 10 failures for one (client IP, username) pair in 5 minutes,
+then 429. A success clears the pair's failures. Reset requests: 5
+per email address per hour; a limited request is answered with the
+same generic 200 as an unknown address, and no token is minted.
+"""
+from backend.auth_routes import _hash_reset_token
+
+
+def _wrong_login(client, username):
+ return client.post("/api/auth/login", json={
+ "username": username, "password": "WrongPass123!"})
+
+
+def _token_hash_for(db_connection, email):
+ with db_connection.cursor() as cur:
+ cur.execute(
+ "SELECT token FROM password_reset_tokens WHERE user_id = "
+ "(SELECT id FROM users WHERE email = %s)", (email,))
+ row = cur.fetchone()
+ return row[0] if row else None
+
+
+def test_login_locks_out_after_repeated_failures(client, user_factory):
+ user = user_factory()
+ for _ in range(10):
+ r = _wrong_login(client, user["username"])
+ assert r.status_code == 401
+ r = _wrong_login(client, user["username"])
+ assert r.status_code == 429
+ assert "Too many failed login attempts" in r.get_json()["message"]
+ # The correct password does not get through while locked out.
+ r = client.post("/api/auth/login", json={
+ "username": user["username"], "password": "TestPass123!"})
+ assert r.status_code == 429
+
+
+def test_successful_login_clears_failure_count(client, user_factory):
+ user = user_factory()
+ for _ in range(9):
+ assert _wrong_login(client, user["username"]).status_code == 401
+ r = client.post("/api/auth/login", json={
+ "username": user["username"], "password": "TestPass123!"})
+ assert r.status_code == 200
+ # The counter cleared on success: one more failure is a plain 401.
+ assert _wrong_login(client, user["username"]).status_code == 401
+
+
+def test_lockout_is_per_username(client, user_factory):
+ locked = user_factory()
+ other = user_factory()
+ for _ in range(11):
+ _wrong_login(client, locked["username"])
+ assert _wrong_login(client, locked["username"]).status_code == 429
+ r = client.post("/api/auth/login", json={
+ "username": other["username"], "password": "TestPass123!"})
+ assert r.status_code == 200
+
+
+def test_reset_requests_capped_per_email(
+ client, user_factory, db_connection):
+ user = user_factory()
+ email = f"{user['username']}@test.local"
+ for _ in range(5):
+ r = client.post("/api/auth/password/reset-request",
+ json={"email": email})
+ assert r.status_code == 200
+ token_after_five = _token_hash_for(db_connection, email)
+ assert token_after_five is not None
+ # The sixth request is answered generically and mints nothing.
+ r = client.post("/api/auth/password/reset-request",
+ json={"email": email})
+ assert r.status_code == 200
+ assert r.get_json()["message"] == (
+ "If your email is registered, you will receive a "
+ "password reset link.")
+ assert _token_hash_for(db_connection, email) == token_after_five
+
+
+def test_reset_limit_does_not_block_other_addresses(
+ client, user_factory, db_connection):
+ capped = user_factory()
+ other = user_factory()
+ capped_email = f"{capped['username']}@test.local"
+ other_email = f"{other['username']}@test.local"
+ for _ in range(6):
+ client.post("/api/auth/password/reset-request",
+ json={"email": capped_email})
+ assert _token_hash_for(db_connection, capped_email) is not None
+ r = client.post("/api/auth/password/reset-request",
+ json={"email": other_email})
+ assert r.status_code == 200
+ assert _token_hash_for(db_connection, other_email) is not None