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.

chore(workflows): serve push registrations only from the node push-api (#116924)

Daniel Marchuka27b562e3529
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index 09fc80907a90..a8984a24f95a 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -155,6 +155,15 @@ procs:
layer: Product services
tech: Node
+ push-api:
+ sandbox: true
+ shell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=push-api HTTP_SERVER_PORT=6746 ./bin/posthog-node'
+ capability: nodejs_cdp_workflows
+ ready_pattern: 'All systems go'
+ groups:
+ layer: Product services
+ tech: Node
+
frontend:
sandbox: true
shell: './bin/start-frontend'
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 32ca54beca2f..3232173c76f1 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -30,6 +30,7 @@ services:
- 'replay-capture:host-gateway'
- 'feature-flags:host-gateway'
- 'hypercache-server:host-gateway'
+ - 'push-api:host-gateway'
environment:
CADDYFILE: |
{
@@ -100,6 +101,11 @@ services:
path /public/m/*
}
+ @push-subscriptions {
+ path /api/push_subscriptions
+ path /api/push_subscriptions/
+ }
+
handle @capture-ai {
reverse_proxy capture-ai:3309
}
@@ -136,6 +142,10 @@ services:
reverse_proxy plugins:6738
}
+ handle @push-subscriptions {
+ reverse_proxy push-api:6750
+ }
+
handle {
reverse_proxy web:8000
}
diff --git a/posthog/urls.py b/posthog/urls.py
index 47b0daa8ca94..06dbc2658e4e 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -49,7 +49,6 @@ from products.customer_analytics.backend.presentation.views.internal import (
)
from products.early_access_features.backend.api import early_access_features
from products.messaging.backend.presentation.views.customerio_webhook import CustomerIOWebhookView
-from products.messaging.backend.presentation.views.push_subscriptions import push_subscriptions
from products.messaging.backend.presentation.views.recipient_preferences import preferences_page, update_preferences
from products.notebooks.backend.facade.sql_v2 import (
notebook_sql_v2_callback,
@@ -182,7 +181,6 @@ urlpatterns = [
opt_slash_path("api/user/redirect_to_website", user.redirect_to_website),
opt_slash_path("api/early_access_features", early_access_features),
opt_slash_path("api/web_experiments", web_experiments),
- opt_slash_path("api/push_subscriptions", push_subscriptions),
opt_slash_path("api/product_tours", product_tours),
re_path(r"^external_surveys/(?P<survey_id>[^/]+)/?$", public_survey_page),
opt_slash_path("api/signup/precheck", signup.SignupEmailPrecheckViewset.as_view()),
diff --git a/products/messaging/backend/presentation/views/push_subscriptions.py b/products/messaging/backend/presentation/views/push_subscriptions.py
deleted file mode 100644
index 25a26b6ed809..000000000000
--- a/products/messaging/backend/presentation/views/push_subscriptions.py
+++ /dev/null
@@ -1,516 +0,0 @@
-import hmac
-import time
-import hashlib
-import threading
-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
-from django.views.decorators.csrf import csrf_exempt
-
-import structlog
-from cachetools import TTLCache
-from prometheus_client import Counter
-from rest_framework import status
-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,
- generate_exception_response,
-)
-from posthog.helpers.encrypted_fields import EncryptedFieldMixin
-from posthog.models.integration import Integration
-from posthog.models.team.team import Team
-from posthog.utils import decompress, load_data_from_request
-from posthog.utils_cors import cors_response
-
-from products.messaging.backend.presentation.views.push_identity_tokens import verify_push_identity_token
-
-# Identity verification is opt-in per integration via config["push_identity_verification"]:
-# "disabled" (default) — no token required; anyone with the public project token can register.
-# "optional" — a token is verified and recorded when present, but never required.
-# "required" — registration/unregistration is rejected without a valid identity token.
-PUSH_IDENTITY_VERIFICATION_COUNTER = Counter(
- "push_subscription_identity_verification",
- "Outcome of push subscription identity token verification.",
- 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__)
-
-# Discarding a registration is this endpoint's normal case: a device registers on app open whether or
-# not its project has a push integration, and most don't. The counter above carries that volume. The
-# log line exists to name the project behind it, and that is the same team and app_id every time, so
-# emitting it per request restates one fact indefinitely. One line per team per window keeps the
-# identification and drops the repetition.
-_DISCARD_LOG_WINDOW_SECONDS = 60
-
-# That same path runs _find_integrations, a JSONB filter, on every request. Cache the team's
-# configured app_ids so a registration for an app_id the team has never configured — the common case
-# — answers from cache instead. Keyed on the team alone: the value is a small bounded list, whereas
-# keying on the request's app_id would let one public project token mint unbounded entries.
-#
-# Staleness costs at most one window: a team that configures push keeps discarding for up to a minute,
-# and the device re-posts on its next launch anyway.
-_CONFIGURED_APP_IDS_CACHE_SECONDS = 60
-
-# A token that resolves to no team costs a Redis miss and then a Postgres query on every request,
-# and the lookup has no negative cache of its own. A misconfigured mobile client repeats the same
-# unknown token on every app open, so that query runs at the client's retry rate indefinitely.
-#
-# This cache is in-process and size-bounded, not in Redis. The token is request-controlled and this
-# endpoint is public, so a Redis key per submitted value would let anyone grow the shared cache and
-# evict unrelated entries. A TTLCache holds at most _INVALID_TOKEN_CACHE_SIZE entries per worker and
-# evicts its own oldest, so the memory cost is fixed no matter what callers send.
-#
-# The TTL is short on purpose. A token can become valid, for example when a project is recreated,
-# and this bounds how long such a token keeps being rejected after that.
-_INVALID_TOKEN_CACHE_SECONDS = 60
-_INVALID_TOKEN_CACHE_SIZE = 2048
-_invalid_token_cache: TTLCache = TTLCache(maxsize=_INVALID_TOKEN_CACHE_SIZE, ttl=_INVALID_TOKEN_CACHE_SECONDS)
-# cachetools is not thread-safe and Granian serves requests on threads within a worker.
-_invalid_token_lock = threading.Lock()
-_PUSH_INTEGRATION_KINDS = ("firebase", "apns")
-
-# 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,
-# 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
-
-# Shared instance: deriving the encryption keys runs PBKDF2 (100k iterations per key) and is
-# cached on the instance, so a module-level singleton avoids re-deriving on every request.
-_encrypted_fields = EncryptedFieldMixin()
-
-DEVICE_SUBSCRIPTION_PREFIX = "$device_push_subscription_"
-
-
-# Verification-mode precedence. An app_id can match more than one integration — config identifiers
-# (project_id / bundle_id) aren't covered by a uniqueness constraint — so mode resolution must fail
-# closed: take the strictest mode across every match so a lax duplicate can't downgrade a sibling's
-# `required` policy. Unknown/garbage values sort to 0 (treated as disabled).
-_VERIFICATION_MODE_PRECEDENCE = {"disabled": 0, "optional": 1, "required": 2}
-
-
-def _is_known_invalid_token(api_key: str) -> bool:
- """True when this worker resolved this token to no team recently. Stores a fingerprint rather
- than the token itself, so the raw value is never held."""
- with _invalid_token_lock:
- return _api_key_fingerprint(api_key) in _invalid_token_cache
-
-
-def _remember_invalid_token(api_key: str) -> None:
- with _invalid_token_lock:
- _invalid_token_cache[_api_key_fingerprint(api_key)] = True
-
-
-def _is_first_discard_in_window(team_id: int) -> bool:
- """Keyed on the team and the window only. app_id is request-controlled and can fill most of the
- 16 KiB body, and the project token that reaches this endpoint ships inside every copy of the app,
- so keying on it would let anyone mint unbounded cache entries. Keyed on the window so a missed
- expiry can never wedge the log shut, and fails open: losing the cache must not lose the only line
- that names the project."""
- window = int(time.time()) // _DISCARD_LOG_WINDOW_SECONDS
- try:
- return cache.add(f"push_subscriptions:discarded:{team_id}:{window}", 1, _DISCARD_LOG_WINDOW_SECONDS)
- except Exception:
- return True
-
-
-def _configurable_app_ids(team_id: int) -> list[str] | None:
- """The app_ids this team has a push integration for, or None when the cache is unavailable.
- None means "don't know", so the caller falls through to the real lookup rather than discarding a
- registration a team is entitled to."""
- key = f"push_subscriptions:app_ids:{team_id}"
- try:
- cached = cache.get(key)
- if cached is not None:
- return cached
- app_ids = [
- app_id
- for integration in Integration.objects.filter(team_id=team_id, kind__in=_PUSH_INTEGRATION_KINDS).only(
- "kind", "config"
- )
- if isinstance(
- app_id := integration.config.get("project_id" if integration.kind == "firebase" else "bundle_id"), str
- )
- ]
- cache.set(key, app_ids, _CONFIGURED_APP_IDS_CACHE_SECONDS)
- return app_ids
- except Exception:
- return None
-
-
-# Resolve integrations from the app_id alone, not the device platform. An app_id is either a
-# Firebase project_id or an APNs bundle_id, so a device can register with either provider regardless
-# of its OS — e.g. an iOS device delivering through Firebase registers with the Firebase project_id.
-# (The client still sends its platform, but it's metadata, not what selects the provider.)
-def _find_integrations(team_id: int, app_id: str) -> list[Integration]:
- return list(
- Integration.objects.filter(team_id=team_id)
- .filter(Q(kind="firebase", config__project_id=app_id) | Q(kind="apns", config__bundle_id=app_id))
- .only("id", "config")
- )
-
-
-def _strictest_verification_mode(integrations: list[Integration]) -> str:
- return max(
- (integration.config.get("push_identity_verification", "disabled") for integration in integrations),
- key=lambda mode: _VERIFICATION_MODE_PRECEDENCE.get(mode, 0),
- default="disabled",
- )
-
-
-# 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 device_subscription_key(app_id: str, device_token: str) -> str:
- """Person property key holding one device's push token.
-
- Naming the device in the key is what lets a person hold several devices on one app; a key on the
- app alone holds one token, and a second device on the same platform replaces the first.
-
- The device part is a digest of the token rather than a client-supplied id, so an SDK already in
- the field lands on the right key without shipping a new build. A device that keeps its token
- re-registers onto the same key. A device whose token rotates lands on a new key, and the provider
- reports the old one unregistered on the next send, which prunes it.
-
- A colon separates the two parts. Neither a Firebase project id nor an APNs bundle id can contain
- one, so the app part of an existing key can never be read as an app plus a device.
- """
- return f"{DEVICE_SUBSCRIPTION_PREFIX}{app_id}:{hashlib.sha256(device_token.encode()).hexdigest()[:16]}"
-
-
-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,
- *,
- error_type: str,
- code: str,
- status_code: int,
- 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
- # 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.
- 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 is client-supplied, so bound it to keep a hostile value from bloating the log line.
- # 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,
- api_key_fingerprint=api_key_fingerprint,
- 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 _rejection_response(
- request,
- "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 _rejection_response(
- request,
- "Request body too large.",
- error_type="validation_error",
- code="request_too_large",
- status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
- )
-
- try:
- 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 _rejection_response(
- request,
- "Invalid JSON body.",
- error_type="validation_error",
- code="invalid_json",
- status_code=status.HTTP_400_BAD_REQUEST,
- )
-
- if not isinstance(data, dict):
- return _rejection_response(
- 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 _rejection_response(
- request,
- "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,
- )
-
- if _is_known_invalid_token(api_key):
- 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),
- app_id=data.get("app_id"),
- )
-
- team = Team.objects.get_team_from_cache_or_token(api_key)
- if not team:
- _remember_invalid_token(api_key)
- # 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),
- app_id=data.get("app_id"),
- )
-
- distinct_id = data.get("distinct_id")
- device_token = data.get("device_token")
- app_id = data.get("app_id")
-
- missing_fields = [
- field_name
- for field_name, value in [
- ("distinct_id", distinct_id),
- ("device_token", device_token),
- ("app_id", app_id),
- ]
- if not value or not isinstance(value, str)
- ]
- if missing_fields:
- # absent vs empty vs invalid separates an SDK that never sends the field (contract drift)
- # from a client bridge passing an empty or mistyped value: they need different fixes.
- field_detail = ",".join(
- f"{field_name}:{'absent' if field_name not in data else 'empty' if data[field_name] == '' else 'invalid'}"
- for field_name in missing_fields
- )
- return _rejection_response(
- 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,
- detail=field_detail,
- )
-
- assert isinstance(distinct_id, str)
- assert isinstance(device_token, str)
- assert isinstance(app_id, str)
-
- # 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)
- integrations = (
- [] if known_app_ids is not None and app_id not in known_app_ids else _find_integrations(team.id, app_id)
- )
- # 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()
- if _is_first_discard_in_window(team.id):
- logger.info("push_subscription_discarded", reason="no_integration", team_id=team.id, app_id=app_id)
- return cors_response(
- request,
- JsonResponse(
- {
- "distinct_id": distinct_id,
- "stored": False,
- "push_enabled": False,
- # The status code cannot say this: a 4xx would make every SDK retry on every app
- # open. Without a reason in the body, a developer whose token goes nowhere sees a
- # success and has no way to tell the difference from a working registration.
- "reason": "no_push_channel_for_app_id",
- "detail": (
- f"This project has no push channel for app_id '{app_id}'. The device token was "
- "not stored. Add a push channel whose Firebase project id or APNs bundle id "
- "matches this app_id, and check the project the SDK is sending to."
- ),
- },
- status=status.HTTP_200_OK,
- ),
- )
-
- operation = "register" if request.method == "POST" else "unregister"
- verification_mode = _strictest_verification_mode(integrations)
- if verification_mode in ("optional", "required"):
- identity_token = data.get("identity_token")
- # Public keys can live on more than one matching integration; try them all.
- public_keys = [
- key for integration in integrations for key in (integration.config.get("push_identity_public_keys") or [])
- ]
- verified = isinstance(identity_token, str) and verify_push_identity_token(
- identity_token, distinct_id, app_id, public_keys=public_keys
- )
- PUSH_IDENTITY_VERIFICATION_COUNTER.labels(
- mode=verification_mode,
- operation=operation,
- outcome="verified" if verified else "unverified",
- ).inc()
- if not verified and verification_mode == "required":
- return _rejection_response(
- request,
- "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 = device_subscription_key(app_id, device_token)
- # The app-wide key holds a single device for the whole app. A device is reachable there until it
- # next registers, and the send path reads it, so one stored that way stays addressable.
- legacy_property_key = f"{DEVICE_SUBSCRIPTION_PREFIX}{app_id}"
-
- # $unset of an absent property is a no-op, so DELETE (logout) is idempotent.
- 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:
- # The legacy key goes with it. One device cannot tell whether that key holds its own token or
- # another device's, so logout clears it as it always did rather than leaving a token behind
- # that nothing can attribute.
- properties = {"$unset": [property_key, legacy_property_key]}
- failure_message = "Failed to remove push subscription."
-
- try:
- capture_internal(
- token=team.api_token,
- event_name="$set",
- event_source="push_subscriptions",
- distinct_id=distinct_id,
- timestamp=datetime.now(UTC),
- properties=properties,
- process_person_profile=True,
- )
- except Exception:
- return _rejection_response(
- request,
- 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(
- request,
- JsonResponse(
- {
- "distinct_id": distinct_id,
- },
- status=status.HTTP_200_OK,
- ),
- )
diff --git a/products/messaging/backend/remote_config.py b/products/messaging/backend/remote_config.py
index 6464879108fd..914336c9e271 100644
--- a/products/messaging/backend/remote_config.py
+++ b/products/messaging/backend/remote_config.py
@@ -1,7 +1,7 @@
from posthog.models.integration import Integration
# Firebase identifies an app by its project_id, APNs by its bundle_id. Kept in step with
-# _find_integrations in products/messaging/backend/presentation/views/push_subscriptions.py, which resolves the same
+# nodejs/src/messaging/push-subscriptions/push-subscriptions.service.ts, which resolves the same
# mapping in the opposite direction (app_id to integration).
PUSH_APP_ID_CONFIG_KEYS = {"firebase": "project_id", "apns": "bundle_id"}
diff --git a/products/messaging/backend/tests/api/test_push_subscriptions.py b/products/messaging/backend/tests/api/test_push_subscriptions.py
deleted file mode 100644
index a3bfc2f203d8..000000000000
--- a/products/messaging/backend/tests/api/test_push_subscriptions.py
+++ /dev/null
@@ -1,838 +0,0 @@
-import gzip
-import json
-
-from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
-
-from django.core.cache import cache
-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
-from posthog.models.team.team import Team
-from posthog.models.team.team_caching import set_team_in_cache
-
-from products.messaging.backend.presentation.views import push_subscriptions
-from products.messaging.backend.presentation.views.push_identity_tokens import sign_push_identity_token_es256
-from products.messaging.backend.presentation.views.push_subscriptions import (
- PUSH_SUBSCRIPTION_DISCARD_COUNTER,
- PUSH_SUBSCRIPTION_REJECTION_COUNTER,
- _api_key_fingerprint,
- _parse_user_agent_sdk,
- _SdkIdentity,
- device_subscription_key,
-)
-
-
-def _es256_keypair() -> tuple[str, str]:
- private_key = ec.generate_private_key(ec.SECP256R1())
- private_pem = private_key.private_bytes(
- serialization.Encoding.PEM,
- serialization.PrivateFormat.PKCS8,
- serialization.NoEncryption(),
- ).decode()
- public_pem = (
- private_key.public_key()
- .public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
- .decode()
- )
- return private_pem, public_pem
-
-
-class TestPushSubscriptionsAPI(BaseTest):
- def setUp(self):
- super().setUp()
- self.client = Client()
-
- self.firebase_integration = Integration.objects.create(
- team=self.team,
- kind="firebase",
- integration_id="my-firebase-project",
- config={"project_id": "my-firebase-project"},
- sensitive_config={},
- )
- self.apns_integration = Integration.objects.create(
- team=self.team,
- kind="apns",
- integration_id="TEAM123.com.example.app",
- config={"bundle_id": "com.example.app", "team_id": "TEAM123", "key_id": "KEY123"},
- sensitive_config={},
- )
- # The discard-log window counter lives in the cache, which no transaction rolls back and which
- # every test in the process shares. Tests here reuse one team id, so without this a test that
- # logged a discard would suppress the line another test asserts on.
- cache.clear()
- push_subscriptions._invalid_token_cache.clear()
-
- def _post(self, data: dict, api_key: str | None = None):
- payload = {**data, "api_key": api_key or self.team.api_token}
- return self.client.post(
- "/api/push_subscriptions/",
- data=json.dumps(payload),
- 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",
- )
-
- def _enable_identity_verification(self, mode: str):
- self.firebase_integration.config["push_identity_verification"] = mode
- self.firebase_integration.save()
- # The endpoint resolves the team from the token cache, so refresh it.
- set_team_in_cache(self.team.api_token, self.team)
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_register_android_token(self, mock_capture: MagicMock):
- mock_capture.return_value = MagicMock(status_code=200)
-
- response = self._post(
- {
- "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"
-
- 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
- assert any(
- key.startswith("$device_push_subscription_my-firebase-project:")
- for key in call_kwargs["properties"]["$set"]
- )
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_two_devices_on_one_app_are_stored_under_separate_keys(self, mock_capture: MagicMock):
- # A second device on the same app used to overwrite the first, leaving it unreachable.
- mock_capture.return_value = MagicMock(status_code=200)
-
- keys = []
- for device_token in ("fcm-token-phone", "fcm-token-tablet"):
- mock_capture.reset_mock()
- response = self._post(
- {
- "distinct_id": "user-1",
- "device_token": device_token,
- "app_id": "my-firebase-project",
- }
- )
- assert response.status_code == status.HTTP_200_OK
- keys.append(next(iter(mock_capture.call_args.kwargs["properties"]["$set"])))
-
- assert keys[0] != keys[1]
- assert keys == [
- device_subscription_key("my-firebase-project", "fcm-token-phone"),
- device_subscription_key("my-firebase-project", "fcm-token-tablet"),
- ]
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_the_same_device_registering_twice_reuses_its_key(self, mock_capture: MagicMock):
- # Re-registration must not accumulate a key per call.
- mock_capture.return_value = MagicMock(status_code=200)
-
- keys = []
- for _ in range(2):
- mock_capture.reset_mock()
- self._post(
- {
- "distinct_id": "user-1",
- "device_token": "fcm-token-phone",
- "app_id": "my-firebase-project",
- }
- )
- keys.append(next(iter(mock_capture.call_args.kwargs["properties"]["$set"])))
-
- assert keys[0] == keys[1]
-
- def test_device_key_matches_the_digest_the_send_path_derives(self):
- # The nodejs read path rebuilds this key from the same digest. If the two drift, a
- # registration lands on a key sends never look at. Pinned on both sides to this literal.
- assert (
- device_subscription_key("my-project", "device-token-abc123")
- == "$device_push_subscription_my-project:7d8d408df65cffa5"
- )
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_register_ios_token(self, mock_capture: MagicMock):
- mock_capture.return_value = MagicMock(status_code=200)
-
- response = self._post(
- {
- "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
- data = response.json()
- assert data["distinct_id"] == "user-1"
-
- mock_capture.assert_called_once()
- call_kwargs = mock_capture.call_args.kwargs
- assert any(
- key.startswith("$device_push_subscription_com.example.app:") for key in call_kwargs["properties"]["$set"]
- )
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_ios_device_registers_a_firebase_token(self, mock_capture: MagicMock):
- # An iOS app delivering via Firebase registers with the Firebase project_id even though its
- # platform is "ios": the provider is resolved from the app_id, not the device platform.
- mock_capture.return_value = MagicMock(status_code=200)
-
- response = self._post(
- {
- "distinct_id": "user-1",
- "device_token": "fcm-token-from-ios",
- "platform": "ios",
- "app_id": "my-firebase-project",
- }
- )
-
- assert response.status_code == status.HTTP_200_OK
- call_kwargs = mock_capture.call_args.kwargs
- assert any(
- key.startswith("$device_push_subscription_my-firebase-project:")
- for key in call_kwargs["properties"]["$set"]
- )
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_token_is_encrypted(self, mock_capture: MagicMock):
- mock_capture.return_value = MagicMock(status_code=200)
-
- response = self._post(
- {
- "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
-
- call_kwargs = mock_capture.call_args.kwargs
- encrypted_value = next(iter(call_kwargs["properties"]["$set"].values()))
- # The encrypted value should not be the raw token
- assert encrypted_value != "fcm-device-token-abc"
- # It should be a non-empty string (Fernet token)
- assert isinstance(encrypted_value, str)
- assert len(encrypted_value) > 0
-
- @patch("products.messaging.backend.presentation.views.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"
-
- 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_subscription_key("my-firebase-project", "fcm-device-token-abc"),
- "$device_push_subscription_my-firebase-project",
- ]
-
- @patch("products.messaging.backend.presentation.views.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"][-1] == "$device_push_subscription_com.example.app"
-
- @patch("products.messaging.backend.presentation.views.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",
- "device_token": "device-token",
- "platform": "android",
- "app_id": "nonexistent-project",
- }
- )
-
- assert response.status_code == status.HTTP_200_OK
- call_kwargs = mock_capture.call_args.kwargs
- assert call_kwargs["properties"]["$unset"][-1] == "$device_push_subscription_nonexistent-project"
-
- def test_missing_api_key_returns_401(self):
- response = self.client.post(
- "/api/push_subscriptions/",
- data=json.dumps({"distinct_id": "user-1", "device_token": "t", "platform": "android", "app_id": "proj"}),
- content_type="application/json",
- )
-
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
-
- def test_invalid_token_returns_401(self):
- response = self._post(
- {"distinct_id": "user-1", "device_token": "t", "platform": "android", "app_id": "proj"},
- api_key="phc_invalid_token",
- )
-
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
-
- def test_repeated_invalid_token_is_rejected_without_a_second_team_lookup(self):
- payload = {"distinct_id": "user-1", "device_token": "t", "platform": "android", "app_id": "proj"}
-
- with patch.object(
- Team.objects, "get_team_from_cache_or_token", wraps=Team.objects.get_team_from_cache_or_token
- ) as lookup:
- first = self._post(payload, api_key="phc_invalid_token")
- second = self._post(payload, api_key="phc_invalid_token")
-
- assert first.status_code == status.HTTP_401_UNAUTHORIZED
- assert second.status_code == status.HTTP_401_UNAUTHORIZED
- assert lookup.call_count == 1
-
- def test_missing_required_fields(self):
- response = self._post({"distinct_id": "user-1"})
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "device_token" in response.json()["detail"]
- assert "platform" not in response.json()["detail"]
- assert "app_id" in response.json()["detail"]
-
- @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
-
- with patch("products.messaging.backend.presentation.views.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 any(
- key.startswith("$device_push_subscription_my-firebase-project:")
- for key in capture.call_args.kwargs["properties"]["$set"]
- )
-
- def test_platform_sent_by_older_sdks_is_ignored(self):
- with patch("products.messaging.backend.presentation.views.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.presentation.views.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",
- "device_token": "device-token",
- "platform": "android",
- "app_id": "nonexistent-project",
- }
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert data["stored"] is False
- assert data["push_enabled"] is False
- # The 200 is what stops SDKs retrying on every app open, so the body has to carry the reason:
- # it is the only thing that tells a developer their token went nowhere.
- assert data["reason"] == "no_push_channel_for_app_id"
- assert "nonexistent-project" in data["detail"]
- mock_capture.assert_not_called()
- assert counter._value.get() == before + 1
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_discard_is_logged_once_per_window_and_counted_every_time(self, mock_capture: MagicMock):
- # The log names the project behind the discards, so it has to survive. It also has to stay
- # bounded: discarding is this endpoint's most common request, so a line per discard restates
- # one fact indefinitely. The counter carries the volume.
- counter = PUSH_SUBSCRIPTION_DISCARD_COUNTER.labels(reason="no_integration")
- before = counter._value.get()
- payload = {
- "distinct_id": "user-1",
- "device_token": "device-token",
- "platform": "android",
- "app_id": "nonexistent-project",
- }
-
- with capture_logs() as logs:
- for _ in range(5):
- assert self._post(payload).status_code == status.HTTP_200_OK
- # A different app_id from the same team stays inside the same window. app_id is
- # request-controlled, so keying the window on it would let one public project token mint
- # unbounded cache entries.
- for _ in range(2):
- assert self._post({**payload, "app_id": "another-project"}).status_code == status.HTTP_200_OK
-
- discard_logs = [log for log in logs if log["event"] == "push_subscription_discarded"]
- assert len(discard_logs) == 1
- assert discard_logs[0]["team_id"] == self.team.id
- assert discard_logs[0]["app_id"] == "nonexistent-project"
- assert counter._value.get() == before + 7
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_configured_app_registers_on_the_cached_path(self, mock_capture: MagicMock):
- # The first request fills the team's app_id cache and the second reads it. A short-circuit
- # that got those ids wrong would discard registrations the team is entitled to, and the device
- # would never retry, because a 200 marks the token delivered.
- mock_capture.return_value = MagicMock(status_code=200)
- payload = {
- "distinct_id": "user-1",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- }
-
- for _ in range(2):
- assert self._post(payload).status_code == status.HTTP_200_OK
-
- assert mock_capture.call_count == 2
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.cache")
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_configured_app_registers_when_the_cache_is_unavailable(
- self, mock_capture: MagicMock, mock_cache: MagicMock
- ):
- # Failing closed here would turn a cache outage into silent fleet-wide discards, which the
- # devices would then record as delivered.
- mock_capture.return_value = MagicMock(status_code=200)
- mock_cache.get.side_effect = Exception("cache down")
- mock_cache.add.side_effect = Exception("cache down")
-
- response = self._post(
- {
- "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
- mock_capture.assert_called_once()
-
- @patch("products.messaging.backend.presentation.views.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,
- kind="firebase",
- integration_id="other-project",
- config={"project_id": "other-project"},
- sensitive_config={},
- )
-
- response = self._post(
- {
- "distinct_id": "user-1",
- "device_token": "device-token",
- "platform": "android",
- "app_id": "other-project",
- }
- )
-
- 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(
- f"/api/push_subscriptions/?token={self.team.api_token}",
- )
-
- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
-
- def test_options_returns_200(self):
- response = self.client.options("/api/push_subscriptions/")
-
- assert response.status_code == status.HTTP_200_OK
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_gzip_compressed_body(self, mock_capture: MagicMock):
- mock_capture.return_value = MagicMock(status_code=200)
-
- payload = {
- "api_key": self.team.api_token,
- "distinct_id": "user-1",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- }
- compressed = gzip.compress(json.dumps(payload).encode())
-
- response = self.client.post(
- "/api/push_subscriptions/",
- data=compressed,
- content_type="application/json",
- HTTP_CONTENT_ENCODING="gzip",
- )
-
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["distinct_id"] == "user-1"
- mock_capture.assert_called_once()
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_oversized_body_is_rejected_before_parsing(self, mock_capture: MagicMock):
- # A body over the cap is rejected before load_data_from_request decompresses it, so a
- # compressed body can't inflate into a memory-exhaustion payload.
- oversized = json.dumps({"api_key": self.team.api_token, "padding": "x" * (16 * 1024 + 1)})
-
- response = self.client.post(
- "/api/push_subscriptions/",
- data=oversized,
- content_type="application/json",
- )
-
- assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
- mock_capture.assert_not_called()
-
- def _register_public_key(self, mode: str, public_pem: str):
- self.firebase_integration.config["push_identity_verification"] = mode
- self.firebase_integration.config["push_identity_public_keys"] = [public_pem]
- self.firebase_integration.save()
- # No shared secret is set: ES256 must verify on the public key alone.
- set_team_in_cache(self.team.api_token, self.team)
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_required_mode_accepts_an_es256_token_signed_by_the_registered_public_key(self, mock_capture: MagicMock):
- # End to end through the endpoint: the integration holds only the EC public key, the device
- # presents a token its backend signed with the private key, and registration succeeds. Guards
- # that the endpoint gathers config["push_identity_public_keys"] and threads them into
- # verification; the verifier's ES256 path is unit-tested, but nothing else drives it over HTTP.
- mock_capture.return_value = MagicMock(status_code=200)
- private_pem, public_pem = _es256_keypair()
- self._register_public_key("required", public_pem)
- token = sign_push_identity_token_es256(private_pem, "user-1", "my-firebase-project")
-
- response = self._post(
- {
- "distinct_id": "user-1",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- "identity_token": token,
- }
- )
-
- assert response.status_code == status.HTTP_200_OK
- mock_capture.assert_called_once()
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_required_mode_rejects_registration_without_a_token(self, mock_capture: MagicMock):
- self._enable_identity_verification("required")
-
- response = self._post(
- {
- "distinct_id": "user-1",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- }
- )
-
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
- assert response.json()["code"] == "identity_verification_failed"
- mock_capture.assert_not_called()
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_required_mode_rejects_a_token_minted_for_another_distinct_id(self, mock_capture: MagicMock):
- # The takeover guard: a token the attacker legitimately minted for their own distinct_id
- # cannot authorize binding a device to the victim's distinct_id.
- private_pem, public_pem = _es256_keypair()
- self._register_public_key("required", public_pem)
- attacker_token = sign_push_identity_token_es256(private_pem, "attacker", "my-firebase-project")
-
- response = self._post(
- {
- "distinct_id": "victim",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- "identity_token": attacker_token,
- }
- )
-
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
- mock_capture.assert_not_called()
-
- @parameterized.expand(
- [
- (
- "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
-
- @parameterized.expand(
- [
- ("empty_value", {"device_token": ""}, "device_token:empty"),
- ("absent_key", {}, "device_token:absent"),
- ]
- )
- def test_missing_fields_rejection_logs_field_detail(self, _name: str, extra: dict, expected_detail: str):
- payload = {"distinct_id": "user-1", "platform": "android", "app_id": "my-firebase-project", **extra}
-
- with capture_logs() as logs:
- response = self._post(payload)
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- rejected = [entry for entry in logs if entry["event"] == "push_subscription_rejected"]
- assert len(rejected) == 1
- assert 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"
-
- 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()
-
- 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.presentation.views.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)
- self._enable_identity_verification("optional")
-
- response = self._post(
- {
- "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
- mock_capture.assert_called_once()
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_required_mode_rejects_unregister_without_a_token(self, mock_capture: MagicMock):
- self._enable_identity_verification("required")
-
- 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_401_UNAUTHORIZED
- mock_capture.assert_not_called()
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_required_mode_accepts_a_valid_token_for_unregister(self, mock_capture: MagicMock):
- mock_capture.return_value = MagicMock(status_code=200)
- private_pem, public_pem = _es256_keypair()
- self._register_public_key("required", public_pem)
- token = sign_push_identity_token_es256(private_pem, "user-1", "my-firebase-project")
-
- response = self._delete(
- {
- "distinct_id": "user-1",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- "identity_token": token,
- }
- )
-
- assert response.status_code == status.HTTP_200_OK
- mock_capture.assert_called_once()
-
- @patch("products.messaging.backend.presentation.views.push_subscriptions.capture_internal")
- def test_strictest_mode_wins_when_two_integrations_share_an_app_id(self, mock_capture: MagicMock):
- # project_id/bundle_id aren't unique, so an app_id can match several integrations. Resolution
- # must fail closed: a second integration with the same project_id and verification disabled
- # must not let a token-less request through when a sibling requires verification.
- self._enable_identity_verification("required")
- Integration.objects.create(
- team=self.team,
- kind="firebase",
- integration_id="my-firebase-project-duplicate",
- config={"project_id": "my-firebase-project", "push_identity_verification": "disabled"},
- sensitive_config={},
- )
-
- response = self._post(
- {
- "distinct_id": "user-1",
- "device_token": "fcm-device-token-abc",
- "platform": "android",
- "app_id": "my-firebase-project",
- }
- )
-
- 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