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): always enforce the app policy on signed-in and login pages (#106400)

Tom Piccirellod5d656b206f2
diff --git a/.agents/security.md b/.agents/security.md
index 16496a8c3c1f..ea2a1c2d18ad 100644
--- a/.agents/security.md
+++ b/.agents/security.md
@@ -167,7 +167,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. 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 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 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 65f463c15356..9c51e50684cf 100644
--- a/posthog/csp_middleware.py
+++ b/posthog/csp_middleware.py
@@ -13,7 +13,7 @@ from django.http import HttpRequest
import structlog
import posthoganalytics
-from posthog.cloud_utils import get_api_host, is_cloud
+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
@@ -68,10 +68,9 @@ def is_embeddable_document(path: str) -> bool:
return path in EMBEDDABLE_PATHS or path.startswith(EMBEDDABLE_PATH_PREFIXES)
-CSP_ENFORCE_APP_POLICY_FLAG = "csp-enforce-app-policy"
-CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG = "csp-enforce-signed-out-pages"
+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 keep the report-only header.
+# 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")
@@ -79,7 +78,7 @@ 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:
+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.
@@ -87,9 +86,12 @@ def signed_out_csp_enforcement_enabled() -> bool:
# 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_SIGNED_OUT_PAGES_FLAG,
+ CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG,
str(uuid.uuid4()),
only_evaluate_locally=True,
send_feature_flag_events=False,
@@ -101,36 +103,16 @@ def signed_out_csp_enforcement_enabled() -> bool:
def csp_enforcement_enabled(request: HttpRequest) -> bool:
- user = getattr(request, "user", None)
- 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,
- # and an unevaluable flag returns None, which leaves the policy report-only.
- #
- # Local evaluation holds the flag's conditions but not the person's properties, so a
- # condition on `email` cannot resolve unless the caller supplies it. Without this the
- # staff-only rollout every other flag here uses would return None and enforce nothing.
- return bool(
- posthoganalytics.feature_enabled(
- CSP_ENFORCE_APP_POLICY_FLAG,
- distinct_id,
- person_properties={"email": user.email} if user.email else {},
- only_evaluate_locally=True,
- )
- )
- except Exception:
- # A failed lookup and a deliberate opt-out both leave the policy report-only. The rollout
- # needs to tell them apart.
- logger.warning("csp.enforcement_flag_check_failed_defaulting_off", exc_info=True)
+ 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 app_csp_header_name(request: HttpRequest) -> str:
@@ -411,29 +393,10 @@ class CSPMiddleware:
},
)
- # Both values are read inside one narrowed block, so nothing below re-checks `user`.
user = getattr(request, "user", None)
- if user is not None and user.is_authenticated:
- is_staff = bool(getattr(user, "is_staff", False))
- distinct_id = getattr(user, "distinct_id", None)
- else:
- is_staff = False
- distinct_id = None
-
- # Staff get the policy enforced ahead of everyone else, so each violation they report is
- # something already broken for a colleague rather than one sample of a trend. At 0.1 we
- # would see one breakage in ten, which is the opposite of what the staff rollout is for.
- # The endpoint does the sampling, so browsers already send every report and taking staff
- # to 1 costs ingestion rather than client traffic.
- #
- # This keys on is_staff rather than on the enforcement flag, which would otherwise track
- # the enforced population exactly. The flag widens until it covers everyone, and would
- # silently take the whole fleet to unsampled reporting; staff stays bounded.
- sample_rate = "1" if is_staff else "0.1"
+ distinct_id = getattr(user, "distinct_id", None) if user is not None and user.is_authenticated else None
- report_params = {"sample_rate": sample_rate}
- if narrowed:
- report_params["v"] = NARROWED_APP_POLICY_REPORT_VERSION
+ report_params: dict[str, str] = {"v": NARROWED_APP_POLICY_REPORT_VERSION} if narrowed else {}
report_uri = csp_report_endpoint(**report_params)
if report_uri:
report_endpoint = report_uri
diff --git a/posthog/test/test_csp_middleware.py b/posthog/test/test_csp_middleware.py
index 3079cd7730b5..8dc9711495e9 100644
--- a/posthog/test/test_csp_middleware.py
+++ b/posthog/test/test_csp_middleware.py
@@ -9,14 +9,15 @@ from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
from posthog.csp_middleware import (
- CSP_ENFORCE_APP_POLICY_FLAG,
- CSP_ENFORCE_SIGNED_OUT_PAGES_FLAG,
+ CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG,
CSPMiddleware,
app_csp_header_name,
narrowed_app_policy,
)
+# Tests run as a self-hosted install, which never enforces. LOCAL enforces without turning on DEBUG.
+@override_settings(CLOUD_DEPLOYMENT="LOCAL")
class TestCSPMiddleware(APIBaseTest):
def test_replay_player_frame_carries_its_own_policy_and_reports_nothing(self):
# The frame exists so a recorded page stops being judged against the app policy. If the
@@ -35,7 +36,7 @@ class TestCSPMiddleware(APIBaseTest):
# The player frame is same-origin, and an http origin does not match the https: source
# that heatmaps need.
response = self.client.get("/")
- assert "frame-src 'self' https:" in response["Content-Security-Policy-Report-Only"]
+ assert "frame-src 'self' https:" in response["Content-Security-Policy"]
@parameterized.expand(
[
@@ -60,7 +61,7 @@ class TestCSPMiddleware(APIBaseTest):
# 'self' alone refuses every preload index.html emits for the boot chain.
with override_settings(**overrides):
response = self.client.get("/")
- assert expected in response["Content-Security-Policy-Report-Only"]
+ assert expected in response["Content-Security-Policy"]
def test_replay_player_frame_serves_the_mount_node_without_a_session(self):
# Shared recordings render the player for logged-out viewers.
@@ -88,7 +89,10 @@ class TestCSPMiddleware(APIBaseTest):
("embeddable_document", "/shared/notarealtoken", False),
]
)
- def test_html_response_without_the_flag_enforces_only_frame_ancestors(self, _name, path, enforces_frame_ancestors):
+ def test_signed_out_page_without_the_flag_enforces_only_frame_ancestors(
+ self, _name, path, enforces_frame_ancestors
+ ):
+ self.client.logout()
response = self.client.get(path)
reported = response["Content-Security-Policy-Report-Only"]
assert "default-src 'self'" in reported
@@ -102,8 +106,7 @@ class TestCSPMiddleware(APIBaseTest):
assert "default-src" not in enforced
assert enforced in reported
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)
- def test_enforcement_reaches_an_app_page_but_not_an_embeddable_one(self, _mock_flag):
+ 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
# TestAppCspHeaderName, which needs no database.
enforced = self.client.get("/")
@@ -117,13 +120,15 @@ class TestCSPMiddleware(APIBaseTest):
@override_settings(CLOUD_DEPLOYMENT="US") # As PostHog Cloud
def test_html_response_declares_default_reporting_endpoint_with_distinct_id(self):
response = self.client.get("/")
- policy = response["Content-Security-Policy-Report-Only"]
+ policy = response["Content-Security-Policy"]
# A `report-to` directive makes browsers ignore `report-uri` and report through the
# Reporting API, which drops violations raised in about:blank and srcdoc frames.
assert "report-to" not in policy
_, report_endpoint = next(part for part in policy.split("; ") if part.startswith("report-uri ")).split()
assert report_endpoint.startswith("https://us.i.posthog.com/report/")
assert f"distinct_id={self.user.distinct_id}" in report_endpoint
+ # An enforced violation is a page that broke for someone, so dropping reports hides breakages.
+ assert "sample_rate" not in report_endpoint
# Browsers only deliver crash reports to the endpoint named `default`, so dropping or
# renaming it silently stops crash ingestion.
assert response["Reporting-Endpoints"] == f'default="{report_endpoint}"'
@@ -132,7 +137,7 @@ class TestCSPMiddleware(APIBaseTest):
def test_reporting_endpoints_omit_distinct_id_when_logged_out(self):
self.client.logout()
response = self.client.get("/login")
- policy = response["Content-Security-Policy-Report-Only"]
+ policy = response["Content-Security-Policy"]
assert "report-uri https://us.i.posthog.com/report/" in policy
assert "distinct_id" not in policy
header = response["Reporting-Endpoints"]
@@ -141,20 +146,30 @@ class TestCSPMiddleware(APIBaseTest):
@parameterized.expand(
[
- ("self_hosted_by_default", {"CLOUD_DEPLOYMENT": None, "DEBUG": False}),
+ # Nobody sees a self-hosted install's violations, so enforcing there would break pages silently.
+ (
+ "self_hosted_by_default",
+ {"CLOUD_DEPLOYMENT": None, "DEBUG": False},
+ "Content-Security-Policy-Report-Only",
+ ),
# DEBUG puts an install in the local run mode rather than the hobby one, and nothing
- # stops a self-hoster deploying that way, so it must report nowhere as well.
- ("self_hosted_with_debug", {"CLOUD_DEPLOYMENT": None, "DEBUG": True}),
+ # stops a self-hoster deploying that way, so it must report nowhere as well. Local
+ # development enforces, so a change that breaks the policy shows up there first.
+ ("self_hosted_with_debug", {"CLOUD_DEPLOYMENT": None, "DEBUG": True}, "Content-Security-Policy"),
# Cloud would otherwise report, so this case proves the empty value turns it off.
- ("explicitly_disabled", {"CLOUD_DEPLOYMENT": "US", "CSP_REPORT_ENDPOINT": ""}),
+ (
+ "explicitly_disabled",
+ {"CLOUD_DEPLOYMENT": "US", "CSP_REPORT_ENDPOINT": ""},
+ "Content-Security-Policy",
+ ),
]
)
- def test_no_endpoint_still_sends_the_policy_but_asks_for_no_reports(self, _name, overrides):
+ def test_no_endpoint_still_sends_the_policy_but_asks_for_no_reports(self, _name, overrides, header):
# A self-hosted install must not report to PostHog, and the policy itself must survive, so
# dropping it here would silently remove a security control.
with override_settings(**{"CSP_REPORT_ENDPOINT": None, **overrides}):
response = self.client.get("/")
- policy = response["Content-Security-Policy-Report-Only"]
+ policy = response[header]
assert "default-src 'self'" in policy
assert "report-uri" not in policy
assert "report-to" not in policy
@@ -164,35 +179,12 @@ class TestCSPMiddleware(APIBaseTest):
def test_report_endpoint_is_configurable(self):
# An operator can point reporting at their own install, so nothing may hardcode ours.
response = self.client.get("/")
- policy = response["Content-Security-Policy-Report-Only"]
- assert "report-uri https://posthog.example.com/report/?sample_rate=0.1" in policy
+ policy = response["Content-Security-Policy"]
+ assert "report-uri https://posthog.example.com/report/" in policy
header = response["Reporting-Endpoints"]
assert "us.i.posthog.com" not in header
assert f"distinct_id={self.user.distinct_id}" in header
- @parameterized.expand(
- [
- ("staff", True, "1", "0.1"),
- ("not_staff", False, "0.1", "1"),
- ]
- )
- @override_settings(CSP_REPORT_ENDPOINT="https://posthog.example.com/report/")
- def test_staff_report_every_violation_while_everyone_else_is_sampled(
- self, _name, is_staff, expected_rate, other_rate
- ):
- # Staff get the policy enforced ahead of everyone else, so a violation of theirs is
- # something already broken for a colleague rather than one sample of a trend. At 0.1 nine
- # in ten of those never arrive, which defeats the point of rolling out to staff first.
- self.user.is_staff = is_staff
- self.user.save()
-
- response = self.client.get("/")
-
- policy = response["Content-Security-Policy-Report-Only"]
- assert f"report-uri https://posthog.example.com/report/?sample_rate={expected_rate}" in policy
- assert f"sample_rate={expected_rate}&distinct_id={self.user.distinct_id}" in policy
- assert f"sample_rate={other_rate}" not in policy
-
@parameterized.expand(
[
("cloud", {"CLOUD_DEPLOYMENT": "US"}, True),
@@ -213,7 +205,7 @@ class TestCSPMiddleware(APIBaseTest):
if expects_reporting:
assert "report-uri https://us.i.posthog.com/report/" in policy
- # Sampling the admin policy too would silently drop violations, so the branches diverge.
+ # Sampling would silently drop violations.
assert "sample_rate" not in policy
# Without it every admin report arrives under a freshly minted id, so one staff session
# counts as many users.
@@ -230,8 +222,9 @@ class TestCSPMiddleware(APIBaseTest):
# after it navigates away. The admin policy there would refuse every request the app makes
# to another origin.
response = self.client.get("/admin/")
- assert "frame-ancestors 'none'" not in response["Content-Security-Policy"]
- assert "connect-src 'self'" in response["Content-Security-Policy-Report-Only"]
+ policy = response["Content-Security-Policy"]
+ assert "frame-ancestors 'none'" not in policy
+ assert "connect-src 'self'" in policy
@parameterized.expand(
[
@@ -272,13 +265,11 @@ class TestCSPMiddleware(APIBaseTest):
self, _name: str, overrides: dict[str, str | None], regions: tuple[str, str] | None
) -> None:
# Cloud enforces the app policy for everyone, so the enforced header is the one that must be narrowed.
- with (
- override_settings(TEST=False, DEBUG=False, **overrides),
- patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True),
- ):
+ with override_settings(TEST=False, DEBUG=False, **overrides):
response = self.client.get("/")
- policy = response["Content-Security-Policy"]
+ # A self-hosted install only reports the policy.
+ policy = response["Content-Security-Policy" if regions else "Content-Security-Policy-Report-Only"]
directives = {name: sources for name, *sources in (part.split() for part in policy.split("; "))}
script_src, connect_src = directives["script-src"], directives["connect-src"]
(report_uri,) = directives["report-uri"]
@@ -305,6 +296,7 @@ class TestCSPMiddleware(APIBaseTest):
assert not any(other_region in (urlsplit(source).hostname or "").split(".") for source in connect_src)
+@override_settings(CLOUD_DEPLOYMENT="LOCAL")
class TestAppCspHeaderName(SimpleTestCase):
def _request(
self, path: str, *, distinct_id: str | None = "abc", email: str = "[email protected]"
@@ -334,92 +326,53 @@ class TestAppCspHeaderName(SimpleTestCase):
@parameterized.expand(
[
- ("app_root", "/"),
- ("project_page", "/project/2/dashboard"),
+ ("app_root", "/", "abc", False),
+ ("project_page", "/project/2/dashboard", "abc", False),
# 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"),
- ("exporter_prefix_without_separator", "/exporterthing"),
+ ("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),
]
)
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)
- def test_ordinary_page_is_enforced_for_a_flagged_user(self, _name, path, _mock_flag):
- assert app_csp_header_name(self._request(path)) == "Content-Security-Policy"
-
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=False)
- def test_ordinary_page_stays_report_only_without_the_flag(self, _mock_flag):
- assert app_csp_header_name(self._request("/")) == "Content-Security-Policy-Report-Only"
-
- @patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=True)
- def test_the_flag_lookup_carries_the_email_for_local_evaluation(self, mock_flag):
- # Local evaluation cannot resolve a condition on email unless the caller supplies it, so a
- # staff-only rollout would enforce nothing.
- app_csp_header_name(self._request("/", email="[email protected]"))
- assert mock_flag.call_args.kwargs["person_properties"] == {"email": "[email protected]"}
- # Local evaluation keeps a flag network call out of every HTML response.
- assert mock_flag.call_args.kwargs["only_evaluate_locally"] is True
+ @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
+ )
+ assert app_csp_header_name(self._request(path, distinct_id=distinct_id)) == "Content-Security-Policy"
@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",
- ),
+ ("other_signed_out_page", "/messaging-preferences/abc"),
+ ("login_prefix_without_separator", "/loginfoo"),
]
)
- @patch("posthog.csp_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.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:
+ # 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("/login", distinct_id=None))
- app_csp_header_name(self._request("/login", distinct_id=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)
@@ -427,14 +380,11 @@ class TestAppCspHeaderName(SimpleTestCase):
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.csp_middleware.posthoganalytics.feature_enabled", side_effect=Exception("flags unavailable"))
- def test_a_failing_flag_lookup_leaves_the_policy_report_only(
- self, _name: str, distinct_id: str | None, _mock_flag: MagicMock
- ) -> None:
+ 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("/login", distinct_id=distinct_id))
+ app_csp_header_name(self._request("/messaging-preferences/abc", distinct_id=None))
== "Content-Security-Policy-Report-Only"
)
@@ -471,19 +421,18 @@ class TestNarrowedAppPolicy(SimpleTestCase):
class TestViewManagedCsp(SimpleTestCase):
@parameterized.expand(
[
- ("custom_policy", "/", False, "default-src 'self'", False),
# The workflow asset endpoint sandboxes captured email HTML and leaves frame-ancestors
# open so the app can frame it. Enforcement must not replace that policy, because the
# app policy drops the sandbox and names a frame-ancestors list the app origin does not
# match, which blanks the viewer.
- ("custom_policy_under_enforcement", "/", True, "sandbox; default-src 'none'", False),
- ("custom_admin", "/admin/", False, "default-src *", True),
- ("no_policy", "/", False, None, True),
+ ("custom_policy", "/", "sandbox; default-src 'none'", False),
+ ("custom_admin", "/admin/", "default-src *", True),
+ ("no_policy", "/", None, True),
]
)
@override_settings(CLOUD_DEPLOYMENT="US")
def test_html_response_with_view_managed_csp(
- self, _name: str, path: str, enforced: bool, policy: str | None, expects_reporting: bool
+ self, _name: str, path: str, policy: str | None, expects_reporting: bool
) -> None:
def view(_request: HttpRequest) -> HttpResponse:
response = HttpResponse("<html><body>artifact</body></html>", content_type="text/html; charset=utf-8")
@@ -493,15 +442,14 @@ class TestViewManagedCsp(SimpleTestCase):
request = RequestFactory().get(path)
request.user = MagicMock(is_authenticated=True, distinct_id="abc", email="[email protected]")
- with patch("posthog.csp_middleware.posthoganalytics.feature_enabled", return_value=enforced):
- response = CSPMiddleware(view)(request)
+ response = CSPMiddleware(view)(request)
if path == "/admin/":
assert "frame-ancestors 'none'" in response["Content-Security-Policy"]
assert "default-src *" not in response["Content-Security-Policy"]
elif policy is not None:
assert response["Content-Security-Policy"] == policy
+ assert "Content-Security-Policy-Report-Only" not in response
else:
- assert response["Content-Security-Policy"].startswith("frame-ancestors ")
- assert ("Content-Security-Policy-Report-Only" in response) == (expects_reporting and path != "/admin/")
+ assert response["Content-Security-Policy"].startswith("default-src 'self'")
assert ("Reporting-Endpoints" in response) == expects_reporting