-
Notifications
You must be signed in to change notification settings - Fork 3.1k
feat(messaging): optional identity verification for push subscriptions #72488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+362
−7
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
20f86f1
feat(messaging): add opt-in identity verification for push registration
claude 8556d8e
Merge branch 'master' into claude/push-identity-verification
dmarchuk 570bac8
fix(messaging): resolve push identity mode fail-closed across duplica…
claude b92709d
Merge branch 'master' into claude/push-identity-verification
dmarchuk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| """ | ||
| Signed identity tokens for push subscription registration. | ||
|
|
||
| A push device token (FCM registration token / APNs device token) is a delivery *address*, not a | ||
| credential: FCM/APNs hand a token to any app instance that registers, and an attacker owns their own | ||
| token legitimately. So possession of a token proves "deliver to this device" — never "this device | ||
| belongs to user X". Binding a token to a `distinct_id` therefore needs proof that the caller is | ||
| allowed to act for that `distinct_id`. The public project token can't provide it: it is embedded in | ||
| the mobile app and world-readable, so anyone can present it and claim any `distinct_id`. | ||
|
|
||
| Following the pattern proven by Braze's "SDK Authentication", the customer's backend — the only party | ||
| that 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 | ||
| registration 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. | ||
| """ | ||
|
|
||
| from datetime import UTC, datetime, timedelta | ||
|
|
||
| import jwt | ||
|
|
||
| from posthog.models.team.team import Team | ||
|
|
||
| PUSH_IDENTITY_TOKEN_AUDIENCE = "posthog:push_identity" | ||
| _ALGORITHM = "HS256" | ||
|
|
||
| # 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 jwt.encode( | ||
| { | ||
| "sub": distinct_id, | ||
| "app_id": app_id, | ||
| "aud": PUSH_IDENTITY_TOKEN_AUDIENCE, | ||
| "exp": datetime.now(UTC) + ttl, | ||
| }, | ||
| secret_api_token, | ||
| algorithm=_ALGORITHM, | ||
| ) | ||
|
|
||
|
|
||
| def verify_push_identity_token(token: str, team: Team, distinct_id: str, app_id: str) -> 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. | ||
|
|
||
| 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: | ||
| return True | ||
| return False | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
products/messaging/backend/api/test/test_push_identity_tokens.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| from datetime import timedelta | ||
|
|
||
| from django.test import SimpleTestCase | ||
|
|
||
| import jwt | ||
| from parameterized import parameterized | ||
|
|
||
| from posthog.models.team.team import Team | ||
|
|
||
| from products.messaging.backend.api.push_identity_tokens import ( | ||
| PUSH_IDENTITY_TOKEN_AUDIENCE, | ||
| sign_push_identity_token, | ||
| verify_push_identity_token, | ||
| ) | ||
|
|
||
| # 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 test_verifies_a_token_signed_with_the_current_secret(self): | ||
| token = sign_push_identity_token(CURRENT_SECRET, DISTINCT_ID, APP_ID) | ||
| assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is True | ||
|
|
||
| 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 | ||
|
|
||
| @parameterized.expand( | ||
| [ | ||
| ("wrong_distinct_id", "someone-else", APP_ID), | ||
| ("wrong_app_id", DISTINCT_ID, "other-app"), | ||
| ] | ||
| ) | ||
| 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 | ||
|
|
||
| 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_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 | ||
|
|
||
| def 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. | ||
| token = jwt.encode( | ||
| {"sub": DISTINCT_ID, "app_id": APP_ID, "aud": PUSH_IDENTITY_TOKEN_AUDIENCE}, | ||
| CURRENT_SECRET, | ||
| algorithm="HS256", | ||
| ) | ||
| assert verify_push_identity_token(token, self._team(), DISTINCT_ID, APP_ID) is False | ||
|
|
||
| def 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 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.