fix(security): throttle failed logins per client address and email

POST /auth/login accepted unlimited password guesses.

- FailureThrottle: thread-safe sliding window kept in process (the
  compose stack runs a single uvicorn process)
- keyed by (client address, email): an attacker cannot lock a victim
  out from everywhere, and users behind one NAT are not punished for
  each other's typos
- after LOGIN_MAX_FAILURES (10) failures within
  LOGIN_FAILURE_WINDOW_SECONDS (900) the endpoint answers 429 with
  Retry-After; a successful login clears the count; 0 disables it
This commit is contained in:
ahp committed 2026-11-26 16:25:34 +03:30
1 parent ee42254ab1
commit 103f72f41e
10 files changed
+156 -2

No files matched your search

+4
View File
@@ -135,6 +135,10 @@ WEBHOOK_ATTEMPTS=2
# Allow callbacks to private/loopback addresses (trusted installs only).
WEBHOOK_ALLOW_PRIVATE_TARGETS=false
# --- Login brute-force guard ---
LOGIN_MAX_FAILURES=10
LOGIN_FAILURE_WINDOW_SECONDS=900
# --- Deployment (deploy/docker-compose.yml) ---
# Required: the compose file refuses to start without a real password.
POSTGRES_PASSWORD=change-me-to-a-long-random-value
+3
View File
@@ -26,6 +26,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
DNS rebinding), redirects are not followed and proxy env vars are ignored.
**Breaking for receivers on private addresses:** set
`WEBHOOK_ALLOW_PRIVATE_TARGETS=true` on trusted single-tenant installs.
- `POST /auth/login` is throttled: after `LOGIN_MAX_FAILURES` (10) failures
per client address and email within `LOGIN_FAILURE_WINDOW_SECONDS` (900)
it answers 429 with `Retry-After`; a successful login clears the count.
### Added
+1
View File
@@ -226,6 +226,7 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
| `STREAMING_DECODE` | `true` | خواندن بلاک‌به‌بلاک صدا (حافظهٔ اوج ∝ پنجره، نه طول فایل) |
| `WEBHOOK_SIGNING_SECRET` | خالی | رمز HMAC برای کال‌بک‌های پایان کار (`X-Sokhan-Signature`)؛ خالی یعنی بدون امضا |
| `WEBHOOK_ALLOW_PRIVATE_TARGETS` | `false` | اجازهٔ کال‌بک به نشانی‌های خصوصی/لوکال (فقط برای نصب تک‌کاربرهٔ مورد اعتماد) |
| `LOGIN_MAX_FAILURES` / `LOGIN_FAILURE_WINDOW_SECONDS` | `10` / `900` | تعداد ورود ناموفق برای هر نشانی و ایمیل پیش از `429`؛ `0` یعنی غیرفعال |
| `SUMMARY_ENABLED` | `false` | فلگ امکان خلاصه‌سازی با LLM |
| `LLM_API_BASE` / `LLM_API_KEY` / `LLM_MODEL` | خالی | endpoint سازگار با OpenAI |
| `TELEGRAM_BOT_TOKEN` | خالی | فعال‌سازی فرایند ربات |
+1
View File
@@ -225,6 +225,7 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
| `STREAMING_DECODE` | `true` | decode audio block-by-block (peak RAM ∝ window, not file length) |
| `WEBHOOK_SIGNING_SECRET` | empty | HMAC secret for job-completion callbacks (`X-Sokhan-Signature`); empty sends them unsigned |
| `WEBHOOK_ALLOW_PRIVATE_TARGETS` | `false` | allow callbacks to private/loopback addresses (trusted single-tenant installs only) |
| `LOGIN_MAX_FAILURES` / `LOGIN_FAILURE_WINDOW_SECONDS` | `10` / `900` | failed logins per client address and email before `429`; `0` disables |
| `SUMMARY_ENABLED` | `false` | LLM summaries feature flag |
| `LLM_API_BASE` / `LLM_API_KEY` / `LLM_MODEL` | empty | OpenAI-compatible endpoint |
| `TELEGRAM_BOT_TOKEN` | empty | enables the bot process |
+36 -2
View File
@@ -11,13 +11,15 @@ Deliberately lightweight for v1:
import re
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from sokhan.api.deps import require_bot
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
from sokhan.config import get_settings
from sokhan.core.throttle import FailureThrottle
from sokhan.db import get_db
from sokhan.models import User
from sokhan.schemas import AuthResponse
@@ -77,12 +79,44 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
return AuthResponse(id=user.id, email=user.email, api_token=token)
_login_throttle: FailureThrottle | None = None
def get_login_throttle() -> FailureThrottle:
global _login_throttle
if _login_throttle is None:
settings = get_settings()
_login_throttle = FailureThrottle(
settings.login_max_failures, settings.login_failure_window_seconds
)
return _login_throttle
def reset_login_throttle() -> None:
global _login_throttle
_login_throttle = None
@router.post("/login", response_model=AuthResponse)
def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
def login(
payload: Credentials, request: Request, session: Session = Depends(get_db)
) -> AuthResponse:
email = payload.email.strip().lower()
throttle = get_login_throttle()
key = (request.client.host if request.client else "", email)
wait_seconds = throttle.retry_after(key)
if wait_seconds:
raise HTTPException(
status.HTTP_429_TOO_MANY_REQUESTS,
"too many failed login attempts, try again later",
headers={"Retry-After": str(wait_seconds)},
)
user = session.scalar(select(User).where(User.email == email))
if user is None or not verify_password(payload.password, user.password_hash):
throttle.record_failure(key)
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid credentials")
throttle.reset(key)
token = generate_token()
user.token_hash = token_hash(token)
+3
View File
@@ -95,6 +95,9 @@ class Settings(BaseSettings):
webhook_attempts: int = 2
webhook_allow_private_targets: bool = False
login_max_failures: int = 10
login_failure_window_seconds: int = 900
@lru_cache(maxsize=1)
def get_settings() -> Settings:
+48
View File
@@ -0,0 +1,48 @@
import threading
import time
from collections import deque
from collections.abc import Callable, Hashable
class FailureThrottle:
def __init__(
self,
max_failures: int,
window_seconds: float,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.max_failures = max_failures
self.window_seconds = window_seconds
self._clock = clock
self._failures: dict[Hashable, deque[float]] = {}
self._lock = threading.Lock()
def _prune(self, key: Hashable, now: float) -> deque[float]:
stamps = self._failures.get(key)
if stamps is None:
return deque()
while stamps and now - stamps[0] >= self.window_seconds:
stamps.popleft()
if not stamps:
del self._failures[key]
return stamps
def retry_after(self, key: Hashable) -> int:
if self.max_failures <= 0:
return 0
with self._lock:
now = self._clock()
stamps = self._prune(key, now)
if len(stamps) < self.max_failures:
return 0
return max(1, int(stamps[0] + self.window_seconds - now + 0.999))
def record_failure(self, key: Hashable) -> None:
with self._lock:
now = self._clock()
self._prune(key, now)
self._failures.setdefault(key, deque()).append(now)
def reset(self, key: Hashable) -> None:
with self._lock:
self._failures.pop(key, None)
+3
View File
@@ -29,15 +29,18 @@ def app(tmp_path, monkeypatch):
monkeypatch.setenv("PLAN_PRO_MAX_FILE_MINUTES", "180")
monkeypatch.setenv("PLAN_PRO_MONTHLY_MINUTES", "1200")
from sokhan.api.routes_auth import reset_login_throttle
from sokhan.config import get_settings
get_settings.cache_clear()
reset_login_throttle()
db.reset()
db.configure(f"sqlite:///{tmp_path / 'test.sqlite3'}")
db.create_all()
yield create_app()
db.reset()
get_settings.cache_clear()
reset_login_throttle()
@pytest.fixture()
+55
View File
@@ -0,0 +1,55 @@
import pytest
from sokhan.core.throttle import FailureThrottle
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
WRONG = {"email": REGISTER["email"], "password": "wrong-pass"}
@pytest.fixture()
def tight_login_limit(app, monkeypatch):
from sokhan.api.routes_auth import reset_login_throttle
from sokhan.config import get_settings
monkeypatch.setenv("LOGIN_MAX_FAILURES", "3")
get_settings.cache_clear()
reset_login_throttle()
def test_login_is_throttled_after_repeated_failures(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
for _ in range(3):
assert client.post("/auth/login", json=WRONG).status_code == 401
blocked = client.post("/auth/login", json=REGISTER)
assert blocked.status_code == 429
assert int(blocked.headers["Retry-After"]) > 0
def test_successful_login_clears_the_failure_count(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
for _ in range(2):
client.post("/auth/login", json=WRONG)
assert client.post("/auth/login", json=REGISTER).status_code == 200
for _ in range(2):
assert client.post("/auth/login", json=WRONG).status_code == 401
def test_other_accounts_are_not_locked_out(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
other = {"email": "sara@example.org", "password": "parool-5678"}
client.post("/auth/register", json=other)
for _ in range(3):
client.post("/auth/login", json=WRONG)
assert client.post("/auth/login", json=other).status_code == 200
def test_throttle_window_slides():
now = [1000.0]
throttle = FailureThrottle(max_failures=2, window_seconds=60, clock=lambda: now[0])
throttle.record_failure("k")
throttle.record_failure("k")
assert throttle.retry_after("k") == 60
now[0] += 30
assert throttle.retry_after("k") == 30
now[0] += 30
assert throttle.retry_after("k") == 0
+2
View File
@@ -49,6 +49,8 @@ services:
STREAMING_DECODE: ${STREAMING_DECODE:-true}
WEBHOOK_SIGNING_SECRET: ${WEBHOOK_SIGNING_SECRET:-}
WEBHOOK_ALLOW_PRIVATE_TARGETS: ${WEBHOOK_ALLOW_PRIVATE_TARGETS:-false}
LOGIN_MAX_FAILURES: ${LOGIN_MAX_FAILURES:-10}
LOGIN_FAILURE_WINDOW_SECONDS: ${LOGIN_FAILURE_WINDOW_SECONDS:-900}
FREE_MINUTES_PER_USER_PER_MONTH: ${FREE_MINUTES_PER_USER_PER_MONTH:-30}
PLAN_FREE_MAX_FILE_MINUTES: ${PLAN_FREE_MAX_FILE_MINUTES:-10}
PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180}