: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
refactor(csp): report style-src and font-src against named hosts (#113389)
Tom Piccirelloee384b6a8e95
diff --git a/.agents/security.md b/.agents/security.mdindex 78a1f79018df..8e8605b6329a 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -198,6 +198,9 @@ A script or request that goes to another PostHog subdomain needs its host in theLocal runs, E2E runs and self-hosted installs keep the wildcards, so a missing host breaks only production.On PostHog Cloud, each app document also sends a report-only policy that holds only `img-src` without `https:`.It blocks nothing, and its reports (`$csp_version` 5) list the image hosts that only `https:` admits.+A second report-only policy holds only `style-src` and `font-src`, with each PostHog host named instead of `*.posthog.com`.+Its reports (`$csp_version` 6) list the PostHog stylesheet and font hosts that the named list misses.+A stylesheet or font from another PostHog subdomain needs its host in the list that `CSPMiddleware` passes to `style_font_shadow_policy()`.Name a new image host in `img-src` anyway, so that removing `https:` later does not break it.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/presentation/views/hog_flow.py`.`CSPMiddleware` returns a view-set header untouched, so widening the app policy does nothing for those two.diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex 4f779089e5b3..a17ce6878ed9 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -165,6 +165,8 @@ _WILDCARD_SOURCES = frozenset({"https://*.posthog.com", "https://*.i.posthog.comNARROWED_APP_POLICY_REPORT_VERSION = "4"# Reports tagged v=5 come from a report-only policy that holds only img-src, without `https:`.IMG_SRC_SHADOW_REPORT_VERSION = "5"+# Reports tagged v=6 come from a report-only policy that holds only style-src and font-src, with named PostHog hosts.+STYLE_FONT_SHADOW_REPORT_VERSION = "6"def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]) -> list[str]:@@ -178,7 +180,9 @@ def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]for part in csp_parts:name, *sources = part.split()if name in replacements:- part = " ".join([name, *(s for s in sources if s not in _WILDCARD_SOURCES), *replacements[name]])+ # A replacement source can repeat one the directive already names.+ kept = dict.fromkeys([*(s for s in sources if s not in _WILDCARD_SOURCES), *replacements[name]])+ part = " ".join([name, *kept])narrowed.append(part)return narrowed@@ -193,6 +197,19 @@ def img_src_shadow_policy(csp_parts: list[str]) -> list[str]:return [" ".join(s for s in part.split() if s != "https:") for part in csp_parts if part.split()[0] == "img-src"]+def style_font_shadow_policy(csp_parts: list[str], sources: list[str]) -> list[str]:+ """The app policy's style-src and font-src with the PostHog wildcards swapped for `sources`, to send as a+ report-only policy of its own.++ Local runs and E2E keep the wildcards, so production is the first place a named list applies. Enforced,+ a host the list misses leaves the page without its styles or fonts and shows the user no error. Reported,+ the same miss arrives as a report while the page still loads. The policy names no other directive, so it+ restricts nothing else.+ """+ narrowed = narrowed_app_policy(csp_parts, {"style-src": sources, "font-src": sources})+ return [part for part in narrowed if part.split()[0] in ("style-src", "font-src")]++class CSPMiddleware:def __init__(self, get_response):self.get_response = get_response@@ -424,6 +441,7 @@ class CSPMiddleware:# 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+ shadows: dict[str, list[str]] = {}if narrowed:bundle = [bundle_origin] if bundle_origin else []agent_proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL@@ -459,6 +477,16 @@ class CSPMiddleware:],},)+ shadows = {+ IMG_SRC_SHADOW_REPORT_VERSION: img_src_shadow_policy(csp_parts),+ # The app's stylesheets and fonts load from its bundle. posthog-js can load the toolbar on+ # an app page, and the toolbar loads its stylesheet and fonts from beside its script under+ # /static/. font-src already names both regions' bundle hosts, and it takes the bundle+ # here too so that fonts follow JS_URL as scripts and stylesheets do.+ STYLE_FONT_SHADOW_REPORT_VERSION: style_font_shadow_policy(+ csp_parts, [*bundle, f"{POSTHOG_JS_CLOUD_HOST}/static/"]+ ),+ }user = getattr(request, "user", None)distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else None@@ -483,15 +511,15 @@ 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 narrowed:- shadow_params = {"v": IMG_SRC_SHADOW_REPORT_VERSION}+ for version, shadow_parts in shadows.items():+ shadow_params = {"v": version}if distinct_id:shadow_params["distinct_id"] = distinct_idshadow_uri = csp_report_endpoint(**shadow_params)if shadow_uri:# One header can carry several policies separated by commas, and the browser checks- # each on its own. On a report-only document the shadow joins the app policy there.- shadow = "; ".join([*img_src_shadow_policy(csp_parts), f"report-uri {shadow_uri}"])+ # each on its own. On a report-only document each shadow joins the app policy there.+ shadow = "; ".join([*shadow_parts, f"report-uri {shadow_uri}"])reported = response.headers.get("Content-Security-Policy-Report-Only")response.headers["Content-Security-Policy-Report-Only"] = (f"{reported}, {shadow}" if reported else shadowdiff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex 94acef049f14..a5eaf61874a6 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -31,6 +31,9 @@ def _report_version(policy: dict[str, list[str]]) -> list[str] | None:return parse_qs(urlsplit(policy.get("report-uri", [""])[0]).query).get("v")+_US_BUNDLE = "https://app-static-prod.posthog.com"++class _PageLoads(HTMLParser):def __init__(self) -> None:super().__init__()@@ -388,12 +391,17 @@ class TestCSPMiddleware(APIBaseTest):@parameterized.expand([- ("enforced_app_page", "/", {"CLOUD_DEPLOYMENT": "US", "SITE_URL": "https://us.posthog.com"}, True),- # This document already sends the app policy report-only, so the shadow must join that header.+ (+ "enforced_app_page",+ "/",+ {"CLOUD_DEPLOYMENT": "US", "SITE_URL": "https://us.posthog.com", "JS_URL": _US_BUNDLE},+ True,+ ),+ # This document already sends the app policy report-only, so the shadows must join that header.("report_only_embeddable_document","/shared/notarealtoken",- {"CLOUD_DEPLOYMENT": "US", "SITE_URL": "https://us.posthog.com"},+ {"CLOUD_DEPLOYMENT": "US", "SITE_URL": "https://us.posthog.com", "JS_URL": _US_BUNDLE},True,),(@@ -408,8 +416,8 @@ class TestCSPMiddleware(APIBaseTest):),])- def test_cloud_reports_images_that_need_https_without_blocking_them(- self, _name: str, path: str, overrides: dict[str, str | None], expects_shadow: bool+ def test_cloud_reports_narrower_sources_without_blocking_them(+ self, _name: str, path: str, overrides: dict[str, str | None], expects_shadows: bool) -> None:with override_settings(TEST=False, DEBUG=False, E2E_TESTING=False, **overrides):response = self.client.get(path)@@ -419,18 +427,32 @@ class TestCSPMiddleware(APIBaseTest):(app_policy,) = [policy for policy in enforced + reported if "default-src" in policy]# The app policy keeps `https:`, so the shadow reports images without blocking any.assert "https:" in app_policy["img-src"]- # Enforced, the shadow would block every image from a host it does not name.- assert [policy for policy in enforced if _report_version(policy) == ["5"]] == []- shadows = [policy for policy in reported if _report_version(policy) == ["5"]]- if not expects_shadow:- assert shadows == []+ # The app policy keeps the wildcards until the v=6 reports show the named hosts are complete.+ assert "https://*.posthog.com" in app_policy["style-src"]+ assert "https://*.posthog.com" in app_policy["font-src"]+ # Enforced, a shadow would block every image, stylesheet or font from a host it does not name.+ assert [policy for policy in enforced if _report_version(policy) in (["5"], ["6"])] == []+ image_shadows = [policy for policy in reported if _report_version(policy) == ["5"]]+ style_font_shadows = [policy for policy in reported if _report_version(policy) == ["6"]]+ if not expects_shadows:+ assert image_shadows == style_font_shadows == []return- (shadow,) = shadows+ (image_shadow,) = image_shadows# Any other directive would make a v=5 report mean something besides "this image needs https:".- assert set(shadow) == {"img-src", "report-uri"}- assert "https:" not in shadow["img-src"]- assert "https://www.gravatar.com" in shadow["img-src"]+ assert set(image_shadow) == {"img-src", "report-uri"}+ assert "https:" not in image_shadow["img-src"]+ assert "https://www.gravatar.com" in image_shadow["img-src"]++ (style_font_shadow,) = style_font_shadows+ # Any other directive would make a v=6 report mean something besides "this host is missing".+ assert set(style_font_shadow) == {"style-src", "font-src", "report-uri"}+ for sources in (style_font_shadow["style-src"], style_font_shadow["font-src"]):+ # A wildcard admits every PostHog host, so a missed host would never report.+ assert "https://*.posthog.com" not in sources+ # Without these, every page load reports its own bundle or the toolbar, and a real miss is lost.+ assert _US_BUNDLE in sources+ assert "https://internal-cf.posthog.com/static/" in sources@override_settings(OBJECT_STORAGE_PUBLIC_ENDPOINT="https://s3.us-east-1.amazonaws.com",