File size: 6,357 Bytes
e3d939d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
 
 
 
 
e3d939d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""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"