: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
fix(messaging): validate preferences token format before lookup (#116715)
Tom Piccirelloc6e791e91d40
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 949fe4826800..4b8aa26316c4 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -1,3 +1,4 @@+import reimport jsonfrom datetime import timedeltafrom typing import Optional, Union@@ -288,7 +289,24 @@ def generate_messaging_preferences_token(team_id: int, identifier: str) -> str:return ""+# A preferences token is a three-segment base64url JWT. The charset has no path separators, so a+# conforming token cannot alter the request path when interpolated below. Reject anything else+# before the call, so an unauthenticated caller can't steer this internal, secret-bearing request+# at another CDP endpoint (requests collapses `..` path segments).+_PREFERENCES_TOKEN_RE = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+")+++def _invalid_token_response() -> requests.Response:+ response = requests.Response()+ response.status_code = 400+ response._content = json.dumps({"error": "Invalid recipient token"}).encode()+ response.headers["Content-Type"] = "application/json"+ return response++def validate_messaging_preferences_token(token: str) -> requests.Response:+ if not isinstance(token, str) or not _PREFERENCES_TOKEN_RE.fullmatch(token):+ return _invalid_token_response()return internal_requests.get(CDP_API_URL + f"/api/messaging/validate_preferences_token/{token}",headers=get_internal_api_headers(),diff --git a/posthog/plugins/test/test_plugin_server_api.py b/posthog/plugins/test/test_plugin_server_api.pynew file mode 100644index 000000000000..a822994905df--- /dev/null+++ b/posthog/plugins/test/test_plugin_server_api.py@@ -0,0 +1,37 @@+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.plugins.plugin_server_api import validate_messaging_preferences_token++VALID_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJ0ZWFtX2lkIjoxLCJpZGVudGlmaWVyIjoiYUBiLmNvbSJ9.c2ln"+++class TestValidateMessagingPreferencesToken(SimpleTestCase):+ @parameterized.expand(+ [+ ("path_traversal", "../../hog_functions/states?teamId=1"),+ ("leading_slash", "/api/hog_functions/states"),+ ("query_injection", "x?teamId=1"),+ ("fragment", "x#frag"),+ ("empty", ""),+ ("not_a_jwt", "just-one-segment"),+ ]+ )+ @patch("posthog.plugins.plugin_server_api.internal_requests")+ def test_malformed_token_never_calls_cdp(self, _name, token, mock_internal_requests):+ response = validate_messaging_preferences_token(token)++ mock_internal_requests.get.assert_not_called()+ self.assertEqual(response.status_code, 400)+ self.assertEqual(response.json(), {"error": "Invalid recipient token"})++ @patch("posthog.plugins.plugin_server_api.internal_requests")+ def test_valid_token_calls_cdp_at_unaltered_path(self, mock_internal_requests):+ validate_messaging_preferences_token(VALID_TOKEN)++ mock_internal_requests.get.assert_called_once()+ called_url = mock_internal_requests.get.call_args.args[0]+ self.assertTrue(called_url.endswith(f"/api/messaging/validate_preferences_token/{VALID_TOKEN}"))