"""Integration and unit tests for Content Security Policy and HTTP security headers.""" import os from unittest.mock import patch from core.security import build_csp_header, get_security_headers def test_build_csp_header_format(): """Verify CSP header string structure, delimiters, and directive inclusion.""" csp = build_csp_header(include_frame_ancestors=True, include_form_action=True) assert "default-src 'self'" in csp assert "script-src" in csp assert "style-src" in csp assert "font-src" in csp assert "img-src" in csp assert "connect-src" in csp assert "frame-src" in csp assert "frame-ancestors 'self' https://huggingface.co https://*.hf.space" in csp assert "form-action 'self' https://github.com" in csp assert "object-src 'none'" in csp assert "base-uri 'self'" in csp assert csp.endswith(";") def test_csp_header_no_invalid_ip_wildcards(): """Ensure connect-src directive does not contain invalid IP wildcards (e.g. 192.168.*.*).""" csp = build_csp_header() assert "192.168.*" not in csp assert "10.*" not in csp assert "172.16.*" not in csp assert "*.*" not in csp def test_csp_script_src_excludes_unsafe_inline_and_unsafe_eval(): """Verify script-src strictly excludes 'unsafe-inline' and 'unsafe-eval' to prevent XSS and eval injection.""" csp = build_csp_header() script_directive = next( (d.strip() for d in csp.split(";") if d.strip().startswith("script-src")), "" ) assert script_directive, "script-src directive must exist in CSP" assert "'unsafe-eval'" not in script_directive, ( "'unsafe-eval' must not be present in script-src" ) assert "'unsafe-inline'" not in script_directive, ( "'unsafe-inline' must not be present in script-src" ) assert "'unsafe-eval'" not in csp, "'unsafe-eval' must not be present anywhere in CSP" def test_csp_style_src_allows_unsafe_inline_for_runtime_styling(): """Verify style-src permits 'unsafe-inline' for CodeMirror 6 (style-mod), KaTeX, and React inline styles.""" csp = build_csp_header() style_directive = next( (d.strip() for d in csp.split(";") if d.strip().startswith("style-src")), "" ) assert style_directive, "style-src directive must exist in CSP" assert "'unsafe-inline'" in style_directive def test_build_csp_header_meta_tag_variant(): """Verify that frame-ancestors and form-action are excluded for HTML meta tags.""" meta_csp = build_csp_header(include_frame_ancestors=False, include_form_action=False) assert "frame-ancestors" not in meta_csp assert "form-action" not in meta_csp assert "default-src 'self'" in meta_csp def test_custom_csp_environment_override(): """Verify CONTENT_SECURITY_POLICY environment variable overrides default policy.""" custom_val = "default-src 'none'; script-src 'self';" with patch.dict(os.environ, {"CONTENT_SECURITY_POLICY": custom_val}): assert build_csp_header() == custom_val def test_csp_report_uri_env(): """Verify CSP_REPORT_URI environment variable appends report-uri directive.""" with patch.dict(os.environ, {"CSP_REPORT_URI": "https://api.algospaced.com/csp-report"}): csp = build_csp_header() assert "report-uri https://api.algospaced.com/csp-report" in csp def test_report_only_environment_flag(): """Verify CONTENT_SECURITY_POLICY_REPORT_ONLY toggles header name.""" with patch.dict(os.environ, {"CONTENT_SECURITY_POLICY_REPORT_ONLY": "true"}): headers = get_security_headers() assert "Content-Security-Policy-Report-Only" in headers assert "Content-Security-Policy" not in headers def test_api_endpoints_include_security_headers(client): """GET /api/config should contain all required defense-in-depth security headers.""" response = client.get("/api/config") assert response.status_code == 200 headers = response.headers assert "content-security-policy" in headers assert "default-src 'self'" in headers["content-security-policy"] assert headers.get("x-content-type-options") == "nosniff" assert headers.get("referrer-policy") == "strict-origin-when-cross-origin" assert "camera=()" in headers.get("permissions-policy", "") assert headers.get("cross-origin-opener-policy") == "same-origin-allow-popups" def test_hugging_face_frame_ancestors_allowed(client): """Ensure frame-ancestors header permits Hugging Face iframe embedding.""" response = client.get("/api/config") csp = response.headers.get("content-security-policy", "") assert "https://huggingface.co" in csp assert "https://*.hf.space" in csp def test_csp_header_websocket_directives(): """Ensure connect-src contains valid wss: protocol and does not contain invalid wss://*.""" csp = build_csp_header() assert "wss:" in csp assert "wss://*" not in csp assert "ws://localhost:*" in csp assert "ws://127.0.0.1:*" in csp def test_index_html_meta_csp_matches_backend_definition(): """Ensure the HTML meta tag in index.html is exactly synchronized with core.security.""" meta_csp = build_csp_header(include_frame_ancestors=False, include_form_action=False) index_html_path = os.path.join( os.path.dirname(__file__), "..", "..", "algospaced-ui", "index.html" ) with open(index_html_path, encoding="utf-8") as f: content = f.read() assert meta_csp in content def test_dist_index_html_meta_csp_matches_backend_definition(): """Ensure the built HTML in dist/index.html is synchronized with core.security if built.""" dist_html_path = os.path.join( os.path.dirname(__file__), "..", "..", "algospaced-ui", "dist", "index.html" ) if os.path.exists(dist_html_path): meta_csp = build_csp_header(include_frame_ancestors=False, include_form_action=False) with open(dist_html_path, encoding="utf-8") as f: content = f.read() assert meta_csp in content def test_static_and_root_responses_include_security_headers(client): """Ensure root SPA endpoint and static assets include required security headers.""" response = client.get("/") assert response.status_code == 200 assert "content-security-policy" in response.headers assert response.headers.get("x-content-type-options") == "nosniff"