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): unregister push subscriptions via DELETE endpoint (#72490)

Ioannis J96aef0c18686
diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.py
index 7498a8f74368..96ceb67bd7a2 100644
--- a/products/messaging/backend/api/push_subscriptions.py
+++ b/products/messaging/backend/api/push_subscriptions.py
@@ -17,7 +17,7 @@ from posthog.exceptions import (
from posthog.helpers.encrypted_fields import EncryptedFieldMixin
from posthog.models.integration import Integration
from posthog.models.team.team import Team
-from posthog.utils import load_data_from_request
+from posthog.utils import decompress, load_data_from_request
from posthog.utils_cors import cors_response
VALID_PLATFORMS = ("android", "ios")
@@ -51,12 +51,12 @@ def push_subscriptions(request: Request):
if request.method == "OPTIONS":
return cors_response(request, HttpResponse(""))
- if request.method != "POST":
+ if request.method not in ("POST", "DELETE"):
return cors_response(
request,
generate_exception_response(
"push_subscriptions",
- "Only POST requests are supported.",
+ "Only POST and DELETE requests are supported.",
type="validation_error",
code="method_not_allowed",
status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
@@ -76,7 +76,12 @@ def push_subscriptions(request: Request):
)
try:
- data = load_data_from_request(request)
+ if request.method == "POST":
+ data = load_data_from_request(request)
+ else:
+ # load_data_from_request only reads the body for POST (other methods read a `data` query
+ # 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(
request,
@@ -185,9 +190,19 @@ def push_subscriptions(request: Request):
),
)
- encrypted_token = _encrypted_fields.encrypt(device_token)
property_key = f"$device_push_subscription_{app_id}"
+ # $unset of an absent property is a no-op, so DELETE (logout) is idempotent. device_token is
+ # required for a symmetric contract but isn't matched against the stored value: logout clears
+ # this app_id's subscription regardless of which token the client last held.
+ properties: dict[str, dict[str, str] | list[str]]
+ if request.method == "POST":
+ properties = {"$set": {property_key: _encrypted_fields.encrypt(device_token)}}
+ failure_message = "Failed to store push subscription."
+ else:
+ properties = {"$unset": [property_key]}
+ failure_message = "Failed to remove push subscription."
+
try:
capture_internal(
token=team.api_token,
@@ -195,7 +210,7 @@ def push_subscriptions(request: Request):
event_source="push_subscriptions",
distinct_id=distinct_id,
timestamp=datetime.now(UTC),
- properties={"$set": {property_key: encrypted_token}},
+ properties=properties,
process_person_profile=True,
)
except Exception:
@@ -203,7 +218,7 @@ def push_subscriptions(request: Request):
request,
generate_exception_response(
"push_subscriptions",
- "Failed to store push subscription.",
+ failure_message,
type="server_error",
code="capture_failed",
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.py
index 7908c3bad53c..ae1a348ac2d5 100644
--- a/products/messaging/backend/api/test/test_push_subscriptions.py
+++ b/products/messaging/backend/api/test/test_push_subscriptions.py
@@ -40,6 +40,14 @@ class TestPushSubscriptionsAPI(BaseTest):
content_type="application/json",
)
+ def _delete(self, data: dict, api_key: str | None = None):
+ payload = {**data, "api_key": api_key or self.team.api_token}
+ return self.client.delete(
+ "/api/push_subscriptions/",
+ data=json.dumps(payload),
+ content_type="application/json",
+ )
+
@patch("products.messaging.backend.api.push_subscriptions.capture_internal")
def test_register_android_token(self, mock_capture: MagicMock):
mock_capture.return_value = MagicMock(status_code=200)
@@ -130,6 +138,63 @@ class TestPushSubscriptionsAPI(BaseTest):
assert isinstance(encrypted_value, str)
assert len(encrypted_value) > 0
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_unregister_unsets_the_subscription_property(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ response = self._delete(
+ {
+ "distinct_id": "user-1",
+ "device_token": "fcm-device-token-abc",
+ "platform": "android",
+ "app_id": "my-firebase-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["distinct_id"] == "user-1"
+ assert data["platform"] == "android"
+
+ mock_capture.assert_called_once()
+ call_kwargs = mock_capture.call_args.kwargs
+ assert call_kwargs["token"] == self.team.api_token
+ assert call_kwargs["distinct_id"] == "user-1"
+ assert call_kwargs["event_name"] == "$set"
+ assert call_kwargs["process_person_profile"] is True
+ # Unregister clears the property instead of storing a token.
+ assert call_kwargs["properties"] == {"$unset": ["$device_push_subscription_my-firebase-project"]}
+
+ @patch("products.messaging.backend.api.push_subscriptions.capture_internal")
+ def test_unregister_ios_token(self, mock_capture: MagicMock):
+ mock_capture.return_value = MagicMock(status_code=200)
+
+ response = self._delete(
+ {
+ "distinct_id": "user-1",
+ "device_token": "apns-device-token-abc",
+ "platform": "ios",
+ "app_id": "com.example.app",
+ }
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ 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):
+ response = self._delete(
+ {
+ "distinct_id": "user-1",
+ "device_token": "device-token",
+ "platform": "android",
+ "app_id": "nonexistent-project",
+ }
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "integration" in response.json()["detail"].lower()
+
def test_missing_api_key_returns_401(self):
response = self.client.post(
"/api/push_subscriptions/",