Files
leocrm/app/core/middleware.py
T
Agent Zero 7fbbe420bd
Check Cross-Plugin Imports / check (push) Has been cancelled
fix: comprehensive system audit fixes (55+ issues)
CRITICAL:
- Fix SQL injection in prestart.sh (parameterized query)
- Fix secret key validation (always validate, not just production)
- Fix workspace model partial index bug (func.text -> text)
- Fix HealthResponse schema (add checks field)
- Fix Tenant import in permissions.py (NameError on every auth request)
- Fix README tech stack (React instead of Alpine.js)
- Delete broken test_cross_tenant_security_v2.py
- Add fail-closed RLS migration 0084 (48 tenant tables)

HIGH:
- Add GeneralRateLimitMiddleware for all API routes
- Add file type blocklist for DMS and attachment uploads
- Fix guest auth: Pydantic schema, tenant_slug required, CSRF bypass
- Fix CSRF bypass path matching (in -> endswith)
- Add worker healthcheck in docker-compose.yml
- Add ARQ max_tries=3 for job retries
- Fix 28 bare pass in mail services (-> logger.debug)
- Fix print() -> logger in main.py and ai_assistant
- Fix duplicate email handling (catch IntegrityError -> 409)
- Add session revocation (invalidate_all_user_sessions)
- Add resource limits to all containers
- Fix CORS default (localhost -> production domain)
- Fix SameSite=Lax -> Strict
- Fix Redis password visibility in healthcheck
- Fix npm vulnerabilities (19 -> 9)
- Fix Sidebar OOM (wildcard lucide import -> curated ICON_MAP)

MEDIUM:
- Localize ErrorBoundary to German
- Wire Mail.tsx save/delete filter to API
- Document system_notif plugin (no routes needed)
- Fix datetime.utcnow() -> datetime.now(UTC)
- Pin litellm version (>=1.0,<2.0)
- Move CSRF token from sessionStorage to in-memory
- Fix restore_backup error handling and transaction
- Fix Dms.tsx useEffect cleanup
- Add skip-to-content link for accessibility
- Add selectinload imports to 3 services
- Add .env.example missing variables
- Fix AppShell/TopBar/Sidebar test mocks

NEW TESTS:
- test_guest_auth.py (6 tests)
- test_user_service.py (8 tests)
- test_backup_service.py (5 tests)

NEW SCHEMAS:
- saved_filter, saved_view, user_preference, workspace, entity_policy

Tests: 22/22 PASSED
2026-07-31 00:58:05 +02:00

138 lines
5.4 KiB
Python

"""CSRF middleware — Origin header + CSRF token validation for state-changing requests."""
from __future__ import annotations
import json
import logging
from fastapi import Request, status
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
from app.config import get_settings
logger = logging.getLogger(__name__)
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Add security headers to all responses."""
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
settings = get_settings()
is_production = settings.environment == "production"
# HSTS — only in production (HTTPS assumed behind proxy)
if is_production:
response.headers["Strict-Transport-Security"] = (
"max-age=63072000; includeSubDomains; preload"
)
# Prevent MIME type sniffing
response.headers["X-Content-Type-Options"] = "nosniff"
# Prevent clickjacking
response.headers["X-Frame-Options"] = "DENY"
# Content Security Policy — restrictive but allows inline styles for SPA
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data: blob:; "
"font-src 'self'; "
"connect-src 'self' wss: ws:; "
"frame-ancestors 'none'; "
"base-uri 'self'; "
"form-action 'self'"
)
# Referrer policy
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
# Permissions policy
response.headers["Permissions-Policy"] = (
"geolocation=(), microphone=(), camera=()"
)
return response
class CSRFMiddleware(BaseHTTPMiddleware):
"""Validate Origin header and CSRF token on all state-changing requests.
SameSite=Strict cookie + Origin validation + double-submit CSRF token.
The CSRF token is generated at login and stored in the Redis session.
The client must send it via the X-CSRF-Token header on unsafe methods.
"""
UNSAFE_METHODS = {"POST", "PATCH", "PUT", "DELETE"}
async def dispatch(self, request: Request, call_next):
# Skip WebSocket upgrade requests — they use GET and are handled separately
if request.headers.get("upgrade", "").lower() == "websocket":
return await call_next(request)
if request.method in self.UNSAFE_METHODS:
# 1. Origin header check
origin = request.headers.get("origin")
if not origin:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"detail": "Missing Origin header", "code": "csrf_missing_origin"},
)
settings = get_settings()
allowed = settings.cors_origin_list
if origin not in allowed:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"detail": "Invalid Origin", "code": "csrf_invalid_origin"},
)
# 2. CSRF token validation (double-submit pattern)
# Skip CSRF token check for auth endpoints (login/password-reset)
path = request.url.path
if path.endswith("/auth/login") or path.endswith("/auth/logout") or path.endswith("/guest/login") or path.endswith("/guest/logout") or path.endswith("/password-reset/request") or path.endswith("/password-reset/confirm") or path.endswith("/api/v1/errors") or path == "/api/v1/errors":
return await call_next(request)
csrf_header = request.headers.get("x-csrf-token")
if not csrf_header:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"detail": "Missing X-CSRF-Token header", "code": "csrf_missing_token"},
)
# Get session ID from cookie to look up stored CSRF token
session_id = request.cookies.get(settings.session_cookie_name)
if not session_id:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"detail": "No session for CSRF validation", "code": "csrf_no_session"},
)
# Look up CSRF token from Redis session (use singleton)
from app.core.auth import get_redis
redis = get_redis()
raw = await redis.get(f"session:{session_id}")
if raw is None:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"detail": "Session expired for CSRF validation", "code": "csrf_session_expired"},
)
session_data = json.loads(raw)
stored_token = session_data.get("csrf_token")
if not stored_token or stored_token != csrf_header:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"detail": "CSRF token mismatch", "code": "csrf_token_mismatch"},
)
# Sliding session: also extend TTL on CSRF-validated unsafe requests
await redis.expire(f"session:{session_id}", settings.session_ttl_seconds)
return await call_next(request)