Skip to content

: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.

fix(csp): stop self-hosted installs reporting violations to us (#91314)

Paul D'Ambra6e878cb4bcef
diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.yml
index cbc9b48f69fa..970f89ddec14 100644
--- a/docker-compose.hobby.yml
+++ b/docker-compose.hobby.yml
@@ -166,6 +166,9 @@ services:
OTEL_EXPORTER_OTLP_ENDPOINT: ''
OTEL_SDK_DISABLED: 'true'
OPT_OUT_CAPTURE: ${OPT_OUT_CAPTURE:-false}
+ # Blank sends no CSP reports. Point it at this instance's own /report/ endpoint to
+ # collect them yourself.
+ CSP_REPORT_ENDPOINT: ${CSP_REPORT_ENDPOINT:-}
DEPLOYMENT: 'hobby'
PERSONHOG_ADDR: 'personhog-router:50052'
PERSONHOG_ENABLED: 'true'
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 369a47ef0b72..9075097043be 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -53,6 +53,7 @@ from posthog.models.activity_logging.utils import (
activity_storage,
)
from posthog.models.utils import generate_random_token
+from posthog.ph_client import PH_US_API_KEY, PH_US_HOST
from posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URL
from posthog.user_permissions import UserPermissions
from posthog.utils import get_ip_address, get_trusted_client_ip
@@ -1136,6 +1137,26 @@ class ActivityLoggingMiddleware:
return response
+_POSTHOG_CSP_REPORT_ENDPOINT = f"{PH_US_HOST}/report/?token={PH_US_API_KEY}&v=2"
+
+
+def csp_report_endpoint(**params: str) -> str:
+ """The URL browsers report CSP violations and crashes to, or "" when reporting is turned off."""
+ endpoint = settings.CSP_REPORT_ENDPOINT
+ if endpoint is None:
+ # Only deployments PostHog runs report to PostHog. Violations from an instance we do not
+ # run tell us nothing we can act on, and reporting sends that instance's document URLs to a
+ # destination its operator never chose. The gate is cloud rather than hobby because a
+ # self-hosted install with DEBUG set runs in the local mode, not the hobby one.
+ endpoint = _POSTHOG_CSP_REPORT_ENDPOINT if is_cloud() else ""
+ if not endpoint or not params:
+ return endpoint
+ # The endpoint carries the destination's project token, so it normally already has a query
+ # string; one an operator sets may not.
+ separator = "&" if "?" in endpoint else "?"
+ return f"{endpoint}{separator}{urlencode(params)}"
+
+
class CSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
@@ -1169,16 +1190,16 @@ class CSPMiddleware:
# used by the error page
"frame-src https://posthog.com",
"base-uri 'self'",
- "report-uri https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&v=2",
- "report-to posthog",
]
- # Browsers only deliver crash reports to the endpoint named `default`; the CSP
- # `report-to posthog` directive keeps routing violations to `posthog`.
- admin_report_endpoint = "https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&v=2"
- response.headers["Reporting-Endpoints"] = (
- f'posthog="{admin_report_endpoint}", default="{admin_report_endpoint}"'
- )
+ admin_report_endpoint = csp_report_endpoint()
+ if admin_report_endpoint:
+ csp_parts += [f"report-uri {admin_report_endpoint}", "report-to posthog"]
+ # 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}"'
+ )
response.headers["Content-Security-Policy"] = "; ".join(csp_parts)
else:
resource_url = "https://*.posthog.com"
@@ -1204,20 +1225,21 @@ class CSPMiddleware:
"frame-src https:",
"manifest-src 'self'",
"base-uri 'self'",
- "report-uri https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&sample_rate=0.1&v=2",
- "report-to posthog",
]
- report_endpoint = "https://us.i.posthog.com/report/?token=sTMFPsFhdP1Ssg&sample_rate=0.1&v=2"
- user = getattr(request, "user", None)
- if user is not None and user.is_authenticated and getattr(user, "distinct_id", None):
- # Crash reports arrive after the tab already died, so the report body is the
- # only chance to attribute them; carrying the distinct_id in the endpoint URL
- # ties the event to the person instead of a random per-report id.
- report_endpoint += "&" + urlencode({"distinct_id": user.distinct_id})
- # 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="{report_endpoint}", default="{report_endpoint}"'
+ report_uri = csp_report_endpoint(sample_rate="0.1")
+ if report_uri:
+ csp_parts += [f"report-uri {report_uri}", "report-to posthog"]
+ report_endpoint = report_uri
+ user = getattr(request, "user", None)
+ if user is not None and user.is_authenticated and getattr(user, "distinct_id", None):
+ # Crash reports arrive after the tab already died, so the report body is the
+ # only chance to attribute them; carrying the distinct_id in the endpoint URL
+ # ties the event to the person instead of a random per-report id.
+ report_endpoint = csp_report_endpoint(sample_rate="0.1", distinct_id=user.distinct_id)
+ # 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="{report_endpoint}", default="{report_endpoint}"'
response.headers["Content-Security-Policy-Report-Only"] = "; ".join(csp_parts)
return response
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index 42c4e1b1195b..eb69d2bfb009 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -83,6 +83,18 @@ CAPTURE_V1_INTERNAL_RETRY_AFTER_CAP_SECONDS = get_from_env(
# Chunk fan-out reuses CAPTURE_INTERNAL_MAX_WORKERS (above) for its thread pool.
CAPTURE_INTERNAL_BATCH_CHUNK_SIZE = get_from_env("CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", type_cast=int, default=200)
+# Outbound: where browsers send CSP violation and crash reports for pages this instance serves.
+# CSPMiddleware puts it in the `report-uri` directive and the `Reporting-Endpoints` header, and
+# picks the destination itself when this is unset. An empty value turns reporting off without
+# changing the policy, so it is a kill switch that needs no deploy.
+#
+# Read straight from the environment because `get_from_env` cannot tell an empty value from an unset
+# one, and the two mean different things here.
+#
+# An operator can point this at their own install, which already serves the receiving `/report/`
+# endpoint: CSP_REPORT_ENDPOINT="https://posthog.example.com/report/?token=<project token>&v=2"
+CSP_REPORT_ENDPOINT: str | None = os.getenv("CSP_REPORT_ENDPOINT")
+
# Inbound bounds for /report/. The endpoint is unauthenticated and expands each CSP violation in
# the body into its own event (a reports+json bundle may also carry other Reporting API types,
# which are accepted but ignored), so without these the generic upload limit
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index e505413eea53..1f39ba2ba850 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1898,6 +1898,7 @@ class TestCSPMiddleware(APIBaseTest):
assert "Content-Security-Policy-Report-Only" in response
assert "Content-Security-Policy" not in response
+ @override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud
def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):
# Browsers only deliver crash reports to the endpoint named `default`, so dropping or
# renaming it silently stops crash ingestion.
@@ -1907,6 +1908,7 @@ class TestCSPMiddleware(APIBaseTest):
assert 'default="https://us.i.posthog.com/report/' in header
assert f"distinct_id={self.user.distinct_id}" in header
+ @override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud
def test_reporting_endpoints_omit_distinct_id_when_logged_out(self):
self.client.logout()
response = self.client.get("/login")
@@ -1914,6 +1916,65 @@ class TestCSPMiddleware(APIBaseTest):
assert 'default="https://us.i.posthog.com/report/' in header
assert "distinct_id" not in header
+ @parameterized.expand(
+ [
+ ("self_hosted_by_default", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}),
+ # DEBUG puts an install in the local run mode rather than the hobby one, and nothing
+ # stops a self-hoster deploying that way, so it must report nowhere as well.
+ ("self_hosted_with_debug", {"CLOUD_DEPLOYMENT": None, "DEBUG": True}),
+ # Cloud would otherwise report, so this case proves the empty value turns it off.
+ ("explicitly_disabled", {"CLOUD_DEPLOYMENT": "US", "CSP_REPORT_ENDPOINT": ""}),
+ ]
+ )
+ def test_no_endpoint_still_sends_the_policy_but_asks_for_no_reports(self, _name, overrides):
+ # A self-hosted install must not report to PostHog, and the policy itself must survive, so
+ # dropping it here would silently remove a security control.
+ with override_settings(**{"CSP_REPORT_ENDPOINT": None, **overrides}):
+ response = self.client.get("/")
+ policy = response["Content-Security-Policy-Report-Only"]
+ assert "default-src 'self'" in policy
+ assert "report-uri" not in policy
+ assert "report-to" not in policy
+ assert "Reporting-Endpoints" not in response
+
+ @override_settings(CSP_REPORT_ENDPOINT="https://posthog.example.com/report/")
+ def test_report_endpoint_is_configurable(self):
+ # An operator can point reporting at their own install, so nothing may hardcode ours.
+ response = self.client.get("/")
+ policy = response["Content-Security-Policy-Report-Only"]
+ assert "report-uri https://posthog.example.com/report/?sample_rate=0.1" in policy
+ header = response["Reporting-Endpoints"]
+ assert "us.i.posthog.com" not in header
+ assert f"distinct_id={self.user.distinct_id}" in header
+
+ @parameterized.expand(
+ [
+ ("cloud", {"CLOUD_DEPLOYMENT": "US"}, True),
+ ("self_hosted", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}, False),
+ ]
+ )
+ def test_admin_pages_enforce_the_policy_and_follow_the_reporting_default(self, _name, overrides, expects_reporting):
+ # The admin policy is enforced, not report-only, and builds its own Reporting-Endpoints
+ # header, so it can drift from the app policy unnoticed. A non-staff request redirects but
+ # still carries that policy, because the middleware picks its branch by path.
+ with override_settings(CSP_REPORT_ENDPOINT=None, **overrides):
+ response = self.client.get("/admin/")
+ policy = response["Content-Security-Policy"]
+ # Only the admin policy forbids framing outright; the non-HTML fallback is default-src alone.
+ assert "frame-ancestors 'none'" in policy
+ assert "Content-Security-Policy-Report-Only" not in response
+
+ if expects_reporting:
+ assert "report-uri https://us.i.posthog.com/report/" in policy
+ 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
+ else:
+ assert "report-uri" not in policy
+ assert "report-to" not in policy
+ assert "Reporting-Endpoints" not in response
+
class TestSocialAuthExceptionMiddleware(APIBaseTest):
CONFIG_AUTO_LOGIN = False