Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(oauth): link id-jag identities to users by idp subject (#113014)

Rafael Audibertcd9925d42da1
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 5c47ee2a525c..359b408a0ff8 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -89,6 +89,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
# RoleMembership has a direct user FK but org is indirect (via role), so the
# script sees it as user_scoped while semgrep correctly has it in org_scoped.
"RoleMembership",
+ # IdJagIdentity has a direct user FK but org is indirect (via its IdentityProviderConfig),
+ # so the script sees it as user_scoped while semgrep has it in org_scoped.
+ "IdJagIdentity",
# --- Ingestion/event tables (not queried by user-supplied ID) ---
"CoreEvent",
"ElementGroup",
@@ -330,6 +333,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"Role",
"RoleMembership",
"LinkedIdentityProviderConfig",
+ "IdJagIdentity",
# --- User-scoped (cross-tenant by design) ---
"NotificationViewed",
"SCIMProvisionedUser",
diff --git a/.semgrep/rules/security/idor-team-scoped-models.py b/.semgrep/rules/security/idor-team-scoped-models.py
index 9b526d531ce8..77f08556a92a 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.py
+++ b/.semgrep/rules/security/idor-team-scoped-models.py
@@ -6,6 +6,7 @@ from products.product_analytics.backend.facade.models import Insight
from products.actions.backend.models.action import Action
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project import Project
+from posthog.models.id_jag_identity import IdJagIdentity
from posthog.models.user_scene_personalisation import UserScenePersonalisation
from ee.models.rbac.role import Role, RoleMembership
@@ -336,6 +337,12 @@ def vulnerable_org_filter_from_data(request):
return RoleMembership.objects.filter(pk=membership_id)
+def vulnerable_org_get_id_jag_identity(request):
+ identity_id = request.data.get("identity_id")
+ # ruleid: idor-taint-user-input-to-org-model, idor-lookup-without-org
+ return IdJagIdentity.objects.get(pk=identity_id)
+
+
# ok: idor-taint-user-input-to-org-model
def safe_org_get_with_organization(request, organization):
project_id = request.GET.get("project_id")
@@ -357,6 +364,13 @@ def safe_org_filter_with_role_organization(request, organization):
return RoleMembership.objects.filter(pk=membership_id, role__organization=organization)
+# ok: idor-taint-user-input-to-org-model
+def safe_org_get_id_jag_identity_with_config(request, idp_config):
+ identity_id = request.data.get("identity_id")
+ # ok: idor-lookup-without-org
+ return IdJagIdentity.objects.get(pk=identity_id, identity_provider_config=idp_config)
+
+
# ============================================================
# idor-lookup-without-org (WARNING - pattern rule)
# ============================================================
@@ -388,6 +402,14 @@ obj, created = Role.objects.get_or_create(name="test")
# ok: idor-lookup-without-org
obj, created = Role.objects.get_or_create(name="test", organization=organization)
+# ruleid: idor-lookup-without-org
+identity, created = IdJagIdentity.objects.get_or_create(subject=subject, defaults={"user": user})
+
+# ok: idor-lookup-without-org
+identity, created = IdJagIdentity.objects.get_or_create(
+ identity_provider_config=idp_config, subject=subject, defaults={"user": user}
+)
+
# ruleid: idor-lookup-without-org
obj = Role.objects.aget_or_create(name="test")
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index a1fd11f0ff51..2c3a325cf199 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -946,6 +946,7 @@ rules:
IDOR: User input flows to organization-scoped model lookup without organization filter.
Fix: Add organization=organization or organization_id=organization_id to the query.
For RoleMembership, use role__organization= or role__organization_id=.
+ For IdJagIdentity, use identity_provider_config= or identity_provider_config_id=.
pattern-sources:
- patterns:
- pattern-either:
@@ -990,6 +991,7 @@ rules:
|CrossProjectDashboard
|CrossProjectDashboardTile
|DesktopBetaTermsAcceptance
+ |IdJagIdentity
|IdentityProviderConfig
|LegalDocument
|ManagedWarehouseSourceLifecycle
@@ -1014,6 +1016,8 @@ rules:
- pattern: $M.objects. ... .$METHOD(..., organization__id=$O, ...)
- pattern: $M.objects. ... .$METHOD(..., role__organization=$O, ...)
- pattern: $M.objects. ... .$METHOD(..., role__organization_id=$O, ...)
+ - pattern: $M.objects. ... .$METHOD(..., identity_provider_config=$C, ...)
+ - pattern: $M.objects. ... .$METHOD(..., identity_provider_config_id=$C, ...)
# get_object_or_404
- pattern: get_object_or_404($M, ..., organization=$O, ...)
- pattern: get_object_or_404($M, ..., organization_id=$O, ...)
@@ -1068,6 +1072,7 @@ rules:
|CrossProjectDashboard
|CrossProjectDashboardTile
|DesktopBetaTermsAcceptance
+ |IdJagIdentity
|IdentityProviderConfig
|LegalDocument
|ManagedWarehouseSourceLifecycle
@@ -1090,6 +1095,8 @@ rules:
- pattern-not: $M.objects. ... .$METHOD2(..., organization__id=$O, ...)
- pattern-not: $M.objects. ... .$METHOD2(..., role__organization=$O, ...)
- pattern-not: $M.objects. ... .$METHOD2(..., role__organization_id=$O, ...)
+ - pattern-not: $M.objects. ... .$METHOD2(..., identity_provider_config=$C, ...)
+ - pattern-not: $M.objects. ... .$METHOD2(..., identity_provider_config_id=$C, ...)
# get_object_or_404
- pattern-not: get_object_or_404($M, ..., organization=$O, ...)
- pattern-not: get_object_or_404($M, ..., organization_id=$O, ...)
@@ -1105,6 +1112,7 @@ rules:
IDOR risk: Lookup on organization-scoped model without organization filter.
Fix: Add organization_id=organization_id or organization=organization to the query.
For RoleMembership, use role__organization= or role__organization_id=.
+ For IdJagIdentity, use identity_provider_config= or identity_provider_config_id=.
languages: [python]
severity: WARNING
metadata:
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index 439a92a73cd4..ba81e865df84 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -14,6 +14,7 @@ from typing import Any, TypedDict, cast
from django.conf import settings
from django.core.cache import cache
+from django.db import IntegrityError
import jwt
import requests
@@ -25,6 +26,7 @@ from posthog.constants import AvailableFeature
from posthog.dataclasses import frozen
from posthog.helpers.email_utils import EmailLookupHandler
from posthog.jwt import ASYMMETRIC_SIGNING_ALGORITHMS
+from posthog.models.id_jag_identity import IDENTITY_FIELD_MAX_LENGTH, IdJagIdentity
from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.user import User
from posthog.scopes import get_oauth_scopes_supported
@@ -111,6 +113,7 @@ class IdJagClaims(TypedDict, total=False):
scope: str
resource: str
jti: str
+ tenant: str
iat: int
nbf: int
exp: int
@@ -121,6 +124,7 @@ class _VerifiedIdJag:
claims: IdJagClaims
provider_name: str
identity_provider_config: IdentityProviderConfig
+ issuer: str
@frozen
@@ -416,34 +420,83 @@ def _verify_and_extract_id_jag_token(assertion: str, authenticated_client_id: st
)
raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)
- verified_email = claims.get("email") or claims.get("sub") or ""
-
- # Membership must match the configuration's organization because the access token is scoped to it.
- is_member = EmailLookupHandler.users_matching_email(
- verified_email,
- User.objects.filter(
- is_active=True,
- organization_membership__organization_id=idp_config.organization_id,
- ),
- ).exists()
- if not is_member:
- raise InvalidGrantError(
- "ID-JAG sub is not an active member of the organization that owns this IdP configuration"
- )
-
return _VerifiedIdJag(
claims=claims,
provider_name=provider_name,
identity_provider_config=idp_config,
+ issuer=expected_issuer,
+ )
+
+
+def _resolve_user(verified_id_jag: _VerifiedIdJag) -> User:
+ """The active org member this ID-JAG speaks for.
+
+ The IdP subject is the stable key. Email only matches a member the first time a subject
+ is seen, and that match is stored, so a later change of email at either end keeps the
+ same account. A member already bound to a different subject is refused: the IdP has
+ given their email address to someone else.
+ """
+ idp_config = verified_id_jag.identity_provider_config
+ claims = verified_id_jag.claims
+ issuer = verified_id_jag.issuer
+ tenant = str(claims.get("tenant") or "")
+ subject = str(claims["sub"])
+ if len(tenant) > IDENTITY_FIELD_MAX_LENGTH or len(subject) > IDENTITY_FIELD_MAX_LENGTH:
+ raise InvalidGrantError(f"ID-JAG sub and tenant must be at most {IDENTITY_FIELD_MAX_LENGTH} characters")
+ # Membership must match the configuration's organization because the access token is scoped to it.
+ members = User.objects.filter(is_active=True, organization_membership__organization_id=idp_config.organization_id)
+ not_a_member = InvalidGrantError(
+ "ID-JAG sub is not an active member of the organization that owns this IdP configuration"
)
+ def linked_member(user_id: int) -> User:
+ linked_user = members.filter(pk=user_id).first()
+ if linked_user is None:
+ raise not_a_member
+ return linked_user
+
+ linked_user_id = (
+ IdJagIdentity.objects.filter(identity_provider_config=idp_config, issuer=issuer, tenant=tenant, subject=subject)
+ .values_list("user_id", flat=True)
+ .first()
+ )
+ if linked_user_id is not None:
+ return linked_member(linked_user_id)
+
+ verified_email = claims.get("email") or subject
+ user = EmailLookupHandler.users_matching_email(verified_email, members).first()
+ if user is None:
+ raise not_a_member
+
+ try:
+ identity, _ = IdJagIdentity.objects.get_or_create(
+ identity_provider_config=idp_config,
+ issuer=issuer,
+ tenant=tenant,
+ subject=subject,
+ defaults={"user": user},
+ )
+ except IntegrityError:
+ # get_or_create recovers from a concurrent link of this subject, so the clash is on the member.
+ logger.info(
+ "id_jag_token_rejected",
+ reason="member is already linked to a different IdP subject",
+ identity_provider_config_id=str(idp_config.id),
+ stage="subject_link",
+ )
+ raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)
+ if identity.user_id != user.pk:
+ # A concurrent first exchange linked this subject to another member, and the subject decides.
+ return linked_member(identity.user_id)
+ return user
+
def _construct_access_token_payload(
claims: IdJagClaims,
provider_name: str,
granted_scopes: list[str],
organization_id: Any,
- verified_email: str,
+ user: User,
) -> dict[str, Any]:
"""
Constructs the payload for the JWT access token which will be issued to the ID-JAG caller.
@@ -457,7 +510,8 @@ def _construct_access_token_payload(
payload: dict[str, Any] = {
"iss": _get_site_url(),
"sub": _get_sub(provider_name, cast(str, claims.get("sub"))),
- "email": verified_email,
+ "email": user.email,
+ "user_uuid": str(user.uuid),
"aud": claims.get("resource"),
"client_id": claims.get("client_id"),
"scope": " ".join(granted_scopes),
@@ -533,13 +587,13 @@ def issue_access_token(
sanitized_id_jag_scopes = [s for s in id_jag_scopes if s in known_scopes]
granted = _get_scopes(sanitized_id_jag_scopes, parsed_requested)
- verified_email = verified_id_jag.claims.get("email") or verified_id_jag.claims.get("sub") or ""
+ user = _resolve_user(verified_id_jag)
payload = _construct_access_token_payload(
verified_id_jag.claims,
verified_id_jag.provider_name,
granted,
organization.pk,
- cast(str, verified_email),
+ user,
)
token = _construct_access_token(payload)
return IssuedAccessToken(
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 5ca03d045b18..0c4ccf60bbfb 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -12,6 +12,7 @@ The strategy is:
"""
import time
+import uuid
from typing import Any
from urllib.parse import urlencode
@@ -41,6 +42,7 @@ from posthog.auth import IDJagAccessTokenAuthentication
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.activity_logging.utils import ACTIVITY_LOG_CREDENTIAL_ID_MAX_LENGTH
+from posthog.models.id_jag_identity import IdJagIdentity
from posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfig
from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.oauth import OAuthApplication
@@ -119,7 +121,7 @@ def _make_id_jag(
"client_id": client_id,
"resource": resource,
"scope": scope,
- "jti": f"id-jag-{now}",
+ "jti": f"id-jag-{uuid.uuid4()}",
"iat": iat if iat is not None else now,
"nbf": nbf if nbf is not None else now,
"exp": now + exp_seconds,
@@ -196,6 +198,17 @@ class TestIdJagTokenEndpoint(APIBaseTest):
return self.client.post("/oauth/token", data=urlencode(data), content_type=content_type)
return self.client.post("/oauth/token", data=data, content_type=content_type)
+ def _exchange(
+ self, *, sub: str, email: str = "[email protected]", tenant: str = "", issuer: str = _IDP_ISSUER
+ ) -> Any:
+ extra_claims: dict[str, Any] = {"email": email, **({"tenant": tenant} if tenant else {})}
+ assertion = _make_id_jag(issuer=issuer, sub=sub, extra_claims=extra_claims)
+ return self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
+
+ def _link_subject(self, sub: str) -> None:
+ resp = self._exchange(sub=sub)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.json())
+
@parameterized.expand(
[
("RS256", _IDP_PRIVATE_KEY_PEM),
@@ -225,6 +238,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.assertEqual(claims["aud"], _RESOURCE_URL)
self.assertEqual(claims["client_id"], _RESOURCE_CLIENT_ID)
self.assertEqual(claims["app_org"], _PROVIDER_NAME)
+ self.assertEqual(claims["user_uuid"], str(self.user.uuid))
self.assertIn("jti", claims)
self.assertIn("iat", claims)
self.assertIn("exp", claims)
@@ -507,6 +521,10 @@ class TestIdJagTokenEndpoint(APIBaseTest):
# verified domain.
attacker_org = Organization.objects.create(name="attacker-org")
+ attacker_org.available_product_features = [
+ {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}
+ ]
+ attacker_org.save()
attacker_domain = OrganizationDomain.objects.create(
organization=attacker_org,
domain="bigco.example",
@@ -535,6 +553,75 @@ class TestIdJagTokenEndpoint(APIBaseTest):
self.assertEqual(resp.json()["error"], "invalid_grant")
self.assertIn("active member", resp.json()["error_description"])
+ def test_linked_subject_keeps_resolving_after_the_email_changes(self) -> None:
+ self._link_subject("idp-user-1")
+
+ self.user.email = "[email protected]"
+ self.user.save()
+ second = self._exchange(sub="idp-user-1", email="[email protected]")
+
+ self.assertEqual(second.status_code, status.HTTP_200_OK, second.json())
+ claims = jwt.decode(
+ second.json()["access_token"],
+ _public_key_for(_AS_PRIVATE_KEY_PEM),
+ algorithms=["RS256"],
+ audience=_RESOURCE_URL,
+ issuer=_AUTH_SERVER_URL,
+ )
+ self.assertEqual(claims["user_uuid"], str(self.user.uuid))
+
+ @parameterized.expand(
+ [("different_subject", "idp-user-2", ""), ("same_subject_other_tenant", "idp-user-1", "other")]
+ )
+ def test_rejects_email_match_for_member_linked_to_another_identity(self, _name: str, sub: str, tenant: str) -> None:
+ self._link_subject("idp-user-1")
+
+ second = self._exchange(sub=sub, tenant=tenant)
+
+ self.assertEqual(second.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(second.json()["error"], "invalid_grant")
+ self.assertEqual(IdJagIdentity.objects.filter(user=self.user).count(), 1)
+
+ def test_link_from_a_replaced_issuer_does_not_resolve_the_new_issuers_subject(self) -> None:
+ self._link_subject("idp-user-1")
+ other_user = UserModel.objects.create_and_join(self.organization, "[email protected]", "x")
+ new_issuer = "https://new-idp.example.com"
+ config = (
+ OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)
+ .identity_provider_configs_for_scope(ConfigScope.ID_JAG)
+ .first()
+ )
+ config.id_jag_issuer_url = new_issuer
+ config.save()
+
+ resp = self._exchange(sub="idp-user-1", email="[email protected]", issuer=new_issuer)
+
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.json())
+ claims = jwt.decode(
+ resp.json()["access_token"],
+ _public_key_for(_AS_PRIVATE_KEY_PEM),
+ algorithms=["RS256"],
+ audience=_RESOURCE_URL,
+ issuer=_AUTH_SERVER_URL,
+ )
+ self.assertEqual(claims["user_uuid"], str(other_user.uuid))
+
+ def test_rejects_linked_subject_whose_user_left_the_organization(self) -> None:
+ self._link_subject("idp-user-1")
+
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()
+ second = self._exchange(sub="idp-user-1")
+
+ self.assertEqual(second.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("active member", second.json()["error_description"])
+
+ @parameterized.expand([("sub", "s" * 256, ""), ("tenant", "idp-user-1", "t" * 256)])
+ def test_rejects_identity_claims_longer_than_stored(self, _name: str, sub: str, tenant: str) -> None:
+ resp = self._exchange(sub=sub, tenant=tenant)
+
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(resp.json()["error"], "invalid_grant")
+
def test_rejects_signature_from_unrecognized_key(self) -> None:
other_pem = generate_rsa_private_key_pem()
assertion = _make_id_jag(signing_pem=other_pem)
@@ -926,6 +1013,7 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
*,
sub: str | None = None,
email: str | None = None,
+ user_uuid: str | None = None,
aud: str = _RESOURCE_URL,
iss: str = _AUTH_SERVER_URL,
scope: str = "feature_flag:read",
@@ -940,6 +1028,7 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
"iss": iss,
"sub": sub if sub is not None else f"{_PROVIDER_NAME}:{self.user.email}",
"email": email if email is not None else self.user.email,
+ "user_uuid": user_uuid if user_uuid is not None else str(self.user.uuid),
"aud": aud,
"client_id": client_id,
"scope": scope,
@@ -1080,36 +1169,23 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
- def test_unknown_user_email_rejected(self) -> None:
- token = self._mint_access_token(
- sub=f"{_PROVIDER_NAME}:[email protected]",
- scope="user:read",
- )
+ def test_unknown_user_uuid_rejected(self) -> None:
+ token = self._mint_access_token(user_uuid=str(uuid.uuid4()), scope="user:read")
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
- def test_opaque_sub_with_email_claim_authenticates_user(self) -> None:
- # OIDC IdPs (Okta, Auth0, Entra) emit opaque `sub` values — the user's
- # PostHog identity is in the separate `email` claim. The resource-side
- # authenticator must key off `email`, not the userSub half of `sub`.
- token = self._mint_access_token(
- sub=f"{_PROVIDER_NAME}:auth0|opaque-id-abc123",
- email=self.user.email,
- scope="user:read",
- )
+ def test_user_is_resolved_by_uuid_not_by_email(self) -> None:
+ token = self._mint_access_token(email="[email protected]", scope="user:read")
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
- self.assertEqual(resp.json()["email"], self.user.email)
+ self.assertEqual(resp.json()["uuid"], str(self.user.uuid))
- def test_missing_email_claim_rejected(self) -> None:
- # `email` is the authenticated identity — a token without it must not
- # fall back to parsing `sub` for an email.
+ def test_missing_user_uuid_claim_rejected(self) -> None:
now = int(time.time())
payload = {
"iss": _AUTH_SERVER_URL,
"sub": f"{_PROVIDER_NAME}:{self.user.email}",
- # email intentionally missing
+ "email": self.user.email,
"aud": _RESOURCE_URL,
"client_id": _RESOURCE_CLIENT_ID,
"scope": "user:read",
@@ -1121,11 +1197,6 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
resp = self._call_authenticated(token)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
- def test_malformed_sub_claim_rejected(self) -> None:
- token = self._mint_access_token(sub="no_provider_prefix", scope="user:read")
- resp = self._call_authenticated(token)
- self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
-
def test_non_id_jag_jwt_passes_through(self) -> None:
"""A JWT without `typ: at+jwt` must not be claimed by ID-JAG auth — it
could be e.g. a sharing JWT handled by another backend."""
diff --git a/posthog/auth.py b/posthog/auth.py
index a4074f505075..3d8638d7cc97 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -608,9 +608,8 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
ID-JAG (XAA) JWT Bearer grant served from the OAuth token endpoint
(`/oauth/token`, logic in `posthog.api.id_jag`). Validates the JWT against the
RS256 public key derived from `OIDC_RSA_PRIVATE_KEY` and binds the request
- to the User whose email matches the `userSub` half of the token's `sub`
- claim (`{provider}:{userSub}` per
- https://xaa.dev/docs/token-structure#sub-claim-format).
+ to the User named by the token's `user_uuid` claim, which the token endpoint
+ resolved from the IdP subject.
Scope enforcement lives in `posthog.permissions.APIScopePermission`; this
class only handles signature + claim validation and user resolution.
@@ -637,20 +636,6 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
return token
- @classmethod
- def _parse_sub(cls, sub: str) -> Optional[tuple[str, str]]:
- """`{providerName}:{userSub}` per spec — split into (provider, user_sub).
-
- Returns None if the format is malformed (no colon, empty provider, empty
- user_sub) so the caller can fail with `invalid_token`.
- """
- if not sub or ":" not in sub:
- return None
- provider, user_sub = sub.split(":", 1)
- if not provider or not user_sub:
- return None
- return provider, user_sub
-
@classmethod
def _is_id_jag_token(cls, token: str) -> bool:
# Personal/OAuth API key prefixes are reserved for those auth backends.
@@ -702,7 +687,7 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
issuer=site_url,
leeway=settings.ID_JAG_CLOCK_SKEW_SECONDS,
options={
- "require": ["iss", "sub", "email", "aud", "exp", "iat", "client_id", "scope", "org_id"],
+ "require": ["iss", "sub", "user_uuid", "aud", "exp", "iat", "client_id", "scope", "org_id"],
"verify_signature": True,
"verify_exp": True,
"verify_aud": True,
@@ -728,30 +713,17 @@ class IDJagAccessTokenAuthentication(ActivityCredentialMixin, authentication.Bas
if claims is None:
raise AuthenticationFailed(detail="ID-JAG access token is invalid.")
- sub_parts = self._parse_sub(str(claims.get("sub", "")))
- if sub_parts is None:
- raise AuthenticationFailed(
- detail="ID-JAG access token sub claim is not in the expected '{provider}:{userSub}' format."
- )
-
organization_id = str(claims.get("org_id") or "")
if not organization_id:
raise AuthenticationFailed(detail="ID-JAG access token is missing the org_id claim.")
- token_email = str(claims.get("email") or "")
- if not token_email:
- raise AuthenticationFailed(detail="ID-JAG access token is missing the email claim.")
-
- # Resolve the user by (email, org_id) so the token only authenticates
- # against the specific organization it was minted for. This prevents
- # a token from authenticating as another user that happens to share
- # the email, and re-validates membership at every request (the user
- # may have been removed from the org after the token was issued).
+ # Membership is re-checked on every request, because the user may have left the
+ # organization after the token was issued.
membership = (
OrganizationMembership.objects.filter(
organization_id=organization_id,
user__is_active=True,
- user__email__iexact=token_email,
+ user__uuid=str(claims["user_uuid"]),
)
.select_related("user", "organization")
.first()
diff --git a/posthog/migrations/1395_id_jag_identity.py b/posthog/migrations/1395_id_jag_identity.py
new file mode 100644
index 000000000000..2756045c7beb
--- /dev/null
+++ b/posthog/migrations/1395_id_jag_identity.py
@@ -0,0 +1,64 @@
+# Generated by Django 5.2.18 on 2026-10-07 01:39
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1394_backfill_secret_tokens_to_psak"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="IdJagIdentity",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("issuer", models.CharField(max_length=512)),
+ ("tenant", models.CharField(blank=True, default="", max_length=255)),
+ ("subject", models.CharField(max_length=255)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "identity_provider_config",
+ models.ForeignKey(
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="id_jag_identities",
+ to="posthog.identityproviderconfig",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="id_jag_identities",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("identity_provider_config", "issuer", "tenant", "subject"),
+ name="unique_id_jag_identity_subject",
+ ),
+ models.UniqueConstraint(
+ fields=("identity_provider_config", "issuer", "user"),
+ name="unique_id_jag_identity_user",
+ ),
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 367641279289..806fd35d63d3 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1394_backfill_secret_tokens_to_psak
+1395_id_jag_identity
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index cd502fc6c937..d17cc2e7c55e 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -36,6 +36,7 @@ from .group_type_mapping import GroupTypeMapping
from .host_definition import HostDefinition
from .health_issue import HealthIssue
from .identity_provider_config import IdentityProviderConfig
+from .id_jag_identity import IdJagIdentity # noqa: F401
from .linked_identity_provider_config import LinkedIdentityProviderConfig # noqa: F401
from .instance_setting import InstanceSetting
from .integration import Integration
diff --git a/posthog/models/id_jag_identity.py b/posthog/models/id_jag_identity.py
new file mode 100644
index 000000000000..1a086f3c1f48
--- /dev/null
+++ b/posthog/models/id_jag_identity.py
@@ -0,0 +1,41 @@
+from django.db import models
+
+from posthog.models.utils import UUIDModel
+
+IDENTITY_FIELD_MAX_LENGTH = 255
+
+
+class IdJagIdentity(UUIDModel):
+ """Binds an IdP subject to the PostHog user it was first matched to by email.
+
+ Later ID-JAGs resolve the user by subject, so an IdP-side email change keeps the same
+ account, and an email address the IdP gives to a different person reaches no account.
+ """
+
+ # db_index=False: both unique constraints lead with this column and serve its lookups.
+ identity_provider_config = models.ForeignKey(
+ "posthog.IdentityProviderConfig", on_delete=models.CASCADE, related_name="id_jag_identities", db_index=False
+ )
+ # The verified `iss`. Subjects are unique only within one issuer, so a link made under an
+ # issuer the configuration no longer names must not resolve tokens from its replacement.
+ issuer = models.CharField(max_length=512)
+ # The draft's `tenant` claim, set by IdPs that issue for several tenants under one `iss`.
+ tenant = models.CharField(max_length=IDENTITY_FIELD_MAX_LENGTH, blank=True, default="")
+ subject = models.CharField(max_length=IDENTITY_FIELD_MAX_LENGTH)
+ # db_constraint=False: posthog_user is a hot table, see safe-django-migrations.md.
+ user = models.ForeignKey(
+ "posthog.User", on_delete=models.CASCADE, db_constraint=False, related_name="id_jag_identities"
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=("identity_provider_config", "issuer", "tenant", "subject"),
+ name="unique_id_jag_identity_subject",
+ ),
+ models.UniqueConstraint(
+ fields=("identity_provider_config", "issuer", "user"),
+ name="unique_id_jag_identity_user",
+ ),
+ ]