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 images that only https: admits in img-src (#108132)

Tom Piccirello08d17dc0ca95
diff --git a/.agents/security.md b/.agents/security.md
index a728365a9ff4..78a1f79018df 100644
--- a/.agents/security.md
+++ b/.agents/security.md
@@ -196,6 +196,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.
+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.
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.py
index f7d9c6e98d21..ee9ff11552a3 100644
--- a/posthog/csp_middleware.py
+++ b/posthog/csp_middleware.py
@@ -151,6 +151,8 @@ _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"
def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]) -> list[str]:
@@ -169,6 +171,16 @@ def narrowed_app_policy(csp_parts: list[str], replacements: dict[str, list[str]]
return narrowed
+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.
+
+ `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.
+ """
+ return [" ".join(s for s in part.split() if s != "https:") for part in csp_parts if part.split()[0] == "img-src"]
+
+
class CSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
@@ -352,7 +364,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.
+ # rather than an archaeology exercise. On cloud, the v=5 report-only policy below
+ # reports each image that only `https:` 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 still
@@ -448,6 +461,19 @@ 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}
+ if distinct_id:
+ shadow_params["distinct_id"] = distinct_id
+ shadow_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}"])
+ 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.py
index c2f9297766b3..621b8ede5512 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -17,6 +17,18 @@ from posthog.csp_middleware import (
)
+def _parse_policies(header: str) -> list[dict[str, list[str]]]:
+ return [
+ {name: sources for name, *sources in (part.split() for part in policy.split("; "))}
+ for policy in header.split(", ")
+ if policy
+ ]
+
+
+def _report_version(policy: dict[str, list[str]]) -> list[str] | None:
+ return parse_qs(urlsplit(policy.get("report-uri", [""])[0]).query).get("v")
+
+
# Tests run as a self-hosted install, which never enforces. LOCAL enforces without turning on DEBUG.
@override_settings(CLOUD_DEPLOYMENT="LOCAL")
class TestCSPMiddleware(APIBaseTest):
@@ -305,6 +317,52 @@ class TestCSPMiddleware(APIBaseTest):
# 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)
+ @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.
+ (
+ "report_only_embeddable_document",
+ "/shared/notarealtoken",
+ {"CLOUD_DEPLOYMENT": "US", "SITE_URL": "https://us.posthog.com"},
+ True,
+ ),
+ (
+ "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_cloud_reports_images_that_need_https_without_blocking_them(
+ self, _name: str, path: str, overrides: dict[str, str | None], expects_shadow: bool
+ ) -> None:
+ with override_settings(TEST=False, DEBUG=False, E2E_TESTING=False, **overrides):
+ response = self.client.get(path)
+
+ 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"]
+ # 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 == []
+ return
+
+ (shadow,) = 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"]
+
@override_settings(
OBJECT_STORAGE_PUBLIC_ENDPOINT="https://s3.us-east-1.amazonaws.com",
OBJECT_STORAGE_BUCKET="posthog-test-bucket",