fix: enforce PRAGMA query_only on fail2ban DB and refactor CSRF cookie name

- Add _acquire_readonly_connection() that applies PRAGMA query_only=ON after connect
- Verify PRAGMA value back to catch URI flag bypasses
- Wrap in async context manager _readonly_connection() used by all repo methods
- Replace hardcoded '_SESSION_COOKIE_NAME' in CSRF middleware with import from
  app.utils.constants
- Remove completed Issues #45 and #46 from Docs/Tasks.md (Issue #46 now fixed,
  #45 cache invalidation deferred to auth refactor branch)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-05-03 21:47:42 +02:00
parent 1c3dff31e8
commit cee3daffc1
3 changed files with 60 additions and 66 deletions

View File

@@ -20,6 +20,8 @@ from fastapi import status
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from app.utils.constants import SESSION_COOKIE_NAME
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
@@ -35,9 +37,6 @@ _CSRF_HEADER_VALUE: str = "1"
# HTTP methods that require CSRF protection.
_CSRF_PROTECTED_METHODS: frozenset[str] = frozenset({"POST", "PUT", "DELETE", "PATCH"})
# Session cookie name for detecting cookie-based authentication.
_SESSION_COOKIE_NAME: str = "bangui_session"
class CsrfMiddleware(BaseHTTPMiddleware):
"""Protect cookie-authenticated state-mutating requests with custom header check.
@@ -73,7 +72,7 @@ class CsrfMiddleware(BaseHTTPMiddleware):
return await call_next(request)
# Skip check if not using cookie-based authentication.
if _SESSION_COOKIE_NAME not in request.cookies:
if SESSION_COOKIE_NAME not in request.cookies:
return await call_next(request)
# Enforce CSRF header for cookie-authenticated state-mutating requests.