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): remove csp-enforce-other-signed-out-pages flag (#116482)

Tom Piccirello7a374833e2f0
diff --git a/.agents/security.md b/.agents/security.md
index a554454e3feb..2ed129f3fb81 100644
--- a/.agents/security.md
+++ b/.agents/security.md
@@ -193,7 +193,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 signed-in user, and for every visitor on login, signup, password reset and email verification. A self-hosted install only reports it, because its violations reach nobody. Other signed-out pages follow the `csp-enforce-other-signed-out-pages` flag, drawn per page load because a signed-out visitor has no user to bucket. They stay report-only while the flag is off. 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, 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.
- **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.py
index a17ce6878ed9..631840a8bdef 100644
--- a/posthog/csp_middleware.py
+++ b/posthog/csp_middleware.py
@@ -4,23 +4,16 @@ The policy lives apart from the other middleware so that team-security owns the
`.github/CODEOWNERS` and reviews every change to it.
"""
-import uuid
from urllib.parse import parse_qsl, urlencode, urlsplit
from django.conf import settings
from django.http import HttpRequest
-import structlog
-import posthoganalytics
-
from posthog.cloud_utils import get_api_host, is_cloud, is_hobby
from posthog.constants import POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN
from posthog.models.utils import generate_random_token
from posthog.ph_client import PH_US_API_KEY, PH_US_HOST
-logger = structlog.get_logger(__name__)
-
-
_POSTHOG_CSP_REPORT_ENDPOINT = f"{PH_US_HOST}/report/?token={PH_US_API_KEY}&v=2"
@@ -104,57 +97,16 @@ def app_frame_ancestor_sources() -> list[str]:
return sources
-CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG = "csp-enforce-other-signed-out-pages"
-
-# The pages that take a password or a one-time code. Other signed-out pages follow the flag above.
-SIGNED_OUT_ENFORCEABLE_PATH_PREFIXES = ("/login", "/signup", "/reset", "/reset_2fa", "/verify_email")
-
-
-def is_signed_out_enforceable_path(path: str) -> bool:
- return any(path == prefix or path.startswith(prefix + "/") for prefix in SIGNED_OUT_ENFORCEABLE_PATH_PREFIXES)
-
-
-def other_signed_out_pages_csp_enforcement_enabled() -> bool:
- try:
- # A signed-out visitor has no person to bucket, so each document draws a random id. The
- # flag's rollout percentage then applies per document.
- #
- # A condition on a person property cannot resolve for a random id, so it evaluates to None
- # and enforces nothing. Flag events stay off, because each document would add a new
- # distinct id to the project.
- #
- # Local evaluation only. A network call here would sit in the path of every HTML response,
- # and an unevaluable flag returns None, which leaves the policy report-only.
- return bool(
- posthoganalytics.feature_enabled(
- CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG,
- str(uuid.uuid4()),
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- logger.warning("csp.signed_out_enforcement_flag_check_failed_defaulting_off", exc_info=True)
- return False
-
-
-def csp_enforcement_enabled(request: HttpRequest) -> bool:
- 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 False
- user = getattr(request, "user", None)
- if user is not None and user.is_authenticated:
- return True
- # The document keeps the policy it loads with. A visitor who signs in from a page the flag
- # leaves report-only goes on to the app inside the same document, still report-only.
- return is_signed_out_enforceable_path(request.path) or other_signed_out_pages_csp_enforcement_enabled()
+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):
return "Content-Security-Policy-Report-Only"
- if csp_enforcement_enabled(request):
+ if csp_enforcement_enabled():
return "Content-Security-Policy"
return "Content-Security-Policy-Report-Only"
diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.py
index a5eaf61874a6..f5fc4146d7a9 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -2,7 +2,7 @@ from html.parser import HTMLParser
from urllib.parse import parse_qs, urlsplit
from posthog.test.base import APIBaseTest, override_settings
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
from django.conf import settings
from django.http import HttpRequest, HttpResponse
@@ -10,13 +10,7 @@ from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
-from posthog.csp_middleware import (
- CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG,
- CSPMiddleware,
- app_csp_header_name,
- narrowed_app_policy,
- object_storage_upload_source,
-)
+from posthog.csp_middleware import CSPMiddleware, app_csp_header_name, narrowed_app_policy, object_storage_upload_source
def _parse_policies(header: str) -> list[dict[str, list[str]]]:
@@ -170,32 +164,19 @@ class TestCSPMiddleware(APIBaseTest):
@parameterized.expand(
[
- ("app_root", "/", True),
+ ("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", True),
- # A customer's page frames this document, and the enforced list names only PostHog
- # origins.
- ("embeddable_document", "/shared/notarealtoken", False),
+ ("path_under_the_replay_frame_prefix", "/replay_player_frame"),
+ ("messaging_preferences", "/messaging-preferences/abc"),
]
)
- def test_signed_out_page_without_the_flag_enforces_only_frame_ancestors(
- self, _name, path, enforces_frame_ancestors
- ):
+ def test_signed_out_page_is_fully_enforced(self, _name, path):
self.client.logout()
response = self.client.get(path)
- 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 'self' https://posthog.com")
- assert "default-src" not in enforced
- assert enforced in reported
+ 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):
# The wiring guard for app_csp_header_name. The matrix of paths lives in
@@ -491,8 +472,7 @@ class TestAppCspHeaderName(SimpleTestCase):
("external_survey", "/external_surveys/019efb7e-0672-0000-729b-e234586f6177"),
]
)
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)
- def test_embeddable_document_stays_report_only_under_enforcement(self, _name, path, _mock_flag):
+ def test_embeddable_document_stays_report_only(self, _name, path):
# 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"
@@ -500,67 +480,28 @@ class TestAppCspHeaderName(SimpleTestCase):
@parameterized.expand(
[
- ("app_root", "/", "abc", False),
- ("project_page", "/project/2/dashboard", "abc", False),
+ ("app_root", "/", "abc"),
+ ("project_page", "/project/2/dashboard", "abc"),
# 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", False),
- ("exporter_prefix_without_separator", "/exporterthing", "abc", False),
- ("login", "/login", None, False),
- ("signup", "/signup", None, False),
- ("reset_link", "/reset/abc/def", None, False),
- ("reset_2fa_link", "/reset_2fa/abc/def", None, False),
- ("verify_email_link", "/verify_email/abc/def", None, False),
- ("other_signed_out_page_with_the_flag", "/messaging-preferences/abc", None, True),
+ ("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),
]
)
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled")
- def test_page_is_enforced(
- self, _name: str, path: str, distinct_id: str | None, flag_enabled: bool, mock_flag: MagicMock
- ) -> None:
- mock_flag.side_effect = lambda key, *args, **kwargs: (
- flag_enabled and key == CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG
- )
+ 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"
- @parameterized.expand(
- [
- ("other_signed_out_page", "/messaging-preferences/abc"),
- ("login_prefix_without_separator", "/loginfoo"),
- ]
- )
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=False)
- def test_other_signed_out_page_stays_report_only_without_the_flag(self, _name: str, path: str, _mock_flag) -> None:
- assert app_csp_header_name(self._request(path, distinct_id=None)) == "Content-Security-Policy-Report-Only"
-
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=False)
- def test_a_request_without_a_user_follows_the_signed_out_rules(self, _mock_flag: MagicMock) -> None:
+ 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-Report-Only"
- )
-
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)
- def test_each_signed_out_document_draws_its_own_bucket(self, mock_flag: MagicMock) -> None:
- app_csp_header_name(self._request("/messaging-preferences/abc", distinct_id=None))
- app_csp_header_name(self._request("/messaging-preferences/abc", distinct_id=None))
- # A fixed id would put every signed-out visitor in one bucket, so a rollout percentage
- # would enforce for everyone or nobody.
- first, second = (call.args[1] for call in mock_flag.call_args_list)
- assert first != second
- assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True
- assert mock_flag.call_args.kwargs["send_feature_flag_events"] is False
-
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", side_effect=Exception("flags unavailable"))
- def test_a_failing_flag_lookup_leaves_the_policy_report_only(self, _mock_flag: MagicMock) -> None:
- # Fail safe: an enforced policy that nobody meant to turn on breaks the page.
- assert (
- app_csp_header_name(self._request("/messaging-preferences/abc", distinct_id=None))
- == "Content-Security-Policy-Report-Only"
- )
+ assert app_csp_header_name(RequestFactory().get("/messaging-preferences/abc")) == "Content-Security-Policy"
class TestNarrowedAppPolicy(SimpleTestCase):