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

+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")