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): # Read content length header content_length = request.headers.get("content-length") if content_length: try: length = int(content_length) # 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 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 # Also limit reading chunks if chunked transfer encoding is used return await call_next(request)