: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): measure img-src against named posthog hosts (#116736)
Tom Piccirello95cfa270d499
diff --git a/.agents/security.md b/.agents/security.mdindex 38d89770adc5..26e07f5ef8e5 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -230,8 +230,9 @@ 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.-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.+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()`.diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex af1d044222a5..f11fecac6743 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -110,8 +110,9 @@ _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"-# 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=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.+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"@@ -134,14 +135,25 @@ def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]return narrowed+def app_bundle_origin() -> str:+ js_url = urlsplit(settings.JS_URL)+ return f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""++def img_src_shadow_policy(csp_parts: list[str]) -> list[str]:- """The app policy's img-src without its `https:` scheme source, to send as a report-only policy of its own.+ """The app policy's img-src without its `https:` scheme source and with `https://*.posthog.com` swapped for+ named PostHog hosts, to send as a report-only policy of its own.- `https:` admits an image from any host, so the named hosts beside it never decide a load. Without- it, each image from an unnamed host reports, which lists the hosts to name, and the images users- supply, before `https:` can go. The policy names no other directive, so it restricts nothing else.+ `https:` admits an image from any host, and the wildcard admits one from any PostHog host, so the named hosts+ beside them never decide a load. Without them, each image from an unnamed host reports, which lists the hosts+ to name, and the images users supply, before either source can go. The policy names no other directive, so it+ restricts nothing else."""- return [" ".join(s for s in part.split() if s != "https:") for part in csp_parts if part.split()[0] == "img-src"]+ # The app's own images load from its bundle. posthog-js can load the toolbar on an app page, and the toolbar's+ # files sit under /static/ on the posthog-js host.+ named_hosts = [source for source in (app_bundle_origin(), f"{POSTHOG_JS_CLOUD_HOST}/static/") if source]+ named = narrowed_app_policy(csp_parts, {"img-src": named_hosts})+ 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]:@@ -274,8 +286,7 @@ class CSPMiddleware:# cited in a task's Artifacts tab. It stays out of app_frame_ancestor_sources(), because# the canvas sandbox document on the user-content origin shares that list.frame_ancestors = f"frame-ancestors 'self' {' '.join(app_frame_ancestor_sources())}"- js_url = urlsplit(settings.JS_URL)- bundle_origin = f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""+ bundle_origin = app_bundle_origin()if settings.DEBUG or settings.TEST:# A devbox serves Vite from its Coder host, not localhost, so JS_URL names it.resource_url = " ".join(dict.fromkeys(filter(None, ["http://localhost:8234", bundle_origin])))@@ -356,8 +367,8 @@ class CSPMiddleware:## The named origins below are the set we actually load images from, and `https:`# makes them redundant. They stay so that removing `https:` is a one-line change- # rather than an archaeology exercise. On cloud, the v=5 report-only policy below- # reports each image that only `https:` admits.+ # rather than an archaeology exercise. On cloud, the v=7 report-only policy below+ # reports each image that only `https:` or the PostHog wildcard admits.## Do not promote this to an enforced header as-is. An open `img-src` is an# exfiltration channel: an attacker who injects markup but cannot run script stilldiff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex f23b237dcc90..27d8119f6076 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -417,24 +417,32 @@ class TestCSPMiddleware(APIBaseTest):enforced = _parse_policies(response.get("Content-Security-Policy", ""))reported = _parse_policies(response.get("Content-Security-Policy-Report-Only", ""))(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"]+ # 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 (["5"], ["6"])] == []- image_shadows = [policy for policy in reported if _report_version(policy) == ["5"]]+ assert [policy for policy in enforced if _report_version(policy) in (["6"], ["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"]] == []+ 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 == []return(image_shadow,) = image_shadows- # Any other directive would make a v=5 report mean something besides "this image needs https:".+ # Any other directive would make a v=7 report mean something besides "this image host is not named".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"]+ img_src = set(image_shadow["img-src"])+ # `https:` admits every host and the wildcard every PostHog host, so with either one a miss never reports.+ assert not {"https:", "https://*.posthog.com"} & img_src+ # Without these, every page load reports its own bundle or the toolbar, and a real miss is lost.+ assert {_US_BUNDLE, "https://internal-cf.posthog.com/static/"} <= img_src+ # 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".