: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(workflows): accept push registrations without a platform field (#100037)
Daniel Marchuk50935fe5708f
diff --git a/docs/internal/push-subscription-registration.md b/docs/internal/push-subscription-registration.mdindex 05897f77cddf..149df8bf60eb 100644--- a/docs/internal/push-subscription-registration.md+++ b/docs/internal/push-subscription-registration.md@@ -9,6 +9,11 @@ A mobile SDK with push capture enabled posts its device token to `/api/push_subsapp starts. The server resolves the `app_id` to a Firebase or APNs integration on the team and storesthe token as a `$device_push_subscription_<app_id>` person property.+`distinct_id`, `device_token` and `app_id` are required. SDKs also send a `platform` field, which the+server ignores: nothing is stored or routed by it, and the provider is selected by `app_id`. A device+whose registration is rejected re-posts on every app open and never registers, so the server does not+reject a registration over a field it does not use.+Push is opt-in per project, and the SDK cannot see whether a project opted in. So an app that shipswith push capture on registers against every project it reports to, configured or not.@@ -91,3 +96,6 @@ SDK that implements rule 3.- Registration outcomes are observable through `push_subscription_rejection{code, method}`,`push_subscription_discarded{reason}`, and the `push_subscription_discarded` log line, which isemitted once per team per minute rather than once per request.+- A `push_subscription_rejected` log line for an invalid project token carries the request's `app_id`+ alongside the token fingerprint, so a burst of rejections from one shipped build can be traced to+ the app rather than only to an opaque fingerprint.diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.pyindex 7816774f1181..13bedfd79b56 100644--- a/products/messaging/backend/api/push_subscriptions.py+++ b/products/messaging/backend/api/push_subscriptions.py@@ -90,10 +90,13 @@ _invalid_token_cache: TTLCache = TTLCache(maxsize=_INVALID_TOKEN_CACHE_SIZE, ttl_invalid_token_lock = threading.Lock()_PUSH_INTEGRATION_KINDS = ("firebase", "apns")-VALID_PLATFORMS = ("android", "ios")+# SDKs send a `platform` field. It is ignored: the property is keyed on app_id and the provider is+# resolved from app_id alone. Rejecting on it cost a registration per device, because a rejected+# device re-posts on every app open and never registers.+# A device registration payload is a handful of short string fields (distinct_id, device_token,-# platform, app_id, api_key) — well under 1 KiB. Cap the raw request body far above that but far below+# app_id, api_key) — well under 1 KiB. Cap the raw request body far above that but far below# Django's global limit, so a compressed body can't inflate into a memory-exhaustion payload when# load_data_from_request decompresses it.MAX_BODY_BYTES = 16 * 1024@@ -240,7 +243,8 @@ def _rejection_response(method=request.method,team_id=team_id,# app_id is client-supplied, so bound it to keep a hostile value from bloating the log line.- app_id=app_id[:128] if isinstance(app_id, str) else app_id,+ # A non-string (a large array or object) is dropped rather than serialized whole.+ app_id=app_id[:128] if isinstance(app_id, str) else None,detail=detail,sdk_name=sdk.name,sdk_version=sdk.version,@@ -325,6 +329,7 @@ def push_subscriptions(request: Request):code="invalid_api_key",status_code=status.HTTP_401_UNAUTHORIZED,api_key_fingerprint=_api_key_fingerprint(api_key),+ app_id=data.get("app_id"),)team = Team.objects.get_team_from_cache_or_token(api_key)@@ -339,11 +344,11 @@ def push_subscriptions(request: Request):code="invalid_api_key",status_code=status.HTTP_401_UNAUTHORIZED,api_key_fingerprint=_api_key_fingerprint(api_key),+ app_id=data.get("app_id"),)distinct_id = data.get("distinct_id")device_token = data.get("device_token")- platform = data.get("platform")app_id = data.get("app_id")missing_fields = [@@ -351,7 +356,6 @@ def push_subscriptions(request: Request):for field_name, value in [("distinct_id", distinct_id),("device_token", device_token),- ("platform", platform),("app_id", app_id),]if not value or not isinstance(value, str)@@ -375,20 +379,8 @@ def push_subscriptions(request: Request):assert isinstance(distinct_id, str)assert isinstance(device_token, str)- assert isinstance(platform, str)assert isinstance(app_id, str)- if platform not in VALID_PLATFORMS:- return _rejection_response(- request,- f"Invalid platform. Must be one of: {', '.join(VALID_PLATFORMS)}.",- error_type="validation_error",- code="invalid_platform",- status_code=status.HTTP_400_BAD_REQUEST,- team_id=team.id,- app_id=app_id,- )-# Skip the JSONB lookup when the team has no integration for this app_id, which is the endpoint's# normal case. A cache miss or outage returns None and falls through to the real query.known_app_ids = _configurable_app_ids(team.id)@@ -410,7 +402,6 @@ def push_subscriptions(request: Request):JsonResponse({"distinct_id": distinct_id,- "platform": platform,"stored": False,"push_enabled": False,},@@ -488,7 +479,6 @@ def push_subscriptions(request: Request):JsonResponse({"distinct_id": distinct_id,- "platform": platform,},status=status.HTTP_200_OK,),diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.pyindex b3342704ccb4..382e1bdbeaa2 100644--- a/products/messaging/backend/api/test/test_push_subscriptions.py+++ b/products/messaging/backend/api/test/test_push_subscriptions.py@@ -112,7 +112,6 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKdata = response.json()assert data["distinct_id"] == "user-1"- assert data["platform"] == "android"mock_capture.assert_called_once()call_kwargs = mock_capture.call_args.kwargs@@ -138,7 +137,6 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKdata = response.json()assert data["distinct_id"] == "user-1"- assert data["platform"] == "ios"mock_capture.assert_called_once()call_kwargs = mock_capture.call_args.kwargs@@ -202,7 +200,6 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKdata = response.json()assert data["distinct_id"] == "user-1"- assert data["platform"] == "android"mock_capture.assert_called_once()call_kwargs = mock_capture.call_args.kwargs@@ -282,21 +279,56 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "device_token" in response.json()["detail"]- assert "platform" in response.json()["detail"]+ assert "platform" not in response.json()["detail"]assert "app_id" in response.json()["detail"]- def test_invalid_platform(self):- response = self._post(- {- "distinct_id": "user-1",- "device_token": "device-token",- "platform": "windows_phone",- "app_id": "proj",- }- )+ @parameterized.expand(+ [+ ("absent_no_user_agent", {}, None),+ ("absent_android_sdk", {}, "posthog-android/3.58.0"),+ ("absent_platform_ambiguous_sdk", {}, "posthog-flutter/5.6.0"),+ ("empty_string", {"platform": ""}, None),+ ]+ )+ def test_registration_without_a_platform_is_accepted_and_stored(+ self, _name: str, extra: dict, user_agent: str | None+ ):+ payload = {+ "distinct_id": "user-1",+ "device_token": "device-token",+ "app_id": "my-firebase-project",+ "api_key": self.team.api_token,+ **extra,+ }+ headers = {"User-Agent": user_agent} if user_agent else None- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert "Invalid platform" in response.json()["detail"]+ with patch("products.messaging.backend.api.push_subscriptions.capture_internal") as capture:+ response = self.client.post(+ "/api/push_subscriptions/",+ data=json.dumps(payload),+ content_type="application/json",+ headers=headers,+ )++ assert response.status_code == status.HTTP_200_OK+ assert "platform" not in response.json()+ assert capture.call_count == 1+ assert "$device_push_subscription_my-firebase-project" in capture.call_args.kwargs["properties"]["$set"]++ def test_platform_sent_by_older_sdks_is_ignored(self):+ with patch("products.messaging.backend.api.push_subscriptions.capture_internal") as capture:+ response = self._post(+ {+ "distinct_id": "user-1",+ "device_token": "device-token",+ "platform": "windows_phone",+ "app_id": "my-firebase-project",+ }+ )++ assert response.status_code == status.HTTP_200_OK+ assert "platform" not in response.json()+ assert capture.call_count == 1@patch("products.messaging.backend.api.push_subscriptions.capture_internal")def test_register_without_integration_returns_200_and_discards(self, mock_capture: MagicMock):@@ -553,16 +585,6 @@ class TestPushSubscriptionsAPI(BaseTest):@parameterized.expand([- (- "invalid_platform",- status.HTTP_400_BAD_REQUEST,- {- "distinct_id": "user-1",- "device_token": "fcm-device-token-abc",- "platform": "windows_phone",- "app_id": "my-firebase-project",- },- ),("missing_fields",status.HTTP_400_BAD_REQUEST,@@ -601,6 +623,26 @@ class TestPushSubscriptionsAPI(BaseTest):assert len(rejected) == 1assert rejected[0]["detail"] == expected_detail+ @parameterized.expand(+ [+ ("string", "my-firebase-project", "my-firebase-project"),+ ("non_string_is_dropped", ["x" * 64] * 64, None),+ ]+ )+ def test_invalid_token_rejection_logs_the_app_id(self, _name: str, app_id: object, logged: str | None):+ payload = {"distinct_id": "user-1", "device_token": "device-token", "app_id": app_id}++ with capture_logs() as logs:+ # The second post is served by the negative cache, a separate rejection site.+ first = self._post(payload, api_key="phc_not_a_real_token")+ second = self._post(payload, api_key="phc_not_a_real_token")++ assert first.status_code == status.HTTP_401_UNAUTHORIZED+ assert second.status_code == status.HTTP_401_UNAUTHORIZED+ rejected = [entry for entry in logs if entry["event"] == "push_subscription_rejected"]+ assert len(rejected) == 2+ assert all(entry["app_id"] == logged for entry in rejected)+def test_invalid_token_rejection_attributes_the_sdk_and_never_logs_the_raw_token(self):bad_token = "phc_invalid_bad_token_value"