: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 style-src and font-src (#116718)
Tom Piccirello549463ba73e3
diff --git a/.agents/security.md b/.agents/security.mdindex 13b1170f50f6..2d1007261062 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -227,15 +227,12 @@ 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()`.+On PostHog Cloud, the app policy's `script-src`, `connect-src`, `style-src` and `font-src` name each PostHog host instead of `*.posthog.com`.+A script, stylesheet or font from another PostHog subdomain, or a request to one, 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.On PostHog Cloud, each app document also sends a report-only policy that holds only `img-src`, without `https:` and with each PostHog host named instead of `*.posthog.com`.It blocks nothing, and its reports (`$csp_version` 7) list the image hosts that only `https:` or `*.posthog.com` admits.An image from another PostHog subdomain needs its host in the list in `img_src_shadow_policy()`, or each load of it reports.-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 20566ec97656..43b42c02e3d4 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -136,9 +136,9 @@ _WILDCARD_SOURCES = frozenset({"https://*.posthog.com", "https://*.i.posthog.comNARROWED_APP_POLICY_REPORT_VERSION = "4"# Reports tagged v=7 come from a report-only policy that holds only img-src, without `https:` and with named# PostHog hosts. Reports tagged v=5 came from one that kept `https://*.posthog.com`, so reusing 5 would mix the two.+# Reports tagged v=6 came from a report-only policy for style-src and font-src, so a new policy must take another+# version.IMG_SRC_SHADOW_REPORT_VERSION = "7"-# 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]:@@ -180,19 +180,6 @@ 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 named 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@@ -464,18 +451,18 @@ class CSPMiddleware:# A task run's live stream, when the server hands out the region's agent-proxy.*agent_proxy,],+ # 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.+ #+ # Production is the first place these two lists apply. A host they miss leaves the page+ # without its styles or fonts and shows the user no error.+ "style-src": [*bundle, f"{POSTHOG_JS_CLOUD_HOST}/static/"],+ "font-src": [*bundle, f"{POSTHOG_JS_CLOUD_HOST}/static/"],},)- 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/"]- ),- }+ shadows = {IMG_SRC_SHADOW_REPORT_VERSION: img_src_shadow_policy(csp_parts)}user = getattr(request, "user", None)distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else Nonediff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex 05d13327568e..f682688635d8 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -361,17 +361,20 @@ class TestCSPMiddleware(APIBaseTest):policy = response["Content-Security-Policy" if regions else "Content-Security-Policy-Report-Only"]directives = {name: sources for name, *sources in (part.split() for part in policy.split("; "))}script_src, connect_src = directives["script-src"], directives["connect-src"]+ style_src, font_src = directives["style-src"], directives["font-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)+ assert "https://*.posthog.com" in style_src+ assert "https://*.posthog.com" in font_src# An operator's endpoint keeps the version they configured.assert report_version == ["2"]returnregion, other_region = regions- assert not wildcards & {*script_src, *connect_src}+ assert not wildcards & {*script_src, *connect_src, *style_src, *font_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.@@ -386,6 +389,13 @@ class TestCSPMiddleware(APIBaseTest):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)+ # The app loads its stylesheets and fonts from the bundle host, and the toolbar loads its own from+ # /static/. Without either source the page renders unstyled, and the user sees no error.+ assert {overrides["JS_URL"], "https://internal-cf.posthog.com/static/"} <= set(style_src)+ assert {overrides["JS_URL"], "https://internal-cf.posthog.com/static/"} <= set(font_src)+ # The swap must remove the wildcard alone. Inline styles, data: fonts and Google Fonts still load.+ assert {"'self'", "'unsafe-inline'", "https://fonts.googleapis.com"} <= set(style_src)+ assert {"'self'", "data:", "https://fonts.gstatic.com"} <= set(font_src)@parameterized.expand([@@ -425,18 +435,16 @@ class TestCSPMiddleware(APIBaseTest):(app_policy,) = [policy for policy in enforced + reported if "default-src" in policy]# The app policy keeps `https:` and the PostHog wildcard, so the shadow reports images without blocking any.assert {"https:", "https://*.posthog.com"} <= set(app_policy["img-src"])- # 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 (["6"], ["7"])] == []+ # Enforced, the shadow would block every image from a host it does not name.+ assert [policy for policy in enforced if _report_version(policy) == ["7"]] == []# A v=5 report names an image that only `https:` admits. The image shadow also reports PostHog hosts the# named list misses, so under 5 its reports would mix with the old ones in one query.assert [policy for policy in enforced + reported if _report_version(policy) == ["5"]] == []+ # The app policy enforces the named stylesheet and font hosts, so a v=6 policy would report each miss twice.+ assert [policy for policy in enforced + reported if _report_version(policy) == ["6"]] == []image_shadows = [policy for policy in reported if _report_version(policy) == ["7"]]- style_font_shadows = [policy for policy in reported if _report_version(policy) == ["6"]]if not expects_shadows:- assert image_shadows == style_font_shadows == []+ assert image_shadows == []return(image_shadow,) = image_shadows@@ -450,16 +458,6 @@ class TestCSPMiddleware(APIBaseTest):# The swap must remove those two sources alone, or every image the others admit reports as a miss.assert {"'self'", "data:", "blob:", "https://posthog.com", "https://www.gravatar.com"} <= 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",OBJECT_STORAGE_BUCKET="posthog-test-bucket",