""" Security Middleware and Headers Implements security best practices for healthcare applications """ import ipaddress import os import secrets import time from typing import Callable, Optional from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware from starlette.types import ASGIApp # --------------------------------------------------------------------------- # Trusted proxy CIDR ranges — only trust X-Forwarded-For from these sources. # OWASP A05:2021 — Security Misconfiguration: trusting unvalidated HTTP headers # allows attackers to spoof their IP and bypass rate-limiting / IP allowlists. # Override via TRUSTED_PROXY_CIDRS env var (comma-separated CIDR list). # --------------------------------------------------------------------------- _DEFAULT_TRUSTED_CIDRS = [ "127.0.0.1/32", # loopback "::1/128", # IPv6 loopback "10.0.0.0/8", # RFC 1918 private "172.16.0.0/12", # RFC 1918 private "192.168.0.0/16", # RFC 1918 private ] def _load_trusted_networks() -> list: raw = os.environ.get("TRUSTED_PROXY_CIDRS", "") cidrs = [c.strip() for c in raw.split(",") if c.strip()] if raw else _DEFAULT_TRUSTED_CIDRS return [ipaddress.ip_network(c, strict=False) for c in cidrs] _TRUSTED_PROXY_NETWORKS = _load_trusted_networks() def _is_trusted_proxy(ip_str: str) -> bool: """Return True if the IP belongs to a configured trusted proxy network.""" try: addr = ipaddress.ip_address(ip_str) return any(addr in net for net in _TRUSTED_PROXY_NETWORKS) except ValueError: return False def get_client_ip(request: Request) -> str: """ Extract client IP address from request, honoring X-Forwarded-For ONLY when the direct TCP peer is a trusted proxy. SECURITY: Blindly trusting XFF allows an attacker to send `X-Forwarded-For: 127.0.0.1` and appear as localhost, bypassing IP-based rate limiting and account lockout. We validate the direct peer first. (OWASP A05:2021 – Security Misconfiguration) """ direct_ip: str = request.client.host if request.client else "" if _is_trusted_proxy(direct_ip): forwarded_for = request.headers.get("X-Forwarded-For", "") if forwarded_for: # Take the leftmost (client) IP from the XFF chain return forwarded_for.split(",")[0].strip() real_ip = request.headers.get("X-Real-IP", "").strip() if real_ip: return real_ip # Direct connection or untrusted peer — use TCP-layer IP return direct_ip or "unknown" class SecurityHeadersMiddleware(BaseHTTPMiddleware): """ Adds security headers to all responses. Headers implemented: - Strict-Transport-Security (HSTS): Force HTTPS - X-Content-Type-Options: Prevent MIME type sniffing - X-Frame-Options: Prevent clickjacking - Content-Security-Policy: Control resource loading - Referrer-Policy: Control referrer information - Permissions-Policy: Control browser features """ async def dispatch(self, request: Request, call_next: Callable) -> Response: # Generate per-request nonce before template rendering nonce = secrets.token_hex(16) request.state.csp_nonce = nonce response = await call_next(request) # HSTS: Force HTTPS for 1 year, include subdomains response.headers["Strict-Transport-Security"] = ( "max-age=31536000; includeSubDomains; preload" ) # Prevent MIME type sniffing response.headers["X-Content-Type-Options"] = "nosniff" # Prevent clickjacking — DENY blocks all framing (OWASP A05:2021) response.headers["X-Frame-Options"] = "DENY" # Content Security Policy — all assets served locally (no external CDNs) # report-uri enables real-time CSP violation reporting (OWASP A05:2021) response.headers["Content-Security-Policy"] = ( "default-src 'self'; " f"script-src 'self' 'nonce-{nonce}'; " "style-src 'self' 'unsafe-inline'; " "img-src 'self' data: blob:; " "font-src 'self' data:; " "connect-src 'self' wss: ws:; " "frame-ancestors 'none'; " "base-uri 'self'; " "form-action 'self'; " "report-uri /api/v1/csp-report; " "report-to csp-endpoint" ) # Strip server-identifying headers — prevents version fingerprinting # (OWASP A05:2021 — Security Misconfiguration) response.headers["Server"] = "" response.headers.pop("X-Powered-By", None) # Referrer Policy - don't leak sensitive URLs response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" # Permissions Policy - restrict browser features response.headers["Permissions-Policy"] = ( "geolocation=(), " "microphone=(), " "camera=(), " "payment=(), " "usb=(), " "magnetometer=(), " "gyroscope=(), " "accelerometer=()" ) # Cache Control for sensitive data if request.url.path.startswith("/api/"): response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, private" response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "0" return response class RateLimitMiddleware(BaseHTTPMiddleware): """ Token-bucket rate limiter using an in-process counter. Limits: - Auth endpoints (/api/v1/auth/*) : 5 req / 60 s per source IP - API endpoints (/api/v1/*) : 200 req / 60 s per tenant_id (fallback to IP when tenant_id header is absent) Override via env vars: RATE_LIMIT_AUTH (default 5) RATE_LIMIT_API (default 200) RATE_LIMIT_WINDOW_S (default 60 seconds) Security (OWASP A04:2021 — Insecure Design): Prevents credential stuffing on auth endpoints and API abuse. For multi-process deployments replace the in-process dict with a Redis INCR/EXPIRE counter to share state across workers. """ def __init__(self, app: ASGIApp) -> None: super().__init__(app) import time as _time from collections import defaultdict self._time = _time self._auth_limit: int = int(os.environ.get("RATE_LIMIT_AUTH", "5")) self._api_limit: int = int(os.environ.get("RATE_LIMIT_API", "200")) self._window: int = int(os.environ.get("RATE_LIMIT_WINDOW_S", "60")) # { key: [request_count, window_start_time] } self._counters: dict = defaultdict(lambda: [0, 0.0]) def _check(self, key: str, limit: int) -> tuple[bool, int]: """Return (allowed, retry_after_seconds).""" now = self._time.time() entry = self._counters[key] if now - entry[1] >= self._window: entry[0] = 0 entry[1] = now entry[0] += 1 if entry[0] > limit: retry_after = int(self._window - (now - entry[1])) + 1 return False, retry_after return True, 0 async def dispatch(self, request: Request, call_next: Callable) -> Response: from fastapi.responses import JSONResponse path = request.url.path if path.startswith("/api/v1/auth"): key = f"auth:{get_client_ip(request)}" allowed, retry_after = self._check(key, self._auth_limit) elif path.startswith("/api/v1"): tenant_key = request.headers.get("X-Tenant-ID") or get_client_ip(request) key = f"api:{tenant_key}" allowed, retry_after = self._check(key, self._api_limit) else: allowed, retry_after = True, 0 if not allowed: return JSONResponse( status_code=429, headers={"Retry-After": str(retry_after)}, content={ "error": "too_many_requests", "message": "Rate limit exceeded. Please slow down.", "retry_after": retry_after, }, ) return await call_next(request) class RequestTimingMiddleware(BaseHTTPMiddleware): """ Add request timing information to response headers. Useful for performance monitoring and debugging. """ async def dispatch(self, request: Request, call_next: Callable) -> Response: start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = f"{process_time:.4f}" return response class IPWhitelistMiddleware(BaseHTTPMiddleware): """ IP Whitelist middleware for restricting access to specific IP addresses. Useful for admin endpoints or internal APIs. """ def __init__(self, app: ASGIApp, allowed_ips: list = None, blocked_paths: list = None): # type: ignore[arg-type, assignment] super().__init__(app) self.allowed_ips = allowed_ips or [] self.blocked_paths = blocked_paths or ["/admin", "/api/v1/admin"] async def dispatch(self, request: Request, call_next: Callable) -> Response: # Check if path requires IP whitelisting requires_whitelist = any(request.url.path.startswith(path) for path in self.blocked_paths) if requires_whitelist and self.allowed_ips: # Use validated get_client_ip — prevents XFF spoofing client_ip = get_client_ip(request) if client_ip not in self.allowed_ips: from fastapi.responses import JSONResponse return JSONResponse( status_code=403, content={ "error": "Forbidden", "message": "Access denied. Your IP address is not whitelisted.", }, ) return await call_next(request)