""" YAZ Care Platform - Canonical Security Headers Middleware OWASP-compliant security headers for all HTTP responses This is the SINGLE source of truth for security headers. All 17 healthcare applications use this implementation. Standards: - OWASP Secure Headers Project - NIST Cybersecurity Framework - HIPAA Security Rule (§164.312) Previous Locations (CONSOLIDATED): - src/middleware/security_headers.py ❌ DELETED - src/middleware/api_gateway.py ❌ DELETED (extracted) - src/middleware/security.py ❌ DELETED (extracted) - src/api/security_middleware.py ❌ DELETED - src/api/middleware/security_advanced.py ❌ DELETED - src/api/middleware/optimization.py ❌ DELETED (extracted) - src/api/middleware/security.py ❌ DELETED - src/core/security/security_headers.py ❌ DELETED - src/core/common/middleware_stack.py ✅ USES THIS Migration: Import from here only: from core.security.headers import SecurityHeadersMiddleware """ import secrets from dataclasses import dataclass, field from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response from typing import Callable, Optional, List import structlog logger = structlog.get_logger() @dataclass class SecurityConfig: """ Security configuration for headers middleware. Standards: OWASP Secure Headers, HIPAA §164.312 """ enable_csp: bool = True enable_hsts: bool = True hsts_max_age: int = 31536000 # 1 year frame_options: str = "DENY" content_type_options: str = "nosniff" referrer_policy: str = "strict-origin-when-cross-origin" permissions_policy: str = "camera=(), microphone=(), geolocation=()" allowed_hosts: List[str] = field(default_factory=lambda: ["*"]) cors_origins: List[str] = field(default_factory=list) class SecurityHeadersMiddleware(BaseHTTPMiddleware): """ Add OWASP-compliant security headers to all responses Headers Added: - X-Frame-Options: Prevent clickjacking - X-Content-Type-Options: Prevent MIME sniffing - X-XSS-Protection: XSS filter (legacy browsers) - Content-Security-Policy: Restrict resource loading - Strict-Transport-Security: Force HTTPS - Permissions-Policy: Disable dangerous browser features - Referrer-Policy: Control referrer information Clinical Context: Protects PHI from XSS, clickjacking, and data exfiltration Performance: Adds ~0.5ms overhead per request (headers only) """ def __init__( self, app, enable_csp: bool = True, enable_hsts: bool = True, hsts_max_age: int = 31536000, # 1 year ): """ Initialize security headers middleware Args: app: ASGI application enable_csp: Enable Content Security Policy (strict) enable_hsts: Enable HTTP Strict Transport Security hsts_max_age: HSTS max-age in seconds (default: 1 year) """ super().__init__(app) self.enable_csp = enable_csp self.enable_hsts = enable_hsts self.hsts_max_age = hsts_max_age async def dispatch(self, request: Request, call_next: Callable) -> Response: """ Add security headers to response Args: request: Incoming HTTP request call_next: Next middleware in chain Returns: Response with security headers added """ # Generate per-request nonce BEFORE template rendering so Jinja2 can access # request.state.csp_nonce — mirrors the existing request.state.csrf_token pattern. nonce = secrets.token_hex(16) request.state.csp_nonce = nonce # Process request response = await call_next(request) # Clickjacking protection (OWASP A05:2021) — DENY blocks all framing response.headers["X-Frame-Options"] = "DENY" # MIME sniffing protection (prevents content type confusion attacks) response.headers["X-Content-Type-Options"] = "nosniff" # XSS protection for legacy browsers (modern browsers use CSP) response.headers["X-XSS-Protection"] = "1; mode=block" # Content Security Policy (OWASP A03:2021) if self.enable_csp: response.headers["Content-Security-Policy"] = self._get_csp_policy(nonce) # Force HTTPS (HIPAA §164.312(e)(1) - transmission security) if self.enable_hsts: response.headers["Strict-Transport-Security"] = ( f"max-age={self.hsts_max_age}; includeSubDomains; preload" ) # Permissions Policy (disable dangerous features) response.headers["Permissions-Policy"] = self._get_permissions_policy() # Referrer Policy (prevent leaking sensitive URLs) response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" # Remove server header (security through obscurity) response.headers.pop("Server", None) return response def _get_csp_policy(self, nonce: str) -> str: """ Get Content Security Policy directives. Each inline