File size: 5,400 Bytes
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
152
153
154
155
156
157
158
159
160
161
162
163
164
"""Core Security Module for AlgoSpaced.

Configures Content Security Policy (CSP), defense-in-depth HTTP security headers,
and ASGI security middleware for FastAPI.
"""

import os
from collections.abc import Awaitable, Callable

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

# Content Security Policy directives
# Defense-in-depth security architecture notes:
# 1. script-src: 'unsafe-inline' and 'unsafe-eval' are strictly excluded.
#    All client JavaScript is bundled into external ES modules or static scripts from 'self',
#    providing robust protection against Cross-Site Scripting (XSS) and code injection.
# 2. style-src: 'unsafe-inline' is permitted exclusively for runtime-generated styles:
#    CodeMirror 6 (style-mod) dynamic editor themes, KaTeX math layouts, and React inline styles.
#    CSS-based data exfiltration is blocked by strict img-src and connect-src origin whitelists.
CSP_DIRECTIVES: dict[str, list[str]] = {
    "default-src": ["'self'"],
    "script-src": [
        "'self'",
        "https://apis.google.com",
        "https://*.firebaseapp.com",
        "https://www.gstatic.com",
        "https://*.gstatic.com",
        "https://cdn.jsdelivr.net",
    ],
    "style-src": [
        "'self'",
        "'unsafe-inline'",
        "https://fonts.googleapis.com",
        "https://cdn.jsdelivr.net",
    ],
    "font-src": [
        "'self'",
        "data:",
        "https://fonts.gstatic.com",
        "https://*.gstatic.com",
    ],
    "img-src": [
        "'self'",
        "data:",
        "blob:",
        "https://*.googleusercontent.com",
        "https://images.unsplash.com",
        "https://avatars.githubusercontent.com",
        "https://raw.githubusercontent.com",
        "https://github.com",
        "https://*.firebasestorage.app",
        "https://firebasestorage.googleapis.com",
        "https://cdn.jsdelivr.net",
        "https://fastapi.tiangolo.com",
    ],
    "connect-src": [
        "'self'",
        "http://localhost:*",
        "http://127.0.0.1:*",
        "ws://localhost:*",
        "ws://127.0.0.1:*",
        "wss:",
        "https://*.googleapis.com",
        "https://*.firebaseio.com",
        "https://*.firebaseapp.com",
        "https://*.firebasestorage.app",
        "https://firebasestorage.googleapis.com",
        "https://accounts.google.com",
        "https://generativelanguage.googleapis.com",
        "https://api.groq.com",
        "https://openrouter.ai",
        "https://api.github.com",
        "https://*.hf.space",
        "https://hf.space",
    ],
    "frame-src": [
        "'self'",
        "https://accounts.google.com",
        "https://*.firebaseapp.com",
        "https://*.firebase.com",
        "https://*.google.com",
        "https://apis.google.com",
    ],
    "worker-src": ["'self'", "blob:"],
    "media-src": ["'self'", "data:", "blob:"],
    "object-src": ["'none'"],
    "base-uri": ["'self'"],
}

FRAME_ANCESTORS: list[str] = [
    "'self'",
    "https://huggingface.co",
    "https://*.hf.space",
]

FORM_ACTIONS: list[str] = [
    "'self'",
    "https://github.com",
]


def build_csp_header(
    include_frame_ancestors: bool = True,
    include_form_action: bool = True,
) -> str:
    """Builds the Content-Security-Policy string from configured directives.

    When include_frame_ancestors or include_form_action are False, those directives
    are omitted (required for HTML <meta> tags, which reject them per W3C specification).
    """
    custom_csp = os.environ.get("CONTENT_SECURITY_POLICY")
    if custom_csp:
        return custom_csp.strip()

    parts: list[str] = [
        f"{directive} {' '.join(sources)}" for directive, sources in CSP_DIRECTIVES.items()
    ]

    if include_form_action:
        parts.append(f"form-action {' '.join(FORM_ACTIONS)}")

    if include_frame_ancestors:
        parts.append(f"frame-ancestors {' '.join(FRAME_ANCESTORS)}")

    report_uri = os.environ.get("CSP_REPORT_URI")
    if report_uri:
        parts.append(f"report-uri {report_uri.strip()}")

    return "; ".join(parts) + ";"


def get_security_headers() -> dict[str, str]:
    """Returns standard defense-in-depth security headers for HTTP responses."""
    is_report_only = os.environ.get("CONTENT_SECURITY_POLICY_REPORT_ONLY", "false").lower() in (
        "true",
        "1",
    )
    csp_header_name = (
        "Content-Security-Policy-Report-Only" if is_report_only else "Content-Security-Policy"
    )

    return {
        csp_header_name: build_csp_header(include_frame_ancestors=True, include_form_action=True),
        "X-Content-Type-Options": "nosniff",
        "Referrer-Policy": "strict-origin-when-cross-origin",
        "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
        "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
    }


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    """Starlette HTTP Middleware that attaches security headers to all responses."""

    async def dispatch(
        self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
    ) -> Response:
        response = await call_next(request)
        for header, value in get_security_headers().items():
            if header not in response.headers:
                response.headers[header] = value
        return response