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

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