feat(2.4): анти-брутфорс логина по email (защита от ротации IP) + тест

2.4(a) гонка rate-limit из аудита — НЕ баг: prod uvicorn без --workers, синхронная
_check_rate_limit без await атомарна в одном event loop. Лишний лок не добавляем.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-10 17:38:30 +10:00
co-authored by Claude Fable 5
parent c9e06cd5af
commit 3492010cd6
2 changed files with 74 additions and 12 deletions
+22 -12
View File
@@ -28,22 +28,26 @@ REFRESH_EXPIRE = 604800 # 7 days
LEGACY_USER = os.environ.get("SMETA_USER", "")
LEGACY_PASS = os.environ.get("SMETA_PASS", "")
# Rate limiting
# Rate limiting — по IP И по email. Только-IP обходится ротацией адресов:
# атакующий брутит один аккаунт с тысяч IP. Лимит по email защищает сам аккаунт.
# Порог по email выше (10/15мин), чтобы снизить риск lockout-DoS чужого аккаунта,
# но всё равно делает перебор паролей бессмысленным.
_login_attempts: dict[str, list[float]] = {}
MAX_ATTEMPTS = 5
MAX_ATTEMPTS = 5 # per-IP
LOCKOUT_SECONDS = 300
MAX_ATTEMPTS_EMAIL = 10 # per-email
LOCKOUT_SECONDS_EMAIL = 900
def _is_locked(ip: str) -> bool:
def _is_locked(key: str, max_attempts: int = MAX_ATTEMPTS, window: int = LOCKOUT_SECONDS) -> bool:
now = time.time()
attempts = _login_attempts.get(ip, [])
attempts = [t for t in attempts if now - t < LOCKOUT_SECONDS]
_login_attempts[ip] = attempts
return len(attempts) >= MAX_ATTEMPTS
attempts = [t for t in _login_attempts.get(key, []) if now - t < window]
_login_attempts[key] = attempts
return len(attempts) >= max_attempts
def _record_attempt(ip: str):
_login_attempts.setdefault(ip, []).append(time.time())
def _record_attempt(key: str):
_login_attempts.setdefault(key, []).append(time.time())
def hash_password(password: str) -> str:
@@ -104,7 +108,11 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
"""
if not SECRET:
return None
if client_ip and _is_locked(client_ip):
ip_key = f"ip:{client_ip}" if client_ip else None
email_key = f"email:{username.lower().strip()}" if username else None
if ip_key and _is_locked(ip_key, MAX_ATTEMPTS, LOCKOUT_SECONDS):
return None
if email_key and _is_locked(email_key, MAX_ATTEMPTS_EMAIL, LOCKOUT_SECONDS_EMAIL):
return None
# 1. Legacy admin user from env vars
@@ -118,8 +126,10 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
if user and user["verified"] and not user.get("blocked") and check_password(password, user["password_hash"]):
return _make_token(user["email"], role=user["role"])
if client_ip:
_record_attempt(client_ip)
if ip_key:
_record_attempt(ip_key)
if email_key:
_record_attempt(email_key)
return None