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.

feat(csp): report what the app policy would block without its wildcard hosts (#104099)

Tom Piccirello4cd213e251d8
diff --git a/posthog/constants.py b/posthog/constants.py
index 268bc8f17e95..efabac260dc9 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -412,3 +412,8 @@ LOGIN_METHODS = [
AUTH_BACKEND_DISPLAY_NAMES = {backend: m["display"] for m in LOGIN_METHODS for backend in m["backends"]}
AUTH_BACKEND_KEYS = {backend: m["key"] for m in LOGIN_METHODS for backend in m["backends"]}
+
+
+# PostHog's own posthog-js instance on PostHog Cloud. The app's CSP names these by exact path.
+POSTHOG_JS_CLOUD_HOST = "https://internal-j.posthog.com"
+POSTHOG_JS_CLOUD_TOKEN = "sTMFPsFhdP1Ssg"
diff --git a/posthog/middleware.py b/posthog/middleware.py
index c995788baa4a..1559a7e62f7d 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -10,7 +10,7 @@ from datetime import UTC, datetime, timedelta
from enum import StrEnum
from ipaddress import ip_address, ip_network
from typing import Optional, cast
-from urllib.parse import urlencode, urlsplit
+from urllib.parse import parse_qsl, urlencode, urlsplit
from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY, logout
@@ -42,7 +42,7 @@ from posthog.api.shared import UserBasicSerializer
from posthog.clickhouse.client.execute import clickhouse_query_counter
from posthog.clickhouse.query_tagging import QueryCounter, get_query_tag_value, reset_query_tags, tag_queries
from posthog.cloud_utils import is_cloud, is_dev_mode
-from posthog.constants import AUTH_BACKEND_KEYS
+from posthog.constants import AUTH_BACKEND_KEYS, POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN
from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_value
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
@@ -1290,10 +1290,12 @@ def csp_report_endpoint(**params: str) -> str:
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)}"
+ # The endpoint carries the destination's project token and report version, so a param the caller
+ # passes replaces the one already there rather than repeating it.
+ parts = urlsplit(endpoint)
+ query = dict(parse_qsl(parts.query, keep_blank_values=True))
+ query.update(params)
+ return parts._replace(query=urlencode(query)).geturl()
# The full path, matched exactly. Django sends every unmatched path to the app catch-all, so a
@@ -1361,6 +1363,30 @@ def app_csp_header_name(request: HttpRequest) -> str:
return "Content-Security-Policy-Report-Only"
+# The app policy reports as v=2 through the endpoint above, and the shadow policy below as v=3.
+NARROWED_APP_POLICY_REPORT_VERSION = "3"
+_WILDCARD_SOURCES = frozenset({"https://*.posthog.com", "https://*.i.posthog.com"})
+
+
+def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]) -> list[str]:
+ """The app policy's directives named in `replacements`, with their wildcard hosts swapped for
+ the sources given there.
+
+ Sent report-only beside the app policy, it reports each load the wildcards admit and the named
+ sources do not, which is the evidence for dropping the wildcards. worker-src comes along because
+ workers fall back to script-src without it. The shadow names no other directive, so nothing else
+ is restricted in it.
+ """
+ narrowed = []
+ for part in csp_parts:
+ name, *sources = part.split()
+ if name in replacements:
+ narrowed.append(" ".join([name, *(s for s in sources if s not in _WILDCARD_SOURCES), *replacements[name]]))
+ elif name == "worker-src":
+ narrowed.append(part)
+ return narrowed
+
+
class CSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
@@ -1590,6 +1616,26 @@ class CSPMiddleware:
sample_rate = "1" if is_staff else "0.1"
report_uri = csp_report_endpoint(sample_rate=sample_rate)
+ shadow_parts: list[str] = []
+ if report_uri and is_cloud() and resource_url == "https://*.posthog.com" and not settings.E2E_TESTING:
+ bundle = [bundle_origin] if bundle_origin else []
+ replacements = {
+ # posthog-js loads its extensions from /static/ and our project's remote config. The
+ # config path names our token because the same path serves every project's config.
+ "script-src": [
+ *bundle,
+ f"{POSTHOG_JS_CLOUD_HOST}/static/",
+ f"{POSTHOG_JS_CLOUD_HOST}/array/{POSTHOG_JS_CLOUD_TOKEN}/config.js",
+ ],
+ # liveEventsHostOrigin() in the frontend streams from live.<region host>.
+ "connect-src": [
+ *bundle,
+ POSTHOG_JS_CLOUD_HOST,
+ f"https://live.{urlsplit(settings.SITE_URL).hostname}",
+ ],
+ }
+ shadow_uri = csp_report_endpoint(sample_rate=sample_rate, v=NARROWED_APP_POLICY_REPORT_VERSION)
+ shadow_parts = [*narrowed_app_policy(csp_parts, replacements), f"report-uri {shadow_uri}"]
if report_uri:
csp_parts += [f"report-uri {report_uri}", "report-to posthog"]
report_endpoint = report_uri
@@ -1603,6 +1649,14 @@ class CSPMiddleware:
response.headers["Reporting-Endpoints"] = f'posthog="{report_endpoint}", default="{report_endpoint}"'
header_name = app_csp_header_name(request)
response.headers[header_name] = "; ".join(csp_parts)
+ if shadow_parts:
+ # One header can carry several policies separated by commas, and the browser checks
+ # each on its own.
+ shadow = "; ".join(shadow_parts)
+ reported = response.headers.get("Content-Security-Policy-Report-Only")
+ response.headers["Content-Security-Policy-Report-Only"] = (
+ f"{reported}, {shadow}" if reported else shadow
+ )
if header_name == "Content-Security-Policy-Report-Only" and not is_embeddable_document(request.path):
# Django owns this header. A responseHeadersPolicy on the Contour ingress replaces
# it, and with it the enforced app policy above, so the ingress must not set one.
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index d1fc114876ce..e326d020bc89 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -34,6 +34,7 @@ from posthog.middleware import (
ManagedProxyClientIPMiddleware,
ManagedProxyClientIPOutcome,
app_csp_header_name,
+ narrowed_app_policy,
per_request_logging_context_middleware,
)
from posthog.models.organization import Organization
@@ -2367,6 +2368,47 @@ class TestCSPMiddleware(APIBaseTest):
assert "report-to" not in policy
assert "Reporting-Endpoints" not in response
+ @parameterized.expand(
+ [
+ (
+ "cloud",
+ {
+ "CLOUD_DEPLOYMENT": "US",
+ "SITE_URL": "https://us.posthog.com",
+ "JS_URL": "https://app-static-prod.posthog.com",
+ },
+ True,
+ ),
+ # An operator can turn reporting on for their own install, but the shadow names PostHog
+ # Cloud's hosts and token, so its reports would tell that operator nothing they can act on.
+ (
+ "self_hosted_with_reporting_on",
+ {
+ "CLOUD_DEPLOYMENT": None,
+ "SITE_URL": "https://posthog.example.com",
+ "CSP_REPORT_ENDPOINT": "https://posthog.example.com/report/?token=phc_test&v=2",
+ },
+ False,
+ ),
+ ]
+ )
+ def test_only_cloud_pages_carry_a_report_only_shadow_without_the_wildcards(self, _name, overrides, expects_shadow):
+ # The shadow is the evidence for dropping the wildcards, so it must report on its own version
+ # and must not quietly keep a wildcard.
+ with override_settings(TEST=False, DEBUG=False, **overrides):
+ response = self.client.get("/")
+
+ app_policy, *shadows = response["Content-Security-Policy-Report-Only"].split(", ")
+ assert "https://*.posthog.com" in app_policy
+ assert "&v=2&" in app_policy
+ assert len(shadows) == (1 if expects_shadow else 0)
+ if expects_shadow:
+ shadow = shadows[0]
+ assert "*.posthog.com" not in shadow
+ assert "https://internal-j.posthog.com/array/sTMFPsFhdP1Ssg/config.js" in shadow
+ assert "https://live.us.posthog.com" in shadow
+ assert "&v=3&" in shadow
+
class TestSocialAuthExceptionMiddleware(APIBaseTest):
CONFIG_AUTO_LOGIN = False
@@ -2899,6 +2941,34 @@ class TestAppCspHeaderName(SimpleTestCase):
assert app_csp_header_name(self._request("/")) == "Content-Security-Policy-Report-Only"
+class TestNarrowedAppPolicy(SimpleTestCase):
+ def test_swaps_the_wildcards_and_keeps_every_other_source(self) -> None:
+ app_policy = [
+ "default-src 'self'",
+ "script-src 'self' 'nonce-abc' 'wasm-unsafe-eval' https://*.posthog.com https://*.i.posthog.com https://js.stripe.com",
+ "worker-src 'self' blob:",
+ "img-src 'self' data: https://*.posthog.com",
+ "connect-src 'self' https://api.github.com https://*.posthog.com",
+ ]
+
+ narrowed = narrowed_app_policy(
+ app_policy,
+ {
+ "script-src": ["https://app-static-prod.posthog.com"],
+ "connect-src": ["https://internal-j.posthog.com"],
+ },
+ )
+
+ # A source the shadow dropped besides the wildcards would report loads the app policy allows,
+ # and a directive it was not asked about would restrict what the shadow does not measure.
+ assert narrowed == [
+ "script-src 'self' 'nonce-abc' 'wasm-unsafe-eval' https://js.stripe.com https://app-static-prod.posthog.com",
+ # Without it, workers fall back to script-src and the shadow reports the app's blob: workers.
+ "worker-src 'self' blob:",
+ "connect-src 'self' https://api.github.com https://internal-j.posthog.com",
+ ]
+
+
class TestViewManagedCsp(SimpleTestCase):
@parameterized.expand(
[
diff --git a/posthog/utils.py b/posthog/utils.py
index 3240ee847ea9..414bf17ea0ee 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -52,7 +52,7 @@ from rest_framework.request import Request
from rest_framework.utils.encoders import JSONEncoder
from posthog.cloud_utils import get_cached_instance_license, is_cloud
-from posthog.constants import AvailableFeature
+from posthog.constants import POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN, AvailableFeature
from posthog.exceptions import RequestParsingError, UnspecifiedCompressionFallbackParsingError
from posthog.exceptions_capture import capture_exception
from posthog.git import get_git_branch, get_git_commit_short
@@ -560,8 +560,8 @@ def _build_template_context(
context["js_posthog_api_key"] = posthoganalytics.api_key
context["js_posthog_host"] = "" # Becomes location.origin in the frontend
else:
- context["js_posthog_api_key"] = "sTMFPsFhdP1Ssg"
- context["js_posthog_host"] = "https://internal-j.posthog.com"
+ context["js_posthog_api_key"] = POSTHOG_JS_CLOUD_TOKEN
+ context["js_posthog_host"] = POSTHOG_JS_CLOUD_HOST
context["js_posthog_ui_host"] = "https://us.posthog.com"
context["js_capture_time_to_see_data"] = settings.CAPTURE_TIME_TO_SEE_DATA