from fastapi import Request, HTTPException, status from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import JSONResponse from app.core.config.Config import settings class SecurityHeadersMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response = await call_next(request) is_docs = request.url.path in ["/docs", "/redoc", "/openapi.json"] # Enforce HSTS if request.url.hostname not in ["localhost", "127.0.0.1"]: response.headers["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains; preload" if not is_docs: response.headers["X-Frame-Options"] = "DENY" response.headers["X-Content-Type-Options"] = "nosniff" response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()" # CSP policies: only apply to docs or frontend pages, NEVER block API connections if is_docs: response.headers["Content-Security-Policy"] = "default-src * 'unsafe-inline' 'unsafe-eval' data: blob:;" elif not request.url.path.startswith("/api/"): response.headers["Content-Security-Policy"] = ( "default-src 'self'; script-src 'self'; connect-src 'self'; " "img-src 'self' data:; style-src 'self' 'unsafe-inline';" ) return response class RequestSizeLimitMiddleware(BaseHTTPMiddleware): def __init__(self, app, max_bytes: int = 10 * 1024 * 1024): # Default 10MB super().__init__(app) self.max_bytes = max_bytes async def dispatch(self, request: Request, call_next): # Read content length header content_length = request.headers.get("content-length") if content_length: try: length = int(content_length) if length > self.max_bytes: max_mb = self.max_bytes // (1024 * 1024) return JSONResponse( status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, content={"detail": f"Payload too large. Maximum size allowed is {max_mb}MB."} ) except ValueError: pass # Also limit reading chunks if chunked transfer encoding is used return await call_next(request)