: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
feat(messaging): verify push identity tokens with ES256 public keys (#76592)
Daniel Marchukf206baa1a4e5
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex a88d860e271c..e8ff5479db59 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -434,8 +434,14 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial# still be classified as a create and could land `disabled` over the policy an admin had just# written. Omitting the key entirely stays open to members and is what connecting a channel# without touching the policy does — that path preserves whatever is already stored.- requested_verification = (validated_data.get("config") or {}).get("push_identity_verification")- if requested_verification and not github_callback_state.has_team_management_access(+ config_in = validated_data.get("config") or {}+ requested_verification = config_in.get("push_identity_verification")+ # Registering/clearing public keys is a security-policy change (it decides which signer is+ # trusted), so it carries the same admin bar as the mode. `is not None` covers clearing too.+ requested_public_keys = config_in.get("push_identity_public_keys")+ if (+ requested_verification or requested_public_keys is not None+ ) and not github_callback_state.has_team_management_access(self.context["request"].user, self.context["get_team"]()):raise PermissionDenied("Changing push identity verification requires project admin access.")@@ -500,6 +506,7 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialteam_id,request.user,push_identity_verification=(validated_data.get("config") or {}).get("push_identity_verification"),+ push_identity_public_keys=(validated_data.get("config") or {}).get("push_identity_public_keys"),)return instance@@ -713,6 +720,7 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialcreated_by=request.user,environment=environment,push_identity_verification=config.get("push_identity_verification"),+ push_identity_public_keys=config.get("push_identity_public_keys"),)return instancediff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 1ed0903273ee..852c00fa4519 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -29,6 +29,8 @@ from django.utils import timezoneimport requestsimport structlog+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom disposable_email_domains import blocklist as disposable_email_domains_listfrom free_email_domains import whitelist as free_email_domains_listfrom google.auth.transport.requests import Request as GoogleRequest@@ -142,52 +144,92 @@ CONFIG_LEGACY_OAUTH_CLIENT = "oauth_uses_legacy_client"CONFIG_PUSH_IDENTITY_VERIFICATION = "push_identity_verification"PUSH_IDENTITY_VERIFICATION_MODES = ("disabled", "optional", "required")+# `config` key holding the customer's EC (P-256) public key(s) used to verify ES256 identity tokens.+# Public halves only — the private key stays on the customer's backend. At most two, so a key can be+# rotated (register the new one, cut over, drop the old) without a gap, mirroring the secret's+# primary/backup pair.+CONFIG_PUSH_IDENTITY_PUBLIC_KEYS = "push_identity_public_keys"+MAX_PUSH_IDENTITY_PUBLIC_KEYS = 2+++def _validate_push_identity_public_keys(public_keys: list[str]) -> None:+ if not isinstance(public_keys, list) or not all(isinstance(key, str) for key in public_keys):+ raise ValidationError("push_identity_public_keys must be a list of PEM-encoded public key strings")+ if len(public_keys) > MAX_PUSH_IDENTITY_PUBLIC_KEYS:+ raise ValidationError(f"push_identity_public_keys accepts at most {MAX_PUSH_IDENTITY_PUBLIC_KEYS} keys")+ for key in public_keys:+ try:+ loaded = serialization.load_pem_public_key(key.encode())+ except Exception:+ raise ValidationError("Each push_identity_public_key must be a valid PEM-encoded public key")+ # ES256 is defined over P-256 specifically. Accepting another curve (P-384/P-521) would store a+ # key the verifier can't use — jwt.decode raises InvalidKeyError against it — so reject it here.+ if not isinstance(loaded, ec.EllipticCurvePublicKey) or not isinstance(loaded.curve, ec.SECP256R1):+ raise ValidationError("push_identity_public_keys must be P-256 (secp256r1) EC public keys for ES256")+def preserved_push_config(team_id: int,kind: str,integration_id: str,push_identity_verification: str | None,+ push_identity_public_keys: list[str] | None = None,) -> dict:"""Config keys a push credential upsert must carry over rather than drop.Connecting a push integration is an upsert, and the provider helpers rebuild `config` from the- credentials they were handed. Anything they don't know about would be lost, so rotating a- Firebase key or APNs .p8 would silently reset an enabled identity verification policy back to- disabled, reopening the device takeover it exists to prevent. Carry the existing value forward- unless the caller explicitly sets a new one.+ credentials they were handed. Anything they don't know about would be lost, so rotating a Firebase+ key or APNs .p8 would silently reset an enabled identity verification policy (its mode and its+ registered public keys) back to nothing, reopening the device takeover it exists to prevent. Carry+ each existing value forward unless the caller explicitly sets a new one; pass an empty list to+ clear the public keys."""if push_identity_verification is not None and push_identity_verification not in PUSH_IDENTITY_VERIFICATION_MODES:raise ValidationError(f"push_identity_verification must be one of: {', '.join(PUSH_IDENTITY_VERIFICATION_MODES)}")+ if push_identity_public_keys is not None:+ _validate_push_identity_public_keys(push_identity_public_keys)# Serialize concurrent setup of this one integration for the rest of the caller's transaction.# `select_for_update` alone only locks a row that already exists, so two first-time setups could# both read "no policy" and the later write would clobber a policy the earlier one had just set.# An advisory lock covers the not-yet-created case too, keyed on the integration's identity so it# only serializes writers racing for the same integration. Every writer takes it, including one- # setting an explicit mode — otherwise it could slip its row in between a preserving writer's read+ # setting explicit values — otherwise it could slip its row in between a preserving writer's read# and write, and have its policy dropped.with connection.cursor() as cursor:cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, f"{kind}:{integration_id}"])- if push_identity_verification is not None:- return {CONFIG_PUSH_IDENTITY_VERIFICATION: push_identity_verification}-existing = (Integration.objects.select_for_update().filter(team_id=team_id, kind=kind, integration_id=integration_id).only("config").first())- existing_mode = (existing.config or {}).get(CONFIG_PUSH_IDENTITY_VERIFICATION) if existing else None- # Drop a stored value we don't recognize rather than carrying it forward. The push endpoint already- # treats an unknown mode as disabled, so preserving it would keep dead data alive indefinitely, and- # raising here would leave a corrupted integration unable to rotate its credentials.- if existing_mode not in PUSH_IDENTITY_VERIFICATION_MODES:- return {}- return {CONFIG_PUSH_IDENTITY_VERIFICATION: existing_mode} if existing_mode else {}+ existing_config = (existing.config or {}) if existing else {}+ result: dict = {}++ if push_identity_verification is not None:+ result[CONFIG_PUSH_IDENTITY_VERIFICATION] = push_identity_verification+ else:+ # Drop a stored mode we don't recognize rather than carrying it forward. The push endpoint+ # already treats an unknown mode as disabled, so preserving it would keep dead data alive, and+ # raising here would leave a corrupted integration unable to rotate its credentials.+ existing_mode = existing_config.get(CONFIG_PUSH_IDENTITY_VERIFICATION)+ if existing_mode in PUSH_IDENTITY_VERIFICATION_MODES:+ result[CONFIG_PUSH_IDENTITY_VERIFICATION] = existing_mode++ if push_identity_public_keys is not None:+ # A non-empty list sets/replaces; an empty list clears (omit the key entirely).+ if push_identity_public_keys:+ result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = push_identity_public_keys+ else:+ existing_keys = existing_config.get(CONFIG_PUSH_IDENTITY_PUBLIC_KEYS)+ if isinstance(existing_keys, list) and existing_keys:+ result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = existing_keys++ return result# Values for the counter's `reason` label, bucketed from the OAuth error response.@@ -2487,6 +2529,7 @@ class FirebaseIntegration:team_id: int,created_by: User | None = None,push_identity_verification: str | None = None,+ push_identity_public_keys: list[str] | None = None,) -> "Integration":scope = "https://www.googleapis.com/auth/firebase.messaging"@@ -2508,7 +2551,9 @@ class FirebaseIntegration:integration_id=project_id,defaults={"config": {- **preserved_push_config(team_id, "firebase", project_id, push_identity_verification),+ **preserved_push_config(+ team_id, "firebase", project_id, push_identity_verification, push_identity_public_keys+ ),"project_id": project_id,"expires_in": credentials.expiry.timestamp() - int(time.time()),"refreshed_at": int(time.time()),@@ -2601,6 +2646,7 @@ class ApplePushIntegration:created_by: User | None = None,environment: str = "production",push_identity_verification: str | None = None,+ push_identity_public_keys: list[str] | None = None,) -> "Integration":if not all([signing_key, key_id, team_id_apple, bundle_id]):raise ValidationError("All APNS fields are required: signing_key, key_id, team_id_apple, bundle_id")@@ -2617,7 +2663,9 @@ class ApplePushIntegration:integration_id=integration_id,defaults={"config": {- **preserved_push_config(team_id, "apns", integration_id, push_identity_verification),+ **preserved_push_config(+ team_id, "apns", integration_id, push_identity_verification, push_identity_public_keys+ ),"team_id": team_id_apple,"bundle_id": bundle_id,"key_id": key_id,diff --git a/posthog/models/test/test_firebase_integration.py b/posthog/models/test/test_firebase_integration.pyindex c48477c8dc99..b21cac5a04c3 100644--- a/posthog/models/test/test_firebase_integration.py+++ b/posthog/models/test/test_firebase_integration.py@@ -5,10 +5,22 @@ from freezegun import freeze_timefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom rest_framework.exceptions import ValidationErrorfrom posthog.models.integration import FirebaseIntegration, Integration++def _ec_public_pem(curve: ec.EllipticCurve | None = None) -> str:+ return (+ ec.generate_private_key(curve or ec.SECP256R1())+ .public_key()+ .public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)+ .decode()+ )++FAKE_KEY_INFO = {"type": "service_account","project_id": "my-firebase-project",@@ -37,7 +49,11 @@ class TestFirebaseIntegration(BaseTest):team_id = overrides.pop("team_id", self.team.id)created_by = overrides.pop("created_by", None)return FirebaseIntegration.integration_from_key(- key_info, team_id, created_by, push_identity_verification=overrides.pop("push_identity_verification", None)+ key_info,+ team_id,+ created_by,+ push_identity_verification=overrides.pop("push_identity_verification", None),+ push_identity_public_keys=overrides.pop("push_identity_public_keys", None),)def test_creates_integration(self):@@ -69,6 +85,25 @@ class TestFirebaseIntegration(BaseTest):with self.assertRaises(ValidationError):self._create_firebase_integration(push_identity_verification="enabled")+ def test_reconnecting_preserves_identity_public_keys(self):+ # Same rotation guard as the mode: re-upserting on a credential rotation must keep the+ # registered public keys, or ES256 verification would start rejecting every real token.+ public_pem = _ec_public_pem()+ self._create_firebase_integration(push_identity_public_keys=[public_pem])+ reconnected = self._create_firebase_integration()++ assert reconnected.config["push_identity_public_keys"] == [public_pem]++ def test_rejects_an_invalid_public_key(self):+ with self.assertRaises(ValidationError):+ self._create_firebase_integration(push_identity_public_keys=["not-a-pem"])++ def test_rejects_a_non_p256_public_key(self):+ # ES256 is defined over P-256 only; a valid PEM on another curve would be stored but unusable+ # by the verifier, so it must be rejected at registration.+ with self.assertRaises(ValidationError):+ self._create_firebase_integration(push_identity_public_keys=[_ec_public_pem(ec.SECP384R1())])+def test_separate_integrations_for_different_projects(self):first = self._create_firebase_integration()diff --git a/products/messaging/backend/api/push_identity_tokens.py b/products/messaging/backend/api/push_identity_tokens.pyindex 25f34c600c7b..3fc4625e12ea 100644--- a/products/messaging/backend/api/push_identity_tokens.py+++ b/products/messaging/backend/api/push_identity_tokens.py@@ -13,10 +13,20 @@ that actually authenticated the end user — mints a short-lived token asserting`distinct_id`, signed with the project's secret API key. PostHog re-verifies the signature atregistration time. An attacker holding only the public project token cannot forge it.-We use symmetric HMAC (HS256) keyed by `Team.secret_api_token` rather than an asymmetric key pair:-PostHog verifies its own ingestion, so there is no third-party verifier that would need a public key,-and the secret already ships with built-in rotation via `secret_api_token_backup`. Verification-accepts either the current or the backup secret so a key rotation doesn't reject in-flight tokens.+Two signing schemes are accepted, checked in this order:++1. Asymmetric ES256 (preferred). The customer holds an EC (P-256) private key and registers only the+ public key on the push channel (`config["push_identity_public_keys"]`). PostHog verifies with the+ public key and never stores a usable signing secret. This matches how Braze and OneSignal secure+ device registration, and it works for projects that only ever created scoped, hashed-at-rest API+ keys (which can't be used for HMAC).+2. Symmetric HS256 keyed by `Team.secret_api_token` (legacy). Kept so integrations set up before+ asymmetric support keep working; accepts the current or backup secret so rotation doesn't reject+ in-flight tokens. `Team.secret_api_token` is the deprecated "feature flags secure API key", so new+ setups should prefer the asymmetric path.++The two algorithms are verified strictly separately (a public key is only ever tried with ES256, a+secret only with HS256) to close the classic JWT algorithm-confusion attack."""from datetime import UTC, datetime, timedelta@@ -26,7 +36,8 @@ import jwtfrom posthog.models.team.team import TeamPUSH_IDENTITY_TOKEN_AUDIENCE = "posthog:push_identity"-_ALGORITHM = "HS256"+_HMAC_ALGORITHM = "HS256"+_ASYMMETRIC_ALGORITHM = "ES256"# Short TTL: the token only needs to survive the round trip from the customer's backend, through the# app, to the registration call. Keeping it small bounds the replay window (a replay can only re-assert@@ -47,6 +58,22 @@ def sign_push_identity_token(it lives here so the signing and verification rules stay in one place and the tests can exercisethe real round trip."""+ return _claims(distinct_id, app_id, ttl, secret_api_token, _HMAC_ALGORITHM)+++def sign_push_identity_token_es256(+ private_key_pem: str,+ distinct_id: str,+ app_id: str,+ ttl: timedelta = DEFAULT_TTL,+) -> str:+ """Reference ES256 signer: what the customer's backend runs with its EC private key. PostHog only+ ever verifies (against the registered public key); this lives here so the round trip stays testable.+ """+ return _claims(distinct_id, app_id, ttl, private_key_pem, _ASYMMETRIC_ALGORITHM)+++def _claims(distinct_id: str, app_id: str, ttl: timedelta, key: str, algorithm: str) -> str:return jwt.encode({"sub": distinct_id,@@ -54,32 +81,50 @@ def sign_push_identity_token("aud": PUSH_IDENTITY_TOKEN_AUDIENCE,"exp": datetime.now(UTC) + ttl,},- secret_api_token,- algorithm=_ALGORITHM,+ key,+ algorithm=algorithm,)-def verify_push_identity_token(token: str, team: Team, distinct_id: str, app_id: str) -> bool:+def verify_push_identity_token(+ token: str,+ team: Team,+ distinct_id: str,+ app_id: str,+ public_keys: list[str] | None = None,+) -> bool:"""Return True iff `token` is a valid, unexpired identity assertion for exactly this- `(distinct_id, app_id)`, signed by the team's current or backup secret API key.+ `(distinct_id, app_id)`.- Binding the claim to `app_id` as well as `distinct_id` stops a token minted for one app being- replayed to register a device under a different app in the same project.+ Tries each registered EC public key with ES256 first, then falls back to the team's current/backup+ secret with HS256. Binding the claim to `app_id` as well as `distinct_id` stops a token minted for+ one app being replayed to register a device under a different app in the same project."""- candidate_secrets = [secret for secret in (team.secret_api_token, team.secret_api_token_backup) if secret]- for secret in candidate_secrets:- try:- payload = jwt.decode(- token,- secret,- algorithms=[_ALGORITHM],- audience=PUSH_IDENTITY_TOKEN_AUDIENCE,- # Require exp explicitly: PyJWT only checks expiry when the claim is present, so without- # this a token minted (by an external signer) with no exp would never expire.- options={"require": ["exp"]},- )- except jwt.InvalidTokenError:- continue- if payload.get("sub") == distinct_id and payload.get("app_id") == app_id:+ for public_key in public_keys or []:+ if _decode_matches(token, public_key, _ASYMMETRIC_ALGORITHM, distinct_id, app_id):+ return True+ for secret in (team.secret_api_token, team.secret_api_token_backup):+ if secret and _decode_matches(token, secret, _HMAC_ALGORITHM, distinct_id, app_id):return Truereturn False+++def _decode_matches(token: str, key: str, algorithm: str, distinct_id: str, app_id: str) -> bool:+ # One algorithm per key type, never a list: verifying an HS256 token with a public key (or vice+ # versa) is the JWT algorithm-confusion attack, so the two schemes are checked in separate passes.+ try:+ payload = jwt.decode(+ token,+ key,+ algorithms=[algorithm],+ audience=PUSH_IDENTITY_TOKEN_AUDIENCE,+ # Require exp explicitly: PyJWT only checks expiry when the claim is present, so without+ # this a token minted (by an external signer) with no exp would never expire.+ options={"require": ["exp"]},+ )+ except jwt.PyJWTError:+ # PyJWTError covers both InvalidTokenError (bad/expired/wrong-signature token) and InvalidKeyError+ # (the key can't be used with this algorithm, e.g. a non-P-256 EC key against ES256). Treat every+ # such case as "not verified" and fail closed, rather than letting InvalidKeyError 500 the endpoint.+ return False+ return payload.get("sub") == distinct_id and payload.get("app_id") == app_iddiff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.pyindex 73a8db492c21..a975b5d5456d 100644--- a/products/messaging/backend/api/push_subscriptions.py+++ b/products/messaging/backend/api/push_subscriptions.py@@ -221,8 +221,13 @@ def push_subscriptions(request: Request):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 (verify picks the+ # one that validates, then falls back to the legacy shared secret).+ 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, team, distinct_id, app_id+ identity_token, team, distinct_id, app_id, public_keys=public_keys)PUSH_IDENTITY_VERIFICATION_COUNTER.labels(mode=verification_mode,@@ -234,8 +239,9 @@ def push_subscriptions(request: Request):request,generate_exception_response("push_subscriptions",- "A valid identity token is required for this device. Your backend must mint one for "- "the signed-in user with the project's secret API key.",+ "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,diff --git a/products/messaging/backend/api/test/test_push_identity_tokens.py b/products/messaging/backend/api/test/test_push_identity_tokens.pyindex f245b8770eb2..dc943ab9a181 100644--- a/products/messaging/backend/api/test/test_push_identity_tokens.py+++ b/products/messaging/backend/api/test/test_push_identity_tokens.py@@ -1,8 +1,14 @@-from datetime import timedelta+import hmac+import json+import base64+import hashlib+from datetime import UTC, datetime, timedeltafrom django.test import SimpleTestCaseimport jwt+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom parameterized import parameterizedfrom posthog.models.team.team import Team@@ -10,9 +16,39 @@ from posthog.models.team.team import Teamfrom products.messaging.backend.api.push_identity_tokens import (PUSH_IDENTITY_TOKEN_AUDIENCE,sign_push_identity_token,+ sign_push_identity_token_es256,verify_push_identity_token,)++# A fresh EC P-256 keypair as (private PEM, public PEM): the customer's signing key and the public+# half they register with PostHog.+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+++# Hand-roll an HS256 JWT: PyJWT refuses to sign HMAC with a PEM public key (it blocks alg confusion at+# the encode step), so an attacker crafting this token wouldn't use PyJWT either.+def _forge_hs256(secret: str, claims: dict) -> str:+ def b64(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()++ signing_input = f"{b64(json.dumps({'alg': 'HS256', 'typ': 'JWT'}).encode())}.{b64(json.dumps(claims).encode())}"+ signature = b64(hmac.new(secret.encode(), signing_input.encode(), hashlib.sha256).digest())+ return f"{signing_input}.{signature}"++# Realistic length (>= 32 bytes) — matches a real phs_ secret and avoids PyJWT's short-key warning.CURRENT_SECRET = "phs_current_secret_0123456789abcdef0123"BACKUP_SECRET = "phs_backup_secret_0123456789abcdef01234"@@ -68,3 +104,58 @@ class TestPushIdentityTokens(SimpleTestCase):def test_rejects_when_the_team_has_no_secret_configured(self):token = sign_push_identity_token(CURRENT_SECRET, DISTINCT_ID, APP_ID)assert verify_push_identity_token(token, self._team(secret=None), DISTINCT_ID, APP_ID) is False++ # --- Asymmetric ES256: the customer signs with a private key, PostHog holds only the public key ---++ def test_verifies_an_es256_token_signed_by_the_registered_public_key(self):+ private_pem, public_pem = _es256_keypair()+ token = sign_push_identity_token_es256(private_pem, DISTINCT_ID, APP_ID)+ team = self._team(secret=None) # no shared secret: only the public-key path can accept it+ assert verify_push_identity_token(token, team, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is True++ def test_rejects_an_es256_token_when_a_different_public_key_is_registered(self):+ signer_private, _ = _es256_keypair()+ _, registered_public = _es256_keypair()+ token = sign_push_identity_token_es256(signer_private, DISTINCT_ID, APP_ID)+ team = self._team(secret=None)+ assert verify_push_identity_token(token, team, DISTINCT_ID, APP_ID, public_keys=[registered_public]) is False++ def test_returns_false_without_crashing_for_a_mismatched_curve_public_key(self):+ # A registered key on the wrong curve makes jwt.decode raise InvalidKeyError, which is not an+ # InvalidTokenError. verify must treat it as unverified rather than let it crash the endpoint.+ private_pem, _ = _es256_keypair()+ token = sign_push_identity_token_es256(private_pem, DISTINCT_ID, APP_ID)+ p384_public = (+ ec.generate_private_key(ec.SECP384R1())+ .public_key()+ .public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)+ .decode()+ )+ assert (+ verify_push_identity_token(token, self._team(secret=None), DISTINCT_ID, APP_ID, public_keys=[p384_public])+ is False+ )++ def test_falls_back_to_the_shared_secret_when_public_keys_are_also_registered(self):+ # A project mid-migration can carry both a legacy secret and registered public keys; a token+ # signed with the secret must still verify so existing integrations keep working.+ _, public_pem = _es256_keypair()+ token = sign_push_identity_token(CURRENT_SECRET, DISTINCT_ID, APP_ID)+ assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID, public_keys=[public_pem]) is True++ def test_rejects_hs256_token_forged_with_the_public_key_as_the_hmac_secret(self):+ # JWT algorithm confusion: the public key is public, so an attacker can sign an HS256 token+ # using it as the HMAC secret. Verifying a public key only under ES256 rejects this; allowing+ # both algorithms per key would let anyone forge an identity for any distinct_id.+ _, public_pem = _es256_keypair()+ forged = _forge_hs256(+ public_pem,+ {+ "sub": DISTINCT_ID,+ "app_id": APP_ID,+ "aud": PUSH_IDENTITY_TOKEN_AUDIENCE,+ "exp": int((datetime.now(UTC) + timedelta(minutes=5)).timestamp()),+ },+ )+ team = self._team(secret=None)+ assert verify_push_identity_token(forged, team, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is Falsediff --git a/products/messaging/backend/api/test/test_push_subscriptions.py b/products/messaging/backend/api/test/test_push_subscriptions.pyindex ae73f2e01519..8ad3e51e2bb4 100644--- a/products/messaging/backend/api/test/test_push_subscriptions.py+++ b/products/messaging/backend/api/test/test_push_subscriptions.py@@ -6,13 +6,30 @@ from unittest.mock import MagicMock, patchfrom django.test import Client+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom rest_framework import statusfrom posthog.models.integration import Integrationfrom posthog.models.team.team import Teamfrom posthog.models.team.team_caching import set_team_in_cache-from products.messaging.backend.api.push_identity_tokens import sign_push_identity_token+from products.messaging.backend.api.push_identity_tokens import sign_push_identity_token, sign_push_identity_token_es256+++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_pemclass TestPushSubscriptionsAPI(BaseTest):@@ -333,6 +350,37 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGEmock_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.api.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.api.push_subscriptions.capture_internal")def test_required_mode_accepts_a_valid_identity_token(self, mock_capture: MagicMock):mock_capture.return_value = MagicMock(status_code=200)diff --git a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.tsindex 8fdee7b4a907..c6dd97ded033 100644--- a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts@@ -10,7 +10,9 @@ import { IntegrationType } from '~/types'import {PushIdentityVerificationMode,+ pushIdentityPublicKeysPayload,pushIdentityVerificationPayload,+ resolvePushIdentityPublicKey,resolvePushIdentityVerification,} from '../PushIdentityVerificationField'@@ -27,6 +29,7 @@ export interface APNSFormType {bundleId: stringenvironment: 'production' | 'sandbox'identityVerification: PushIdentityVerificationMode+ identityPublicKey: string}// Apple hands out the signing key as a .p8 file, so accepting an upload saves opening it in an@@ -38,6 +41,7 @@ export interface apnsSetupModalLogicValues {apnsIntegration: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -49,6 +53,7 @@ export interface apnsSetupModalLogicValues {{bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -64,6 +69,7 @@ export interface apnsSetupModalLogicValues {{bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -83,6 +89,7 @@ export interface apnsSetupModalLogicActions {resetApnsIntegration: (values?: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -91,6 +98,7 @@ export interface apnsSetupModalLogicActions {values?: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -111,6 +119,7 @@ export interface apnsSetupModalLogicActions {values: DeepPartial<{bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -120,6 +129,7 @@ export interface apnsSetupModalLogicActions {values: DeepPartial<{bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -145,6 +155,7 @@ export interface apnsSetupModalLogicActions {submitApnsIntegrationRequest: (apnsIntegration: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -153,6 +164,7 @@ export interface apnsSetupModalLogicActions {apnsIntegration: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -162,6 +174,7 @@ export interface apnsSetupModalLogicActions {submitApnsIntegrationSuccess: (apnsIntegration: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -170,6 +183,7 @@ export interface apnsSetupModalLogicActions {apnsIntegration: {bundleId: stringenvironment: 'production'+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModekeyId: stringsigningKey: string@@ -241,6 +255,7 @@ export const apnsSetupModalLogic = kea<apnsSetupModalLogicType>([bundleId: '',environment: 'production' as const,identityVerification: resolvePushIdentityVerification(props.integration),+ identityPublicKey: resolvePushIdentityPublicKey(props.integration),},errors: ({ signingKey, keyId, teamId, bundleId }) => ({signingKey: signingKey.trim() ? undefined : 'Signing key is required',@@ -262,6 +277,10 @@ export const apnsSetupModalLogic = kea<apnsSetupModalLogicType>([values.apnsIntegration.identityVerification,props.integration),+ ...pushIdentityPublicKeysPayload(+ values.apnsIntegration.identityPublicKey,+ props.integration+ ),},})actions.loadIntegrations()diff --git a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.tsindex 5d43d943bd74..8875ce0249e2 100644--- a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts@@ -10,7 +10,9 @@ import { IntegrationType } from '~/types'import {PushIdentityVerificationMode,+ pushIdentityPublicKeysPayload,pushIdentityVerificationPayload,+ resolvePushIdentityPublicKey,resolvePushIdentityVerification,} from '../PushIdentityVerificationField'@@ -23,11 +25,13 @@ export interface FCMSetupModalLogicProps {export interface FCMFormType {serviceAccountKey: stringidentityVerification: PushIdentityVerificationMode+ identityPublicKey: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface fcmSetupModalLogicValues {fcmIntegration: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}@@ -35,6 +39,7 @@ export interface fcmSetupModalLogicValues {fcmIntegrationChanged: booleanfcmIntegrationErrors: DeepPartialMap<{+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string},@@ -46,6 +51,7 @@ export interface fcmSetupModalLogicValues {fcmIntegrationTouches: Record<string, boolean>fcmIntegrationValidationErrors: DeepPartialMap<{+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string},@@ -60,10 +66,12 @@ export interface fcmSetupModalLogicValues {export interface fcmSetupModalLogicActions {loadIntegrations: () => any // integrationsLogicresetFcmIntegration: (values?: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}) => {values?: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}@@ -80,11 +88,13 @@ export interface fcmSetupModalLogicActions {}setFcmIntegrationValues: (values: DeepPartial<{+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}>) => {values: DeepPartial<{+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}>@@ -100,19 +110,23 @@ export interface fcmSetupModalLogicActions {errors: Record<string, any>}submitFcmIntegrationRequest: (fcmIntegration: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}) => {fcmIntegration: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}}submitFcmIntegrationSuccess: (fcmIntegration: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}) => {fcmIntegration: {+ identityPublicKey: stringidentityVerification: PushIdentityVerificationModeserviceAccountKey: string}@@ -139,6 +153,7 @@ export const fcmSetupModalLogic = kea<fcmSetupModalLogicType>([defaults: {serviceAccountKey: '',identityVerification: resolvePushIdentityVerification(props.integration),+ identityPublicKey: resolvePushIdentityPublicKey(props.integration),},errors: ({ serviceAccountKey }) => ({serviceAccountKey: serviceAccountKey.trim() ? undefined : 'Service account key is required',@@ -161,6 +176,10 @@ export const fcmSetupModalLogic = kea<fcmSetupModalLogicType>([values.fcmIntegration.identityVerification,props.integration),+ ...pushIdentityPublicKeysPayload(+ values.fcmIntegration.identityPublicKey,+ props.integration+ ),},})actions.loadIntegrations()diff --git a/products/workflows/frontend/Channels/PushIdentityVerificationField.tsx b/products/workflows/frontend/Channels/PushIdentityVerificationField.tsxindex 573246f2fd6e..23c89c19cb45 100644--- a/products/workflows/frontend/Channels/PushIdentityVerificationField.tsx+++ b/products/workflows/frontend/Channels/PushIdentityVerificationField.tsx@@ -1,4 +1,4 @@-import { LemonSegmentedButton } from '@posthog/lemon-ui'+import { LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'@@ -32,6 +32,30 @@ export function pushIdentityVerificationPayload(return mode === resolvePushIdentityVerification(integration) ? {} : { push_identity_verification: mode }}+/**+ * Seed the public-key field from the stored key. The backend keeps up to two (for rotation); the UI+ * edits the primary one, so an empty field means "no key registered".+ */+export function resolvePushIdentityPublicKey(integration?: IntegrationType | null): string {+ const stored = integration?.config?.push_identity_public_keys+ return Array.isArray(stored) && typeof stored[0] === 'string' ? stored[0] : ''+}++/**+ * Config fragment for the public key. Like the mode, an unchanged field is omitted so reconnecting a+ * channel carries the stored key forward; a non-empty value registers/replaces it, an empty one clears it.+ */+export function pushIdentityPublicKeysPayload(+ publicKey: string,+ integration?: IntegrationType | null+): { push_identity_public_keys?: string[] } {+ const trimmed = publicKey.trim()+ if (trimmed === resolvePushIdentityPublicKey(integration)) {+ return {}+ }+ return { push_identity_public_keys: trimmed ? [trimmed] : [] }+}+const MODE_HELP: Record<PushIdentityVerificationMode, string> = {disabled: 'Any client with your project API key can register a device for any user.',optional:@@ -46,20 +70,34 @@ const MODE_HELP: Record<PushIdentityVerificationMode, string> = {*/export function PushIdentityVerificationField({ mode }: { mode: PushIdentityVerificationMode }): JSX.Element {return (- <LemonField- name="identityVerification"- label="Identity verification"- info="A device token says where to deliver a notification, not who the device belongs to. Turn this on to have your backend sign a short-lived token for the logged-in user, which your app sends when registering the device."- help={MODE_HELP[mode]}- >- <LemonSegmentedButton- options={[- { value: 'disabled', label: 'Disabled' },- { value: 'optional', label: 'Optional' },- { value: 'required', label: 'Required' },- ]}- fullWidth- />- </LemonField>+ <>+ <LemonField+ name="identityVerification"+ label="Identity verification"+ info="A device token says where to deliver a notification, not who the device belongs to. Turn this on to have your backend sign a short-lived token for the logged-in user, which your app sends when registering the device."+ help={MODE_HELP[mode]}+ >+ <LemonSegmentedButton+ options={[+ { value: 'disabled', label: 'Disabled' },+ { value: 'optional', label: 'Optional' },+ { value: 'required', label: 'Required' },+ ]}+ fullWidth+ />+ </LemonField>+ {mode !== 'disabled' && (+ <LemonField+ name="identityPublicKey"+ label="Public key"+ info="Paste the EC (P-256) public key that pairs with your backend's signing key. Your backend signs each identity token (ES256) with the private key; PostHog verifies it with this public key, which never leaves your control. Leave blank to instead verify with your project's Feature flags secure API key (HS256)."+ >+ <LemonTextArea+ placeholder={'-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----'}+ minRows={4}+ />+ </LemonField>+ )}+ </>)}