: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): enforce the app policy on shared and embedded documents (#116719)
Tom Piccirelloedbe37079290
diff --git a/.agents/security.md b/.agents/security.mdindex 26e07f5ef8e5..13b1170f50f6 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -201,7 +201,7 @@ A refused resource produces no user-visible error, so the feature simply does noThree policies exist, and a change lands in whichever one covers the page:-- **The app policy** governs every SPA page. On PostHog Cloud and in local development, it is enforced for every visitor, signed-in or not. A self-hosted install only reports it, because its violations reach nobody. Embeddable documents, such as shared dashboards, always stay report-only.+- **The app policy** governs every SPA page. On PostHog Cloud and in local development, it is enforced for every visitor, signed-in or not. A self-hosted install only reports it, because its violations reach nobody. Embeddable documents, such as shared dashboards, get the policy without `frame-ancestors`, because customers frame them on their own sites. Two routes in `REPORT_ONLY_ROUTES` stay report-only. The bare `/exporter` render document stays report-only, because a replay export can run an `eval` in a frame of the render, and an enforced policy would refuse it. It stays report-only until the caller of that `eval` is traced. `/external_surveys/<id>` stays report-only on a response that the survey view did not build.- **The admin policy** governs `/admin/`. It is enforced for every staff member, so a mistake here breaks admin immediately.- **A view may set its own policy.** The canvas artifact and the workflow asset endpoint do this to sandbox untrusted HTML. `CSPMiddleware` returns a response that already carries the header unchanged, so do not expect the app policy on those documents.diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex f11fecac6743..20566ec97656 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -4,6 +4,7 @@ The policy lives apart from the other middleware so that team-security owns the`.github/CODEOWNERS` and reviews every change to it."""+import refrom urllib.parse import parse_qsl, urlencode, urlsplitfrom django.conf import settings@@ -63,8 +64,9 @@ def object_storage_upload_source() -> str:# prefix match would also hand the app document this policy and stop it from starting.REPLAY_PLAYER_FRAME_PATH = "/replay_player_frame/index.html"-# The app policy names only PostHog origins in `frame-ancestors`. Enforcing it on these paths stops-# every embedded dashboard, shared link and survey from rendering on a customer's site.+# The app policy names only PostHog origins in `frame-ancestors`. Enforcing that directive on these+# paths stops every embedded dashboard, shared link and survey from rendering on a customer's site,+# so these documents get the app policy without it.## The list follows `posthog/urls.py`. The Contour ingress keeps a similar list in# `charts/argocd/contour-ingress/values/values.{dev,prod-us,prod-eu}.yaml`, which omits@@ -83,6 +85,28 @@ def is_embeddable_document(path: str) -> bool:return path in EMBEDDABLE_PATHS or path.startswith(EMBEDDABLE_PATH_PREFIXES)+# The embeddable documents that only report the app policy, on every install.+#+# The pattern matches the routes in `posthog/urls.py` exactly. The path picks the policy for a whole+# document, and the app can navigate inside it, so an unrouted subpath gets the enforced policy.+#+# The image exporter in `products/exports/backend/tasks/image_exporter.py` loads the bare `/exporter`+# render document in a headless browser. A replay export can evaluate a string as script in an+# about:blank frame of that render, and the frame inherits this policy, which has no 'unsafe-eval'.+# An enforced policy would refuse that `eval`, and the effect on the exported image is unknown, so+# the document stays report-only until the caller of that `eval` is traced. `/exporter/<token>`+# serves the shared page, so it enforces like `/shared/`.+#+# The hosted survey view sets its own policy, so the app policy reaches `/external_surveys/` only on+# a response that the view did not build. No report shows how such a response behaves under an+# enforced policy.+REPORT_ONLY_ROUTES = re.compile(r"/exporter|/external_surveys/[^/]+/?")+++def is_report_only_document(path: str) -> bool:+ return REPORT_ONLY_ROUTES.fullmatch(path) is not None++def app_frame_ancestor_sources() -> list[str]:"""The origins that may frame the app, as `frame-ancestors` sources.@@ -97,7 +121,7 @@ def app_frame_ancestor_sources() -> list[str]:def app_csp_header_name(path: str) -> str:- if is_embeddable_document(path):+ if is_report_only_document(path):return "Content-Security-Policy-Report-Only"if is_hobby():# A self-hosted install reports its violations nowhere, and its asset hosts can differ from@@ -396,9 +420,10 @@ class CSPMiddleware:]if is_embeddable_document(request.path):# Customers frame these documents on their own sites, and no list of ancestors can- # name every such site. In a report-only policy the directive only sends a report for- # each embed. Chrome cuts the document URL of that report to the origin, so it looks- # the same as a report from an app page that the browser blocks in a frame.+ # name every such site. In an enforced policy the directive stops the document from+ # rendering in the customer's page. In a report-only policy it only sends a report+ # for each embed. Chrome cuts the document URL of that report to the origin, so it+ # looks the same as a report from an app page that the browser blocks in a frame.csp_parts.remove(frame_ancestors)# The hosts and the config token below belong to PostHog Cloud, so self-hosted installs, E2Ediff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.pyindex 27d8119f6076..05d13327568e 100644--- a/posthog/test/test_csp_middleware.py+++ b/posthog/test/test_csp_middleware.py@@ -180,16 +180,22 @@ class TestCSPMiddleware(APIBaseTest):assert "default-src 'self'" in response["Content-Security-Policy"]assert "Content-Security-Policy-Report-Only" not in response- def test_enforcement_reaches_an_app_page_but_not_an_embeddable_one(self):+ def test_enforcement_reaches_app_and_shared_pages_but_not_the_exporter(self):# The wiring guard for app_csp_header_name. The matrix of paths lives in# TestAppCspHeaderName, which needs no database.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- assert "frame-ancestors" not in embedded["Content-Security-Policy-Report-Only"]+ for path in ("/shared/notarealtoken", "/exporter/notarealtoken"):+ shared = self.client.get(path)+ assert "default-src 'self'" in shared["Content-Security-Policy"], path+ assert "frame-ancestors" not in shared["Content-Security-Policy"], path+ assert "Content-Security-Policy-Report-Only" not in shared, path++ exporter = self.client.get("/exporter")+ assert "Content-Security-Policy" not in exporter+ assert "frame-ancestors" not in exporter["Content-Security-Policy-Report-Only"]@override_settings(CLOUD_DEPLOYMENT=None, DEBUG=False) # As a self-hosted installdef test_self_hosted_install_enforces_only_frame_ancestors(self) -> None:@@ -389,9 +395,9 @@ class TestCSPMiddleware(APIBaseTest):{"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.+ # This document enforces the app policy, and the shadows must stay in the report-only header.(- "report_only_embeddable_document",+ "enforced_embeddable_document","/shared/notarealtoken",{"CLOUD_DEPLOYMENT": "US", "SITE_URL": "https://us.posthog.com", "JS_URL": _US_BUNDLE},True,@@ -475,19 +481,56 @@ class TestCSPMiddleware(APIBaseTest):class TestAppCspHeaderName(SimpleTestCase):@parameterized.expand([- ("shared_dashboard", "/shared_dashboard/abc123"),- ("shared", "/shared/abc123"),- ("embedded", "/embedded/abc123"),- ("exporter_with_token", "/exporter/abc123"),- ("exporter_render", "/exporter"),- ("render_query", "/render_query"),- ("external_survey", "/external_surveys/019efb7e-0672-0000-729b-e234586f6177"),+ ("shared_dashboard", "/shared_dashboard/abc123", {}, True),+ ("shared", "/shared/abc123", {}, True),+ ("embedded", "/embedded/abc123", {}, True),+ ("render_query", "/render_query", {}, True),+ # A replay export can run an eval in a frame of this document, and an enforced policy refuses it.+ ("exporter_render", "/exporter", {}, False),+ # This route serves the shared page, so it enforces like /shared/.+ ("exporter_with_token", "/exporter/abc123", {}, True),+ # The survey view sets its own policy, so this is a response that the view did not build.+ ("external_survey", "/external_surveys/019efb7e-0672-0000-729b-e234586f6177", {}, False),+ # No route serves these, so the app catch-all answers them, and the app then runs in that+ # document like on any other page.+ ("unrouted_exporter_subpath", "/exporter/a/b", {}, True),+ ("unrouted_survey_subpath", "/external_surveys/a/b", {}, True),+ # A self-hosted install enforces nothing here, and that includes the frame-ancestors+ # header that an app page gets on such an install.+ ("shared_on_a_self_hosted_install", "/shared/abc123", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}, False),+ # Cloud sends other report-only policies in the same header, and they must not replace+ # the app policy there.+ (+ "exporter_on_cloud",+ "/exporter",+ {+ "TEST": False,+ "DEBUG": False,+ "E2E_TESTING": False,+ "CLOUD_DEPLOYMENT": "US",+ "SITE_URL": "https://us.posthog.com",+ "JS_URL": _US_BUNDLE,+ },+ False,+ ),])- def test_embeddable_document_stays_report_only(self, _name: str, path: str) -> None:- # A customer's site frames each of these. The app policy names only PostHog origins in- # frame-ancestors, so enforcing it here stops the document rendering on their page.- assert app_csp_header_name(path) == "Content-Security-Policy-Report-Only"+ def test_embeddable_document_sends_the_app_policy_without_frame_ancestors(+ self, _name: str, path: str, overrides: dict[str, str | bool | None], expects_enforced: bool+ ) -> None:+ def view(_request: HttpRequest) -> HttpResponse:+ return HttpResponse("<html><body>shared</body></html>", content_type="text/html; charset=utf-8")++ with override_settings(**overrides):+ response = CSPMiddleware(view)(RequestFactory().get(path))++ enforced = response.get("Content-Security-Policy", "")+ reported = response.get("Content-Security-Policy-Report-Only", "")+ assert ("default-src" in enforced, "default-src" in reported) == (expects_enforced, not expects_enforced)+ # A customer's site frames each of these, and the app policy names only PostHog origins in+ # frame-ancestors. Enforced, the directive stops the document rendering on their page.+ # Reported, it sends a report for every embed.+ assert "frame-ancestors" not in enforced + reported@parameterized.expand([