From 36749dcd2f84ae69b972511ce1e55b7b93f997b1 Mon Sep 17 00:00:00 2001 From: Guy Korland Date: Wed, 25 Feb 2026 07:48:25 +0200 Subject: [PATCH 1/6] Add missing security headers to SecurityMiddleware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add X-Content-Type-Options, X-Frame-Options, Content-Security-Policy, Referrer-Policy, and Permissions-Policy headers to all responses. - X-Content-Type-Options: nosniff — prevents MIME-sniffing attacks - X-Frame-Options: DENY — prevents clickjacking - Content-Security-Policy — mitigates XSS and injection attacks - Referrer-Policy: strict-origin-when-cross-origin — prevents referrer leaks - Permissions-Policy — restricts unnecessary browser API access Expand security header tests from 2 to 8 covering each new header. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- api/app_factory.py | 37 ++++++++++++++++++++----- tests/test_hsts_header.py | 57 +++++++++++++++++++++++++++++++-------- 2 files changed, 77 insertions(+), 17 deletions(-) diff --git a/api/app_factory.py b/api/app_factory.py index e26509a8..018db114 100644 --- a/api/app_factory.py +++ b/api/app_factory.py @@ -44,12 +44,37 @@ async def dispatch(self, request: Request, call_next): response = await call_next(request) - # 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 + # HSTS: prevent man-in-the-middle attacks + response.headers["Strict-Transport-Security"] = ( + "max-age=31536000; includeSubDomains; preload" + ) + + # Prevent MIME-sniffing attacks + response.headers["X-Content-Type-Options"] = "nosniff" + + # Prevent clickjacking + response.headers["X-Frame-Options"] = "DENY" + + # XSS mitigation via Content Security Policy + response.headers["Content-Security-Policy"] = ( + "default-src 'self'; " + "script-src 'self'; " + "style-src 'self' 'unsafe-inline'; " + "img-src 'self' data:; " + "font-src 'self'; " + "connect-src 'self'; " + "frame-ancestors 'none'; " + "object-src 'none'; " + "base-uri 'self'" + ) + + # Prevent referrer data leaks to third parties + response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" + + # Restrict browser features + response.headers["Permissions-Policy"] = ( + "camera=(), microphone=(), geolocation=(), payment=()" + ) return response diff --git a/tests/test_hsts_header.py b/tests/test_hsts_header.py index 51a5d0f0..cb81fcca 100644 --- a/tests/test_hsts_header.py +++ b/tests/test_hsts_header.py @@ -1,13 +1,13 @@ """ -Test for HSTS header presence in responses. +Test for security header presence in responses. """ import pytest from fastapi.testclient import TestClient from api.index import app -class TestHSTSHeader: - """Test HSTS security header.""" +class TestSecurityHeaders: + """Test security headers.""" @pytest.fixture def client(self): @@ -16,13 +16,9 @@ def client(self): 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 @@ -30,14 +26,53 @@ def test_hsts_header_present(self, client): 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 + + 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 Content-Security-Policy header is present.""" + response = client.get("/") + csp = response.headers.get("content-security-policy") + assert csp is not None + assert "default-src 'self'" in csp + assert "script-src 'self'" in csp + assert "frame-ancestors 'none'" in csp + assert "object-src 'none'" in 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 + + 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 From ec043c46470ffe849b3e9a0bddad8f50d43a854c Mon Sep 17 00:00:00 2001 From: Guy Korland Date: Wed, 25 Feb 2026 10:54:24 +0200 Subject: [PATCH 2/6] Address PR review comments on security headers - Fix connect-src to allow https://api.github.com (GitHub star counts) - Fix style-src/font-src to allow Google Fonts (googleapis/gstatic) - Add separate permissive CSP for /docs, /redoc, /openapi routes - Refactor header application into helper method so early-return 403 responses also get all security headers - Add missing payment=() assertion in permissions-policy test - Add tests for GitHub API, Google Fonts, docs CSP, and 403 headers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- api/app_factory.py | 85 +++++++++++++++++++++++++-------------- tests/test_hsts_header.py | 28 +++++++++++++ 2 files changed, 82 insertions(+), 31 deletions(-) diff --git a/api/app_factory.py b/api/app_factory.py index 018db114..9d42bed4 100644 --- a/api/app_factory.py +++ b/api/app_factory.py @@ -33,49 +33,72 @@ 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"}) + # CSP for FastAPI interactive docs (/docs, /redoc) which load CDN assets + 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; " + "font-src 'self' https://fonts.gstatic.com data:; " + "connect-src 'self'; " + "frame-ancestors 'none'; " + "object-src 'none'; " + "base-uri 'self'" + ) - response = await call_next(request) + # CSP for the SPA and all other routes + DEFAULT_CSP = ( + "default-src 'self'; " + "script-src 'self'; " + "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + "img-src 'self' data:; " + "font-src 'self' https://fonts.gstatic.com; " + "connect-src 'self' https://api.github.com; " + "frame-ancestors 'none'; " + "object-src 'none'; " + "base-uri 'self'" + ) - # HSTS: prevent man-in-the-middle attacks + @staticmethod + def _apply_security_headers(response, path: str): + """Apply all security headers to a response.""" response.headers["Strict-Transport-Security"] = ( "max-age=31536000; includeSubDomains; preload" ) - - # Prevent MIME-sniffing attacks response.headers["X-Content-Type-Options"] = "nosniff" - - # Prevent clickjacking response.headers["X-Frame-Options"] = "DENY" - - # XSS mitigation via Content Security Policy - response.headers["Content-Security-Policy"] = ( - "default-src 'self'; " - "script-src 'self'; " - "style-src 'self' 'unsafe-inline'; " - "img-src 'self' data:; " - "font-src 'self'; " - "connect-src 'self'; " - "frame-ancestors 'none'; " - "object-src 'none'; " - "base-uri 'self'" - ) - - # Prevent referrer data leaks to third parties response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" - - # Restrict browser features response.headers["Permissions-Policy"] = ( "camera=(), microphone=(), geolocation=(), payment=()" ) + # Use a more permissive CSP for FastAPI docs pages + if path.startswith(("/docs", "/redoc", "/openapi")): + response.headers["Content-Security-Policy"] = ( + SecurityMiddleware.DOCS_CSP + ) + else: + response.headers["Content-Security-Policy"] = ( + SecurityMiddleware.DEFAULT_CSP + ) + + async def dispatch(self, request: Request, call_next): + 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 "../" in filename or filename.endswith("/"): + 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 diff --git a/tests/test_hsts_header.py b/tests/test_hsts_header.py index cb81fcca..15e998e3 100644 --- a/tests/test_hsts_header.py +++ b/tests/test_hsts_header.py @@ -67,6 +67,7 @@ def test_permissions_policy(self, client): 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.""" @@ -76,3 +77,30 @@ def test_security_headers_on_api_endpoints(self, client): assert "content-security-policy" in response.headers assert "referrer-policy" in response.headers assert "permissions-policy" in response.headers + + def test_csp_allows_github_api(self, client): + """Test that CSP connect-src allows GitHub API for star counts.""" + response = client.get("/") + csp = response.headers.get("content-security-policy") + assert "https://api.github.com" in csp + + def test_csp_allows_google_fonts(self, client): + """Test that CSP allows Google Fonts for styles and font files.""" + response = client.get("/") + csp = response.headers.get("content-security-policy") + assert "https://fonts.googleapis.com" in csp + assert "https://fonts.gstatic.com" in csp + + def test_csp_docs_allows_cdn(self, client): + """Test that /docs gets a permissive CSP for CDN assets.""" + response = client.get("/docs") + csp = response.headers.get("content-security-policy") + assert "https://cdn.jsdelivr.net" in 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 + assert "strict-transport-security" in response.headers + assert "x-content-type-options" in response.headers + assert "content-security-policy" in response.headers From 5ff6e0c66467021164df366a984dfa9142802649 Mon Sep 17 00:00:00 2001 From: Anchel135 Date: Sun, 23 Aug 2026 12:12:23 +0300 Subject: [PATCH 3/6] feat: enhance security header tests with CSP parsing and expectations --- tests/test_hsts_header.py | 84 +++++++++++++++++++++++++++++++-------- 1 file changed, 67 insertions(+), 17 deletions(-) diff --git a/tests/test_hsts_header.py b/tests/test_hsts_header.py index 15e998e3..3d7514d2 100644 --- a/tests/test_hsts_header.py +++ b/tests/test_hsts_header.py @@ -6,6 +6,54 @@ 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:"], + "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"], + "font-src": ["'self'", "https://fonts.gstatic.com", "data:"], + "connect-src": ["'self'"], + "frame-ancestors": ["'none'"], + "object-src": ["'none'"], + "base-uri": ["'self'"], +} + + class TestSecurityHeaders: """Test security headers.""" @@ -45,14 +93,11 @@ def test_x_frame_options(self, client): assert response.headers.get("x-frame-options") == "DENY" def test_content_security_policy(self, client): - """Test that Content-Security-Policy header is present.""" + """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 "default-src 'self'" in csp - assert "script-src 'self'" in csp - assert "frame-ancestors 'none'" in csp - assert "object-src 'none'" in csp + assert parse_csp(csp) == EXPECTED_DEFAULT_CSP def test_referrer_policy(self, client): """Test that Referrer-Policy header is present.""" @@ -78,24 +123,29 @@ def test_security_headers_on_api_endpoints(self, client): assert "referrer-policy" in response.headers assert "permissions-policy" in response.headers - def test_csp_allows_github_api(self, client): - """Test that CSP connect-src allows GitHub API for star counts.""" - response = client.get("/") - csp = response.headers.get("content-security-policy") - assert "https://api.github.com" in csp + def test_csp_allows_live_cross_origin_fetches(self, client): + """Test that the CSP permits every origin the SPA actually calls. - def test_csp_allows_google_fonts(self, client): - """Test that CSP allows Google Fonts for styles and font files.""" + 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("/") - csp = response.headers.get("content-security-policy") - assert "https://fonts.googleapis.com" in csp - assert "https://fonts.gstatic.com" in csp + 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_docs_allows_cdn(self, client): - """Test that /docs gets a permissive CSP for CDN assets.""" + """Test that /docs gets the permissive CSP needed for CDN assets.""" response = client.get("/docs") csp = response.headers.get("content-security-policy") - assert "https://cdn.jsdelivr.net" in csp + assert csp is not None + assert parse_csp(csp) == EXPECTED_DOCS_CSP def test_security_headers_on_forbidden_static(self, client): """Test that early-return 403 responses also include security headers.""" From f02f433085aad63225e41ea697b374e5789edf5c Mon Sep 17 00:00:00 2001 From: Anchel135 Date: Wed, 26 Aug 2026 10:29:18 +0300 Subject: [PATCH 4/6] fix(security): stop the CSP breaking avatars and leaking the docs policy Five findings from review, all reproducible against the current code: - DEFAULT_CSP allowed images only from 'self', but /auth-status passes the identity provider's picture URL through verbatim and the SPA renders it in . Every logged-in avatar was CSP-blocked in production and fell back to initials. img-src now names the Google and GitHub avatar hosts. - The docs CSP was selected with a prefix test, and the SPA catch-all serves index.html for any unmatched path, so /docs-preview and friends were served the application's own HTML with 'unsafe-inline', 'unsafe-eval' and two CDN script sources enabled. It now matches the four exact FastAPI endpoints. - DOCS_CSP had no worker-src, so ReDoc's blob: search worker fell back to default-src 'self' and was blocked; and its img-src omitted the host serving the default docs favicon. - CSRFMiddleware was registered after SecurityMiddleware, which made it the outer layer, so its 403 returned attacker-reachable JSON with no nosniff and no CSP. SecurityMiddleware is now registered last so it wraps CSRF. - The middleware methods carried no type annotations. Tests now assert the full header set on both early-return 403 paths, pin the avatar hosts, and cover the lookalike docs paths. The class is marked unit so it is classified under --strict-markers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- api/app_factory.py | 45 +++++++++++++++++------- tests/test_hsts_header.py | 72 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 100 insertions(+), 17 deletions(-) diff --git a/api/app_factory.py b/api/app_factory.py index 3959c847..ccdb0c96 100644 --- a/api/app_factory.py +++ b/api/app_factory.py @@ -10,7 +10,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.openapi import MCPType, RouteMap @@ -36,27 +37,41 @@ class SecurityMiddleware(BaseHTTPMiddleware): # pylint: disable=too-few-public- STATIC_PREFIX = "/static/" - # CSP for FastAPI interactive docs (/docs, /redoc) which load CDN assets + # 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"} + ) + + # 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; " + "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 + # 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:; " + "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'; " @@ -65,7 +80,7 @@ class SecurityMiddleware(BaseHTTPMiddleware): # pylint: disable=too-few-public- ) @staticmethod - def _apply_security_headers(response, path: str): + 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" @@ -78,7 +93,7 @@ def _apply_security_headers(response, path: str): ) # Use a more permissive CSP for FastAPI docs pages - if path.startswith(("/docs", "/redoc", "/openapi")): + if path in SecurityMiddleware.DOCS_PATHS: response.headers["Content-Security-Policy"] = ( SecurityMiddleware.DOCS_CSP ) @@ -87,7 +102,9 @@ def _apply_security_headers(response, path: str): SecurityMiddleware.DEFAULT_CSP ) - async def dispatch(self, request: Request, call_next): + async def dispatch( + self, request: Request, call_next: RequestResponseEndpoint + ) -> Response: path = request.url.path # Block directory access in static files @@ -134,7 +151,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 @@ -314,12 +333,14 @@ def custom_openapi(): max_age=60 * 60 * 24 * 14, # 14 days - measured by 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 index 3d7514d2..8805bc71 100644 --- a/tests/test_hsts_header.py +++ b/tests/test_hsts_header.py @@ -22,7 +22,12 @@ def parse_csp(csp: str) -> dict[str, list[str]]: "default-src": ["'self'"], "script-src": ["'self'"], "style-src": ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], - "img-src": ["'self'", "data:"], + "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'"], @@ -45,15 +50,33 @@ def parse_csp(csp: str) -> dict[str, list[str]]: "https://cdn.jsdelivr.net", "https://fonts.googleapis.com", ], - "img-src": ["'self'", "data:", "https://cdn.jsdelivr.net"], + "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.""" @@ -140,6 +163,18 @@ def test_csp_allows_live_cross_origin_fetches(self, client): ] 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 "https://*.googleusercontent.com" in directives["img-src"] + assert "https://avatars.githubusercontent.com" in directives["img-src"] + def test_csp_docs_allows_cdn(self, client): """Test that /docs gets the permissive CSP needed for CDN assets.""" response = client.get("/docs") @@ -147,10 +182,37 @@ def test_csp_docs_allows_cdn(self, client): 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 - assert "strict-transport-security" in response.headers - assert "x-content-type-options" in response.headers - assert "content-security-policy" in response.headers + for header in COMMON_SECURITY_HEADERS: + assert header in response.headers, header + + 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 From 9a6b863b3d35aac0399a23f9bf0c60a969eacec0 Mon Sep 17 00:00:00 2001 From: Anchel135 Date: Wed, 26 Aug 2026 10:38:43 +0300 Subject: [PATCH 5/6] test(security): assert the avatar sources by exact list, not membership CodeQL flags the 'https://...' in directives['img-src'] form as incomplete URL substring sanitization. It is list membership rather than a substring test, so the alert is a false positive, but comparing the whole source list is both stricter and consistent with how every other CSP assertion in this file works. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/test_hsts_header.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/test_hsts_header.py b/tests/test_hsts_header.py index 8805bc71..af830490 100644 --- a/tests/test_hsts_header.py +++ b/tests/test_hsts_header.py @@ -172,8 +172,12 @@ def test_csp_allows_the_avatars_the_spa_renders(self, client): """ response = client.get("/") directives = parse_csp(response.headers["content-security-policy"]) - assert "https://*.googleusercontent.com" in directives["img-src"] - assert "https://avatars.githubusercontent.com" in directives["img-src"] + 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.""" From 3765adb8511d09818f7f5da52cd33746e63e6ca3 Mon Sep 17 00:00:00 2001 From: Anchel135 Date: Wed, 26 Aug 2026 11:54:03 +0300 Subject: [PATCH 6/6] fix(security): block bare ".." segments in the static path guard Substring-matching "../" missed a bare trailing ".." and the backslash form, so the guard now splits the path into segments and rejects any ".." among them. In practice this is defence in depth: Starlette's StaticFiles resolves and confines paths itself, and httpx normalises "/static/../etc/passwd" down to "/etc/passwd" before it is ever sent, so the unencoded forms cannot even be driven through TestClient. A raw client is under no such obligation, hence both an HTTP-level test for the forms that do reach the middleware and a direct test of the segment check for the ones that cannot. Also renames the module to test_security_headers.py, since it long ago outgrew covering only HSTS. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- api/app_factory.py | 15 ++++++- ...sts_header.py => test_security_headers.py} | 44 ++++++++++++++++++- 2 files changed, 57 insertions(+), 2 deletions(-) rename tests/{test_hsts_header.py => test_security_headers.py} (84%) diff --git a/api/app_factory.py b/api/app_factory.py index ab434303..21a37720 100644 --- a/api/app_factory.py +++ b/api/app_factory.py @@ -104,6 +104,15 @@ def _apply_security_headers(response: Response, path: str) -> None: 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: @@ -112,7 +121,11 @@ async def dispatch( # Block directory access in static files if path.startswith(self.STATIC_PREFIX): filename = path[len(self.STATIC_PREFIX) :] - if not filename or "../" in filename or filename.endswith("/"): + if ( + not filename + or filename.endswith("/") + or self._has_traversal_segment(filename) + ): response = JSONResponse( status_code=403, content={"detail": "Forbidden"} ) diff --git a/tests/test_hsts_header.py b/tests/test_security_headers.py similarity index 84% rename from tests/test_hsts_header.py rename to tests/test_security_headers.py index af830490..d6ef26ec 100644 --- a/tests/test_hsts_header.py +++ b/tests/test_security_headers.py @@ -1,8 +1,9 @@ """ -Test for security header presence in responses. +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 @@ -208,6 +209,47 @@ def test_security_headers_on_forbidden_static(self, client): 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.