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): add a flag to enforce the app policy on signed-out auth pages (#104774)

Tom Piccirello1432b6920f90
diff --git a/.agents/security.md b/.agents/security.md
index 56b9cd6232cd..e7a7259f57e7 100644
--- a/.agents/security.md
+++ b/.agents/security.md
@@ -166,7 +166,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. It is enforced per user behind the `csp-enforce-app-policy` flag, and report-only otherwise.
+- **The app policy** governs every SPA page. It is enforced per user behind the `csp-enforce-app-policy` flag, and report-only otherwise. A signed-out visitor has no user to bucket, so on login, signup, password reset and email verification the `csp-enforce-signed-out-pages` flag enforces it per page load instead. Other signed-out pages stay report-only. Embeddable documents, such as shared dashboards, stay report-only under both flags.
- **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/middleware.py b/posthog/middleware.py
index 53b0622766ad..2f984a617e62 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1324,14 +1324,47 @@ def is_embeddable_document(path: str) -> bool:
CSP_ENFORCE_APP_POLICY_FLAG = "csp-enforce-app-policy"
+CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG = "csp-enforce-signed-out-pages"
+
+# The pages that take a password or a one-time code. Other signed-out pages keep the report-only header.
+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 signed_out_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.
+ return bool(
+ posthoganalytics.feature_enabled(
+ CSP_ENFORCE_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:
user = getattr(request, "user", None)
- distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else None
- if user is None or not distinct_id:
- # An anonymous page has nobody to bucket, so login, signup and the OAuth pages keep the
- # report-only header until enforcement covers everyone.
+ if user is None:
+ return False
+ if not user.is_authenticated:
+ # The document keeps the policy it loads with. A visitor who signs in on login goes on to
+ # the app inside the same document, so the draw here also covers that visit.
+ return is_signed_out_enforceable_path(request.path) and signed_out_csp_enforcement_enabled()
+ distinct_id = getattr(user, "distinct_id", None)
+ if not distinct_id:
return False
try:
# Local evaluation only. A network call here would sit in the path of every HTML response,
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 120e748b2864..5d0b80a21a25 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -30,6 +30,8 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParamete
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.middleware import (
+ CSP_ENFORCE_APP_POLICY_FLAG,
+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,
CSPMiddleware,
ManagedProxyClientIPMiddleware,
ManagedProxyClientIPOutcome,
@@ -2909,6 +2911,7 @@ class TestAppCspHeaderName(SimpleTestCase):
# 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"
@parameterized.expand(
[
@@ -2937,17 +2940,84 @@ class TestAppCspHeaderName(SimpleTestCase):
# Local evaluation keeps a flag network call out of every HTML response.
assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True
+ @parameterized.expand(
+ [
+ ("login", "/login", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),
+ ("signup", "/signup", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),
+ ("reset_link", "/reset/abc/def", None, CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy"),
+ (
+ "reset_2fa_link",
+ "/reset_2fa/abc/def",
+ None,
+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,
+ "Content-Security-Policy",
+ ),
+ (
+ "verify_email_link",
+ "/verify_email/abc/def",
+ None,
+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,
+ "Content-Security-Policy",
+ ),
+ ("login_without_a_flag", "/login", None, None, "Content-Security-Policy-Report-Only"),
+ (
+ "login_with_the_app_flag",
+ "/login",
+ None,
+ CSP_ENFORCE_APP_POLICY_FLAG,
+ "Content-Security-Policy-Report-Only",
+ ),
+ ("signed_in", "/login", "abc", CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG, "Content-Security-Policy-Report-Only"),
+ (
+ "other_signed_out_page",
+ "/messaging-preferences/abc",
+ None,
+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,
+ "Content-Security-Policy-Report-Only",
+ ),
+ (
+ "login_prefix_without_separator",
+ "/loginfoo",
+ None,
+ CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,
+ "Content-Security-Policy-Report-Only",
+ ),
+ ]
+ )
+ @patch("posthog.middleware.posthoganalytics.feature_enabled")
+ def test_each_flag_enforces_only_its_own_pages(
+ self,
+ _name: str,
+ path: str,
+ distinct_id: str | None,
+ enabled_flag: str | None,
+ expected: str,
+ mock_flag: MagicMock,
+ ) -> None:
+ mock_flag.side_effect = lambda key, *args, **kwargs: key == enabled_flag
+ assert app_csp_header_name(self._request(path, distinct_id=distinct_id)) == expected
+
@patch("posthog.middleware.posthoganalytics.feature_enabled", return_value=True)
- def test_anonymous_request_stays_report_only(self, mock_flag):
- # Nothing identifies an anonymous viewer, so the flag cannot bucket them. Login and signup
- # keep the report-only header until enforcement covers everyone.
- assert app_csp_header_name(self._request("/login", distinct_id=None)) == "Content-Security-Policy-Report-Only"
- mock_flag.assert_not_called()
+ def test_each_signed_out_document_draws_its_own_bucket(self, mock_flag: MagicMock) -> None:
+ app_csp_header_name(self._request("/login", distinct_id=None))
+ app_csp_header_name(self._request("/login", 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
+ @parameterized.expand([("signed_in", "abc"), ("signed_out", None)])
@patch("posthog.middleware.posthoganalytics.feature_enabled", side_effect=Exception("flags unavailable"))
- def test_a_failing_flag_lookup_leaves_the_policy_report_only(self, _mock_flag):
+ def test_a_failing_flag_lookup_leaves_the_policy_report_only(
+ self, _name: str, distinct_id: str | None, _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("/")) == "Content-Security-Policy-Report-Only"
+ assert (
+ app_csp_header_name(self._request("/login", distinct_id=distinct_id))
+ == "Content-Security-Policy-Report-Only"
+ )
class TestNarrowedAppPolicy(SimpleTestCase):