feat: csrf-schutz, origin-prüfung und sperre bei fehlanmeldungen

- CSRF-Token pro Session, Pflicht-Header X-CSRF-Token bei POST/PUT/PATCH/DELETE
- Middleware lehnt zustandsändernde Requests mit fremdem Origin ab
- Sperre nach 5 Fehlversuchen pro Benutzername in 15 Minuten (HTTP 429)
- IP-Sperre vorbereitet, per LOGIN_IP_LOCKOUT aktivierbar
- stündliches Aufräumen abgelaufener Sessions und alter Login-Versuche

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 11:04:33 +01:00
1 parent 18f0d04ce9
commit 5b4545b60f
7 files changed
+350 -4

No files matched your search

+70 -2
View File
@@ -1,13 +1,73 @@
from datetime import timedelta
from sqlalchemy import delete, func, select
from sqlalchemy.orm import Session
from app.models import LoginAttempt, User
from app.config import get_settings
from app.models import LoginAttempt, User, utcnow
from app.security import hash_password, password_needs_rehash, verify_password
from app.services.users import get_by_username, normalize_username
# Login attempts are kept this long for lockout checks and later review
ATTEMPT_RETENTION = timedelta(days=7)
class LoginBlocked(Exception):
"""Too many failed attempts for this username or IP."""
def __init__(self, retry_after_seconds: int) -> None:
super().__init__("login temporarily blocked")
self.retry_after_seconds = retry_after_seconds
def _recent_failures(db: Session, column, value: str, since) -> int:
return (
db.scalar(
select(func.count())
.select_from(LoginAttempt)
.where(
column == value, LoginAttempt.success.is_(False), LoginAttempt.attempted_at >= since
)
)
or 0
)
def _last_success(db: Session, username: str):
return db.scalar(
select(func.max(LoginAttempt.attempted_at)).where(
LoginAttempt.username == username, LoginAttempt.success.is_(True)
)
)
def _check_not_blocked(db: Session, username: str, ip: str | None) -> None:
settings = get_settings()
window = timedelta(minutes=settings.login_failure_window_minutes)
since = utcnow() - window
# A successful login resets the per-user counter
user_since = max(filter(None, [since, _last_success(db, username)]))
blocked = (
_recent_failures(db, LoginAttempt.username, username, user_since)
>= settings.login_max_failures_per_user
)
if not blocked and settings.login_ip_lockout and ip:
blocked = (
_recent_failures(db, LoginAttempt.ip, ip, since) >= settings.login_max_failures_per_ip
)
if blocked:
raise LoginBlocked(int(window.total_seconds()))
def authenticate(db: Session, username: str, password: str, ip: str | None) -> User | None:
"""Verify credentials and record the attempt. Inactive users cannot log in."""
"""Verify credentials and record the attempt. Inactive users cannot log in.
Raises LoginBlocked without recording anything while a lockout is active, so the
lock lifts once the failures leave the time window.
"""
username = normalize_username(username)[:255]
_check_not_blocked(db, username, ip)
user = get_by_username(db, username)
valid = verify_password(user.password_hash if user else None, password)
success = valid and user is not None and user.is_active
@@ -17,3 +77,11 @@ def authenticate(db: Session, username: str, password: str, ip: str | None) -> U
user.password_hash = hash_password(password)
db.commit()
return user if success else None
def delete_old_login_attempts(db: Session) -> int:
result = db.execute(
delete(LoginAttempt).where(LoginAttempt.attempted_at < utcnow() - ATTEMPT_RETENTION)
)
db.commit()
return result.rowcount