2026-03-01 11:50:34 -05:00
|
|
|
"""Test security headers middleware in FastAPI app."""
|
|
|
|
|
|
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_security_headers_present(client: TestClient):
|
|
|
|
|
"""Test that security headers are present in all responses."""
|
|
|
|
|
response = client.get("/")
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
# Check for security headers
|
|
|
|
|
assert "X-Frame-Options" in response.headers
|
|
|
|
|
assert response.headers["X-Frame-Options"] == "SAMEORIGIN"
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
assert "X-Content-Type-Options" in response.headers
|
|
|
|
|
assert response.headers["X-Content-Type-Options"] == "nosniff"
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
assert "X-XSS-Protection" in response.headers
|
|
|
|
|
assert response.headers["X-XSS-Protection"] == "1; mode=block"
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
assert "Referrer-Policy" in response.headers
|
|
|
|
|
assert response.headers["Referrer-Policy"] == "strict-origin-when-cross-origin"
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
assert "Content-Security-Policy" in response.headers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_csp_header_content(client: TestClient):
|
|
|
|
|
"""Test that Content Security Policy is properly configured."""
|
|
|
|
|
response = client.get("/")
|
|
|
|
|
csp = response.headers.get("Content-Security-Policy", "")
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
# Should restrict default-src to self
|
|
|
|
|
assert "default-src 'self'" in csp
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
# Should allow scripts from self and CDN
|
2026-03-04 17:15:46 -05:00
|
|
|
assert "script-src 'self' 'unsafe-inline' 'unsafe-eval' cdn.jsdelivr.net" in csp
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
# Should allow styles from self, CDN, and Google Fonts
|
|
|
|
|
assert "style-src 'self' 'unsafe-inline' fonts.googleapis.com cdn.jsdelivr.net" in csp
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
# Should restrict frame ancestors to self
|
|
|
|
|
assert "frame-ancestors 'self'" in csp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_health_endpoint_has_security_headers(client: TestClient):
|
|
|
|
|
"""Test that security headers are present on all endpoints."""
|
|
|
|
|
response = client.get("/health")
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-01 11:50:34 -05:00
|
|
|
assert "X-Frame-Options" in response.headers
|
|
|
|
|
assert "X-Content-Type-Options" in response.headers
|
|
|
|
|
assert "Content-Security-Policy" in response.headers
|