Skip to content

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

chore: gate xaa behind billing feature (#62516)

Reece Jones46acc5ba5a0c
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
index b1dc970cf47f..087a8e475039 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
@@ -102,6 +102,7 @@ const ALL_FEATURES = [
AvailableFeature.SSO_ENFORCEMENT,
AvailableFeature.SAML,
AvailableFeature.SCIM,
+ AvailableFeature.XAA_AUTHENTICATION,
]
type Story = StoryObj<typeof App>
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
index d862f924e872..b034bba21a23 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
@@ -107,6 +107,7 @@ function VerifiedDomainsTable(): JSX.Element {
isSSOEnforcementAvailable,
isSAMLAvailable,
isSCIMAvailable,
+ isXAAAuthenticationAvailable,
} = useValues(verifiedDomainsLogic)
const { currentOrganization } = useValues(organizationLogic)
const {
@@ -121,7 +122,7 @@ function VerifiedDomainsTable(): JSX.Element {
const { preflight } = useValues(preflightLogic)
const { featureFlags } = useValues(featureFlagLogic)
- const isXAAAuthenticationEnabled = !!featureFlags[FEATURE_FLAGS.XAA_AUTHENTICATION]
+ const showXAAControls = !!featureFlags[FEATURE_FLAGS.XAA_AUTHENTICATION] && isXAAAuthenticationAvailable
const restrictionReason = useRestrictedArea({
minimumAccessLevel: OrganizationMembershipLevel.Admin,
@@ -287,7 +288,7 @@ function VerifiedDomainsTable(): JSX.Element {
)
}
- if (isXAAAuthenticationEnabled && has_id_jag) {
+ if (showXAAControls && has_id_jag) {
badges.push(
<IntegrationBadge
key="xaa"
@@ -333,7 +334,7 @@ function VerifiedDomainsTable(): JSX.Element {
>
Configure SCIM
</LemonButton>
- {isXAAAuthenticationEnabled && (
+ {showXAAControls && (
<LemonButton
onClick={() => setConfigureIdJagModalId(id)}
fullWidth
@@ -483,7 +484,7 @@ function VerifiedDomainsTable(): JSX.Element {
<AddDomainModal />
<ConfigureSAMLModal />
<ConfigureSCIMModal />
- {isXAAAuthenticationEnabled && <ConfigureIdJagModal />}
+ {showXAAControls && <ConfigureIdJagModal />}
<ScimLogsModal />
<VerifyDomainModal />
</div>
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
index 5b8860aafdbb..7b66b7c3f330 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
@@ -30,6 +30,7 @@ exports[`verifiedDomainsLogic values has proper defaults 1`] = `
"isSSOEnforcementAvailable": false,
"isSamlConfigSubmitting": false,
"isSamlConfigValid": true,
+ "isXAAAuthenticationAvailable": false,
"samlConfig": {},
"samlConfigAllErrors": {
"saml_acs_url": undefined,
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
index 7bb5b678aa50..1f6a4a6dffa6 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
@@ -330,6 +330,10 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
() => [userLogic.selectors.hasAvailableFeature],
(hasAvailableFeature): boolean => hasAvailableFeature(AvailableFeature.SCIM),
],
+ isXAAAuthenticationAvailable: [
+ () => [userLogic.selectors.hasAvailableFeature],
+ (hasAvailableFeature): boolean => hasAvailableFeature(AvailableFeature.XAA_AUTHENTICATION),
+ ],
}),
afterMount(({ actions }) => actions.loadVerifiedDomains()),
bindModalToUrl({
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 01e318a56a38..88dda083c963 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -149,6 +149,7 @@ export enum AvailableFeature {
SAML = 'saml',
SCIM = 'scim',
SSO_ENFORCEMENT = 'sso_enforcement',
+ XAA_AUTHENTICATION = 'xaa_authentication',
WHITE_LABELLING = 'white_labelling',
COMMUNITY_SUPPORT = 'community_support',
DEDICATED_SUPPORT = 'dedicated_support',
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index 192250a21917..9baee5182491 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -29,6 +29,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.constants import AvailableFeature
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User
from posthog.scopes import get_oauth_scopes_supported
@@ -101,6 +102,13 @@ class InvalidTargetError(IdJagError):
error_code = "invalid_target"
+class AccessDeniedError(IdJagError):
+ # Special error for cases when the organization is not entitled to the XAA billing feature.
+ # This is different from the generic `InvalidGrantError` which is used for cases when the ID-JAG is invalid.
+ error_code = "access_denied"
+ http_status = status.HTTP_403_FORBIDDEN
+
+
class IdJagClaims(TypedDict, total=False):
iss: str
sub: str
@@ -493,6 +501,10 @@ def issue_access_token(
claims, provider_name, org_domain = _verify_and_extract_id_jag_token(assertion)
+ organization = org_domain.organization
+ if not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):
+ raise AccessDeniedError("ID-JAG (XAA) is not enabled for this organization")
+
if request_client_id and request_client_id != claims.get("client_id"):
raise InvalidGrantError("ID-JAG client_id doesn't match the authenticating client")
@@ -505,7 +517,7 @@ def issue_access_token(
granted = _get_scopes(sanitized_id_jag_scopes, parsed_requested)
verified_email = claims.get("email") or claims.get("sub") or ""
payload = _construct_access_token_payload(
- claims, provider_name, granted, org_domain.organization.pk, cast(str, verified_email)
+ claims, provider_name, granted, organization.pk, cast(str, verified_email)
)
token = _construct_access_token(payload)
return token, granted, settings.ID_JAG_ACCESS_TOKEN_TTL_SECONDS
diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.py
index 1930ccdd93ce..0a2afeb36b02 100644
--- a/posthog/api/organization_domain.py
+++ b/posthog/api/organization_domain.py
@@ -190,6 +190,13 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):
code="feature_not_available",
)
+ if instance and attrs.get("id_jag_issuer_url"):
+ if not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):
+ raise serializers.ValidationError(
+ {"id_jag_issuer_url": "XAA (ID-JAG) is not available for this organization."},
+ code="feature_not_available",
+ )
+
return attrs
def update(self, instance: OrganizationDomain, validated_data: dict[str, Any]) -> OrganizationDomain:
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index af2fc8e03797..4958a62ca702 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -35,6 +35,7 @@ from posthog.api.id_jag import (
issue_access_token,
)
from posthog.auth import IDJagAccessTokenAuthentication
+from posthog.constants import AvailableFeature
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User as UserModel
@@ -122,6 +123,10 @@ class TestIdJagTokenEndpoint(APIBaseTest):
super().setUpTestData()
cls.user.email = "[email protected]"
cls.user.save()
+ cls.organization.available_product_features = [
+ {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}
+ ]
+ cls.organization.save()
OrganizationDomain.objects.create(
organization=cls.organization,
domain=_VERIFIED_DOMAIN,
@@ -178,6 +183,29 @@ class TestIdJagTokenEndpoint(APIBaseTest):
# kid matches the JWKS thumbprint so resource servers can select the key during rotation
self.assertEqual(header["kid"], jwk_from_pem(_AS_PRIVATE_KEY_PEM).thumbprint())
+ def test_rejects_when_org_lacks_xaa_billing_feature(self) -> None:
+ # XAA is billing-gated: even a fully valid ID-JAG must be rejected when
+ # the organization that owns the verified domain is not entitled. The
+ # check runs after signature + membership verification, so the failure
+ # surfaces as access_denied (403) rather than the generic rejection.
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ assertion = _make_id_jag()
+ resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.json()["error"], "access_denied")
+
+ def test_issue_access_token_helper_rejects_without_billing_feature(self) -> None:
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ from posthog.api.id_jag import AccessDeniedError
+
+ assertion = _make_id_jag()
+ with self.assertRaises(AccessDeniedError):
+ issue_access_token(assertion, requested_scope=None, request_client_id=None)
+
def test_email_claim_is_preferred_over_sub_for_user_lookup(self) -> None:
# IdPs are not required to put an email in `sub` — it may be an opaque
# stable identifier. When the `email` claim is present we should use it
@@ -756,6 +784,10 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
super().setUp()
self.user.email = "[email protected]"
self.user.save()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}
+ ]
+ self.organization.save()
def _mint_access_token(
self,
@@ -803,6 +835,17 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):
self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
self.assertEqual(resp.json()["email"], self.user.email)
+ def test_rejects_when_org_loses_xaa_billing_feature(self) -> None:
+ # Entitlement is re-checked on every request, mirroring the membership
+ # re-validation: a token minted while the org was entitled must stop
+ # authenticating once the XAA billing feature is removed.
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ token = self._mint_access_token(scope="user:read")
+ resp = self._call_authenticated(token)
+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
+
def test_scope_claim_drives_permission(self) -> None:
# `user:read` is the scope needed for /api/users/@me/.
ok = self._mint_access_token(scope="user:read")
diff --git a/posthog/api/test/test_organization_domain.py b/posthog/api/test/test_organization_domain.py
index 6ca1d31178c3..a89862ab15c8 100644
--- a/posthog/api/test/test_organization_domain.py
+++ b/posthog/api/test/test_organization_domain.py
@@ -671,6 +671,10 @@ class TestOrganizationDomainsAPI(APIBaseTest):
self.organization_membership.save()
self.domain.verified_at = timezone.now()
self.domain.save()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}
+ ]
+ self.organization.save()
response = self.client.patch(
f"/api/organizations/@current/domains/{self.domain.id}/",
@@ -692,6 +696,29 @@ class TestOrganizationDomainsAPI(APIBaseTest):
self.assertEqual(self.domain.id_jag_jwks_url, "https://example.com/keys.json")
self.assertEqual(self.domain.id_jag_allowed_clients, ["client-a", "client-b"])
+ def test_cannot_configure_id_jag_without_available_feature(self):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.domain.verified_at = timezone.now()
+ self.domain.save()
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ response = self.client.patch(
+ f"/api/organizations/@current/domains/{self.domain.id}/",
+ {"id_jag_issuer_url": "https://example.com"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ {
+ "type": "validation_error",
+ "code": "feature_not_available",
+ "detail": "XAA (ID-JAG) is not available for this organization.",
+ "attr": "id_jag_issuer_url",
+ },
+ )
+
def test_can_clear_id_jag_configuration(self):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
@@ -734,6 +761,10 @@ class TestOrganizationDomainsAPI(APIBaseTest):
self.organization_membership.save()
self.domain.verified_at = timezone.now()
self.domain.save()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}
+ ]
+ self.organization.save()
response = self.client.patch(
f"/api/organizations/@current/domains/{self.domain.id}/",
diff --git a/posthog/auth.py b/posthog/auth.py
index 57a92c3680a5..7b4e14e499b0 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -33,6 +33,7 @@ from posthog.constants import AvailableFeature
from posthog.helpers.two_factor_session import enforce_two_factor
from posthog.jwt import PosthogJwtAudience, decode_jwt, get_oidc_verification_keys
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrand
+from posthog.models.organization import OrganizationMembership
from posthog.models.personal_api_key import (
LEGACY_PERSONAL_API_KEY_SALT,
PERSONAL_API_KEY_AUTH_COUNTER,
@@ -648,21 +649,25 @@ class IDJagAccessTokenAuthentication(authentication.BaseAuthentication):
# 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).
- user_qs = User.objects.filter(
- is_active=True,
- email__iexact=token_email,
- organization_membership__organization_id=organization_id,
- ).distinct()
- users = list(user_qs[:2])
- if not users:
- raise AuthenticationFailed(
- detail="No active PostHog user matches the ID-JAG access token subject for this organization."
+ membership = (
+ OrganizationMembership.objects.filter(
+ organization_id=organization_id,
+ user__is_active=True,
+ user__email__iexact=token_email,
)
- if len(users) > 1:
+ .select_related("user", "organization")
+ .first()
+ )
+ if not membership:
raise AuthenticationFailed(
- detail="ID-JAG access token resolves to multiple users; refusing to authenticate."
+ detail="No active PostHog user matches the ID-JAG access token subject for this organization."
)
- user = users[0]
+
+ user = membership.user
+ organization = membership.organization
+
+ if not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):
+ raise AuthenticationFailed(detail="ID-JAG (XAA) is not enabled for this organization.")
self.id_jag_claims = claims
self.scopes = str(claims.get("scope") or "").split()
diff --git a/posthog/constants.py b/posthog/constants.py
index 4821e152e821..f14249cf4ebc 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -49,6 +49,7 @@ class AvailableFeature(StrEnum):
SESSION_REPLAY_DATA_RETENTION = "session_replay_data_retention"
AUDIT_LOGS = "audit_logs"
APPROVALS = "approvals"
+ XAA_AUTHENTICATION = "xaa_authentication"
TREND_FILTER_TYPE_ACTIONS = "actions"