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

+9 -2
View File
@@ -18,7 +18,7 @@ from app.schemas.auth import (
)
from app.security import verify_password
from app.services import sessions as session_service
from app.services.auth import authenticate
from app.services.auth import LoginBlocked, authenticate
from app.services.users import set_password
router = APIRouter(prefix="/auth", tags=["auth"])
@@ -27,7 +27,14 @@ router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login", response_model=UserOut)
def login(body: LoginRequest, request: Request, response: Response, db: DbSession):
ip = client_ip(request)
user = authenticate(db, body.username, body.password, ip)
try:
user = authenticate(db, body.username, body.password, ip)
except LoginBlocked as exc:
raise HTTPException(
status.HTTP_429_TOO_MANY_REQUESTS,
"Zu viele Fehlversuche. Bitte später erneut versuchen.",
headers={"Retry-After": str(exc.retry_after_seconds)},
) from None
if user is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Benutzername oder Passwort ist falsch.")
+6
View File
@@ -1,3 +1,4 @@
import secrets
from typing import Annotated
from fastapi import Depends, HTTPException, Request, Response, status
@@ -5,6 +6,7 @@ from sqlalchemy.orm import Session
from app.config import get_settings
from app.db import get_db
from app.middleware import SAFE_METHODS
from app.models import User, UserSession
from app.services.sessions import resolve_session
@@ -18,6 +20,10 @@ def get_current_session(request: Request, db: DbSession) -> UserSession:
session = resolve_session(db, request.cookies.get(SESSION_COOKIE))
if session is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Nicht angemeldet.")
if request.method not in SAFE_METHODS:
sent = request.headers.get("x-csrf-token", "")
if not secrets.compare_digest(sent.encode(), session.csrf_token.encode()):
raise HTTPException(status.HTTP_403_FORBIDDEN, "CSRF-Token fehlt oder ist ungültig.")
return session
+41
View File
@@ -1,13 +1,52 @@
import asyncio
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import FileResponse, JSONResponse
from app import __version__
from app.api import auth, health
from app.config import get_settings
from app.db import _session_factory
from app.middleware import OriginCheckMiddleware
from app.services.auth import delete_old_login_attempts
from app.services.sessions import delete_expired_sessions
from app.services.users import UserError
logger = logging.getLogger(__name__)
CLEANUP_INTERVAL_SECONDS = 3600
def _cleanup() -> None:
with _session_factory()() as db:
sessions = delete_expired_sessions(db)
attempts = delete_old_login_attempts(db)
if sessions or attempts:
logger.info("Cleanup: %d sessions, %d login attempts removed", sessions, attempts)
async def _cleanup_loop() -> None:
while True:
try:
await run_in_threadpool(_cleanup)
except Exception:
logger.exception("Cleanup failed")
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
task = asyncio.create_task(_cleanup_loop())
try:
yield
finally:
task.cancel()
def _register_frontend(app: FastAPI, static_dir: Path) -> None:
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
@@ -32,7 +71,9 @@ def create_app() -> FastAPI:
docs_url="/api/docs",
openapi_url="/api/openapi.json",
redoc_url=None,
lifespan=lifespan,
)
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
app.include_router(health.router, prefix="/api")
app.include_router(auth.router, prefix="/api")
+26
View File
@@ -0,0 +1,26 @@
from starlette.datastructures import Headers
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
class OriginCheckMiddleware:
"""Reject state-changing requests whose Origin header is not an allowed origin.
Browsers always send Origin on cross-site POST/PUT/PATCH/DELETE. Requests without
the header come from non-browser clients and are left to the authentication layer.
"""
def __init__(self, app: ASGIApp, allowed_origins: list[str]) -> None:
self.app = app
self.allowed_origins = frozenset(allowed_origins)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http" and scope["method"] not in SAFE_METHODS:
origin = Headers(scope=scope).get("origin")
if origin is not None and origin.rstrip("/") not in self.allowed_origins:
response = JSONResponse({"detail": "Ungültige Herkunft (Origin)."}, 403)
await response(scope, receive, send)
return
await self.app(scope, receive, send)
+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