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.

chore(security): tighten csp tests after flag removal (#116642)

Tom Piccirello161145c24145
diff --git a/.agents/security.md b/.agents/security.md
index 20e3e71516e9..38d89770adc5 100644
--- a/.agents/security.md
+++ b/.agents/security.md
@@ -202,7 +202,7 @@ A refused resource produces no user-visible error, so the feature simply does no
Three 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 admin policy** governs `/admin/`. It is enforced for every staff member, with no flag, so a mistake here breaks admin immediately.
+- **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.
### What the app policy forbids
diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.py
index 30eb98e3c8bc..af1d044222a5 100644
--- a/posthog/csp_middleware.py
+++ b/posthog/csp_middleware.py
@@ -7,7 +7,6 @@ The policy lives apart from the other middleware so that team-security owns the
from urllib.parse import parse_qsl, urlencode, urlsplit
from django.conf import settings
-from django.http import HttpRequest
from posthog.cloud_utils import get_api_host, is_cloud, is_hobby
from posthog.constants import POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN
@@ -97,18 +96,14 @@ def app_frame_ancestor_sources() -> list[str]:
return sources
-def csp_enforcement_enabled() -> bool:
- # A self-hosted install reports its violations nowhere, and its asset hosts can differ from
- # ours, so an enforced policy there would break pages with no signal.
- return not is_hobby()
-
-
-def app_csp_header_name(request: HttpRequest) -> str:
- if is_embeddable_document(request.path):
+def app_csp_header_name(path: str) -> str:
+ if is_embeddable_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
+ # ours, so an enforced policy there would break pages with no signal.
return "Content-Security-Policy-Report-Only"
- if csp_enforcement_enabled():
- return "Content-Security-Policy"
- return "Content-Security-Policy-Report-Only"
+ return "Content-Security-Policy"
_WILDCARD_SOURCES = frozenset({"https://*.posthog.com", "https://*.i.posthog.com"})
@@ -232,8 +227,8 @@ class CSPMiddleware:
# Without this the directive falls back to `default-src 'self'`, which drops the
# `data:` icons Django admin and our own admin pages render, and the `blob:` images
# the admin tools build client-side. Neither can execute, and this policy is
- # enforced for every staff member rather than flag-gated, so the fallback was
- # breaking admin pages outright.
+ # enforced for every staff member, so the fallback was breaking admin pages
+ # outright.
"img-src 'self' data: blob:",
"worker-src 'none'",
"child-src 'none'",
@@ -272,9 +267,9 @@ 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.
+ # Enforced even where the rest of the policy is report-only, because this directive is
+ # what admits these origins: a frame-ancestors directive makes browsers ignore
+ # X-Frame-Options, which names only our own origin.
# `'self'` lets the app show one of its own pages in a frame, such as a PostHog object
# 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.
@@ -467,7 +462,7 @@ class CSPMiddleware:
csp_parts.append(f"report-uri {report_endpoint}")
# Browsers only deliver crash reports to the endpoint named `default`.
response.headers["Reporting-Endpoints"] = f'default="{report_endpoint}"'
- header_name = app_csp_header_name(request)
+ header_name = app_csp_header_name(request.path)
response.headers[header_name] = "; ".join(csp_parts)
for version, shadow_parts in shadows.items():
shadow_params = {"v": version}
diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.py
index 79b4c767c8c3..f23b237dcc90 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -164,17 +164,19 @@ class TestCSPMiddleware(APIBaseTest):
@parameterized.expand(
[
- ("app_root", "/"),
# 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"),
- ("messaging_preferences", "/messaging-preferences/abc"),
+ ("path_under_the_replay_frame_prefix", "/replay_player_frame", 302),
+ # The status proves the page renders for a signed-out visitor. A path that redirects to
+ # /login only repeats the row above.
+ ("page_that_needs_no_login", "/preflight", 200),
]
)
- def test_signed_out_page_is_fully_enforced(self, _name, path):
+ def test_signed_out_page_is_fully_enforced(self, _name: str, path: str, status: int) -> None:
self.client.logout()
response = self.client.get(path)
+ assert response.status_code == status
assert "default-src 'self'" in response["Content-Security-Policy"]
assert "Content-Security-Policy-Report-Only" not in response
@@ -189,6 +191,15 @@ class TestCSPMiddleware(APIBaseTest):
assert "Content-Security-Policy" not in embedded
assert "frame-ancestors" not in embedded["Content-Security-Policy-Report-Only"]
+ @override_settings(CLOUD_DEPLOYMENT=None, DEBUG=False) # As a self-hosted install
+ def test_self_hosted_install_enforces_only_frame_ancestors(self) -> None:
+ response = self.client.get("/")
+ enforced = response["Content-Security-Policy"]
+ # The enforced list has to be the one the reported policy names, or the two drift apart.
+ assert enforced.startswith("frame-ancestors 'self' https://posthog.com")
+ assert "default-src" not in enforced
+ assert enforced in response["Content-Security-Policy-Report-Only"]
+
@override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud
def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):
response = self.client.get("/")
@@ -454,13 +465,6 @@ class TestCSPMiddleware(APIBaseTest):
@override_settings(CLOUD_DEPLOYMENT="LOCAL")
class TestAppCspHeaderName(SimpleTestCase):
- def _request(
- self, path: str, *, distinct_id: str | None = "abc", email: str = "[email protected]"
- ) -> HttpRequest:
- request = RequestFactory().get(path)
- request.user = MagicMock(is_authenticated=distinct_id is not None, distinct_id=distinct_id, email=email)
- return request
-
@parameterized.expand(
[
("shared_dashboard", "/shared_dashboard/abc123"),
@@ -472,36 +476,23 @@ class TestAppCspHeaderName(SimpleTestCase):
("external_survey", "/external_surveys/019efb7e-0672-0000-729b-e234586f6177"),
]
)
- def test_embeddable_document_stays_report_only(self, _name, path):
+ 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(self._request(path)) == "Content-Security-Policy-Report-Only"
- assert app_csp_header_name(self._request(path, distinct_id=None)) == "Content-Security-Policy-Report-Only"
+ assert app_csp_header_name(path) == "Content-Security-Policy-Report-Only"
@parameterized.expand(
[
- ("app_root", "/", "abc"),
- ("project_page", "/project/2/dashboard", "abc"),
+ ("app_root", "/"),
+ ("project_page", "/project/2/dashboard"),
# Neither prefix owns these. A shorter prefix match would hand the app catch-all the
# carve-out and quietly exempt an ordinary page from enforcement.
- ("shared_prefix_without_separator", "/sharedthing", "abc"),
- ("exporter_prefix_without_separator", "/exporterthing", "abc"),
- ("login", "/login", None),
- ("signup", "/signup", None),
- ("reset_link", "/reset/abc/def", None),
- ("reset_2fa_link", "/reset_2fa/abc/def", None),
- ("verify_email_link", "/verify_email/abc/def", None),
- ("other_signed_out_page", "/messaging-preferences/abc", None),
+ ("shared_prefix_without_separator", "/sharedthing"),
+ ("exporter_prefix_without_separator", "/exporterthing"),
]
)
- def test_page_is_enforced(self, _name: str, path: str, distinct_id: str | None) -> None:
- assert app_csp_header_name(self._request(path, distinct_id=distinct_id)) == "Content-Security-Policy"
-
- def test_a_request_without_a_user_is_enforced(self) -> None:
- # CSPMiddleware runs before AuthenticationMiddleware, so a response from a middleware between
- # the two carries no request.user.
- assert app_csp_header_name(RequestFactory().get("/login")) == "Content-Security-Policy"
- assert app_csp_header_name(RequestFactory().get("/messaging-preferences/abc")) == "Content-Security-Policy"
+ def test_page_is_enforced(self, _name: str, path: str) -> None:
+ assert app_csp_header_name(path) == "Content-Security-Policy"
@parameterized.expand(
[