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:
1 parent
18f0d04ce9
commit
5b4545b60f
7 files changed
+349
-3
No files matched your search
@@ -18,7 +18,7 @@ from app.schemas.auth import (
|
|||||||
)
|
)
|
||||||
from app.security import verify_password
|
from app.security import verify_password
|
||||||
from app.services import sessions as session_service
|
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
|
from app.services.users import set_password
|
||||||
|
|
||||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
@@ -27,7 +27,14 @@ router = APIRouter(prefix="/auth", tags=["auth"])
|
|||||||
@router.post("/login", response_model=UserOut)
|
@router.post("/login", response_model=UserOut)
|
||||||
def login(body: LoginRequest, request: Request, response: Response, db: DbSession):
|
def login(body: LoginRequest, request: Request, response: Response, db: DbSession):
|
||||||
ip = client_ip(request)
|
ip = client_ip(request)
|
||||||
|
try:
|
||||||
user = authenticate(db, body.username, body.password, ip)
|
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:
|
if user is None:
|
||||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Benutzername oder Passwort ist falsch.")
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Benutzername oder Passwort ist falsch.")
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import secrets
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import Depends, HTTPException, Request, Response, status
|
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.config import get_settings
|
||||||
from app.db import get_db
|
from app.db import get_db
|
||||||
|
from app.middleware import SAFE_METHODS
|
||||||
from app.models import User, UserSession
|
from app.models import User, UserSession
|
||||||
from app.services.sessions import resolve_session
|
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))
|
session = resolve_session(db, request.cookies.get(SESSION_COOKIE))
|
||||||
if session is None:
|
if session is None:
|
||||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Nicht angemeldet.")
|
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
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,52 @@
|
|||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import FastAPI, HTTPException, Request, status
|
from fastapi import FastAPI, HTTPException, Request, status
|
||||||
|
from fastapi.concurrency import run_in_threadpool
|
||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse
|
||||||
|
|
||||||
from app import __version__
|
from app import __version__
|
||||||
from app.api import auth, health
|
from app.api import auth, health
|
||||||
from app.config import get_settings
|
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
|
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:
|
def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
||||||
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
|
"""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",
|
docs_url="/api/docs",
|
||||||
openapi_url="/api/openapi.json",
|
openapi_url="/api/openapi.json",
|
||||||
redoc_url=None,
|
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(health.router, prefix="/api")
|
||||||
app.include_router(auth.router, prefix="/api")
|
app.include_router(auth.router, prefix="/api")
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -1,13 +1,73 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete, func, select
|
||||||
from sqlalchemy.orm import Session
|
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.security import hash_password, password_needs_rehash, verify_password
|
||||||
from app.services.users import get_by_username, normalize_username
|
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:
|
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]
|
username = normalize_username(username)[:255]
|
||||||
|
_check_not_blocked(db, username, ip)
|
||||||
|
|
||||||
user = get_by_username(db, username)
|
user = get_by_username(db, username)
|
||||||
valid = verify_password(user.password_hash if user else None, password)
|
valid = verify_password(user.password_hash if user else None, password)
|
||||||
success = valid and user is not None and user.is_active
|
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)
|
user.password_hash = hash_password(password)
|
||||||
db.commit()
|
db.commit()
|
||||||
return user if success else None
|
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
|
||||||
@@ -13,6 +13,18 @@ from app.db import _session_factory, get_engine
|
|||||||
BACKEND_DIR = Path(__file__).resolve().parent.parent
|
BACKEND_DIR = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fast_password_hashing(monkeypatch):
|
||||||
|
"""Production argon2 parameters are deliberately slow; tests use cheap ones."""
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
|
||||||
|
from app import security
|
||||||
|
|
||||||
|
hasher = PasswordHasher(time_cost=1, memory_cost=1024, parallelism=1)
|
||||||
|
monkeypatch.setattr(security, "_hasher", hasher)
|
||||||
|
monkeypatch.setattr(security, "_DUMMY_HASH", hasher.hash("dummy"))
|
||||||
|
|
||||||
|
|
||||||
def _clear_caches() -> None:
|
def _clear_caches() -> None:
|
||||||
get_settings.cache_clear()
|
get_settings.cache_clear()
|
||||||
get_engine.cache_clear()
|
get_engine.cache_clear()
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.models import LoginAttempt, UserSession, utcnow
|
||||||
|
from tests.conftest import login
|
||||||
|
|
||||||
|
WRONG = "wrong password!!"
|
||||||
|
|
||||||
|
|
||||||
|
# --- Origin -------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_foreign_origin_is_rejected_on_login(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"username": "anna", "password": "correct horse battery"},
|
||||||
|
headers={"Origin": "https://evil.example"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert "lc_session" not in client.cookies
|
||||||
|
|
||||||
|
|
||||||
|
def test_null_origin_is_rejected(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"username": "anna", "password": "correct horse battery"},
|
||||||
|
headers={"Origin": "null"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_allowed_origin_is_accepted(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"username": "anna", "password": "correct horse battery"},
|
||||||
|
headers={"Origin": "https://testserver"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_requests_ignore_origin(client):
|
||||||
|
response = client.get("/api/health", headers={"Origin": "https://evil.example"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
# --- CSRF ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_change_without_csrf_token_is_rejected(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
del client.headers["X-CSRF-Token"]
|
||||||
|
|
||||||
|
assert client.post("/api/auth/logout").status_code == 403
|
||||||
|
assert client.get("/api/auth/me").status_code == 200 # still logged in
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_change_with_wrong_csrf_token_is_rejected(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
|
||||||
|
response = client.post("/api/auth/logout", headers={"X-CSRF-Token": "forged"})
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_csrf_token_of_other_session_is_rejected(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
make_user("bert")
|
||||||
|
with TestClient(client.app, base_url="https://testserver") as bert:
|
||||||
|
login(bert, "bert")
|
||||||
|
login(client, "anna")
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/logout", headers={"X-CSRF-Token": bert.cookies["lc_csrf"]}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# --- Lockout ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_is_locked_after_repeated_failures(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
for _ in range(5):
|
||||||
|
assert login(client, "anna", WRONG).status_code == 401
|
||||||
|
|
||||||
|
blocked = login(client, "anna") # even the correct password
|
||||||
|
|
||||||
|
assert blocked.status_code == 429
|
||||||
|
assert blocked.headers["Retry-After"] == "900"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lockout_applies_to_unknown_users_too(client):
|
||||||
|
for _ in range(5):
|
||||||
|
login(client, "ghost", WRONG)
|
||||||
|
|
||||||
|
assert login(client, "ghost", WRONG).status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
def test_lockout_is_case_insensitive(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
for name in ["anna", "ANNA", "Anna", "aNNa", "annA"]:
|
||||||
|
login(client, name, WRONG)
|
||||||
|
|
||||||
|
assert login(client, "anna").status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
def test_lockout_expires_after_window(client, make_user, db):
|
||||||
|
make_user("anna")
|
||||||
|
for _ in range(5):
|
||||||
|
login(client, "anna", WRONG)
|
||||||
|
db.query(LoginAttempt).update({LoginAttempt.attempted_at: utcnow() - timedelta(minutes=16)})
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
assert login(client, "anna").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_blocked_attempts_do_not_extend_lockout(client, make_user, db):
|
||||||
|
make_user("anna")
|
||||||
|
for _ in range(5):
|
||||||
|
login(client, "anna", WRONG)
|
||||||
|
for _ in range(3):
|
||||||
|
login(client, "anna", WRONG)
|
||||||
|
|
||||||
|
assert db.query(LoginAttempt).count() == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_successful_login_resets_counter(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
for _ in range(4):
|
||||||
|
login(client, "anna", WRONG)
|
||||||
|
assert login(client, "anna").status_code == 200
|
||||||
|
client.post("/api/auth/logout")
|
||||||
|
|
||||||
|
for _ in range(4):
|
||||||
|
assert login(client, "anna", WRONG).status_code == 401
|
||||||
|
assert login(client, "anna").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_ip_lockout_disabled_by_default(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
for i in range(25):
|
||||||
|
login(client, f"user{i}", WRONG)
|
||||||
|
|
||||||
|
assert login(client, "anna").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def ip_lockout(monkeypatch, app_env):
|
||||||
|
monkeypatch.setenv("LOGIN_IP_LOCKOUT", "true")
|
||||||
|
get_settings.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_ip_lockout_when_enabled(ip_lockout, client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
for i in range(20):
|
||||||
|
login(client, f"user{i}", WRONG)
|
||||||
|
|
||||||
|
assert login(client, "anna").status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
# --- Cleanup ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_cleanup_removes_expired_data(client, make_user, db):
|
||||||
|
from app.main import _cleanup
|
||||||
|
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
login(client, "anna", WRONG)
|
||||||
|
db.query(UserSession).update({UserSession.expires_at: utcnow() - timedelta(seconds=1)})
|
||||||
|
db.query(LoginAttempt).update({LoginAttempt.attempted_at: utcnow() - timedelta(days=8)})
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
_cleanup()
|
||||||
|
|
||||||
|
assert db.query(UserSession).count() == 0
|
||||||
|
assert db.query(LoginAttempt).count() == 0
|
||||||
Reference in new issue
Block a user