"""Security headers on every response (app/middleware/security_headers.py). These are defense-in-depth against content sniffing, clickjacking and referrer leakage — the assertions pin presence and value, not placement. """ import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from app.middleware.security_headers import SecurityHeadersMiddleware @pytest.fixture() def client() -> TestClient: app = FastAPI() app.add_middleware(SecurityHeadersMiddleware) @app.get("/anything") def anything() -> dict[str, bool]: return {"ok": True} return TestClient(app) def test_headers_present_on_json_response(client: TestClient) -> None: resp = client.get("/anything") assert resp.headers["X-Content-Type-Options"] == "nosniff" assert resp.headers["X-Frame-Options"] == "DENY" assert resp.headers["Referrer-Policy"] == "strict-origin-when-cross-origin" def test_headers_do_not_override_existing_values(client: TestClient) -> None: app = FastAPI() app.add_middleware(SecurityHeadersMiddleware) @app.get("/preset") def preset() -> dict[str, bool]: return {"ok": True} @app.middleware("http") async def set_frame_header(request, call_next): # type: ignore[no-untyped-def] response = await call_next(request) # An endpoint that deliberately frames itself keeps its value. response.headers["X-Frame-Options"] = "SAMEORIGIN" return response with TestClient(app) as c: assert c.get("/preset").headers["X-Frame-Options"] == "SAMEORIGIN"