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 = 50 * 1024 * 1024, large_paths_max_bytes: int = 4 * 1024 * 1024 * 1024, # 4GB for migration / archives large_paths: tuple = ("/api/v1/migration", "/api/v1/files/upload") ): super().__init__(app) self.max_bytes = max_bytes self.large_paths_max_bytes = large_paths_max_bytes self.large_paths = large_paths async def dispatch(self, request: Request, call_next): # Determine limit based on endpoint path is_large_path = any(request.url.path.startswith(prefix) for prefix in self.large_paths) limit = self.large_paths_max_bytes if is_large_path else self.max_bytes # 1. Content-Length Header Guard content_length = request.headers.get("content-length") if content_length: try: length = int(content_length) if length > limit: max_mb = limit // (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 # 2. Chunked Transfer-Encoding Streaming Guard transfer_encoding = (request.headers.get("transfer-encoding") or "").lower() if "chunked" in transfer_encoding or not content_length: bytes_received = 0 original_receive = request._receive async def custom_receive(): nonlocal bytes_received message = await original_receive() if message.get("type") == "http.request": body = message.get("body", b"") bytes_received += len(body) if bytes_received > limit: max_mb = limit // (1024 * 1024) raise HTTPException( status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail=f"Payload too large. Streaming transfer exceeded maximum limit of {max_mb}MB." ) return message request._receive = custom_receive try: return await call_next(request) except HTTPException as exc: if exc.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE: return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail} ) raise