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.

fix(csp): emit the enforced frame-ancestors header from django (#100691)

Tom Piccirello47e39b5835d5
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 816fc4c408a4..b99c392a8a68 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1310,10 +1310,16 @@ class CSPMiddleware:
return response
else:
resource_url = "https://*.posthog.com"
+ # Enforced for every viewer, flag or not, because this directive is what admits these
+ # origins: a frame-ancestors directive makes browsers ignore X-Frame-Options, which
+ # names only our own origin.
+ frame_ancestors = "frame-ancestors https://posthog.com https://preview.posthog.com"
if settings.DEBUG or settings.TEST:
resource_url = "http://localhost:8234"
elif settings.SITE_URL.endswith(".dev.posthog.dev"):
resource_url = "https://*.dev.posthog.dev"
+ # The posthog.com dev server frames the dev app.
+ frame_ancestors += " http://localhost:8001"
connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""
csp_parts = [
@@ -1374,7 +1380,7 @@ class CSPMiddleware:
# exfiltration channel: an attacker who injects markup but cannot run script still
# gets a beacon out through an image URL.
f"img-src 'self' data: https: {resource_url} https://posthog.com https://www.gravatar.com https://res.cloudinary.com https://platform.slack-edge.com https://raw.githubusercontent.com",
- "frame-ancestors https://posthog.com https://preview.posthog.com https://vercel.com",
+ frame_ancestors,
f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://raw.githubusercontent.com https://api.github.com",
# https: lets heatmaps frame a customer's site. 'self' is for the replay player
# frame, whose document is same-origin: an http origin does not match https:.
@@ -1399,7 +1405,12 @@ class CSPMiddleware:
# Browsers only deliver crash reports to the endpoint named `default`; the CSP
# `report-to posthog` directive keeps routing violations to `posthog`.
response.headers["Reporting-Endpoints"] = f'posthog="{report_endpoint}", default="{report_endpoint}"'
- response.headers[app_csp_header_name(request)] = "; ".join(csp_parts)
+ header_name = app_csp_header_name(request)
+ response.headers[header_name] = "; ".join(csp_parts)
+ 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.
+ response.headers["Content-Security-Policy"] = frame_ancestors
return response
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index b5834de70890..20e29e1c7e37 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1927,24 +1927,37 @@ class TestCSPMiddleware(APIBaseTest):
@parameterized.expand(
[
- ("app_root", "/"),
+ ("app_root", "/", True),
# No route serves this path, so the app catch-all answers it. It must keep the app
# policy, because the frame policy is enforced and its script-src 'none' stops the app
# from starting.
- ("path_under_the_replay_frame_prefix", "/replay_player_frame"),
+ ("path_under_the_replay_frame_prefix", "/replay_player_frame", True),
+ # A customer's page frames this document, and the enforced list names only PostHog
+ # origins.
+ ("embeddable_document", "/shared/notarealtoken", False),
]
)
- def test_html_response_gets_report_only_csp(self, _name, path):
+ def test_html_response_without_the_flag_enforces_only_frame_ancestors(self, _name, path, enforces_frame_ancestors):
response = self.client.get(path)
- assert response.status_code == 200
- assert "Content-Security-Policy-Report-Only" in response
- assert "Content-Security-Policy" not in response
+ reported = response["Content-Security-Policy-Report-Only"]
+ assert "default-src 'self'" in reported
+ if not enforces_frame_ancestors:
+ assert "Content-Security-Policy" not in response
+ return
+ # Framing is enforced ahead of the flag because it is what lets posthog.com frame the app.
+ # The enforced list has to be the one the reported policy names, or the two drift apart.
+ enforced = response["Content-Security-Policy"]
+ assert enforced.startswith("frame-ancestors https://posthog.com")
+ assert "default-src" not in enforced
+ assert enforced in reported
@patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)
def test_enforcement_reaches_an_app_page_but_not_an_embeddable_one(self, _mock_flag):
# The wiring guard for app_csp_header_name. The matrix of paths lives in
# TestAppCspHeaderName, which needs no database.
- assert "Content-Security-Policy" in self.client.get("/")
+ enforced = self.client.get("/")
+ assert "default-src 'self'" in enforced["Content-Security-Policy"]
+ assert "Content-Security-Policy-Report-Only" not in enforced
embedded = self.client.get("/shared/notarealtoken")
assert "Content-Security-Policy" not in embedded
@@ -2593,6 +2606,6 @@ class TestViewManagedCsp(SimpleTestCase):
elif policy is not None:
assert response["Content-Security-Policy"] == policy
else:
- assert "Content-Security-Policy" not in response
+ assert response["Content-Security-Policy"].startswith("frame-ancestors ")
assert ("Content-Security-Policy-Report-Only" in response) == (expects_reporting and path != "/admin/")
assert ("Reporting-Endpoints" in response) == expects_reporting