Files
dbildhauerandClaude Opus 5.5 5b4545b60f 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>
2026-10-25 11:04:33 +01:00

94 lines
2.7 KiB
Python

from collections.abc import Iterator
from pathlib import Path
import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.config import get_settings
from app.db import _session_factory, get_engine
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:
get_settings.cache_clear()
get_engine.cache_clear()
_session_factory.cache_clear()
@pytest.fixture
def static_dir(tmp_path):
"""Directory for the built frontend; empty by default (no SPA routes)."""
path = tmp_path / "static"
path.mkdir()
return path
@pytest.fixture
def app_env(tmp_path, static_dir, monkeypatch) -> Iterator[None]:
"""Isolated settings and a migrated database for one test."""
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("STATIC_DIR", str(static_dir))
monkeypatch.setenv("ALLOWED_ORIGINS", "https://testserver")
monkeypatch.delenv("INITIAL_ADMIN_USERNAME", raising=False)
monkeypatch.delenv("INITIAL_ADMIN_PASSWORD", raising=False)
_clear_caches()
command.upgrade(Config(str(BACKEND_DIR / "alembic.ini")), "head")
yield
get_engine().dispose()
_clear_caches()
@pytest.fixture
def db(app_env) -> Iterator[Session]:
with _session_factory()() as session:
yield session
@pytest.fixture
def client(app_env) -> Iterator[TestClient]:
from app.main import create_app
# https so that Secure cookies are sent back by the test client
with TestClient(create_app(), base_url="https://testserver") as test_client:
yield test_client
PASSWORD = "correct horse battery"
@pytest.fixture
def make_user(db):
from app.models import Role
from app.services.users import create_user
def _make(username: str = "anna", role: Role = Role.USER, password: str = PASSWORD):
return create_user(db, username, password, role)
return _make
def login(client: TestClient, username: str, password: str = PASSWORD):
"""Log in and return the response; the CSRF token is set as default header."""
response = client.post("/api/auth/login", json={"username": username, "password": password})
if response.status_code == 200:
client.headers["X-CSRF-Token"] = client.cookies["lc_csrf"]
return response