""" Security headers middleware for DMARQ application. Implements various security headers to protect against common web vulnerabilities: - Content Security Policy (CSP) - X-Frame-Options - X-Content-Type-Options - Strict-Transport-Security (HSTS) - X-XSS-Protection - Referrer-Policy - Permissions-Policy """ import logging from typing import Callable from fastapi import Request from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import Response logger = logging.getLogger(__name__) class SecurityHeadersMiddleware(BaseHTTPMiddleware): """ Middleware to add security headers to all HTTP responses. """ def __init__(self, app, environment: str = "development"): """ Initialize security headers middleware. Args: app: FastAPI application instance environment: Application environment (development/production) """ super().__init__(app) self.environment = environment async def dispatch(self, request: Request, call_next: Callable) -> Response: """ Process the request and add security headers to the response. Args: request: Incoming HTTP request call_next: Next middleware/handler in the chain Returns: HTTP response with security headers added """ response = await call_next(request) # Content Security Policy (CSP) # Restricts sources of content that can be loaded # # SECURITY TODO: Current CSP includes 'unsafe-inline' which weakens # XSS protection. To remove it: # # For script-src 'unsafe-inline': # 1. Move all inline