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(messaging): return 200 for push registration without an integration (#83456)

Harley Alexander38685f6b4f4e
diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.py
index a975b5d5456d..d212f440af96 100644
--- a/products/messaging/backend/api/push_subscriptions.py
+++ b/products/messaging/backend/api/push_subscriptions.py
@@ -4,6 +4,7 @@ from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
+import structlog
from prometheus_client import Counter
from rest_framework import status
from rest_framework.request import Request
@@ -33,6 +34,20 @@ PUSH_IDENTITY_VERIFICATION_COUNTER = Counter(
labelnames=["mode", "operation", "outcome"],
)
+PUSH_SUBSCRIPTION_REJECTION_COUNTER = Counter(
+ "push_subscription_rejection",
+ "Push subscription requests rejected, by rejection code.",
+ labelnames=["code", "method"],
+)
+
+PUSH_SUBSCRIPTION_DISCARD_COUNTER = Counter(
+ "push_subscription_discarded",
+ "Push subscription registrations acknowledged without storing, by reason.",
+ labelnames=["reason"],
+)
+
+logger = structlog.get_logger(__name__)
+
VALID_PLATFORMS = ("android", "ios")
# A device registration payload is a handful of short string fields (distinct_id, device_token,
@@ -73,33 +88,70 @@ def _strictest_verification_mode(integrations: list[Integration]) -> str:
)
+# The error body goes back to the client only, and Django's own request log records just
+# "Bad Request: /api/push_subscriptions/", so without this counter and log line the rejection
+# reason is unrecoverable from production telemetry.
+def _rejection_response(
+ request: Request,
+ message: str,
+ *,
+ error_type: str,
+ code: str,
+ status_code: int,
+ team_id: int | None = None,
+ app_id: str | None = None,
+ exc_info: bool = False,
+) -> HttpResponse:
+ # request.method is an arbitrary attacker-controlled token on the method_not_allowed path (any
+ # HTTP verb reaches this view), so bound the counter label to the supported verbs to keep
+ # Prometheus cardinality fixed. The log below keeps the raw method — structured log fields aren't
+ # a time-series cardinality risk and the real verb helps diagnose who is hitting the endpoint.
+ method_label = request.method if request.method in ("POST", "DELETE") else "other"
+ PUSH_SUBSCRIPTION_REJECTION_COUNTER.labels(code=code, method=method_label).inc()
+ # exc_info attaches the active exception's traceback for paths that swallow one (capture_failed),
+ # so a 500 is diagnosable from this single labeled event rather than just the counter.
+ logger.warning(
+ "push_subscription_rejected",
+ code=code,
+ status_code=status_code,
+ method=request.method,
+ team_id=team_id,
+ app_id=app_id,
+ exc_info=exc_info,
+ )
+ return cors_response(
+ request,
+ generate_exception_response(
+ "push_subscriptions",
+ message,
+ type=error_type,
+ code=code,
+ status_code=status_code,
+ ),
+ )
+
+
@csrf_exempt
def push_subscriptions(request: Request):
if request.method == "OPTIONS":
return cors_response(request, HttpResponse(""))
if request.method not in ("POST", "DELETE"):
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "Only POST and DELETE requests are supported.",
- type="validation_error",
- code="method_not_allowed",
- status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
- ),
+ "Only POST and DELETE requests are supported.",
+ error_type="validation_error",
+ code="method_not_allowed",
+ status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
)
if len(request.body) > MAX_BODY_BYTES:
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "Request body too large.",
- type="validation_error",
- code="request_too_large",
- status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
- ),
+ "Request body too large.",
+ error_type="validation_error",
+ code="request_too_large",
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
)
try:
@@ -110,53 +162,41 @@ def push_subscriptions(request: Request):
# param). DELETE carries the same gzipped JSON body as POST, so decompress it directly.
data = decompress(request.body, request.headers.get("content-encoding", "").lower())
except (RequestParsingError, UnspecifiedCompressionFallbackParsingError):
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "Invalid JSON body.",
- type="validation_error",
- code="invalid_json",
- status_code=status.HTTP_400_BAD_REQUEST,
- ),
+ "Invalid JSON body.",
+ error_type="validation_error",
+ code="invalid_json",
+ status_code=status.HTTP_400_BAD_REQUEST,
)
if not isinstance(data, dict):
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "Invalid JSON body.",
- type="validation_error",
- code="invalid_json",
- status_code=status.HTTP_400_BAD_REQUEST,
- ),
+ "Invalid JSON body.",
+ error_type="validation_error",
+ code="invalid_json",
+ status_code=status.HTTP_400_BAD_REQUEST,
)
api_key = get_token(data, request)
if not api_key:
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "Project token not provided. You can find your project token in your PostHog project settings.",
- type="authentication_error",
- code="missing_api_key",
- status_code=status.HTTP_401_UNAUTHORIZED,
- ),
+ "Project token not provided. You can find your project token in your PostHog project settings.",
+ error_type="authentication_error",
+ code="missing_api_key",
+ status_code=status.HTTP_401_UNAUTHORIZED,
)
team = Team.objects.get_team_from_cache_or_token(api_key)
if not team:
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "Invalid project token.",
- type="authentication_error",
- code="invalid_api_key",
- status_code=status.HTTP_401_UNAUTHORIZED,
- ),
+ "Invalid project token.",
+ error_type="authentication_error",
+ code="invalid_api_key",
+ status_code=status.HTTP_401_UNAUTHORIZED,
)
distinct_id = data.get("distinct_id")
@@ -175,15 +215,13 @@ def push_subscriptions(request: Request):
if not value or not isinstance(value, str)
]
if missing_fields:
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- f"Missing required fields: {', '.join(missing_fields)}.",
- type="validation_error",
- code="missing_fields",
- status_code=status.HTTP_400_BAD_REQUEST,
- ),
+ f"Missing required fields: {', '.join(missing_fields)}.",
+ error_type="validation_error",
+ code="missing_fields",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ team_id=team.id,
)
assert isinstance(distinct_id, str)
@@ -192,28 +230,36 @@ def push_subscriptions(request: Request):
assert isinstance(app_id, str)
if platform not in VALID_PLATFORMS:
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- f"Invalid platform. Must be one of: {', '.join(VALID_PLATFORMS)}.",
- type="validation_error",
- code="invalid_platform",
- status_code=status.HTTP_400_BAD_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,
)
integrations = _find_integrations(team.id, app_id)
- if not integrations:
+ # A missing integration is an account state, not a request error: SDKs auto-register on every
+ # app open, so for most teams this is the endpoint's normal case, and a 4xx here turns the
+ # whole fleet into an error firehose. Acknowledge registration with a 200 and skip the store,
+ # so unconsumable tokens don't become person properties and capture events; devices re-register
+ # on every app open, so a team that later configures an integration is covered within a day.
+ # DELETE falls through: logout must clear any subscription stored while an integration existed.
+ if not integrations and request.method == "POST":
+ PUSH_SUBSCRIPTION_DISCARD_COUNTER.labels(reason="no_integration").inc()
+ logger.info("push_subscription_discarded", reason="no_integration", team_id=team.id, app_id=app_id)
return cors_response(
request,
- generate_exception_response(
- "push_subscriptions",
- f"No push integration found for app_id '{app_id}'. "
- "Please configure the integration in your PostHog project settings.",
- type="validation_error",
- code="integration_not_found",
- status_code=status.HTTP_400_BAD_REQUEST,
+ JsonResponse(
+ {
+ "distinct_id": distinct_id,
+ "platform": platform,
+ "stored": False,
+ "push_enabled": False,
+ },
+ status=status.HTTP_200_OK,
),
)
@@ -235,17 +281,16 @@ def push_subscriptions(request: Request):
outcome="verified" if verified else "unverified",
).inc()
if not verified and verification_mode == "required":
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- "A valid identity token is required for this device. Your backend must sign a "
- "short-lived token for the signed-in user with the key configured for this "
- "channel's identity verification.",
- type="authentication_error",
- code="identity_verification_failed",
- status_code=status.HTTP_401_UNAUTHORIZED,
- ),
+ "A valid identity token is required for this device. Your backend must sign a "
+ "short-lived token for the signed-in user with the key configured for this "
+ "channel's identity verification.",
+ error_type="authentication_error",
+ code="identity_verification_failed",
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ team_id=team.id,
+ app_id=app_id,
)
property_key = f"$device_push_subscription_{app_id}"
@@ -272,15 +317,15 @@ def push_subscriptions(request: Request):
process_person_profile=True,
)
except Exception:
- return cors_response(
+ return _rejection_response(
request,
- generate_exception_response(
- "push_subscriptions",
- failure_message,
- type="server_error",
- code="capture_failed",
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- ),
+ failure_message,
+ error_type="server_error",
+ code="capture_failed",
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ team_id=team.id,
+ app_id=app_id,
+ exc_info=True,
)
return cors_response(
diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.py
index 8ad3e51e2bb4..88685f419ade 100644
--- a/products/messaging/backend/api/test/test_push_subscriptions.py
+++ b/products/messaging/backend/api/test/test_push_subscriptions.py
@@ -8,6 +8,7 @@ from django.test import Client
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
+from parameterized import parameterized
from rest_framework import status
from posthog.models.integration import Integration
@@ -15,6 +16,10 @@ from posthog.models.team.team import Team
from posthog.models.team.team_caching import set_team_in_cache
from products.messaging.backend.api.push_identity_tokens import sign_push_identity_token, sign_push_identity_token_es256
+from products.messaging.backend.api.push_subscriptions import (
+ PUSH_SUBSCRIPTION_DISCARD_COUNTER,
+ PUSH_SUBSCRIPTION_REJECTION_COUNTER,
+)
def _es256_keypair() -> tuple[str, str]:
@@ -213,7 +218,10 @@ class TestPushSubscriptionsAPI(BaseTest):
call_kwargs = mock_capture.call_args.kwargs
assert call_kwargs["properties"]["$unset"] == ["$device_push_subscription_com.example.app"]
- def test_unregister_integration_not_found(self):
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_unregister_without_integration_still_unsets(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
response = self._delete(
{
"distinct_id": "user-1",
@@ -223,8 +231,9 @@ class TestPushSubscriptionsAPI(BaseTest):
}
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "integration" in response.json()["detail"].lower()
+ assert response.status_code == status.HTTP_200_OK
+ call_kwargs = mock_capture.call_args.kwargs
+ assert call_kwargs["properties"]["$unset"] == ["$device_push_subscription_nonexistent-project"]
def test_missing_api_key_returns_401(self):
response = self.client.post(
@@ -264,7 +273,11 @@ class TestPushSubscriptionsAPI(BaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "Invalid platform" in response.json()["detail"]
- def test_integration_not_found(self):
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_register_without_integration_returns_200_and_discards(self, mock_capture: MagicMock):
+ counter = PUSH_SUBSCRIPTION_DISCARD_COUNTER.labels(reason="no_integration")
+ before = counter._value.get()
+
response = self._post(
{
"distinct_id": "user-1",
@@ -274,10 +287,15 @@ class TestPushSubscriptionsAPI(BaseTest):
}
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "integration" in response.json()["detail"].lower()
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["stored"] is False
+ assert data["push_enabled"] is False
+ mock_capture.assert_not_called()
+ assert counter._value.get() == before + 1
- def test_team_isolation(self):
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_team_isolation(self, mock_capture: MagicMock):
other_team = Team.objects.create(organization=self.organization, name="Other Team")
Integration.objects.create(
team=other_team,
@@ -296,8 +314,9 @@ class TestPushSubscriptionsAPI(BaseTest):
}
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "integration" in response.json()["detail"].lower()
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["stored"] is False
+ mock_capture.assert_not_called()
def test_get_method_not_allowed(self):
response = self.client.get(
@@ -437,6 +456,48 @@ class TestPushSubscriptionsAPI(BaseTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
mock_capture.assert_not_called()
+ @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,
+ {
+ "distinct_id": "user-1",
+ "platform": "android",
+ "app_id": "my-firebase-project",
+ },
+ ),
+ ]
+ )
+ def test_rejection_increments_counter_with_code(self, code: str, status_code: int, payload: dict):
+ counter = PUSH_SUBSCRIPTION_REJECTION_COUNTER.labels(code=code, method="POST")
+ before = counter._value.get()
+
+ response = self._post(payload)
+
+ assert response.status_code == status_code
+ assert response.json()["code"] == code
+ assert counter._value.get() == before + 1
+
+ def test_unsupported_method_collapses_counter_label(self):
+ counter = PUSH_SUBSCRIPTION_REJECTION_COUNTER.labels(code="method_not_allowed", method="other")
+ before = counter._value.get()
+
+ response = self.client.patch("/api/push_subscriptions/", data="{}", content_type="application/json")
+
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+ assert counter._value.get() == before + 1
+
@patch("products.messaging.backend.api.push_subscriptions.capture_internal")
def test_optional_mode_stores_even_without_a_token(self, mock_capture: MagicMock):
mock_capture.return_value = MagicMock(status_code=200)