"""Core Security Module for AlgoSpaced. Configures Content Security Policy (CSP), defense-in-depth HTTP security headers, and ASGI security middleware for FastAPI. """ import os from collections.abc import Awaitable, Callable from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response # Content Security Policy directives # Defense-in-depth security architecture notes: # 1. script-src: 'unsafe-inline' and 'unsafe-eval' are strictly excluded. # All client JavaScript is bundled into external ES modules or static scripts from 'self', # providing robust protection against Cross-Site Scripting (XSS) and code injection. # 2. style-src: 'unsafe-inline' is permitted exclusively for runtime-generated styles: # CodeMirror 6 (style-mod) dynamic editor themes, KaTeX math layouts, and React inline styles. # CSS-based data exfiltration is blocked by strict img-src and connect-src origin whitelists. CSP_DIRECTIVES: dict[str, list[str]] = { "default-src": ["'self'"], "script-src": [ "'self'", "https://apis.google.com", "https://*.firebaseapp.com", "https://www.gstatic.com", "https://*.gstatic.com", "https://cdn.jsdelivr.net", ], "style-src": [ "'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdn.jsdelivr.net", ], "font-src": [ "'self'", "data:", "https://fonts.gstatic.com", "https://*.gstatic.com", ], "img-src": [ "'self'", "data:", "blob:", "https://*.googleusercontent.com", "https://images.unsplash.com", "https://avatars.githubusercontent.com", "https://raw.githubusercontent.com", "https://github.com", "https://*.firebasestorage.app", "https://firebasestorage.googleapis.com", "https://cdn.jsdelivr.net", "https://fastapi.tiangolo.com", ], "connect-src": [ "'self'", "http://localhost:*", "http://127.0.0.1:*", "ws://localhost:*", "ws://127.0.0.1:*", "wss:", "https://*.googleapis.com", "https://*.firebaseio.com", "https://*.firebaseapp.com", "https://*.firebasestorage.app", "https://firebasestorage.googleapis.com", "https://accounts.google.com", "https://generativelanguage.googleapis.com", "https://api.groq.com", "https://openrouter.ai", "https://api.github.com", "https://*.hf.space", "https://hf.space", ], "frame-src": [ "'self'", "https://accounts.google.com", "https://*.firebaseapp.com", "https://*.firebase.com", "https://*.google.com", "https://apis.google.com", ], "worker-src": ["'self'", "blob:"], "media-src": ["'self'", "data:", "blob:"], "object-src": ["'none'"], "base-uri": ["'self'"], } FRAME_ANCESTORS: list[str] = [ "'self'", "https://huggingface.co", "https://*.hf.space", ] FORM_ACTIONS: list[str] = [ "'self'", "https://github.com", ] def build_csp_header( include_frame_ancestors: bool = True, include_form_action: bool = True, ) -> str: """Builds the Content-Security-Policy string from configured directives. When include_frame_ancestors or include_form_action are False, those directives are omitted (required for HTML tags, which reject them per W3C specification). """ custom_csp = os.environ.get("CONTENT_SECURITY_POLICY") if custom_csp: return custom_csp.strip() parts: list[str] = [ f"{directive} {' '.join(sources)}" for directive, sources in CSP_DIRECTIVES.items() ] if include_form_action: parts.append(f"form-action {' '.join(FORM_ACTIONS)}") if include_frame_ancestors: parts.append(f"frame-ancestors {' '.join(FRAME_ANCESTORS)}") report_uri = os.environ.get("CSP_REPORT_URI") if report_uri: parts.append(f"report-uri {report_uri.strip()}") return "; ".join(parts) + ";" def get_security_headers() -> dict[str, str]: """Returns standard defense-in-depth security headers for HTTP responses.""" is_report_only = os.environ.get("CONTENT_SECURITY_POLICY_REPORT_ONLY", "false").lower() in ( "true", "1", ) csp_header_name = ( "Content-Security-Policy-Report-Only" if is_report_only else "Content-Security-Policy" ) return { csp_header_name: build_csp_header(include_frame_ancestors=True, include_form_action=True), "X-Content-Type-Options": "nosniff", "Referrer-Policy": "strict-origin-when-cross-origin", "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()", "Cross-Origin-Opener-Policy": "same-origin-allow-popups", } class SecurityHeadersMiddleware(BaseHTTPMiddleware): """Starlette HTTP Middleware that attaches security headers to all responses.""" async def dispatch( self, request: Request, call_next: Callable[[Request], Awaitable[Response]] ) -> Response: response = await call_next(request) for header, value in get_security_headers().items(): if header not in response.headers: response.headers[header] = value return response