:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(csp): sample the code behind eval reports on the exporter render (#116745)
Tom Piccirellod72b7275d248
diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex 631840a8bdef..30eb98e3c8bc 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -289,6 +289,12 @@ class CSPMiddleware:connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""object_storage_source = object_storage_upload_source()+ # The image exporter renders replay exports in the bare /exporter document, and a frame of+ # that render calls eval. 'report-sample' puts the first 40 characters of the evaluated+ # code in each script-src report, which identifies the code behind those reports. A sample+ # can carry page code to the report endpoint, so no other document asks for one, and that+ # includes the shared page at /exporter/<token>.+ report_sample = " 'report-sample'" if request.path == "/exporter" else ""csp_parts = [# Firefox checks <link rel="modulepreload"> against default-src instead of script-src,# so without the bundle host it refuses the preloads index.html emits for the boot@@ -320,7 +326,7 @@ class CSPMiddleware:# matched against the URL path alone, so the `?2` the library appends does not# defeat it. The cost is that a version bump which moves the file needs this line# updated, or the editor stops loading.- f"script-src 'self' 'nonce-{nonce}' 'wasm-unsafe-eval' {resource_url} https://*.i.posthog.com https://js.stripe.com https://challenges.cloudflare.com https://editor.unlayer.com/embed.js",+ f"script-src 'self' 'nonce-{nonce}' 'wasm-unsafe-eval'{report_sample} {resource_url} https://*.i.posthog.com https://js.stripe.com https://challenges.cloudflare.com https://editor.unlayer.com/embed.js",# A data: font cannot execute script, and this directive governs font loading only,# so the token widens nothing else. It also carries nothing out: a data: URL makes# no request, which is what the CSS-injection attacks on this directive need. Thediff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex f5fc4146d7a9..79b4c767c8c3 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -503,6 +503,43 @@ class TestAppCspHeaderName(SimpleTestCase):assert app_csp_header_name(RequestFactory().get("/login")) == "Content-Security-Policy"assert app_csp_header_name(RequestFactory().get("/messaging-preferences/abc")) == "Content-Security-Policy"+ @parameterized.expand(+ [+ # A prefix match on /exporter would include this route, which serves the shared page.+ ("exporter_with_token", "/exporter/abc123"),+ ("shared", "/shared/abc123"),+ ("app_root", "/"),+ ]+ )+ @override_settings(+ TEST=False,+ DEBUG=False,+ E2E_TESTING=False,+ CLOUD_DEPLOYMENT="US",+ SITE_URL="https://us.posthog.com",+ JS_URL=_US_BUNDLE,+ )+ def test_only_the_exporter_render_asks_for_script_samples(self, _name: str, path: str) -> None:+ def view(_request: HttpRequest) -> HttpResponse:+ return HttpResponse("<html><body>page</body></html>", content_type="text/html; charset=utf-8")++ def script_src(request_path: str) -> list[str]:+ response = CSPMiddleware(view)(RequestFactory().get(request_path))+ policies = _parse_policies(response.get("Content-Security-Policy", "")) + _parse_policies(+ response.get("Content-Security-Policy-Report-Only", "")+ )+ (app_policy,) = [policy for policy in policies if "default-src" in policy]+ # Each response carries its own nonce.+ return [source for source in app_policy["script-src"] if not source.startswith("'nonce-")]++ exporter, other = script_src("/exporter"), script_src(path)+ # Without a sample, an eval report from a replay export render does not show which code ran.+ assert "'report-sample'" in exporter+ # A sample can carry page code to the report endpoint.+ assert "'report-sample'" not in other+ # Cloud rebuilds script-src when it narrows the wildcards, so the keyword must be the only difference.+ assert [source for source in exporter if source != "'report-sample'"] == other+class TestNarrowedAppPolicy(SimpleTestCase):def test_swaps_the_wildcards_and_keeps_every_other_source(self) -> None: