: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(workflows): verify push identity tokens with ES256 only (#103644)
Daniel Marchuke10f99b6c473
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 19d37919f8fd..cf65d1c60b3f 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -20,6 +20,8 @@ from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport requests+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom fakeredis import FakeConnectionfrom parameterized import parameterizedfrom prometheus_client import REGISTRY@@ -82,6 +84,15 @@ from products.cdp.backend.models.hog_function_template import HogFunctionTemplatfrom products.workflows.backend.models import HogFlow+def _p256_public_pem() -> str:+ return (+ ec.generate_private_key(ec.SECP256R1())+ .public_key()+ .public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)+ .decode()+ )++class TestSlackIntegration:@pytest.fixture(autouse=True)def setup_integration(self, db):@@ -6979,9 +6990,12 @@ class TestPushIdentityVerificationAPI(APIBaseTest):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()+ @parameterized.expand([("with_a_public_key", True), ("without_a_public_key", False)])@patch("posthog.models.integration.push.GoogleRequest")@patch("posthog.models.integration.push.service_account.Credentials.from_service_account_info")- def test_setting_the_mode_reaches_the_integration(self, mock_from_sa, _mock_google_request):+ def test_setting_the_mode_reaches_the_integration(+ self, _name: str, with_public_key: bool, mock_from_sa: MagicMock, _mock_google_request: MagicMock+ ) -> None:# The serializer builds each provider's arguments from named config fields, so a key it doesn't# know about is dropped before it ever reaches the integration. That silently made the setup# UI's toggle inert; this covers the plumbing rather than just the model helper underneath it.@@ -7001,11 +7015,17 @@ class TestPushIdentityVerificationAPI(APIBaseTest):"token_uri": "https://oauth2.googleapis.com/token",},"push_identity_verification": "required",+ **({"push_identity_public_keys": [_p256_public_pem()]} if with_public_key else {}),},},format="json",)+ if not with_public_key:+ # Verification checks tokens against a public key only, so without one every device is refused.+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert not Integration.objects.filter(team=self.team, kind="firebase").exists()+ returnassert response.status_code == status.HTTP_201_CREATED, response.contentintegration = Integration.objects.get(team=self.team, kind="firebase")assert integration.config["push_identity_verification"] == "required"diff --git a/posthog/models/integration/push.py b/posthog/models/integration/push.pyindex 15a65a93254e..0085b4afb213 100644--- a/posthog/models/integration/push.py+++ b/posthog/models/integration/push.py@@ -113,6 +113,11 @@ def preserved_push_config(if isinstance(existing_keys, list) and existing_keys:result[CONFIG_PUSH_IDENTITY_PUBLIC_KEYS] = existing_keys+ # Verification checks tokens against a registered public key only, so `required` with no key would+ # stop every device from registering. `optional` never rejects, and existing channels use it keyless.+ if result.get(CONFIG_PUSH_IDENTITY_VERIFICATION) == "required" and not result.get(CONFIG_PUSH_IDENTITY_PUBLIC_KEYS):+ raise ValidationError("Add a public key to turn on identity verification.")+return resultdiff --git a/posthog/models/test/test_apple_push_integration.py b/posthog/models/test/test_apple_push_integration.pyindex 4ef63ffdb98a..29aeeb98b1ac 100644--- a/posthog/models/test/test_apple_push_integration.py+++ b/posthog/models/test/test_apple_push_integration.py@@ -2,6 +2,8 @@ from typing import Anyfrom posthog.test.base import BaseTest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ecfrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError@@ -9,6 +11,15 @@ from posthog.models.integration import ApplePushIntegration, Integrationfrom posthog.models.integration.push import is_apns_bundle_id, is_apns_team_id+def _ec_public_pem() -> str:+ return (+ ec.generate_private_key(ec.SECP256R1())+ .public_key()+ .public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)+ .decode()+ )++class TestApplePushIntegration(BaseTest):def _create_apple_push_integration(self,@@ -18,6 +29,7 @@ class TestApplePushIntegration(BaseTest):bundle_id: str = "com.example.app",environment: str = "production",push_identity_verification: str | None = None,+ push_identity_public_keys: list[str] | None = None,) -> Integration:return ApplePushIntegration.integration_from_key(signing_key=signing_key,@@ -27,6 +39,7 @@ class TestApplePushIntegration(BaseTest):team_id=self.team.id,environment=environment,push_identity_verification=push_identity_verification,+ push_identity_public_keys=push_identity_public_keys,)def test_creates_integration(self):@@ -50,14 +63,24 @@ class TestApplePushIntegration(BaseTest):def test_reconnecting_preserves_identity_verification(self):# Rotating the .p8 signing key is a routine action that re-upserts the integration. It must# not silently reset the verification policy, which would reopen device takeover.- self._create_apple_push_integration(push_identity_verification="required")+ public_pem = _ec_public_pem()+ self._create_apple_push_integration(+ push_identity_verification="required", push_identity_public_keys=[public_pem]+ )reconnected = self._create_apple_push_integration(key_id="ROTATED_KEY")assert reconnected.config["push_identity_verification"] == "required"+ assert reconnected.config["push_identity_public_keys"] == [public_pem]- def test_rejects_an_unknown_identity_verification_mode(self):+ @parameterized.expand(+ [+ ("unknown_mode", {"push_identity_verification": "enabled"}),+ ("required_without_a_public_key", {"push_identity_verification": "required"}),+ ]+ )+ def test_rejects_an_unusable_identity_verification_policy(self, _name: str, policy: dict[str, Any]) -> None:with self.assertRaises(ValidationError):- self._create_apple_push_integration(push_identity_verification="enabled")+ self._create_apple_push_integration(**policy)def test_separate_integrations_for_different_bundles(self):first = self._create_apple_push_integration(bundle_id="com.example.app1")diff --git a/posthog/models/test/test_firebase_integration.py b/posthog/models/test/test_firebase_integration.pyindex 807996b9a8e4..a7053eb2bb1d 100644--- a/posthog/models/test/test_firebase_integration.py+++ b/posthog/models/test/test_firebase_integration.py@@ -1,5 +1,6 @@import timefrom datetime import timedelta+from typing import Anyimport time_machinefrom posthog.test.base import BaseTest@@ -7,6 +8,7 @@ from unittest.mock import MagicMock, patchfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import ec+from parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom posthog.models.integration import FirebaseIntegration, Integration@@ -76,14 +78,29 @@ class TestFirebaseIntegration(BaseTest):def test_reconnecting_preserves_identity_verification(self):# Rotating the service account key is a routine action that re-upserts the integration. It# must not silently reset the verification policy, which would reopen device takeover.- self._create_firebase_integration(push_identity_verification="required")+ public_pem = _ec_public_pem()+ self._create_firebase_integration(push_identity_verification="required", push_identity_public_keys=[public_pem])reconnected = self._create_firebase_integration()assert reconnected.config["push_identity_verification"] == "required"+ assert reconnected.config["push_identity_public_keys"] == [public_pem]- def test_rejects_an_unknown_identity_verification_mode(self):+ @parameterized.expand(+ [+ ("unknown_mode", {"push_identity_verification": "enabled"}),+ ("required_without_a_public_key", {"push_identity_verification": "required"}),+ ]+ )+ def test_rejects_an_unusable_identity_verification_policy(self, _name: str, policy: dict[str, Any]) -> None:with self.assertRaises(ValidationError):- self._create_firebase_integration(push_identity_verification="enabled")+ self._create_firebase_integration(**policy)++ def test_reconnecting_an_optional_channel_without_a_public_key(self):+ self._create_firebase_integration(push_identity_verification="optional")+ reconnected = self._create_firebase_integration()++ assert reconnected.config["push_identity_verification"] == "optional"+ assert "push_identity_public_keys" not in reconnected.configdef test_reconnecting_preserves_identity_public_keys(self):# Same rotation guard as the mode: re-upserting on a credential rotation must keep thediff --git a/products/messaging/backend/api/push_identity_tokens.py b/products/messaging/backend/api/push_identity_tokens.pyindex 82e8df0ef79d..456aff57137d 100644--- a/products/messaging/backend/api/push_identity_tokens.py+++ b/products/messaging/backend/api/push_identity_tokens.py@@ -10,66 +10,32 @@ the mobile app and world-readable, so anyone can present it and claim any `distiFollowing the pattern proven by Braze's "SDK Authentication", the customer's backend — the only partythat actually authenticated the end user — mints a short-lived token asserting the user's-`distinct_id`, signed with the project's secret API key. PostHog re-verifies the signature at+`distinct_id`, signed with a private key only that backend holds. PostHog re-verifies the signature atregistration time. An attacker holding only the public project token cannot forge it.-Two signing schemes are accepted, checked in this order:+The token is signed ES256. The customer holds an EC (P-256) private key and registers only the public+key on the push channel (`config["push_identity_public_keys"]`), so PostHog never stores a key that+can mint a token. This matches how Braze and OneSignal secure device registration, and it works for+projects that only ever created scoped API keys, which are hashed at rest and cannot sign.-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.+Only ES256 is accepted. A second symmetric pass over a shared secret would reopen the classic JWT+algorithm-confusion attack, because the registered public key is readable by anyone who can see the+channel and would then double as an HMAC secret."""from datetime import UTC, datetime, timedeltaimport jwt-from prometheus_client import Counter--from posthog.models.team.team import TeamPUSH_IDENTITY_TOKEN_AUDIENCE = "posthog:push_identity"-_HMAC_ALGORITHM = "HS256"_ASYMMETRIC_ALGORITHM = "ES256"-# Counts the registrations that verified only through the HS256 fallback, which is what says whether-# the scheme can be withdrawn. Channel config cannot answer that on its own, because a channel that-# registers a public key still reaches the fallback when the customer signs with the shared secret.-PUSH_IDENTITY_HMAC_FALLBACK_COUNTER = Counter(- "push_subscription_identity_hmac_fallback",- "Identity tokens accepted only by the deprecated shared-secret scheme.",-)-# 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# the same (distinct_id, app_id) binding the legitimate user already holds, so the value is low anyway).DEFAULT_TTL = timedelta(minutes=5)-def sign_push_identity_token(- secret_api_token: str,- distinct_id: str,- app_id: str,- ttl: timedelta = DEFAULT_TTL,-) -> str:- """Mint a signed identity token.-- This is the reference implementation of what the *customer's backend* runs after it has- authenticated the end user. It is not called by PostHog's own ingestion (which only verifies);- it lives here so the signing and verification rules stay in one place and the tests can exercise- the 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,@@ -97,7 +63,6 @@ def _claims(distinct_id: str, app_id: str, ttl: timedelta, key: str, algorithm:def verify_push_identity_token(token: str,- team: Team,distinct_id: str,app_id: str,public_keys: list[str] | None = None,@@ -105,28 +70,21 @@ def verify_push_identity_token("""Return True iff `token` is a valid, unexpired identity assertion for exactly this`(distinct_id, app_id)`.- 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.+ 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."""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):- PUSH_IDENTITY_HMAC_FALLBACK_COUNTER.inc()+ if _decode_matches(token, public_key, 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.+def _decode_matches(token: str, key: str, distinct_id: str, app_id: str) -> bool:try:payload = jwt.decode(token,key,- algorithms=[algorithm],+ algorithms=[_ASYMMETRIC_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.diff --git a/products/messaging/backend/api/push_subscriptions.py b/products/messaging/backend/api/push_subscriptions.pyindex a6b911c041fc..8d837957bd04 100644--- a/products/messaging/backend/api/push_subscriptions.py+++ b/products/messaging/backend/api/push_subscriptions.py@@ -422,13 +422,12 @@ 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 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, team, distinct_id, app_id, public_keys=public_keys+ identity_token, distinct_id, app_id, public_keys=public_keys)PUSH_IDENTITY_VERIFICATION_COUNTER.labels(mode=verification_mode,diff --git a/products/messaging/backend/api/test/test_push_identity_tokens.py b/products/messaging/backend/api/test/test_push_identity_tokens.pyindex 81b0fa194546..20dffd4c66f2 100644--- a/products/messaging/backend/api/test/test_push_identity_tokens.py+++ b/products/messaging/backend/api/test/test_push_identity_tokens.py@@ -2,6 +2,7 @@ import hmacimport jsonimport base64import hashlib+import secretsfrom datetime import UTC, datetime, timedeltafrom django.test import SimpleTestCase@@ -10,13 +11,9 @@ import jwtfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import ecfrom parameterized import parameterized-from prometheus_client import REGISTRY--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,)@@ -50,30 +47,15 @@ def _forge_hs256(secret: str, claims: dict) -> str: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"DISTINCT_ID = "user-1"APP_ID = "my-firebase-project"class TestPushIdentityTokens(SimpleTestCase):- def _team(self, secret: str | None = CURRENT_SECRET, backup: str | None = None) -> Team:- return Team(secret_api_token=secret, secret_api_token_backup=backup)-- def _fallback_count(self) -> float:- return REGISTRY.get_sample_value("push_subscription_identity_hmac_fallback_total") or 0.0-- def test_verifies_a_token_signed_with_the_current_secret(self):- token = sign_push_identity_token(CURRENT_SECRET, DISTINCT_ID, APP_ID)- before = self._fallback_count()- assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is True- assert self._fallback_count() == before + 1-- def test_verifies_a_token_signed_with_the_backup_secret_after_rotation(self):- token = sign_push_identity_token(BACKUP_SECRET, DISTINCT_ID, APP_ID)- team = self._team(secret=CURRENT_SECRET, backup=BACKUP_SECRET)- assert verify_push_identity_token(token, team, DISTINCT_ID, APP_ID) is True+ def test_verifies_a_token_signed_by_the_registered_public_key(self) -> None:+ private_pem, public_pem = _es256_keypair()+ token = sign_push_identity_token_es256(private_pem, DISTINCT_ID, APP_ID)+ assert verify_push_identity_token(token, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is True@parameterized.expand([@@ -83,59 +65,40 @@ class TestPushIdentityTokens(SimpleTestCase):)def test_rejects_a_token_whose_claims_do_not_match_the_registration(self, _name, sub, app_id):# The rebind guard: a token minted for one (distinct_id, app_id) cannot authorize a different one.- token = sign_push_identity_token(CURRENT_SECRET, sub, app_id)- assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is False+ private_pem, public_pem = _es256_keypair()+ token = sign_push_identity_token_es256(private_pem, sub, app_id)+ assert verify_push_identity_token(token, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is False- def test_rejects_a_token_signed_with_a_different_secret(self):- token = sign_push_identity_token("phs_attacker_secret_0123456789abcdef012", DISTINCT_ID, APP_ID)- assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is False+ def test_rejects_a_token_when_a_different_public_key_is_registered(self) -> None:+ signer_private, _ = _es256_keypair()+ _, registered_public = _es256_keypair()+ token = sign_push_identity_token_es256(signer_private, DISTINCT_ID, APP_ID)+ assert verify_push_identity_token(token, DISTINCT_ID, APP_ID, public_keys=[registered_public]) is Falsedef test_rejects_an_expired_token(self):- token = sign_push_identity_token(CURRENT_SECRET, DISTINCT_ID, APP_ID, ttl=timedelta(seconds=-1))- assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is False+ private_pem, public_pem = _es256_keypair()+ token = sign_push_identity_token_es256(private_pem, DISTINCT_ID, APP_ID, ttl=timedelta(seconds=-1))+ assert verify_push_identity_token(token, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is Falsedef test_rejects_a_token_with_no_exp_claim(self):- # An external signer (customer backend / SDK) could omit exp; without requiring it a token would- # never expire, so the verifier must reject it even though the signature is valid.+ # An external signer could omit exp; without requiring it a token would never expire, so the+ # verifier must reject it even though the signature is valid.+ private_pem, public_pem = _es256_keypair()token = jwt.encode({"sub": DISTINCT_ID, "app_id": APP_ID, "aud": PUSH_IDENTITY_TOKEN_AUDIENCE},- CURRENT_SECRET,- algorithm="HS256",+ private_pem,+ algorithm="ES256",)- assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is False+ assert verify_push_identity_token(token, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is Falsedef test_rejects_a_malformed_token(self):- assert verify_push_identity_token("not-a-jwt", self._team(), DISTINCT_ID, APP_ID) is False-- 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+ _, public_pem = _es256_keypair()+ assert verify_push_identity_token("not-a-jwt", DISTINCT_ID, APP_ID, public_keys=[public_pem]) is False- def test_an_es256_token_does_not_count_as_using_the_shared_secret(self):- # A channel can register a public key while its team still holds a shared secret. Counting- # that as a fallback use would keep the scheme alive for a customer who never signs with it.- private_pem, public_pem = _es256_keypair()+ def test_rejects_every_token_when_no_public_key_is_registered(self) -> None:+ private_pem, _ = _es256_keypair()token = sign_push_identity_token_es256(private_pem, DISTINCT_ID, APP_ID)- team = self._team(secret=CURRENT_SECRET)- before = self._fallback_count()-- assert verify_push_identity_token(token, team, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is True- assert self._fallback_count() == before-- 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+ assert verify_push_identity_token(token, DISTINCT_ID, APP_ID) is Falsedef 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@@ -148,17 +111,22 @@ class TestPushIdentityTokens(SimpleTestCase):.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- )+ assert verify_push_identity_token(token, 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.+ def test_rejects_a_token_signed_with_a_project_secret(self):+ # The shared-secret scheme this endpoint used to accept. A project that still signs that way+ # gets a 401 rather than a silent downgrade to a weaker check._, 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+ forged = _forge_hs256(+ secrets.token_hex(32),+ {+ "sub": DISTINCT_ID,+ "app_id": APP_ID,+ "aud": PUSH_IDENTITY_TOKEN_AUDIENCE,+ "exp": int((datetime.now(UTC) + timedelta(minutes=5)).timestamp()),+ },+ )+ assert verify_push_identity_token(forged, DISTINCT_ID, APP_ID, public_keys=[public_pem]) is Falsedef 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@@ -174,5 +142,4 @@ class TestPushIdentityTokens(SimpleTestCase):"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 False+ assert verify_push_identity_token(forged, 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 3f36589602d2..9294e968b464 100644--- a/products/messaging/backend/api/test/test_push_subscriptions.py+++ b/products/messaging/backend/api/test/test_push_subscriptions.py@@ -19,7 +19,7 @@ from posthog.models.team.team import Teamfrom posthog.models.team.team_caching import set_team_in_cachefrom products.messaging.backend.api import push_subscriptions-from products.messaging.backend.api.push_identity_tokens import sign_push_identity_token, sign_push_identity_token_es256+from products.messaging.backend.api.push_identity_tokens import sign_push_identity_token_es256from products.messaging.backend.api.push_subscriptions import (PUSH_SUBSCRIPTION_DISCARD_COUNTER,PUSH_SUBSCRIPTION_REJECTION_COUNTER,@@ -45,9 +45,6 @@ def _es256_keypair() -> tuple[str, str]:class TestPushSubscriptionsAPI(BaseTest):- # Realistic length (>= 32 bytes) so signing/verification exercises a real phs_ secret.- SECRET = "phs_project_secret_0123456789abcdef0123"-def setUp(self):super().setUp()self.client = Client()@@ -91,9 +88,7 @@ class TestPushSubscriptionsAPI(BaseTest):def _enable_identity_verification(self, mode: str):self.firebase_integration.config["push_identity_verification"] = modeself.firebase_integration.save()- self.team.secret_api_token = self.SECRET- self.team.save()- # The endpoint resolves the team from the token cache, so refresh it with the secret set.+ # 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.api.push_subscriptions.capture_internal")@@ -531,25 +526,6 @@ class TestPushSubscriptionsAPI(BaseTest):assert response.status_code == status.HTTP_200_OKmock_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)- self._enable_identity_verification("required")- token = sign_push_identity_token(self.SECRET, "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_rejects_registration_without_a_token(self, mock_capture: MagicMock):self._enable_identity_verification("required")@@ -571,8 +547,9 @@ class TestPushSubscriptionsAPI(BaseTest):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.- self._enable_identity_verification("required")- attacker_token = sign_push_identity_token(self.SECRET, "attacker", "my-firebase-project")+ 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({@@ -722,8 +699,9 @@ class TestPushSubscriptionsAPI(BaseTest):@patch("products.messaging.backend.api.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)- self._enable_identity_verification("required")- token = sign_push_identity_token(self.SECRET, "user-1", "my-firebase-project")+ 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({diff --git a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.tsindex 3bdafe6d8751..0da6cea2e0d7 100644--- a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts@@ -10,11 +10,12 @@ import { IntegrationType } from '~/types'import {PushIdentityVerificationMode,+ pushIdentityPublicKeyError,pushIdentityPublicKeysPayload,pushIdentityVerificationPayload,resolvePushIdentityPublicKey,resolvePushIdentityVerification,-} from '../PushIdentityVerificationField'+} from '../pushIdentityVerification'export interface APNSSetupModalLogicProps {integration?: IntegrationType | null@@ -257,11 +258,12 @@ export const apnsSetupModalLogic = kea<apnsSetupModalLogicType>([identityVerification: resolvePushIdentityVerification(props.integration),identityPublicKey: resolvePushIdentityPublicKey(props.integration),},- errors: ({ signingKey, keyId, teamId, bundleId }) => ({+ errors: ({ signingKey, keyId, teamId, bundleId, identityVerification, identityPublicKey }) => ({signingKey: signingKey.trim() ? undefined : 'Signing key is required',keyId: keyId.trim() ? undefined : 'Key ID is required',teamId: teamId.trim() ? undefined : 'Team ID is required',bundleId: bundleId.trim() ? undefined : 'Bundle ID is required',+ identityPublicKey: pushIdentityPublicKeyError(identityVerification, identityPublicKey),}),submit: async () => {try {diff --git a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.tsindex 80cfe0758653..e8e3f54c3f88 100644--- a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts@@ -10,11 +10,12 @@ import { IntegrationType } from '~/types'import {PushIdentityVerificationMode,+ pushIdentityPublicKeyError,pushIdentityPublicKeysPayload,pushIdentityVerificationPayload,resolvePushIdentityPublicKey,resolvePushIdentityVerification,-} from '../PushIdentityVerificationField'+} from '../pushIdentityVerification'export interface FCMSetupModalLogicProps {integration?: IntegrationType | null@@ -155,8 +156,9 @@ export const fcmSetupModalLogic = kea<fcmSetupModalLogicType>([identityVerification: resolvePushIdentityVerification(props.integration),identityPublicKey: resolvePushIdentityPublicKey(props.integration),},- errors: ({ serviceAccountKey }) => ({+ errors: ({ serviceAccountKey, identityVerification, identityPublicKey }) => ({serviceAccountKey: serviceAccountKey.trim() ? undefined : 'Service account key is required',+ identityPublicKey: pushIdentityPublicKeyError(identityVerification, identityPublicKey),}),submit: async () => {let keyInfo: Record<string, unknown>diff --git a/products/workflows/frontend/Channels/PushIdentityVerificationField.tsx b/products/workflows/frontend/Channels/PushIdentityVerificationField.tsxindex 23c89c19cb45..e86ff1dae5f5 100644--- a/products/workflows/frontend/Channels/PushIdentityVerificationField.tsx+++ b/products/workflows/frontend/Channels/PushIdentityVerificationField.tsx@@ -2,59 +2,7 @@ import { LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'-import { IntegrationType } from '~/types'--export type PushIdentityVerificationMode = 'disabled' | 'optional' | 'required'--export const PUSH_IDENTITY_VERIFICATION_MODES: PushIdentityVerificationMode[] = ['disabled', 'optional', 'required']--export const PUSH_IDENTITY_VERIFICATION_DEFAULT: PushIdentityVerificationMode = 'disabled'--/**- * Seed the form from what the integration already has. Reconnecting to rotate credentials submits- * this field like any other, so defaulting to `disabled` would silently turn verification off for a- * channel that had it on — the backend can't tell that apart from someone deliberately disabling it.- */-export function resolvePushIdentityVerification(integration?: IntegrationType | null): PushIdentityVerificationMode {- const stored = integration?.config?.push_identity_verification- return PUSH_IDENTITY_VERIFICATION_MODES.includes(stored) ? stored : PUSH_IDENTITY_VERIFICATION_DEFAULT-}--/**- * Config fragment to merge into the create payload. Sending the key at all counts as changing the- * policy and requires project admin, so an unchanged field is omitted — that lets a member connect or- * reconnect a channel, and leaves the stored policy for the backend to carry forward.- */-export function pushIdentityVerificationPayload(- mode: PushIdentityVerificationMode,- integration?: IntegrationType | null-): { push_identity_verification?: PushIdentityVerificationMode } {- 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] : [] }-}+import { PushIdentityVerificationMode } from './pushIdentityVerification'const MODE_HELP: Record<PushIdentityVerificationMode, string> = {disabled: 'Any client with your project API key can register a device for any user.',@@ -90,7 +38,7 @@ export function PushIdentityVerificationField({ mode }: { mode: PushIdentityVeri<LemonFieldname="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)."+ 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."><LemonTextAreaplaceholder={'-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----'}diff --git a/products/workflows/frontend/Channels/pushIdentityVerification.test.ts b/products/workflows/frontend/Channels/pushIdentityVerification.test.tsnew file mode 100644index 000000000000..55f4cb72a0ca--- /dev/null+++ b/products/workflows/frontend/Channels/pushIdentityVerification.test.ts@@ -0,0 +1,16 @@+import { PushIdentityVerificationMode, pushIdentityPublicKeyError } from './pushIdentityVerification'++describe('pushIdentityPublicKeyError', () => {+ const key = '-----BEGIN PUBLIC KEY-----\nabc\n-----END PUBLIC KEY-----'++ it.each<[PushIdentityVerificationMode, string, boolean]>([+ ['disabled', '', false],+ ['optional', '', false],+ ['required', '', true],+ ['required', ' \n', true],+ ['optional', key, false],+ ['required', key, false],+ ])('mode %s with key %j reports an error: %s', (mode, publicKey, hasError) => {+ expect(pushIdentityPublicKeyError(mode, publicKey) !== undefined).toBe(hasError)+ })+})diff --git a/products/workflows/frontend/Channels/pushIdentityVerification.ts b/products/workflows/frontend/Channels/pushIdentityVerification.tsnew file mode 100644index 000000000000..7e32403844e9--- /dev/null+++ b/products/workflows/frontend/Channels/pushIdentityVerification.ts@@ -0,0 +1,58 @@+import { IntegrationType } from '~/types'++export type PushIdentityVerificationMode = 'disabled' | 'optional' | 'required'++export const PUSH_IDENTITY_VERIFICATION_MODES: PushIdentityVerificationMode[] = ['disabled', 'optional', 'required']++export const PUSH_IDENTITY_VERIFICATION_DEFAULT: PushIdentityVerificationMode = 'disabled'++/**+ * Seed the form from what the integration already has. Reconnecting to rotate credentials submits+ * this field like any other, so defaulting to `disabled` would silently turn verification off for a+ * channel that had it on — the backend can't tell that apart from someone deliberately disabling it.+ */+export function resolvePushIdentityVerification(integration?: IntegrationType | null): PushIdentityVerificationMode {+ const stored = integration?.config?.push_identity_verification+ return PUSH_IDENTITY_VERIFICATION_MODES.includes(stored) ? stored : PUSH_IDENTITY_VERIFICATION_DEFAULT+}++/**+ * Config fragment to merge into the create payload. Sending the key at all counts as changing the+ * policy and requires project admin, so an unchanged field is omitted — that lets a member connect or+ * reconnect a channel, and leaves the stored policy for the backend to carry forward.+ */+export function pushIdentityVerificationPayload(+ mode: PushIdentityVerificationMode,+ integration?: IntegrationType | null+): { push_identity_verification?: PushIdentityVerificationMode } {+ 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] : [] }+}++/** Verification checks tokens against the registered public key only, so `required` needs one to accept any device. */+export function pushIdentityPublicKeyError(mode: PushIdentityVerificationMode, publicKey: string): string | undefined {+ return mode === 'required' && !publicKey.trim() ? 'Public key is required to verify identity tokens' : undefined+}