: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
fix(csp): attribute admin csp reports to the staff member (#103949)
Tom Piccirello1db5c0bd3260
diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 2f090496d9f9..dfdfca83455a 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -1433,10 +1433,18 @@ class CSPMiddleware:admin_report_endpoint = csp_report_endpoint()if admin_report_endpoint:csp_parts += [f"report-uri {admin_report_endpoint}", "report-to posthog"]+ # Without a distinct_id the report endpoint mints a new one for every report, so a+ # single staff session reads as a crowd of users. Only this header carries it, as in+ # the app policy below.+ user = getattr(request, "user", None)+ distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else None+ reporting_endpoint = (+ csp_report_endpoint(distinct_id=distinct_id) if distinct_id else admin_report_endpoint+ )# Browsers only deliver crash reports to the endpoint named `default`; the CSP# `report-to posthog` directive keeps routing violations to `posthog`.response.headers["Reporting-Endpoints"] = (- f'posthog="{admin_report_endpoint}", default="{admin_report_endpoint}"'+ f'posthog="{reporting_endpoint}", default="{reporting_endpoint}"')response.headers["Content-Security-Policy"] = "; ".join(csp_parts)elif "Content-Security-Policy" in response.headers:diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 89efe91b5a37..225b2e144c7f 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -2332,7 +2332,9 @@ class TestCSPMiddleware(APIBaseTest):assert "report-to posthog" in policy# Sampling the admin policy too would silently drop violations, so the branches diverge.assert "sample_rate" not in policy- assert "Reporting-Endpoints" in response+ # Without it every admin report arrives under a freshly minted id, so one staff session+ # counts as many users.+ assert f"distinct_id={self.user.distinct_id}" in response["Reporting-Endpoints"]else:assert "report-uri" not in policyassert "report-to" not in policy