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): attribute push subscription rejections to the SDK (#91522)

Daniel Marchukae6a16ff64d9
diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.py
index b7d948dc3dca..9099c84e00ac 100644
--- a/products/messaging/backend/api/push_subscriptions.py
+++ b/products/messaging/backend/api/push_subscriptions.py
@@ -1,6 +1,9 @@
+import hmac
import time
+import hashlib
from datetime import UTC, datetime
+from django.conf import settings
from django.core.cache import cache
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
@@ -13,6 +16,7 @@ from rest_framework.request import Request
from posthog.api.capture import capture_internal
from posthog.api.utils import get_token
+from posthog.dataclasses import frozen
from posthog.exceptions import (
RequestParsingError,
UnspecifiedCompressionFallbackParsingError,
@@ -147,6 +151,35 @@ 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.
+@frozen
+class _SdkIdentity:
+ # name and version are both optional strings, so a dataclass with named fields keeps them from
+ # being read or swapped positionally.
+ name: str | None = None
+ version: str | None = None
+
+
+def _parse_user_agent_sdk(request: Request) -> _SdkIdentity:
+ # PostHog SDKs identify as "posthog-<name>/<version>" (for example posthog-android/3.59.0). Parse
+ # it so a rejection can be attributed to the SDK or wrapper from this log alone, without joining
+ # access logs. Bound each part and ignore any non-PostHog user agent so the field stays a fixed
+ # shape and an arbitrary user agent cannot bloat the log line.
+ user_agent = request.META.get("HTTP_USER_AGENT") or ""
+ if not user_agent.startswith("posthog-"):
+ return _SdkIdentity()
+ name, _, version = user_agent.partition("/")
+ if not version:
+ return _SdkIdentity()
+ return _SdkIdentity(name=name[:64], version=version.split()[0][:32])
+
+
+def _api_key_fingerprint(api_key: str) -> str:
+ # A stable, non-reversible fingerprint of the submitted token, so many invalid-token rejections
+ # can be grouped to one source without logging the raw credential. Keyed with the server secret
+ # so a fingerprint cannot be precomputed for a guessed token.
+ return hmac.new(settings.SECRET_KEY.encode(), api_key.encode(), hashlib.sha256).hexdigest()[:16]
+
+
def _rejection_response(
request: Request,
message: str,
@@ -157,6 +190,7 @@ def _rejection_response(
team_id: int | None = None,
app_id: str | None = None,
detail: str | None = None,
+ api_key_fingerprint: str | None = None,
exc_info: bool = False,
) -> HttpResponse:
# request.method is an arbitrary attacker-controlled token on the method_not_allowed path (any
@@ -167,14 +201,19 @@ def _rejection_response(
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.
+ sdk = _parse_user_agent_sdk(request)
logger.warning(
"push_subscription_rejected",
code=code,
status_code=status_code,
method=request.method,
team_id=team_id,
- app_id=app_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,
detail=detail,
+ sdk_name=sdk.name,
+ sdk_version=sdk.version,
+ api_key_fingerprint=api_key_fingerprint,
exc_info=exc_info,
)
return cors_response(
@@ -249,12 +288,15 @@ def push_subscriptions(request: Request):
team = Team.objects.get_team_from_cache_or_token(api_key)
if not team:
+ # Fingerprint the rejected token so a cohort of these can be traced to one bad app
+ # configuration, which is the usual cause of a burst of invalid-token rejections.
return _rejection_response(
request,
"Invalid project token.",
error_type="authentication_error",
code="invalid_api_key",
status_code=status.HTTP_401_UNAUTHORIZED,
+ api_key_fingerprint=_api_key_fingerprint(api_key),
)
distinct_id = data.get("distinct_id")
diff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.py
index 6f99a74a0842..562d2fa460cd 100644
--- a/products/messaging/backend/api/test/test_push_subscriptions.py
+++ b/products/messaging/backend/api/test/test_push_subscriptions.py
@@ -5,12 +5,13 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
-from django.test import Client
+from django.test import Client, RequestFactory, SimpleTestCase
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from parameterized import parameterized
from rest_framework import status
+from rest_framework.request import Request
from structlog.testing import capture_logs
from posthog.models.integration import Integration
@@ -21,6 +22,9 @@ from products.messaging.backend.api.push_identity_tokens import sign_push_identi
from products.messaging.backend.api.push_subscriptions import (
PUSH_SUBSCRIPTION_DISCARD_COUNTER,
PUSH_SUBSCRIPTION_REJECTION_COUNTER,
+ _api_key_fingerprint,
+ _parse_user_agent_sdk,
+ _SdkIdentity,
)
@@ -582,6 +586,36 @@ class TestPushSubscriptionsAPI(BaseTest):
assert len(rejected) == 1
assert rejected[0]["detail"] == expected_detail
+ def test_invalid_token_rejection_attributes_the_sdk_and_never_logs_the_raw_token(self):
+ bad_token = "phc_invalid_bad_token_value"
+
+ with capture_logs() as logs:
+ response = self.client.post(
+ "/api/push_subscriptions/",
+ data=json.dumps(
+ {
+ "api_key": bad_token,
+ "distinct_id": "user-1",
+ "device_token": "t",
+ "platform": "android",
+ "app_id": "proj",
+ }
+ ),
+ content_type="application/json",
+ HTTP_USER_AGENT="posthog-android/3.59.0",
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ rejected = [entry for entry in logs if entry["event"] == "push_subscription_rejected"]
+ assert len(rejected) == 1
+ entry = rejected[0]
+ assert entry["code"] == "invalid_api_key"
+ assert entry["sdk_name"] == "posthog-android"
+ assert entry["sdk_version"] == "3.59.0"
+ assert entry["api_key_fingerprint"] and entry["api_key_fingerprint"] != bad_token
+ # The raw token is a credential, so it must never reach the log, in any field.
+ assert bad_token not in json.dumps(entry)
+
def test_unsupported_method_collapses_counter_label(self):
counter = PUSH_SUBSCRIPTION_REJECTION_COUNTER.labels(code="method_not_allowed", method="other")
before = counter._value.get()
@@ -668,3 +702,32 @@ class TestPushSubscriptionsAPI(BaseTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
mock_capture.assert_not_called()
+
+
+class TestPushSubscriptionRejectionHelpers(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("android", "posthog-android/3.59.0", _SdkIdentity(name="posthog-android", version="3.59.0")),
+ (
+ "wrapper_with_suffix",
+ "posthog-flutter/1.2.3 (Dart 3.0)",
+ _SdkIdentity(name="posthog-flutter", version="1.2.3"),
+ ),
+ ("non_posthog", "okhttp/4.9.0", _SdkIdentity()),
+ ("no_version", "posthog-android", _SdkIdentity()),
+ ("empty", "", _SdkIdentity()),
+ ]
+ )
+ def test_parse_user_agent_sdk(self, _name: str, user_agent: str, expected: _SdkIdentity):
+ request = Request(RequestFactory().post("/api/push_subscriptions/", HTTP_USER_AGENT=user_agent))
+ assert _parse_user_agent_sdk(request) == expected
+
+ def test_api_key_fingerprint_is_stable_and_hides_the_token(self):
+ token = "phc_some_project_token"
+
+ fingerprint = _api_key_fingerprint(token)
+
+ assert fingerprint == _api_key_fingerprint(token)
+ assert fingerprint != token
+ assert len(fingerprint) == 16
+ assert _api_key_fingerprint("phc_other_token") != fingerprint