diff --git a/api/app_factory.py b/api/app_factory.py index 175a65bd..21a37720 100644 --- a/api/app_factory.py +++ b/api/app_factory.py @@ -9,7 +9,8 @@ from fastapi.responses import RedirectResponse, JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from starlette.middleware.sessions import SessionMiddleware -from starlette.middleware.base import BaseHTTPMiddleware +from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint +from starlette.responses import Response from fastmcp import FastMCP from fastmcp.server.providers.openapi import MCPType, RouteMap @@ -38,24 +39,101 @@ class SecurityMiddleware(BaseHTTPMiddleware): # pylint: disable=too-few-public- STATIC_PREFIX = "/static/" - async def dispatch(self, request: Request, call_next): - # Block directory access in static files - if request.url.path.startswith(self.STATIC_PREFIX): - # Remove /static/ prefix to get the actual path - filename = request.url.path[len(self.STATIC_PREFIX) :] - # Basic security check for directory traversal - if not filename or "../" in filename or filename.endswith("/"): - return JSONResponse(status_code=403, content={"detail": "Forbidden"}) + # The exact FastAPI documentation endpoints, which are the only paths + # allowed the permissive DOCS_CSP. A prefix test would also match SPA + # routes such as /docs-preview, handing them 'unsafe-eval' and two CDNs. + DOCS_PATHS = frozenset( + {"/docs", "/docs/oauth2-redirect", "/redoc", "/openapi.json"} + ) - response = await call_next(request) + # CSP for FastAPI interactive docs (/docs, /redoc) which load CDN assets. + # ReDoc builds its search index in a blob: worker, and both doc pages + # default to a favicon served from fastapi.tiangolo.com. + DOCS_CSP = ( + "default-src 'self'; " + "script-src 'self' 'unsafe-inline' 'unsafe-eval' " + "https://cdn.jsdelivr.net https://unpkg.com; " + "style-src 'self' 'unsafe-inline' " + "https://cdn.jsdelivr.net https://fonts.googleapis.com; " + "img-src 'self' data: https://cdn.jsdelivr.net " + "https://fastapi.tiangolo.com; " + "font-src 'self' https://fonts.gstatic.com data:; " + "connect-src 'self'; " + "worker-src 'self' blob:; " + "frame-ancestors 'none'; " + "object-src 'none'; " + "base-uri 'self'" + ) + + # CSP for the SPA and all other routes. img-src has to name the identity + # providers because the SPA renders the logged-in avatar straight from the + # provider URL that /auth-status passes through. + DEFAULT_CSP = ( + "default-src 'self'; " + "script-src 'self'; " + "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + "img-src 'self' data: https://*.googleusercontent.com " + "https://avatars.githubusercontent.com; " + "font-src 'self' https://fonts.gstatic.com; " + "connect-src 'self' https://api.github.com; " + "frame-ancestors 'none'; " + "object-src 'none'; " + "base-uri 'self'" + ) + + @staticmethod + def _apply_security_headers(response: Response, path: str) -> None: + """Apply all security headers to a response.""" + response.headers["Strict-Transport-Security"] = ( + "max-age=31536000; includeSubDomains; preload" + ) + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["X-Frame-Options"] = "DENY" + response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" + response.headers["Permissions-Policy"] = ( + "camera=(), microphone=(), geolocation=(), payment=()" + ) - # Add HSTS header to prevent man-in-the-middle attacks - # max-age=31536000: 1 year in seconds - # includeSubDomains: apply to all subdomains - # preload: eligible for browser HSTS preload lists - hsts_value = "max-age=31536000; includeSubDomains; preload" - response.headers["Strict-Transport-Security"] = hsts_value + # Use a more permissive CSP for FastAPI docs pages + if path in SecurityMiddleware.DOCS_PATHS: + response.headers["Content-Security-Policy"] = ( + SecurityMiddleware.DOCS_CSP + ) + else: + response.headers["Content-Security-Policy"] = ( + SecurityMiddleware.DEFAULT_CSP + ) + + @staticmethod + def _has_traversal_segment(filename: str) -> bool: + """True if any segment of the path is a parent-directory marker. + + Substring-matching "../" misses a bare trailing ".." and the + backslash-separated form, so the path is split into segments instead. + """ + return ".." in filename.replace("\\", "/").split("/") + async def dispatch( + self, request: Request, call_next: RequestResponseEndpoint + ) -> Response: + path = request.url.path + + # Block directory access in static files + if path.startswith(self.STATIC_PREFIX): + filename = path[len(self.STATIC_PREFIX) :] + if ( + not filename + or filename.endswith("/") + or self._has_traversal_segment(filename) + ): + response = JSONResponse( + status_code=403, content={"detail": "Forbidden"} + ) + self._apply_security_headers(response, path) + return response + + response = await call_next(request) + self._apply_security_headers(response, path) return response @@ -100,7 +178,9 @@ class CSRFMiddleware(BaseHTTPMiddleware): # pylint: disable=too-few-public-meth "/mcp", ) - async def dispatch(self, request: Request, call_next): + async def dispatch( + self, request: Request, call_next: RequestResponseEndpoint + ) -> Response: # Validate CSRF for unsafe, non-exempt, non-Bearer requests if ( request.method not in self.SAFE_METHODS @@ -297,12 +377,14 @@ def custom_openapi(): max_age=session_ttl_seconds(), ) - # Add security middleware - app.add_middleware(SecurityMiddleware) - # Add CSRF middleware (double-submit cookie pattern) app.add_middleware(CSRFMiddleware) + # Add security middleware. add_middleware prepends, so registering this + # last makes it the outermost layer: its headers then also cover the 403 + # that CSRFMiddleware returns before call_next is ever reached. + app.add_middleware(SecurityMiddleware) + # Mount static files from the React build (app/dist) # This serves the bundled assets (JS, CSS, images, etc.) dist_path = os.path.join(os.path.dirname(__file__), "../app/dist") diff --git a/tests/test_hsts_header.py b/tests/test_hsts_header.py deleted file mode 100644 index 51a5d0f0..00000000 --- a/tests/test_hsts_header.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Test for HSTS header presence in responses. -""" -import pytest -from fastapi.testclient import TestClient -from api.index import app - - -class TestHSTSHeader: - """Test HSTS security header.""" - - @pytest.fixture - def client(self): - """Create a test client.""" - return TestClient(app) - - def test_hsts_header_present(self, client): - """Test that the HSTS header is present in responses.""" - # Make a request to the root endpoint - response = client.get("/") - - # Verify HSTS header is present - assert "strict-transport-security" in response.headers - - # Verify header value contains required directives - hsts_header = response.headers["strict-transport-security"] - assert "max-age=31536000" in hsts_header - assert "includeSubDomains" in hsts_header - assert "preload" in hsts_header - - def test_hsts_header_on_api_endpoints(self, client): - """Test that the HSTS header is present on API endpoints.""" - # Test on graphs endpoint - response = client.get("/graphs") - - # Verify HSTS header is present - assert "strict-transport-security" in response.headers - - # Verify header value contains required directives - hsts_header = response.headers["strict-transport-security"] - assert "max-age=31536000" in hsts_header - assert "includeSubDomains" in hsts_header - assert "preload" in hsts_header diff --git a/tests/test_security_headers.py b/tests/test_security_headers.py new file mode 100644 index 00000000..d6ef26ec --- /dev/null +++ b/tests/test_security_headers.py @@ -0,0 +1,264 @@ +""" +Tests for the security headers applied to every response. +""" +import pytest +from fastapi.testclient import TestClient +from api.app_factory import SecurityMiddleware +from api.index import app + + +def parse_csp(csp: str) -> dict[str, list[str]]: + """Split a Content-Security-Policy header into {directive: [sources]}.""" + directives = {} + for part in csp.split(";"): + tokens = part.split() + if tokens: + directives[tokens[0]] = tokens[1:] + return directives + + +# Expected source lists are spelled out in full rather than substring-matched, +# so widening a directive has to be a deliberate change in both files. +EXPECTED_DEFAULT_CSP = { + "default-src": ["'self'"], + "script-src": ["'self'"], + "style-src": ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], + "img-src": [ + "'self'", + "data:", + "https://*.googleusercontent.com", + "https://avatars.githubusercontent.com", + ], + "font-src": ["'self'", "https://fonts.gstatic.com"], + "connect-src": ["'self'", "https://api.github.com"], + "frame-ancestors": ["'none'"], + "object-src": ["'none'"], + "base-uri": ["'self'"], +} + +EXPECTED_DOCS_CSP = { + "default-src": ["'self'"], + "script-src": [ + "'self'", + "'unsafe-inline'", + "'unsafe-eval'", + "https://cdn.jsdelivr.net", + "https://unpkg.com", + ], + "style-src": [ + "'self'", + "'unsafe-inline'", + "https://cdn.jsdelivr.net", + "https://fonts.googleapis.com", + ], + "img-src": [ + "'self'", + "data:", + "https://cdn.jsdelivr.net", + "https://fastapi.tiangolo.com", + ], + "font-src": ["'self'", "https://fonts.gstatic.com", "data:"], + "connect-src": ["'self'"], + "worker-src": ["'self'", "blob:"], + "frame-ancestors": ["'none'"], + "object-src": ["'none'"], + "base-uri": ["'self'"], +} + +# Every header SecurityMiddleware is contracted to set, so a response that +# skips the middleware cannot pass by asserting only a subset. +COMMON_SECURITY_HEADERS = ( + "strict-transport-security", + "x-content-type-options", + "x-frame-options", + "referrer-policy", + "permissions-policy", + "content-security-policy", +) + + +@pytest.mark.unit +class TestSecurityHeaders: + """Test security headers.""" + + @pytest.fixture + def client(self): + """Create a test client.""" + return TestClient(app) + + def test_hsts_header_present(self, client): + """Test that the HSTS header is present in responses.""" + response = client.get("/") + + assert "strict-transport-security" in response.headers + hsts_header = response.headers["strict-transport-security"] + assert "max-age=31536000" in hsts_header + assert "includeSubDomains" in hsts_header + assert "preload" in hsts_header + + def test_hsts_header_on_api_endpoints(self, client): + """Test that the HSTS header is present on API endpoints.""" + response = client.get("/graphs") + + assert "strict-transport-security" in response.headers + hsts_header = response.headers["strict-transport-security"] + assert "max-age=31536000" in hsts_header + assert "includeSubDomains" in hsts_header + assert "preload" in hsts_header + + def test_x_content_type_options(self, client): + """Test that X-Content-Type-Options is set to nosniff.""" + response = client.get("/") + assert response.headers.get("x-content-type-options") == "nosniff" + + def test_x_frame_options(self, client): + """Test that X-Frame-Options is set to DENY.""" + response = client.get("/") + assert response.headers.get("x-frame-options") == "DENY" + + def test_content_security_policy(self, client): + """Test that the SPA CSP matches the expected source lists exactly.""" + response = client.get("/") + csp = response.headers.get("content-security-policy") + assert csp is not None + assert parse_csp(csp) == EXPECTED_DEFAULT_CSP + + def test_referrer_policy(self, client): + """Test that Referrer-Policy header is present.""" + response = client.get("/") + assert response.headers.get("referrer-policy") == "strict-origin-when-cross-origin" + + def test_permissions_policy(self, client): + """Test that Permissions-Policy header is present.""" + response = client.get("/") + policy = response.headers.get("permissions-policy") + assert policy is not None + assert "camera=()" in policy + assert "microphone=()" in policy + assert "geolocation=()" in policy + assert "payment=()" in policy + + def test_security_headers_on_api_endpoints(self, client): + """Test that all security headers are present on API endpoints.""" + response = client.get("/graphs") + assert "x-content-type-options" in response.headers + assert "x-frame-options" in response.headers + assert "content-security-policy" in response.headers + assert "referrer-policy" in response.headers + assert "permissions-policy" in response.headers + + def test_csp_allows_live_cross_origin_fetches(self, client): + """Test that the CSP permits every origin the SPA actually calls. + + The SPA reads GitHub star counts from api.github.com and pulls + Google Fonts from an @import in app/src/index.css. Dev serves no CSP + header, so a missing source here only breaks production. + """ + response = client.get("/") + directives = parse_csp(response.headers["content-security-policy"]) + assert directives["connect-src"] == ["'self'", "https://api.github.com"] + assert directives["style-src"] == [ + "'self'", + "'unsafe-inline'", + "https://fonts.googleapis.com", + ] + assert directives["font-src"] == ["'self'", "https://fonts.gstatic.com"] + + def test_csp_allows_the_avatars_the_spa_renders(self, client): + """Test that img-src covers the identity providers' avatar hosts. + + /auth-status passes the provider's picture URL through verbatim and + the SPA renders it in , so a self-only img-src silently + degrades every logged-in avatar to the initials fallback. + """ + response = client.get("/") + directives = parse_csp(response.headers["content-security-policy"]) + assert directives["img-src"] == [ + "'self'", + "data:", + "https://*.googleusercontent.com", + "https://avatars.githubusercontent.com", + ] + + def test_csp_docs_allows_cdn(self, client): + """Test that /docs gets the permissive CSP needed for CDN assets.""" + response = client.get("/docs") + csp = response.headers.get("content-security-policy") + assert csp is not None + assert parse_csp(csp) == EXPECTED_DOCS_CSP + + @pytest.mark.parametrize( + "path", ["/docs-preview", "/redoc-x", "/openapi-foo", "/docsanything"] + ) + def test_docs_csp_is_not_handed_to_lookalike_paths(self, client, path): + """Test that only the exact docs endpoints get the permissive CSP. + + The SPA catch-all serves index.html for any unmatched path, so a + prefix match would let an attacker pick a URL that turns on + 'unsafe-inline', 'unsafe-eval' and two CDN script sources. + """ + response = client.get(path) + assert parse_csp(response.headers["content-security-policy"]) == ( + EXPECTED_DEFAULT_CSP + ) + + def test_security_headers_on_forbidden_static(self, client): + """Test that early-return 403 responses also include security headers.""" + response = client.get("/static/") + assert response.status_code == 403 + for header in COMMON_SECURITY_HEADERS: + assert header in response.headers, header + + @pytest.mark.parametrize( + "path", + [ + "/static/..%2fetc%2fpasswd", + "/static/assets%2f..%2f..%2fetc", + "/static/..\\windows", + ], + ) + def test_traversal_is_blocked_over_http(self, client, path): + """Test that a traversal attempt reaching the middleware is refused.""" + response = client.get(path) + assert response.status_code == 403 + assert response.json()["detail"] == "Forbidden" + + @pytest.mark.parametrize( + "filename, is_traversal", + [ + ("..", True), + ("../etc/passwd", True), + ("assets/..", True), + ("assets/../../etc/passwd", True), + ("..\\windows", True), + ("app.js", False), + ("assets/index-abc123.js", False), + ("..dotfile", False), + ("file..name", False), + ], + ) + def test_traversal_segment_detection(self, filename, is_traversal): + """Test that a bare ".." segment counts, not just the "../" substring. + + These cannot all be driven over HTTP: httpx normalises + "/static/../etc/passwd" down to "/etc/passwd" before the request is + sent, so the request never reaches this middleware. A raw client is + under no such obligation, so the guard is exercised directly. + """ + # pylint: disable=protected-access + assert ( + SecurityMiddleware._has_traversal_segment(filename) is is_traversal + ) + + def test_security_headers_on_csrf_rejection(self, client): + """Test that CSRFMiddleware's own 403 still carries the headers. + + CSRFMiddleware returns before call_next, so SecurityMiddleware only + covers it while it is registered as the outer layer. This body is + attacker-reachable JSON, which makes the nosniff header matter. + """ + response = client.post("/tokens/generate") + assert response.status_code == 403 + assert response.json()["detail"] == "CSRF token missing or invalid" + for header in COMMON_SECURITY_HEADERS: + assert header in response.headers, header