: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): name the posthog hosts in the app script-src and connect-src (#106238)
Tom Piccirelloe564fa7d7c52
diff --git a/.agents/security.md b/.agents/security.mdindex 7ab7df099c18..16496a8c3c1f 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -193,6 +193,9 @@ Three policies exist, and a change lands in whichever one covers the page:Add the source to the policy that covers the document, which is not always `CSPMiddleware`.An app or admin page takes the matching list in `CSPMiddleware`.+On PostHog Cloud, the app policy's `script-src` and `connect-src` name each PostHog host instead of `*.posthog.com`.+A script or request that goes to another PostHog subdomain needs its host in the lists that `CSPMiddleware` passes to `narrowed_app_policy()`.+Local runs, E2E runs and self-hosted installs keep the wildcards, so a missing host breaks only production.A canvas artifact takes `artifact_csp()` in `products/canvas/backend/contract.py`, and a workflow message asset takes the header its endpoint sets in `products/workflows/backend/api/hog_flow.py`.`CSPMiddleware` returns a view-set header untouched, so widening the app policy does nothing for those two.Say why the source is needed in a comment either way, then run `posthog/test/test_csp_middleware.py`.diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex 8867e82771ea..65f463c15356 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -141,27 +141,25 @@ 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"})+# The wildcard app policy and the admin policy report as v=2, through the default endpoint above. Reports+# tagged v=3 came from a report-only shadow of the narrowed policy, so reusing 3 would mix the two in one query.+NARROWED_APP_POLICY_REPORT_VERSION = "4"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.+ """The app policy with the wildcard hosts of each directive named in `replacements` swapped for+ the sources given there. Every other directive and source passes through unchanged.- 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.+ The wildcards admit every PostHog subdomain. The ingestion hosts among them serve any project's+ remote config as a script, so an injected tag could load code from a project an attacker owns."""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)+ part = " ".join([name, *(s for s in sources if s not in _WILDCARD_SOURCES), *replacements[name]])+ narrowed.append(part)return narrowed@@ -375,6 +373,44 @@ class CSPMiddleware:"form-action 'self' https://accounts.google.com",]+ # The hosts and the config token below belong to PostHog Cloud, so self-hosted installs, E2E+ # runs and the dev environment keep the wildcards. A load from a PostHog host that is not+ # listed here therefore fails only in production.+ narrowed = is_cloud() and resource_url == "https://*.posthog.com" and not settings.E2E_TESTING+ if narrowed:+ bundle = [bundle_origin] if bundle_origin else []+ agent_proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL+ agent_proxy = (+ [urlsplit(agent_proxy_url)._replace(path="", query="", fragment="").geturl()]+ if agent_proxy_url+ else []+ )+ csp_parts = narrowed_app_policy(+ csp_parts,+ {+ # 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}",+ # publicWebhooksHostOrigin() in the frontend posts source-webhook tests and manual+ # workflow triggers to webhooks.<region host>.+ f"https://webhooks.{urlsplit(settings.SITE_URL).hostname}",+ # The onboarding adblock check probes the region's ingestion host.+ f"{get_api_host()}/decide/",+ # A task run's live stream, when the server hands out the region's agent-proxy.+ *agent_proxy,+ ],+ },+ )+# Both values are read inside one narrowed block, so nothing below re-checks `user`.user = getattr(request, "user", None)if user is not None and user.is_authenticated:@@ -395,44 +431,17 @@ class CSPMiddleware:# silently take the whole fleet to unsampled reporting; staff stays bounded.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 []- agent_proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL- agent_proxy = (- [urlsplit(agent_proxy_url)._replace(path="", query="", fragment="").geturl()]- if agent_proxy_url- 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}",- # The onboarding adblock check probes the region's ingestion host.- f"{get_api_host()}/decide/",- # A task run's live stream, when the server hands out the region's agent-proxy.- *agent_proxy,- ],- }- 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}"]+ report_params = {"sample_rate": sample_rate}+ if narrowed:+ report_params["v"] = NARROWED_APP_POLICY_REPORT_VERSION+ report_uri = csp_report_endpoint(**report_params)if report_uri:report_endpoint = report_uriif distinct_id:# A report body never names the person, and a crash report arrives after the tab# already died, so only the URL can carry the distinct_id. Without it, the report# endpoint mints a random id for every report.- report_endpoint = csp_report_endpoint(sample_rate=sample_rate, distinct_id=distinct_id)+ report_endpoint = csp_report_endpoint(**report_params, distinct_id=distinct_id)# The policy has no `report-to` directive, even though CSP3 marks `report-uri` as# deprecated. While a policy names `report-to`, browsers ignore its `report-uri` and# send reports only through the Reporting API. That API drops violations raised in@@ -444,14 +453,6 @@ class CSPMiddleware:response.headers["Reporting-Endpoints"] = f'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_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex 742e4f084c15..3079cd7730b5 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -1,4 +1,4 @@-from urllib.parse import urlsplit+from urllib.parse import parse_qs, urlsplitfrom posthog.test.base import APIBaseTest, override_settingsfrom unittest.mock import MagicMock, patch@@ -255,8 +255,8 @@ class TestCSPMiddleware(APIBaseTest):},("eu", "us"),),- # 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.+ # The named hosts and the config token are PostHog Cloud's, so another install that swapped+ # its wildcards for them would refuse loads from its own hosts.("self_hosted_with_reporting_on",{@@ -268,28 +268,41 @@ class TestCSPMiddleware(APIBaseTest):),])- def test_only_cloud_pages_carry_a_report_only_shadow_without_the_wildcards(self, _name, overrides, regions):- # 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):+ def test_only_cloud_pages_swap_the_wildcards_for_named_posthog_hosts(+ self, _name: str, overrides: dict[str, str | None], regions: tuple[str, str] | None+ ) -> None:+ # Cloud enforces the app policy for everyone, so the enforced header is the one that must be narrowed.+ with (+ override_settings(TEST=False, DEBUG=False, **overrides),+ patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True),+ ):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 regions else 0)- if regions:- region, other_region = regions- shadow = shadows[0]- assert "*.posthog.com" not in shadow- assert "https://internal-cf.posthog.com/array/sTMFPsFhdP1Ssg/config.js" in shadow- assert "&v=3&" in shadow- connect_src = next(part for part in shadow.split("; ") if part.startswith("connect-src ")).split()- assert f"https://live.{region}.posthog.com" in connect_src- assert f"https://{region}.i.posthog.com/decide/" in connect_src- assert f"https://agent-proxy.{region}.posthog.com" in connect_src- # Allowing the other region would hide a request that crossed regions by mistake.- assert not any(other_region in (urlsplit(source).hostname or "").split(".") for source in connect_src)+ policy = response["Content-Security-Policy"]+ directives = {name: sources for name, *sources in (part.split() for part in policy.split("; "))}+ script_src, connect_src = directives["script-src"], directives["connect-src"]+ (report_uri,) = directives["report-uri"]+ report_version = parse_qs(urlsplit(report_uri).query)["v"]+ wildcards = {"https://*.posthog.com", "https://*.i.posthog.com"}+ if not regions:+ assert wildcards <= set(script_src)+ # An operator's endpoint keeps the version they configured.+ assert report_version == ["2"]+ return++ region, other_region = regions+ assert not wildcards & {*script_src, *connect_src}+ # Under the wildcard policy's version, reports from the two policies mix in one query.+ assert report_version == ["4"]+ # The app cannot start without its bundle host.+ assert overrides["JS_URL"] in script_src+ assert "https://internal-cf.posthog.com/array/sTMFPsFhdP1Ssg/config.js" in script_src+ assert f"https://live.{region}.posthog.com" in connect_src+ assert f"https://webhooks.{region}.posthog.com" in connect_src+ assert f"https://{region}.i.posthog.com/decide/" in connect_src+ assert f"https://agent-proxy.{region}.posthog.com" in connect_src+ # Allowing the other region would hide a request that crossed regions by mistake.+ assert not any(other_region in (urlsplit(source).hostname or "").split(".") for source in connect_src)class TestAppCspHeaderName(SimpleTestCase):@@ -444,12 +457,13 @@ class TestNarrowedAppPolicy(SimpleTestCase):},)- # 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.+ # This builds the enforced policy, so any directive or source it drops besides the wildcards+ # changes what the app can load. img-src keeps its wildcard because no list replaces it.assert narrowed == [+ "default-src 'self'","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:",+ "img-src 'self' data: https://*.posthog.com","connect-src 'self' https://api.github.com https://internal-j.posthog.com",]