: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
chore: remove deprecated idp logic on org domain code (#68795)
Reece Jones7c3fcabdd64a
diff --git a/ee/api/scim/test/test_groups_api.py b/ee/api/scim/test/test_groups_api.pyindex e2589f313fc0..a4bcefcf48f2 100644--- a/ee/api/scim/test/test_groups_api.py+++ b/ee/api/scim/test/test_groups_api.py@@ -5,6 +5,7 @@ from rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, User+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomainfrom ee.api.scim.auth import generate_scim_token@@ -26,7 +27,8 @@ class TestSCIMGroupsAPI(APILicensedTest):self.organization.available_product_features = featuresself.organization.save()- # Create organization domain with SCIM enabled+ # Create organization domain with a linked, SCIM-enabled IdP config (SCIM auth resolves+ # through the linked config, not the domain's own legacy columns).self.domain = OrganizationDomain.objects.create(organization=self.organization,domain="example.com",@@ -35,8 +37,10 @@ class TestSCIMGroupsAPI(APILicensedTest):# Generate SCIM tokenself.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}diff --git a/ee/api/scim/test/test_scim_api.py b/ee/api/scim/test/test_scim_api.pyindex 642d4585c9b8..5804c1e3dca7 100644--- a/ee/api/scim/test/test_scim_api.py+++ b/ee/api/scim/test/test_scim_api.py@@ -4,6 +4,7 @@ from rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, Userfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomainfrom ee.api.scim.auth import generate_scim_token@@ -24,7 +25,8 @@ class TestSCIMAPI(APILicensedTest):self.organization.available_product_features = featuresself.organization.save()- # Create organization domain with SCIM enabled+ # Create organization domain with a linked, SCIM-enabled IdP config (SCIM auth resolves+ # through the linked config, not the domain's own legacy columns).self.domain = OrganizationDomain.objects.create(organization=self.organization,domain="example.com",@@ -33,8 +35,10 @@ class TestSCIMAPI(APILicensedTest):# Generate SCIM tokenself.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -71,8 +75,10 @@ class TestSCIMAPI(APILicensedTest):domain="unverified.example.com",verified_at=None,)- unverified._scim_enabled = True- unverified._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ unverified.identity_provider_config = configunverified.save()assert unverified.has_scim # config is SCIM-enabled with a token@@ -267,8 +273,10 @@ class TestSCIMEmailDomainValidation(APILicensedTest):)self.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -504,8 +512,10 @@ class TestSCIMAuditLogging(APILicensedTest):)self.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -598,8 +608,10 @@ class TestSCIMGroupAuditLogging(APILicensedTest):)self.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}diff --git a/ee/api/scim/test/test_scim_request_log.py b/ee/api/scim/test/test_scim_request_log.pyindex b532ced75361..2994c22865cc 100644--- a/ee/api/scim/test/test_scim_request_log.py+++ b/ee/api/scim/test/test_scim_request_log.py@@ -10,6 +10,7 @@ from rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Organization+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain@@ -36,8 +37,10 @@ class TestSCIMRequestLogCapture(APILicensedTest):verified_at="2024-01-01T00:00:00Z",)self.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()def test_get_request_creates_log(self):diff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.pyindex eb875883d411..d1464b026685 100644--- a/ee/api/scim/test/test_users_api.py+++ b/ee/api/scim/test/test_users_api.py@@ -3,6 +3,7 @@ from rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, User+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomainfrom ee.api.scim.auth import generate_scim_token@@ -24,7 +25,8 @@ class TestSCIMUsersAPI(APILicensedTest):self.organization.available_product_features = featuresself.organization.save()- # Create organization domain with SCIM enabled+ # Create organization domain with a linked, SCIM-enabled IdP config (SCIM auth resolves+ # through the linked config, not the domain's own legacy columns).self.domain = OrganizationDomain.objects.create(organization=self.organization,domain="example.com",@@ -33,8 +35,10 @@ class TestSCIMUsersAPI(APILicensedTest):# Generate SCIM tokenself.plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token+ )+ self.domain.identity_provider_config = configself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}diff --git a/ee/api/scim/utils.py b/ee/api/scim/utils.pyindex caf0b84bd8d4..ab81606ff19a 100644--- a/ee/api/scim/utils.py+++ b/ee/api/scim/utils.py@@ -88,42 +88,6 @@ def mask_headers(headers: dict[str, str]) -> dict[str, str]:return result-def enable_scim_for_domain(domain: OrganizationDomain) -> str:- """- Enable SCIM for an OrganizationDomain and generate a new bearer token.- Returns the plain text token (only shown once).- """- plain_token, hashed_token = generate_scim_token()-- domain._scim_enabled = True- domain._scim_bearer_token = hashed_token- domain.save()-- return plain_token---def disable_scim_for_domain(domain: OrganizationDomain) -> None:- """- Disable SCIM for an OrganizationDomain.- """- domain._scim_enabled = False- domain._scim_bearer_token = None- domain.save()---def regenerate_scim_token(domain: OrganizationDomain) -> str:- """- Regenerate SCIM bearer token for a domain.- Returns the new plain text token (only shown once).- """- plain_token, hashed_token = generate_scim_token()-- domain._scim_bearer_token = hashed_token- domain.save()-- return plain_token--def enable_scim_for_config(config: IdentityProviderConfig) -> str:"""Enable SCIM for an IdentityProviderConfig and generate a new bearer token.diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex ec8055b731b7..2e66ba1458fb 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -21,6 +21,7 @@ from social_django.models import UserSocialAuthfrom posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership, User+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomainfrom ee.api.authentication import CustomGoogleOAuth2@@ -320,9 +321,12 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):verified_at=timezone.now(),organization=cls.organization,jit_provisioning_enabled=True,- _saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",- _saml_acs_url="https://idp.hogflix.io/saml",- _saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEG+ )+ cls.organization_domain.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=cls.organization,+ saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",+ saml_acs_url="https://idp.hogflix.io/saml",+ saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEUMBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEcMBoGCSqGSIb3DQEJARYNaW5mb0Bva3RhLmNvbTAeFw0yMTA4MjExMTIyMjNaFw0zMTA4MjExMTIzMjNaMIGUMQswCQYD@@ -340,6 +344,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):dcKmj4EG6bfcI3KY6wK46JoogXZdHDaFP+WOJNj/pJ165hYsYLcqkJktj/rEgGQmqAXWPOXHmFJb5FPleoJTchctnzUw+QfmSsLWQ838/lUQsN7FsQ==""",)+ cls.organization_domain.save()def _assert_saml_login_social_failure_redirect(self, response, error_detail_substring: str) -> None:"""SocialAuthExceptionMiddleware catches AuthFailed and redirects instead of propagating."""@@ -647,7 +652,9 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):@freeze_time("2021-08-25T22:09:14.252Z")def test_cannot_login_with_improperly_signed_payload(self):- self.organization_domain._saml_x509_cert = """MIIDPjCCAiYCCQC864/0fftWQTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJV+ config = self.organization_domain.identity_provider_config+ assert config is not None+ config.saml_x509_cert = """MIIDPjCCAiYCCQC864/0fftWQTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJVUzELMAkGA1UECAwCVVMxCzAJBgNVBAcMAlVTMQswCQYDVQQKDAJVUzELMAkGA1UECwwCVVMxCzAJBgNVBAMMAlVTMREwDwYJKoZIhvcNAQkBFgJVUzAeFw0yMTA4MjYwMDAxMzNaFw0zMTA4MjYwMDAxMzNaMGExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJV@@ -665,7 +672,7 @@ AQB8ytXAmU4oYjANiEJVVO5LZUCx3OrY/P1OX73eoXi624yj7xvhaa7whlk1SSL/yh4jGarFborxwACgg6fCiMbHVq8qlcSkRvSW03u89s3Y4mxhMX3F4AZb56ddyfMkLERK8jfXCMVmWPTy830CtQaZX2AJyBwHG4ElP2BOZNbFAvGzrKaBmK2Ym/OJxkhxYotAcSbU3p5bzd11wpyebYHB"""- self.organization_domain.save()+ config.save()response = self.client.get("/login/saml/[email protected]")self.assertEqual(response.status_code, status.HTTP_302_FOUND)@@ -915,10 +922,16 @@ YotAcSbU3p5bzd11wpyebYHB"""verified_at=timezone.now(),organization=other_org,jit_provisioning_enabled=True,- _saml_entity_id=self.organization_domain._saml_entity_id,- _saml_acs_url=self.organization_domain._saml_acs_url,- _saml_x509_cert=self.organization_domain._saml_x509_cert,)+ my_config = self.organization_domain.identity_provider_config+ assert my_config is not None+ other_domain.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=other_org,+ saml_entity_id=my_config.saml_entity_id,+ saml_acs_url=my_config.saml_acs_url,+ saml_x509_cert=my_config.saml_x509_cert,+ )+ other_domain.save()response = self.client.get("/login/saml/[email protected]")self.assertEqual(response.status_code, status.HTTP_302_FOUND)@@ -1081,9 +1094,6 @@ class TestSSOEnforcement(APILicensedTest):organization=self.organization,verified_at=timezone.now(),sso_enforcement="saml",- _saml_entity_id="http://www.okta.com/test",- _saml_acs_url="https://idp.test.io/saml",- _saml_x509_cert="test_cert",)# Test that Google OAuth2 is blocked@@ -1150,9 +1160,12 @@ class TestSSOEnforcement(APILicensedTest):organization=self.organization,verified_at=timezone.now(),sso_enforcement="google-oauth2",- _saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",- _saml_acs_url="https://my.posthog.app/complete/saml/",- _saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEG+ )+ org_domain_saml.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=self.organization,+ saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",+ saml_acs_url="https://my.posthog.app/complete/saml/",+ saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEUMBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEcMBoGCSqGSIb3DQEJARYNaW5mb0Bva3RhLmNvbTAeFw0yMTA4MjExMTIyMjNaFw0zMTA4MjExMTIzMjNaMIGUMQswCQYD@@ -1170,6 +1183,7 @@ jSjV4Oxsv3ogajnnGYGv22iBgS1qccK/cg41YkpgfP36HbiwA10xjUMv5zs97Ljep4ejp6yoKrGLdcKmj4EG6bfcI3KY6wK46JoogXZdHDaFP+WOJNj/pJ165hYsYLcqkJktj/rEgGQmqAXWPOXHmFJb5FPleoJTchctnzUw+QfmSsLWQ838/lUQsN7FsQ==""",)+ org_domain_saml.save()# Set the SAML state in session (required for SAML authentication)_session = self.client.sessiondiff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex a72592bd37b4..9931bb9c4368 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -117,50 +117,12 @@ export interface OrganizationDomainApi {sso_enforcement?: string/** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */readonly has_saml: boolean- /**- * SAML IdP entity ID (issuer).- * @maxLength 512- * @nullable- */- saml_entity_id?: string | null- /**- * SAML single sign-on (ACS) URL.- * @maxLength 512- * @nullable- */- saml_acs_url?: string | null- /**- * SAML IdP X.509 signing certificate (PEM).- * @nullable- */- saml_x509_cert?: string | null/** Returns whether SCIM is configured and enabled for this domain. */readonly has_scim: boolean- /** Whether SCIM provisioning is enabled for this domain. */- scim_enabled?: boolean/** @nullable */readonly scim_base_url: string | null- /** @nullable */- readonly scim_bearer_token: string | null/** Returns whether ID-JAG (XAA) is configured for this domain. */readonly has_id_jag: boolean- /**- * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.- * @maxLength 512- * @nullable- */- id_jag_issuer_url?: string | null- /**- * Override JWKS URL. Defaults to OIDC discovery on the issuer URL.- * @maxLength 512- * @nullable- */- id_jag_jwks_url?: string | null- /**- * Allowed ID-JAG client IDs. Empty list allows any client_id.- * @items.maxLength 256- */- id_jag_allowed_clients?: string[]/*** Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.* @nullable@@ -191,50 +153,12 @@ export interface PatchedOrganizationDomainApi {sso_enforcement?: string/** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */readonly has_saml?: boolean- /**- * SAML IdP entity ID (issuer).- * @maxLength 512- * @nullable- */- saml_entity_id?: string | null- /**- * SAML single sign-on (ACS) URL.- * @maxLength 512- * @nullable- */- saml_acs_url?: string | null- /**- * SAML IdP X.509 signing certificate (PEM).- * @nullable- */- saml_x509_cert?: string | null/** Returns whether SCIM is configured and enabled for this domain. */readonly has_scim?: boolean- /** Whether SCIM provisioning is enabled for this domain. */- scim_enabled?: boolean/** @nullable */readonly scim_base_url?: string | null- /** @nullable */- readonly scim_bearer_token?: string | null/** Returns whether ID-JAG (XAA) is configured for this domain. */readonly has_id_jag?: boolean- /**- * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.- * @maxLength 512- * @nullable- */- id_jag_issuer_url?: string | null- /**- * Override JWKS URL. Defaults to OIDC discovery on the issuer URL.- * @maxLength 512- * @nullable- */- id_jag_jwks_url?: string | null- /**- * Allowed ID-JAG client IDs. Empty list allows any client_id.- * @items.maxLength 256- */- id_jag_allowed_clients?: string[]/*** Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.* @nullablediff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex e08d55708cc1..7cdf6f126dba 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -349,27 +349,6 @@ export const domainsScimLogsRetrieve = async (})}-export const getDomainsScimTokenCreateUrl = (organizationId: string, id: string) => {- return `/api/organizations/${organizationId}/domains/${id}/scim/token/`-}--/**- * Regenerate SCIM bearer token.- */-export const domainsScimTokenCreate = async (- organizationId: string,- id: string,- organizationDomainApi: NonReadonly<OrganizationDomainApi>,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getDomainsScimTokenCreateUrl(organizationId, id), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(organizationDomainApi),- })-}-export const getDomainsVerifyCreateUrl = (organizationId: string, id: string) => {return `/api/organizations/${organizationId}/domains/${id}/verify/`}diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 2864753dc262..5ee4ffcedaf8 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -30,42 +30,10 @@ export const domainsCreateBodyDomainMax = 128export const domainsCreateBodySsoEnforcementMax = 28-export const domainsCreateBodySamlEntityIdMax = 512--export const domainsCreateBodySamlAcsUrlMax = 512--export const domainsCreateBodyIdJagIssuerUrlMax = 512--export const domainsCreateBodyIdJagJwksUrlMax = 512--export const domainsCreateBodyIdJagAllowedClientsItemMax = 256-export const DomainsCreateBody = /* @__PURE__ */ zod.object({domain: zod.string().max(domainsCreateBodyDomainMax),jit_provisioning_enabled: zod.boolean().optional(),sso_enforcement: zod.string().max(domainsCreateBodySsoEnforcementMax).optional(),- saml_entity_id: zod- .string()- .max(domainsCreateBodySamlEntityIdMax)- .nullish()- .describe('SAML IdP entity ID (issuer).'),- saml_acs_url: zod.string().max(domainsCreateBodySamlAcsUrlMax).nullish().describe('SAML single sign-on (ACS) URL.'),- saml_x509_cert: zod.string().nullish().describe('SAML IdP X.509 signing certificate (PEM).'),- scim_enabled: zod.boolean().optional().describe('Whether SCIM provisioning is enabled for this domain.'),- id_jag_issuer_url: zod- .string()- .max(domainsCreateBodyIdJagIssuerUrlMax)- .nullish()- .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.'),- id_jag_jwks_url: zod- .string()- .max(domainsCreateBodyIdJagJwksUrlMax)- .nullish()- .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),- id_jag_allowed_clients: zod- .array(zod.string().max(domainsCreateBodyIdJagAllowedClientsItemMax))- .optional()- .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),identity_provider_config: zod.uuid().nullish()@@ -78,42 +46,10 @@ export const domainsUpdateBodyDomainMax = 128export const domainsUpdateBodySsoEnforcementMax = 28-export const domainsUpdateBodySamlEntityIdMax = 512--export const domainsUpdateBodySamlAcsUrlMax = 512--export const domainsUpdateBodyIdJagIssuerUrlMax = 512--export const domainsUpdateBodyIdJagJwksUrlMax = 512--export const domainsUpdateBodyIdJagAllowedClientsItemMax = 256-export const DomainsUpdateBody = /* @__PURE__ */ zod.object({domain: zod.string().max(domainsUpdateBodyDomainMax),jit_provisioning_enabled: zod.boolean().optional(),sso_enforcement: zod.string().max(domainsUpdateBodySsoEnforcementMax).optional(),- saml_entity_id: zod- .string()- .max(domainsUpdateBodySamlEntityIdMax)- .nullish()- .describe('SAML IdP entity ID (issuer).'),- saml_acs_url: zod.string().max(domainsUpdateBodySamlAcsUrlMax).nullish().describe('SAML single sign-on (ACS) URL.'),- saml_x509_cert: zod.string().nullish().describe('SAML IdP X.509 signing certificate (PEM).'),- scim_enabled: zod.boolean().optional().describe('Whether SCIM provisioning is enabled for this domain.'),- id_jag_issuer_url: zod- .string()- .max(domainsUpdateBodyIdJagIssuerUrlMax)- .nullish()- .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.'),- id_jag_jwks_url: zod- .string()- .max(domainsUpdateBodyIdJagJwksUrlMax)- .nullish()- .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),- id_jag_allowed_clients: zod- .array(zod.string().max(domainsUpdateBodyIdJagAllowedClientsItemMax))- .optional()- .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),identity_provider_config: zod.uuid().nullish()@@ -126,101 +62,10 @@ export const domainsPartialUpdateBodyDomainMax = 128export const domainsPartialUpdateBodySsoEnforcementMax = 28-export const domainsPartialUpdateBodySamlEntityIdMax = 512--export const domainsPartialUpdateBodySamlAcsUrlMax = 512--export const domainsPartialUpdateBodyIdJagIssuerUrlMax = 512--export const domainsPartialUpdateBodyIdJagJwksUrlMax = 512--export const domainsPartialUpdateBodyIdJagAllowedClientsItemMax = 256-export const DomainsPartialUpdateBody = /* @__PURE__ */ zod.object({domain: zod.string().max(domainsPartialUpdateBodyDomainMax).optional(),jit_provisioning_enabled: zod.boolean().optional(),sso_enforcement: zod.string().max(domainsPartialUpdateBodySsoEnforcementMax).optional(),- saml_entity_id: zod- .string()- .max(domainsPartialUpdateBodySamlEntityIdMax)- .nullish()- .describe('SAML IdP entity ID (issuer).'),- saml_acs_url: zod- .string()- .max(domainsPartialUpdateBodySamlAcsUrlMax)- .nullish()- .describe('SAML single sign-on (ACS) URL.'),- saml_x509_cert: zod.string().nullish().describe('SAML IdP X.509 signing certificate (PEM).'),- scim_enabled: zod.boolean().optional().describe('Whether SCIM provisioning is enabled for this domain.'),- id_jag_issuer_url: zod- .string()- .max(domainsPartialUpdateBodyIdJagIssuerUrlMax)- .nullish()- .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.'),- id_jag_jwks_url: zod- .string()- .max(domainsPartialUpdateBodyIdJagJwksUrlMax)- .nullish()- .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),- id_jag_allowed_clients: zod- .array(zod.string().max(domainsPartialUpdateBodyIdJagAllowedClientsItemMax))- .optional()- .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),- identity_provider_config: zod- .uuid()- .nullish()- .describe(- 'Linked IdP configuration (SAML\/SCIM\/XAA) that backs this domain. Must belong to the same organization.'- ),-})--/**- * Regenerate SCIM bearer token.- */-export const domainsScimTokenCreateBodyDomainMax = 128--export const domainsScimTokenCreateBodySsoEnforcementMax = 28--export const domainsScimTokenCreateBodySamlEntityIdMax = 512--export const domainsScimTokenCreateBodySamlAcsUrlMax = 512--export const domainsScimTokenCreateBodyIdJagIssuerUrlMax = 512--export const domainsScimTokenCreateBodyIdJagJwksUrlMax = 512--export const domainsScimTokenCreateBodyIdJagAllowedClientsItemMax = 256--export const DomainsScimTokenCreateBody = /* @__PURE__ */ zod.object({- domain: zod.string().max(domainsScimTokenCreateBodyDomainMax),- jit_provisioning_enabled: zod.boolean().optional(),- sso_enforcement: zod.string().max(domainsScimTokenCreateBodySsoEnforcementMax).optional(),- saml_entity_id: zod- .string()- .max(domainsScimTokenCreateBodySamlEntityIdMax)- .nullish()- .describe('SAML IdP entity ID (issuer).'),- saml_acs_url: zod- .string()- .max(domainsScimTokenCreateBodySamlAcsUrlMax)- .nullish()- .describe('SAML single sign-on (ACS) URL.'),- saml_x509_cert: zod.string().nullish().describe('SAML IdP X.509 signing certificate (PEM).'),- scim_enabled: zod.boolean().optional().describe('Whether SCIM provisioning is enabled for this domain.'),- id_jag_issuer_url: zod- .string()- .max(domainsScimTokenCreateBodyIdJagIssuerUrlMax)- .nullish()- .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.'),- id_jag_jwks_url: zod- .string()- .max(domainsScimTokenCreateBodyIdJagJwksUrlMax)- .nullish()- .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),- id_jag_allowed_clients: zod- .array(zod.string().max(domainsScimTokenCreateBodyIdJagAllowedClientsItemMax))- .optional()- .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),identity_provider_config: zod.uuid().nullish()@@ -233,46 +78,10 @@ export const domainsVerifyCreateBodyDomainMax = 128export const domainsVerifyCreateBodySsoEnforcementMax = 28-export const domainsVerifyCreateBodySamlEntityIdMax = 512--export const domainsVerifyCreateBodySamlAcsUrlMax = 512--export const domainsVerifyCreateBodyIdJagIssuerUrlMax = 512--export const domainsVerifyCreateBodyIdJagJwksUrlMax = 512--export const domainsVerifyCreateBodyIdJagAllowedClientsItemMax = 256-export const DomainsVerifyCreateBody = /* @__PURE__ */ zod.object({domain: zod.string().max(domainsVerifyCreateBodyDomainMax),jit_provisioning_enabled: zod.boolean().optional(),sso_enforcement: zod.string().max(domainsVerifyCreateBodySsoEnforcementMax).optional(),- saml_entity_id: zod- .string()- .max(domainsVerifyCreateBodySamlEntityIdMax)- .nullish()- .describe('SAML IdP entity ID (issuer).'),- saml_acs_url: zod- .string()- .max(domainsVerifyCreateBodySamlAcsUrlMax)- .nullish()- .describe('SAML single sign-on (ACS) URL.'),- saml_x509_cert: zod.string().nullish().describe('SAML IdP X.509 signing certificate (PEM).'),- scim_enabled: zod.boolean().optional().describe('Whether SCIM provisioning is enabled for this domain.'),- id_jag_issuer_url: zod- .string()- .max(domainsVerifyCreateBodyIdJagIssuerUrlMax)- .nullish()- .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.'),- id_jag_jwks_url: zod- .string()- .max(domainsVerifyCreateBodyIdJagJwksUrlMax)- .nullish()- .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),- id_jag_allowed_clients: zod- .array(zod.string().max(domainsVerifyCreateBodyIdJagAllowedClientsItemMax))- .optional()- .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),identity_provider_config: zod.uuid().nullish()diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsxindex 5c2d45802ece..d77cc680adae 100644--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx@@ -51,15 +51,9 @@ const VERIFIED_DOMAIN_WITH_SAML_SCIM: OrganizationDomainType = {jit_provisioning_enabled: true,sso_enforcement: 'google-oauth2',has_saml: true,- saml_entity_id: 'https://idp.posthog.com',- saml_acs_url: 'https://idp.posthog.com/acs',- saml_x509_cert: 'cert',- scim_enabled: true,+ has_scim: true,scim_base_url: 'https://posthog.com/scim/v2',has_id_jag: true,- id_jag_issuer_url: 'https://idp.posthog.com',- id_jag_jwks_url: null,- id_jag_allowed_clients: ['posthog-mcp'],}const VERIFIED_DOMAIN_NO_SAML_SCIM: OrganizationDomainType = {@@ -71,14 +65,8 @@ const VERIFIED_DOMAIN_NO_SAML_SCIM: OrganizationDomainType = {jit_provisioning_enabled: false,sso_enforcement: '',has_saml: false,- saml_entity_id: '',- saml_acs_url: '',- saml_x509_cert: '',- scim_enabled: false,+ has_scim: false,has_id_jag: false,- id_jag_issuer_url: null,- id_jag_jwks_url: null,- id_jag_allowed_clients: [],}const UNVERIFIED_DOMAIN: OrganizationDomainType = {@@ -90,10 +78,7 @@ const UNVERIFIED_DOMAIN: OrganizationDomainType = {jit_provisioning_enabled: false,sso_enforcement: '',has_saml: false,- saml_entity_id: '',- saml_acs_url: '',- saml_x509_cert: '',- scim_enabled: false,+ has_scim: false,has_id_jag: false,}diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsxindex b034bba21a23..9619779a3f3f 100644--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx@@ -205,10 +205,7 @@ function VerifiedDomainsTable(): JSX.Element {{key: 'integrations',title: 'Integrations',- render: function Integrations(- _,- { has_saml, saml_acs_url, saml_entity_id, saml_x509_cert, scim_enabled, has_id_jag }- ) {+ render: function Integrations(_, { has_saml, has_scim, has_id_jag }) {const billingLink = urls.organizationBilling([ProductKey.PLATFORM_AND_SUPPORT])const badges: JSX.Element[] = []@@ -233,16 +230,6 @@ function VerifiedDomainsTable(): JSX.Element {tooltip="SAML is enabled"/>)- } else if (saml_acs_url || saml_entity_id || saml_x509_cert) {- badges.push(- <IntegrationBadge- key="saml"- label="SAML"- type="warning"- icon={SAML_ICON}- tooltip="SAML is partially configured"- />- )} else {badges.push(<IntegrationBadge@@ -266,7 +253,7 @@ function VerifiedDomainsTable(): JSX.Element {to={billingLink}/>)- } else if (scim_enabled) {+ } else if (has_scim) {badges.push(<IntegrationBadgekey="scim"diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.tsindex d25446786e74..f2ceaa10c1a9 100644--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts@@ -13,19 +13,18 @@ import {identityProviderConfigsCreate,identityProviderConfigsDestroy,identityProviderConfigsPartialUpdate,+ identityProviderConfigsRetrieve,identityProviderConfigsScimTokenCreate,} from '~/generated/core/api'+import { IdentityProviderConfigApi } from '~/generated/core/api.schemas'import { AvailableFeature, OrganizationDomainType, PaginatedSCIMRequestLogs } from '~/types'import type { verifiedDomainsLogicType } from './verifiedDomainsLogicType'/*** Resolve the `IdentityProviderConfig` id that backs a domain, creating and linking an empty- * config first if the domain doesn't have one yet. The config is the source of truth for- * SAML/SCIM/ID-JAG settings, so all IdP-config CRUD targets it rather than the domain.- *- * We link the (still empty) config to the domain *before* populating any fields, so the- * domain→config mirror that runs on the link's domain save sees no divergence to clobber.+ * config first if the domain doesn't have one yet. The config is the sole read/write interface+ * for SAML/SCIM/ID-JAG settings, so all IdP-config CRUD targets it rather than the domain.* If linking fails, the freshly created config is deleted so we don't leave an orphan behind.*/async function ensureIdpConfigId(organizationId: string, domain: OrganizationDomainType): Promise<string> {@@ -44,7 +43,18 @@ async function ensureIdpConfigId(organizationId: string, domain: OrganizationDomreturn config.id}-/** Re-fetch a single domain and replace it in local state, reflecting reverse-synced IdP columns. */+/** Fetch the IdP config linked to a domain, or null if none is linked yet. */+async function fetchLinkedConfig(+ organizationId: string,+ domain: OrganizationDomainType+): Promise<IdentityProviderConfigApi | null> {+ if (!domain.identity_provider_config) {+ return null+ }+ return identityProviderConfigsRetrieve(organizationId, domain.identity_provider_config)+}++/** Re-fetch a single domain and replace it in local state (e.g. after linking/updating its IdP config). */async function refreshDomain(organizationId: string,domainId: string,@@ -61,18 +71,20 @@ export type OrganizationDomainUpdatePayload = Partial<Pick<OrganizationDomainType, 'id'>export type SAMLConfigType = Partial<- Pick<OrganizationDomainType, 'saml_acs_url' | 'saml_entity_id' | 'saml_x509_cert'> &- Pick<OrganizationDomainType, 'id'>+ Pick<IdentityProviderConfigApi, 'saml_acs_url' | 'saml_entity_id' | 'saml_x509_cert'> & { id: string }>export type SCIMConfigType = Partial<- Pick<OrganizationDomainType, 'scim_enabled' | 'scim_base_url' | 'scim_bearer_token'> &- Pick<OrganizationDomainType, 'id'>+ Pick<IdentityProviderConfigApi, 'scim_enabled' | 'scim_bearer_token'> & {+ id: string+ scim_base_url: string | null+ }>export type IdJagConfigType = Partial<- Pick<OrganizationDomainType, 'id_jag_issuer_url' | 'id_jag_jwks_url' | 'id_jag_allowed_clients'> &- Pick<OrganizationDomainType, 'id'>+ Pick<IdentityProviderConfigApi, 'id_jag_issuer_url' | 'id_jag_jwks_url' | 'id_jag_allowed_clients'> & {+ id: string+ }>export const isSecureURL = (url: string): boolean => {@@ -230,9 +242,12 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([{loadScimConfig: async (domainId: string) => {const domain = values.verifiedDomains.find(({ id }) => id === domainId)+ const config = domain+ ? await fetchLinkedConfig(values.currentOrganizationId as string, domain)+ : nullreturn {id: domainId,- scim_enabled: domain?.scim_enabled ?? false,+ scim_enabled: config?.scim_enabled ?? false,scim_base_url: domain?.scim_base_url,}},@@ -244,7 +259,7 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([}const configId = await ensureIdpConfigId(orgId, domain)const config = await identityProviderConfigsPartialUpdate(orgId, configId, { scim_enabled: true })- // Refresh the domain so its SCIM base URL (per-domain, reverse-synced) is current.+ // Refresh the domain so its SCIM base URL and identity_provider_config link are current.const refreshed = await refreshDomain(orgId, domainId, actions.replaceDomain)lemonToast.success('SCIM enabled successfully!')return {@@ -322,23 +337,40 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([],})),listeners(({ actions, values }) => ({- setConfigureSAMLModalId: ({ id }) => {+ setConfigureSAMLModalId: async ({ id }) => {const domain = values.verifiedDomains.find(({ id: _idToFind }) => _idToFind === id)- if (id && domain) {- const { saml_acs_url, saml_entity_id, saml_x509_cert } = domain- actions.setSamlConfigValues({ saml_acs_url, saml_entity_id, saml_x509_cert, id })+ if (!id || !domain) {+ return+ }+ try {+ const config = await fetchLinkedConfig(values.currentOrganizationId as string, domain)+ actions.setSamlConfigValues({+ id,+ saml_acs_url: config?.saml_acs_url ?? '',+ saml_entity_id: config?.saml_entity_id ?? '',+ saml_x509_cert: config?.saml_x509_cert ?? '',+ })+ } catch {+ lemonToast.error('Could not load the SAML configuration for this domain. Please try again.')+ actions.setConfigureSAMLModalId(null)}},- setConfigureIdJagModalId: ({ id }) => {+ setConfigureIdJagModalId: async ({ id }) => {const domain = values.verifiedDomains.find(({ id: _idToFind }) => _idToFind === id)- if (id && domain) {- const { id_jag_issuer_url, id_jag_jwks_url, id_jag_allowed_clients } = domain+ if (!id || !domain) {+ return+ }+ try {+ const config = await fetchLinkedConfig(values.currentOrganizationId as string, domain)actions.setIdJagConfigValues({id,- id_jag_issuer_url: id_jag_issuer_url ?? '',- id_jag_jwks_url: id_jag_jwks_url ?? '',- id_jag_allowed_clients: id_jag_allowed_clients ?? [],+ id_jag_issuer_url: config?.id_jag_issuer_url ?? '',+ id_jag_jwks_url: config?.id_jag_jwks_url ?? '',+ id_jag_allowed_clients: config?.id_jag_allowed_clients ?? [],})+ } catch {+ lemonToast.error('Could not load the ID-JAG configuration for this domain. Please try again.')+ actions.setConfigureIdJagModalId(null)}},setConfigureSCIMModalId: ({ id }) => {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 7daee6aae8af..6ed6e15dad2c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -579,17 +579,10 @@ export interface OrganizationDomainType {jit_provisioning_enabled: booleansso_enforcement: SSOProvider | ''has_saml: boolean- saml_entity_id: string- saml_acs_url: string- saml_x509_cert: string- scim_enabled?: boolean+ has_scim?: booleanscim_base_url?: string- scim_bearer_token?: stringhas_id_jag?: boolean- id_jag_issuer_url?: string | null- id_jag_jwks_url?: string | null- id_jag_allowed_clients?: string[]- /** Linked IdP config (SAML/SCIM/XAA), the source of truth for those settings. */+ /** Linked IdP config (SAML/SCIM/XAA) — the sole read/write interface for those settings. */identity_provider_config?: string | null}diff --git a/posthog/admin/admins/organization_domain_admin.py b/posthog/admin/admins/organization_domain_admin.pyindex b6e42c8b20a2..e20d77cfee21 100644--- a/posthog/admin/admins/organization_domain_admin.py+++ b/posthog/admin/admins/organization_domain_admin.py@@ -27,6 +27,10 @@ class OrganizationDomainAdmin(admin.ModelAdmin):"verified_at","verification_challenge","last_verification_retry",+ # Legacy, frozen columns — edit SAML settings via IdentityProviderConfigAdmin instead.+ "_saml_entity_id",+ "_saml_acs_url",+ "_saml_x509_cert",)autocomplete_fields = ["organization", "identity_provider_config"]fieldsets = (diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.pyindex 1e1ca2144925..c23e8e20d168 100644--- a/posthog/api/organization_domain.py+++ b/posthog/api/organization_domain.py@@ -1,13 +1,12 @@import refrom typing import Any, cast-from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db.models import Q, QuerySetimport django_filtersimport posthoganalyticsfrom drf_spectacular.utils import extend_schema-from rest_framework import exceptions, request, response, serializers, status+from rest_framework import exceptions, request, response, serializersfrom rest_framework.pagination import PageNumberPaginationfrom rest_framework.request import Requestfrom rest_framework.viewsets import ModelViewSet@@ -19,18 +18,11 @@ from posthog.cloud_utils import is_cloudfrom posthog.constants import AvailableFeaturefrom posthog.event_usage import groupsfrom posthog.models import OrganizationDomain, User-from posthog.models.identity_provider_config import IDP_CONFIG_SYNCED_FIELDS, IdentityProviderConfig+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission-from ee.api.scim.utils import (- disable_scim_for_domain,- enable_scim_for_domain,- get_scim_base_url,- mask_email,- mask_string,- regenerate_scim_token,-)+from ee.api.scim.utils import get_scim_base_url, mask_email, mask_stringfrom ee.models.scim_request_log import SCIMRequestLogDOMAIN_REGEX = r"^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"@@ -62,76 +54,19 @@ def _capture_domain_event(request, domain: OrganizationDomain, event_type: str,class OrganizationDomainSerializer(serializers.ModelSerializer):# Maps each verification-gated attribute's serializer source (the key seen in `validated_data`)- # to the public field name used in error responses. The IdP fields are stored on the model as- # underscore-prefixed attributes, so their source differs from the public name.+ # to the public field name used in error responses.UPDATE_ONLY_WHEN_VERIFIED = {"jit_provisioning_enabled": "jit_provisioning_enabled","sso_enforcement": "sso_enforcement",- "_scim_enabled": "scim_enabled",- "_id_jag_issuer_url": "id_jag_issuer_url",- "_id_jag_jwks_url": "id_jag_jwks_url",- "_id_jag_allowed_clients": "id_jag_allowed_clients",}scim_base_url = serializers.SerializerMethodField()- scim_bearer_token = serializers.SerializerMethodField()identity_provider_config = _OrgScopedIdentityProviderConfigField(queryset=IdentityProviderConfig.objects.all(),required=False,allow_null=True,help_text="Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.",)- # The IdP columns live on the model as underscore-prefixed attributes (read through the linked- # config); these declarations keep the public API field names while sourcing the stored columns.- saml_entity_id = serializers.CharField(- source="_saml_entity_id",- max_length=512,- required=False,- allow_null=True,- allow_blank=True,- help_text="SAML IdP entity ID (issuer).",- )- saml_acs_url = serializers.CharField(- source="_saml_acs_url",- max_length=512,- required=False,- allow_null=True,- allow_blank=True,- help_text="SAML single sign-on (ACS) URL.",- )- saml_x509_cert = serializers.CharField(- source="_saml_x509_cert",- required=False,- allow_null=True,- allow_blank=True,- help_text="SAML IdP X.509 signing certificate (PEM).",- )- scim_enabled = serializers.BooleanField(- source="_scim_enabled", required=False, help_text="Whether SCIM provisioning is enabled for this domain."- )- id_jag_issuer_url = serializers.CharField(- source="_id_jag_issuer_url",- max_length=512,- required=False,- allow_null=True,- allow_blank=True,- help_text="Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.",- )- id_jag_jwks_url = serializers.CharField(- source="_id_jag_jwks_url",- max_length=512,- required=False,- allow_null=True,- allow_blank=True,- help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",- )- id_jag_allowed_clients = serializers.ListField(- source="_id_jag_allowed_clients",- child=serializers.CharField(max_length=256),- required=False,- allow_empty=True,- help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",- )class Meta:model = OrganizationDomain@@ -144,17 +79,9 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):"jit_provisioning_enabled","sso_enforcement","has_saml",- "saml_entity_id",- "saml_acs_url",- "saml_x509_cert","has_scim",- "scim_enabled","scim_base_url",- "scim_bearer_token","has_id_jag",- "id_jag_issuer_url",- "id_jag_jwks_url",- "id_jag_allowed_clients","identity_provider_config",)extra_kwargs = {@@ -164,14 +91,9 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):"has_saml": {"read_only": True},"has_scim": {"read_only": True},"scim_base_url": {"read_only": True},- "scim_bearer_token": {"read_only": True},"has_id_jag": {"read_only": True},}- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- self._scim_plain_token: str | None = None-def get_fields(self):fields = super().get_fields()if self.instance is not None:@@ -187,10 +109,6 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):"jit_provisioning_enabled", None) # can never be set on creation because domain must be verifiedvalidated_data.pop("sso_enforcement", None) # can never be set on creation because domain must be verified- validated_data.pop("_scim_enabled", None)- validated_data.pop("_id_jag_issuer_url", None)- validated_data.pop("_id_jag_jwks_url", None)- validated_data.pop("_id_jag_allowed_clients", None)instance: OrganizationDomain = super().create(validated_data)return instance@@ -200,21 +118,6 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):raise serializers.ValidationError("Please enter a valid domain or subdomain name.")return domain- @staticmethod- def _normalize_optional_url(value: str | None) -> str | None:- if value is None:- return None- stripped = value.strip()- if not stripped:- return None- return stripped.rstrip("/")-- def validate_id_jag_issuer_url(self, value: str | None) -> str | None:- return self._normalize_optional_url(value)-- def validate_id_jag_jwks_url(self, value: str | None) -> str | None:- return self._normalize_optional_url(value)-def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:instance = cast(OrganizationDomain, self.instance)organization: Organization = self.context["view"].organization@@ -233,71 +136,17 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):code="feature_not_available",)- if instance and attrs.get("_scim_enabled") is not None:- if not organization.is_feature_available(AvailableFeature.SCIM):- raise serializers.ValidationError(- {"scim_enabled": "SCIM provisioning is not available for this organization."},- 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 attrsdef update(self, instance: OrganizationDomain, validated_data: dict[str, Any]) -> OrganizationDomain:validated_data.pop("domain", None) # domain is immutable after creation- scim_enabled = validated_data.pop("_scim_enabled", None)-- # When linking an IdP config (the source of truth), adopt its settings onto the domain's- # legacy IdP columns so the forward mirror in `OrganizationDomain.save()` sees no- # divergence to clobber. Explicit IdP fields in the same request still win (applied after,- # by `super().update`).- linked_config = validated_data.get("identity_provider_config")- if linked_config is not None:- for field in IDP_CONFIG_SYNCED_FIELDS:- setattr(instance, f"_{field}", getattr(linked_config, field))-- instance = super().update(instance, validated_data)-- # Enable/disable SCIM only after `super().update()` has applied any newly linked- # `identity_provider_config`, so the freshly generated token is mirrored to the- # currently-linked config — never to a config the domain was previously linked to.- scim_plain_token: str | None = None- if scim_enabled is not None:- if scim_enabled:- if not instance._scim_enabled:- scim_plain_token = enable_scim_for_domain(instance)- else:- if instance._scim_enabled:- disable_scim_for_domain(instance)-- self._scim_plain_token = scim_plain_token-- id_jag_fields = {"_id_jag_issuer_url", "_id_jag_jwks_url", "_id_jag_allowed_clients"}- if id_jag_fields.intersection(validated_data):- try:- instance.full_clean()- except DjangoValidationError as e:- # `clean()` keys errors by the model field name (underscore-prefixed); surface them- # under the public API field name instead.- errors = {(k[1:] if k.startswith("_id_jag_") else k): v for k, v in e.message_dict.items()}- raise serializers.ValidationError(errors) from e-- return instance+ return super().update(instance, validated_data)def get_scim_base_url(self, obj: OrganizationDomain) -> str | None:if not obj.has_scim:return Nonereturn get_scim_base_url(obj, self.context.get("request"))- def get_scim_bearer_token(self, obj: OrganizationDomain) -> str | None:- return getattr(self, "_scim_plain_token", None)-class SCIMRequestLogSerializer(serializers.ModelSerializer):class Meta:@@ -392,11 +241,7 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):def _capture_domain_setting_event(self, request: Request) -> None:data = request.data- if any(f.startswith("saml_") for f in data):- event_type = "saml configured"- elif any(f.startswith("id_jag_") for f in data):- event_type = "id-jag configured"- elif "sso_enforcement" in data:+ if "sso_enforcement" in data:event_type = "sso enforcement updated"elif data.get("jit_provisioning_enabled") is True:event_type = "jit provisioning enabled"@@ -429,31 +274,6 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):instance.delete()return response.Response(status=204)- @action(methods=["POST"], detail=True, url_path="scim/token")- def scim_token(self, request: Request, **kwargs) -> response.Response:- """- Regenerate SCIM bearer token.- """- domain: OrganizationDomain = self.get_object()-- if not domain.organization.is_feature_available(AvailableFeature.SCIM):- raise exceptions.PermissionDenied("SCIM is not available for this organization")-- if not domain.has_scim:- return response.Response(- {"detail": "SCIM is not enabled for this domain"}, status=status.HTTP_400_BAD_REQUEST- )-- plain_token = regenerate_scim_token(domain)-- return response.Response(- {- "scim_enabled": True,- "scim_base_url": get_scim_base_url(domain, request),- "scim_bearer_token": plain_token,- }- )-@action(methods=["GET"], detail=True, url_path="scim/logs")def scim_logs(self, request: Request, **kwargs) -> response.Response:membership = OrganizationMembership.objects.filter(diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex 6ad4eaf80950..349f32c16652 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 ()from posthog.auth import IDJagAccessTokenAuthenticationfrom posthog.constants import AvailableFeature+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomainfrom posthog.models.user import User as UserModel@@ -116,12 +117,15 @@ class TestIdJagTokenEndpoint(APIBaseTest):{"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}]cls.organization.save()- OrganizationDomain.objects.create(+ domain = OrganizationDomain.objects.create(organization=cls.organization,domain=_VERIFIED_DOMAIN,verified_at=timezone.now(),- _id_jag_issuer_url=_IDP_ISSUER,)+ domain.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=cls.organization, id_jag_issuer_url=_IDP_ISSUER+ )+ domain.save()def setUp(self) -> None:super().setUp()@@ -459,12 +463,15 @@ class TestIdJagTokenEndpoint(APIBaseTest):# verified domain.attacker_org = Organization.objects.create(name="attacker-org")- OrganizationDomain.objects.create(+ attacker_domain = OrganizationDomain.objects.create(organization=attacker_org,domain="bigco.example",verified_at=timezone.now(),- _id_jag_issuer_url=_IDP_ISSUER,)+ attacker_domain.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=attacker_org, id_jag_issuer_url=_IDP_ISSUER+ )+ attacker_domain.save()# Victim user whose email is on the attacker's verified domain but who# belongs to a completely unrelated org.@@ -626,8 +633,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):# ID-JAG is opt-in per domain. With `id_jag_issuer_url` cleared, an# otherwise valid ID-JAG must be rejected — the org hasn't bound an IdP yet.domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)- domain._id_jag_issuer_url = None- domain.save(update_fields=["_id_jag_issuer_url"])+ config = domain.identity_provider_config+ config.id_jag_issuer_url = None+ config.save()assertion = _make_id_jag()resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -641,8 +649,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):# The IdP binding is exact-match on the issuer URL — even a sibling IdP# that happens to know the same user is rejected unless explicitly bound.domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)- domain._id_jag_issuer_url = "https://idp.example.com"- domain.save(update_fields=["_id_jag_issuer_url"])+ config = domain.identity_provider_config+ config.id_jag_issuer_url = "https://idp.example.com"+ config.save()assertion = _make_id_jag(issuer="https://other-idp.example.com")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -658,8 +667,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):# legitimate IdPs that always include a trailing slash on `iss` would# be impossible to bind.domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)- domain._id_jag_issuer_url = _IDP_ISSUER- domain.save(update_fields=["_id_jag_issuer_url"])+ config = domain.identity_provider_config+ config.id_jag_issuer_url = _IDP_ISSUER+ config.save()assertion = _make_id_jag(issuer=_IDP_ISSUER + "/")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -671,8 +681,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):# arguments passed to `_get_jwks_client` rather than reasserting the# signature (the mock already returns our test public key).domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)- domain._id_jag_jwks_url = "https://idp.example.com/keys.json"- domain.save(update_fields=["_id_jag_jwks_url"])+ config = domain.identity_provider_config+ config.id_jag_jwks_url = "https://idp.example.com/keys.json"+ config.save()# Re-patch to capture call args; the base setUp patch doesn't expose# them in a way that survives across multiple tests.@@ -690,8 +701,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):def test_allowed_clients_permits_listed_client_id(self) -> None:domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)- domain._id_jag_allowed_clients = ["client_first", "client_second"]- domain.save(update_fields=["_id_jag_allowed_clients"])+ config = domain.identity_provider_config+ config.id_jag_allowed_clients = ["client_first", "client_second"]+ config.save()assertion = _make_id_jag(client_id="client_second")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -699,8 +711,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):def test_allowed_clients_rejects_unlisted_client_id(self) -> None:domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)- domain._id_jag_allowed_clients = ["client_first", "client_second"]- domain.save(update_fields=["_id_jag_allowed_clients"])+ config = domain.identity_provider_config+ config.id_jag_allowed_clients = ["client_first", "client_second"]+ config.save()assertion = _make_id_jag(client_id="client_third")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})diff --git a/posthog/api/test/test_organization_domain.py b/posthog/api/test/test_organization_domain.pyindex 8b6eca08078d..4ade870add0a 100644--- a/posthog/api/test/test_organization_domain.py+++ b/posthog/api/test/test_organization_domain.py@@ -15,9 +15,7 @@ from parameterized import parameterizedfrom rest_framework import serializers, statusfrom posthog.api.organization_domain import OrganizationDomainSerializer, OrganizationDomainViewset-from posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team-from posthog.models.identity_provider_config import IdentityProviderConfigfrom ee.api.test.base import APILicensedTestfrom ee.models.scim_request_log import SCIMRequestLog@@ -108,7 +106,6 @@ class TestOrganizationDomainsAPI(APIBaseTest):"verification_challenge": "123", # ignore me"jit_provisioning_enabled": True, # ignore me"sso_enforcement": "saml", # ignore me- "scim_enabled": True, # ignore me},)self.assertEqual(response.status_code, status.HTTP_201_CREATED)@@ -116,7 +113,6 @@ class TestOrganizationDomainsAPI(APIBaseTest):self.assertEqual(response_data["domain"], "the.posthog.com")self.assertEqual(response_data["verified_at"], None)self.assertEqual(response_data["jit_provisioning_enabled"], False)- self.assertEqual(response_data["scim_enabled"], False)self.assertRegex(response_data["verification_challenge"], r"[0-9A-Za-z_-]{32}")instance = OrganizationDomain.objects.get(id=response_data["id"])@@ -124,7 +120,6 @@ class TestOrganizationDomainsAPI(APIBaseTest):self.assertEqual(instance.verified_at, None)self.assertEqual(instance.last_verification_retry, None)self.assertEqual(instance.sso_enforcement, "")- self.assertEqual(instance._scim_enabled, False)# Verify the domain creation capture event was calledmock_capture.assert_any_call(@@ -532,282 +527,10 @@ class TestOrganizationDomainsAPI(APIBaseTest):self.assertEqual(response.json(), self.permission_denied_response())self.another_domain.refresh_from_db()- # SCIM configuration-- def test_can_enable_scim(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization.available_product_features = [{"key": AvailableFeature.SCIM, "name": "SCIM"}]- self.organization_membership.save()- self.organization.save()- self.domain.verified_at = timezone.now()- self.domain.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"scim_enabled": True},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["scim_enabled"], True)- self.assertIsNotNone(response.json()["scim_bearer_token"])- self.assertIn("scim_base_url", response.json())-- self.domain.refresh_from_db()- self.assertEqual(self.domain._scim_enabled, True)- self.assertIsNotNone(self.domain._scim_bearer_token)-- def test_enabling_scim_while_linking_new_config_writes_token_to_new_config_only(self):- # Regression: enabling SCIM in the same request that links a new config must mirror the- # token to the newly linked config, never to the previously linked one.- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization.available_product_features = [{"key": AvailableFeature.SCIM, "name": "SCIM"}]- self.organization_membership.save()- self.organization.save()- self.domain.verified_at = timezone.now()- self.domain.save()-- old_config = IdentityProviderConfig.objects.create(organization=self.organization, name="old")- new_config = IdentityProviderConfig.objects.create(organization=self.organization, name="new")- self.domain.identity_provider_config = old_config- self.domain.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"identity_provider_config": str(new_config.id), "scim_enabled": True},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- old_config.refresh_from_db()- new_config.refresh_from_db()- self.domain.refresh_from_db()- self.assertEqual(self.domain.identity_provider_config_id, new_config.id)- self.assertTrue(new_config.scim_enabled)- self.assertIsNotNone(new_config.scim_bearer_token)- self.assertFalse(old_config.scim_enabled)- self.assertIsNone(old_config.scim_bearer_token)-- def test_cannot_enable_scim_without_available_feature(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()- self.domain.verified_at = timezone.now()- self.domain.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"scim_enabled": True},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("not available", response.json()["detail"].lower())-- def test_cannot_enable_scim_on_unverified_domain(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization.available_product_features = [{"key": AvailableFeature.SCIM, "name": "SCIM"}]- self.organization_membership.save()- self.organization.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"scim_enabled": True},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(- response.json(),- {- "type": "validation_error",- "code": "verification_required",- "detail": "This attribute cannot be updated until the domain is verified.",- "attr": "scim_enabled",- },- )-- def test_can_disable_scim(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization.available_product_features = [{"key": AvailableFeature.SCIM, "name": "SCIM"}]- self.organization_membership.save()- self.organization.save()- self.domain.verified_at = timezone.now()- self.domain.save()-- # First enable SCIM- enable_response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"scim_enabled": True},- )- self.assertEqual(enable_response.status_code, status.HTTP_200_OK)-- # Then disable it- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"scim_enabled": False},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["scim_enabled"], False)- self.assertIsNone(response.json()["scim_bearer_token"])-- self.domain.refresh_from_db()- self.assertEqual(self.domain._scim_enabled, False)- self.assertIsNone(self.domain._scim_bearer_token)-- def test_can_regenerate_scim_token(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization.available_product_features = [{"key": AvailableFeature.SCIM, "name": "SCIM"}]- self.organization_membership.save()- self.organization.save()- self.domain.verified_at = timezone.now()- self.domain.save()-- # First enable SCIM- enable_response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"scim_enabled": True},- )- self.assertEqual(enable_response.status_code, status.HTTP_200_OK)- original_token = enable_response.json()["scim_bearer_token"]-- # Regenerate token- response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/scim/token")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["scim_enabled"], True)- new_token = response.json()["scim_bearer_token"]- self.assertIsNotNone(new_token)- self.assertNotEqual(original_token, new_token)-- def test_cannot_regenerate_scim_token_without_available_feature(self):- from ee.api.scim.auth import generate_scim_token-- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()- self.domain.verified_at = timezone.now()- self.domain.save()-- # Manually enable SCIM (bypassing validation)- plain_token, hashed_token = generate_scim_token()- self.domain._scim_enabled = True- self.domain._scim_bearer_token = hashed_token- self.domain.save()-- # Remove feature- self.organization.available_product_features = []- self.organization.save()-- response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/scim/token")- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)-- # ID-JAG (XAA) configuration-- def test_can_configure_id_jag(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 = [- {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}- ]- self.organization.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {- "id_jag_issuer_url": "https://example.com/",- "id_jag_jwks_url": "https://example.com/keys.json",- "id_jag_allowed_clients": ["client-a", "client-b"],- },- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- response_data = response.json()- self.assertEqual(response_data["id_jag_issuer_url"], "https://example.com")- self.assertEqual(response_data["id_jag_jwks_url"], "https://example.com/keys.json")- self.assertEqual(response_data["id_jag_allowed_clients"], ["client-a", "client-b"])- self.assertTrue(response_data["has_id_jag"])-- self.domain.refresh_from_db()- self.assertEqual(self.domain._id_jag_issuer_url, "https://example.com")- 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()- self.domain.verified_at = timezone.now()- self.domain._id_jag_issuer_url = "https://example.com"- self.domain.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"id_jag_issuer_url": "", "id_jag_jwks_url": "", "id_jag_allowed_clients": []},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertFalse(response.json()["has_id_jag"])- self.assertIsNone(response.json()["id_jag_issuer_url"])-- self.domain.refresh_from_db()- self.assertIsNone(self.domain._id_jag_issuer_url)-- def test_cannot_configure_id_jag_on_unverified_domain(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.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": "verification_required",- "detail": "This attribute cannot be updated until the domain is verified.",- "attr": "id_jag_issuer_url",- },- )-- def test_rejects_disallowed_id_jag_urls(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 = [- {"key": AvailableFeature.XAA_AUTHENTICATION, "name": "XAA Authentication"}- ]- self.organization.save()-- response = self.client.patch(- f"/api/organizations/@current/domains/{self.domain.id}/",- {"id_jag_issuer_url": "http://127.0.0.1"},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(- response.json(),- {- "type": "validation_error",- "code": "invalid_input",- "detail": "URL is not allowed: Local/Loopback host not allowed",- "attr": "id_jag_issuer_url",- },- )+ # SAML, SCIM, and ID-JAG (XAA) configuration are written exclusively through+ # IdentityProviderConfigViewSet now — see TestIdentityProviderConfigAPI in+ # posthog/api/test/test_identity_provider_config.py. This domain endpoint no longer declares+ # those fields at all, so writes to them are silently dropped rather than persisted.class TestSCIMRequestLogsAPI(APILicensedTest):@@ -819,7 +542,6 @@ class TestSCIMRequestLogsAPI(APILicensedTest):organization=self.organization,domain="logs-test.com",verified_at=timezone.now(),- _scim_enabled=True,)def _create_log(self, **kwargs):diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 7885ced6bb4a..c95787439e6f 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -23,6 +23,7 @@ from posthog.api.signup import _save_session_with_recovery, process_social_invitfrom posthog.cloud_utils import TEST_clear_instance_license_cachefrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, Team, User+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain@@ -939,13 +940,16 @@ class TestSignupAPI(APIBaseTest):with self.is_cloud(True):mock_sso_providers.return_value = {"google-oauth2": True}new_org = Organization.objects.create(name="Test org")- OrganizationDomain.objects.create(+ domain = OrganizationDomain.objects.create(domain="posthog.net",verified_at=timezone.now(),jit_provisioning_enabled=True,- _scim_enabled=True,organization=new_org,)+ domain.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=new_org, scim_enabled=True+ )+ domain.save()Team.objects.create(organization=new_org, name="Test Project")response = self.client.get(reverse("social:begin", kwargs={"backend": "google-oauth2"}))@@ -982,13 +986,16 @@ class TestSignupAPI(APIBaseTest):mock_sso_providers.return_value = {"google-oauth2": True}new_org = Organization.objects.create(name="Test org")- OrganizationDomain.objects.create(+ domain = OrganizationDomain.objects.create(domain="posthog.net",verified_at=timezone.now(),jit_provisioning_enabled=True,- _scim_enabled=True,organization=new_org,)+ domain.identity_provider_config = IdentityProviderConfig.objects.create(+ organization=new_org, scim_enabled=True+ )+ domain.save()Team.objects.create(organization=new_org, name="Test Project")response = self.client.get(reverse("social:begin", kwargs={"backend": "google-oauth2"}))diff --git a/posthog/management/commands/sync_identity_provider_configs.py b/posthog/management/commands/sync_identity_provider_configs.pydeleted file mode 100644index c987229e1464..000000000000--- a/posthog/management/commands/sync_identity_provider_configs.py+++ /dev/null@@ -1,62 +0,0 @@-from collections import Counter-from typing import Any--from django.core.management.base import BaseCommand--import structlog--from posthog.models.identity_provider_config import sync_identity_provider_config_from_domain-from posthog.models.organization_domain import OrganizationDomain--logger = structlog.get_logger(__name__)---class Command(BaseCommand):- help = (- "Backfill and sync IdentityProviderConfig rows from OrganizationDomain (the current "- "source of truth for SAML/SCIM/XAA settings). Creates a config for every domain with "- "IdP settings and links it; re-running updates any drifted configs. Idempotent."- )-- def add_arguments(self, parser) -> None:- parser.add_argument(- "--dry-run",- action="store_true",- help="Report what would change without writing anything.",- )- parser.add_argument(- "--organization-id",- type=str,- default=None,- help="Only sync domains belonging to this organization ID.",- )-- def handle(self, *args: Any, **options: Any) -> None:- dry_run: bool = options["dry_run"]- organization_id: str | None = options["organization_id"]-- queryset = OrganizationDomain.objects.select_related("identity_provider_config").order_by(- "organization_id", "domain"- )- if organization_id:- queryset = queryset.filter(organization_id=organization_id)-- counts: Counter[str] = Counter()- for domain in queryset.iterator(chunk_size=500):- action = sync_identity_provider_config_from_domain(domain, dry_run=dry_run)- counts[action] += 1- if action in ("created", "updated"):- self.stdout.write(- f"{'[DRY RUN] would have ' if dry_run else ''}{action}: domain={domain.domain} "- f"organization={domain.organization_id} config={domain.identity_provider_config_id or '<new>'}"- )-- total = sum(counts.values())- prefix = "[DRY RUN] " if dry_run else ""- self.stdout.write(- self.style.SUCCESS(- f"{prefix}Processed {total} domain(s): "- f"{counts['created']} created, {counts['updated']} updated, "- f"{counts['unchanged']} unchanged, {counts['skipped']} skipped (no IdP settings)"- )- )diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 3348e2efbd4b..851748e50a09 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -57,6 +57,7 @@ ActivityScope = Literal["LegalDocument","Organization","OrganizationDomain",+ "IdentityProviderConfig","OrganizationMembership","Role","UserGroup",@@ -260,6 +261,10 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {"verification_challenge","_saml_x509_cert",],+ "IdentityProviderConfig": [+ "scim_bearer_token",+ "saml_x509_cert",+ ],"User": ["email","password",@@ -307,6 +312,11 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {"_scim_enabled": "SCIM provisioning","verified_at": "domain verification",},+ "IdentityProviderConfig": {+ "saml_entity_id": "SAML entity ID",+ "saml_acs_url": "SAML ACS URL",+ "saml_x509_cert": "SAML X.509 certificate",+ },}# Fields that prevent activity signal triggering entirely when only these fields change@@ -409,6 +419,11 @@ field_exclusions: dict[AuditableScope, list[str]] = {# Internal link to the IdP config mirror; the mirrored fields themselves are already logged"identity_provider_config",],+ "IdentityProviderConfig": [+ "organization",+ # Reverse relation from `OrganizationDomain.identity_provider_config`; not a plain field diff.+ "domains",+ ],"Subscription": [# Scheduler-derived field; keep it out of user-facing change diffs even when another# field changes in the same save (signal_exclusions only governs whether the signal fires).diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex ce95e656c342..7a7f929b5393 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -41,6 +41,7 @@ from posthog.models.activity_logging.personal_api_key_utils import (from posthog.models.activity_logging.project_secret_api_key_utils import log_project_secret_api_key_activityfrom posthog.models.activity_logging.tag_utils import get_tagged_item_related_object_infofrom posthog.models.activity_logging.utils import activity_storage+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.oauth import OAuthApplicationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain@@ -328,6 +329,50 @@ def handle_organization_domain_change()[email protected](frozen=True)+class IdentityProviderConfigContext(ActivityContextBase):+ organization_id: str+ organization_name: str+++@mutable_receiver(model_activity_signal, sender=IdentityProviderConfig)+def handle_identity_provider_config_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ config_instance = after_update or before_update++ if not config_instance:+ return++ context = IdentityProviderConfigContext(+ organization_id=str(config_instance.organization_id),+ organization_name=config_instance.organization.name,+ )++ config_name = config_instance.name or str(config_instance.id)+ if activity == "created":+ detail_name = f"Identity provider config {config_name} added to {config_instance.organization.name}"+ elif activity == "deleted":+ detail_name = f"Identity provider config {config_name} removed from {config_instance.organization.name}"+ else:+ detail_name = f"Identity provider config {config_name} updated in {config_instance.organization.name}"++ log_activity(+ organization_id=config_instance.organization_id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ item_id=config_instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )++@mutable_receiver(model_activity_signal, sender=ExperimentSavedMetric)def handle_experiment_saved_metric_change(sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargsdiff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.pyindex 808534c34212..5066024e127d 100644--- a/posthog/models/identity_provider_config.py+++ b/posthog/models/identity_provider_config.py@@ -1,33 +1,15 @@-from typing import TYPE_CHECKING, Any-from django.contrib.postgres.fields import ArrayField-from django.db import models, transaction+from django.db import modelsimport structlog+from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import UUIDModel-if TYPE_CHECKING:- from posthog.models.organization_domain import OrganizationDomain-logger = structlog.get_logger(__name__)-# IdP-specific fields that are mirrored between `OrganizationDomain` (current source of-# truth) and `IdentityProviderConfig`. Used by the dual-write hook in-# `OrganizationDomain.save()` and the `sync_identity_provider_configs` management command.-IDP_CONFIG_SYNCED_FIELDS: tuple[str, ...] = (- "saml_entity_id",- "saml_acs_url",- "saml_x509_cert",- "scim_enabled",- "scim_bearer_token",- "id_jag_issuer_url",- "id_jag_jwks_url",- "id_jag_allowed_clients",-)---class IdentityProviderConfig(UUIDModel):++class IdentityProviderConfig(ModelActivityMixin, UUIDModel):"""Identity provider (IdP) configuration for an organization.@@ -36,12 +18,8 @@ class IdentityProviderConfig(UUIDModel):multiple `OrganizationDomain` rows (via `OrganizationDomain.identity_provider_config`),and an organization can have zero, one, or many configs.- This model is the source of truth for IdP reads (SAML/SCIM/ID-JAG). The legacy IdP columns- on `OrganizationDomain` are kept in sync in both directions so neither can clobber the other:- `OrganizationDomain.save()` mirrors the domain's columns into the linked config- (`sync_identity_provider_config_from_domain`), and `save()` here mirrors the config back onto- every linked domain (`sync_domains_from_identity_provider_config`). Both use queryset- `update()` for the cross-write to avoid re-entering the other model's `save()`.+ This model is the sole read/write interface for IdP settings (SAML/SCIM/ID-JAG). The legacy+ IdP columns on `OrganizationDomain` are no longer written to — they're frozen."""organization = models.ForeignKey(@@ -97,12 +75,6 @@ class IdentityProviderConfig(UUIDModel):def __str__(self) -> str:return self.name or str(self.id)- def save(self, *args, **kwargs) -> None:- # Atomic so the config write and the mirrored domain writes cannot diverge.- with transaction.atomic():- super().save(*args, **kwargs)- sync_domains_from_identity_provider_config(self)-@propertydef has_saml(self) -> bool:"""@@ -123,94 +95,3 @@ class IdentityProviderConfig(UUIDModel):Returns whether ID-JAG (XAA) is configured."""return bool(self.id_jag_issuer_url)---def _domain_has_any_idp_config(domain: "OrganizationDomain") -> bool:- # Reads the domain's own columns (the underscore-prefixed attributes, not `domain.has_saml`,- # which resolves through the linked config): this is the domain→config write path, so it must- # inspect the source side.- return (- (bool(domain._saml_entity_id) and bool(domain._saml_acs_url) and bool(domain._saml_x509_cert))- or domain._scim_enabled- or bool(domain._scim_bearer_token)- or bool(domain._id_jag_issuer_url)- or bool(domain._id_jag_jwks_url)- or bool(domain._id_jag_allowed_clients)- )---def sync_identity_provider_config_from_domain(domain: "OrganizationDomain", dry_run: bool = False) -> str:- """- Mirror a domain's IdP fields into its linked `IdentityProviderConfig`, creating and- linking one if needed. `OrganizationDomain` is the source of truth until reads are- switched over to the config model.-- Returns the action taken: "created", "updated", "unchanged", or "skipped" (domain has- no IdP configuration and no linked config).- """- # Imported here to avoid a circular import with `organization_domain`, which calls- # this function from `save()`.- from posthog.models.organization_domain import OrganizationDomain # noqa: PLC0415-- config = domain.identity_provider_config-- # Fail closed on a cross-org link: never mirror one organization's IdP settings into- # another organization's config. A linked config must belong to the same organization- # as the domain, otherwise saving the domain (or the backfill command) would silently- # overwrite the other org's SAML/SCIM/XAA settings — an authentication-bypass vector.- if config is not None and config.organization_id != domain.organization_id:- raise ValueError(- f"OrganizationDomain {domain.pk} (organization {domain.organization_id}) is linked to "- f"IdentityProviderConfig {config.pk} owned by a different organization "- f"({config.organization_id}); refusing to mirror IdP settings across organizations."- )-- if config is None:- if not _domain_has_any_idp_config(domain):- return "skipped"- if dry_run:- return "created"- config = IdentityProviderConfig.objects.create(- organization_id=domain.organization_id,- name=domain.domain,- # The domain's columns are the underscore-prefixed attributes; the config's are not.- **{field: getattr(domain, f"_{field}") for field in IDP_CONFIG_SYNCED_FIELDS},- )- # Link via a queryset update to avoid recursing into `OrganizationDomain.save()`- # (and to avoid emitting a second activity log entry for the same write).- OrganizationDomain.objects.filter(pk=domain.pk).update(identity_provider_config=config)- domain.identity_provider_config = config- return "created"-- changed_fields: dict[str, Any] = {- field: getattr(domain, f"_{field}")- for field in IDP_CONFIG_SYNCED_FIELDS- if getattr(config, field) != getattr(domain, f"_{field}")- }- if not changed_fields:- return "unchanged"- if dry_run:- return "updated"- for field, value in changed_fields.items():- setattr(config, field, value)- config.save(update_fields=[*changed_fields.keys(), "updated_at"])- return "updated"---def sync_domains_from_identity_provider_config(config: "IdentityProviderConfig") -> int:- """- Mirror an IdP config's fields onto every `OrganizationDomain` linked to it, keeping the- domains' legacy IdP columns in sync with the config (the source of truth for reads). This is- the reverse of `sync_identity_provider_config_from_domain`: with both directions in place,- the forward mirror in `OrganizationDomain.save()` never sees a divergence to clobber.-- Uses a queryset `update()` (not `domain.save()`) so it cannot re-enter the forward mirror —- the two directions would otherwise recurse. Returns the number of domains updated.- """- # Imported here to avoid a circular import with `organization_domain`.- from posthog.models.organization_domain import OrganizationDomain # noqa: PLC0415-- # Write to the domain's underscore-prefixed columns (the config's fields are not prefixed).- return OrganizationDomain.objects.filter(identity_provider_config=config).update(- **{f"_{field}": getattr(config, field) for field in IDP_CONFIG_SYNCED_FIELDS}- )diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.pyindex e52204291176..017aeebabefb 100644--- a/posthog/models/organization_domain.py+++ b/posthog/models/organization_domain.py@@ -1,8 +1,9 @@import secrets-from typing import Optional+from typing import Any, Optionalfrom django.contrib.postgres.fields import ArrayField-from django.db import models, transaction+from django.core.exceptions import ValidationError+from django.db import modelsfrom django.utils import timezoneimport structlog@@ -11,11 +12,7 @@ import dns.resolverfrom posthog.constants import AvailableFeaturefrom posthog.models import Organizationfrom posthog.models.activity_logging.model_activity import ModelActivityMixin-from posthog.models.identity_provider_config import (- IDP_CONFIG_SYNCED_FIELDS,- IdentityProviderConfig,- sync_identity_provider_config_from_domain,-)+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.utils import UUIDTModelfrom posthog.utils import get_instance_available_sso_providers@@ -190,26 +187,27 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):max_length=28, blank=True) # currently only used for PostHog Cloud; SSO enforcement on self-hosted is set by env var- # ---- SAML / SCIM / ID-JAG attributes ----- # These are mirrored from the linked `IdentityProviderConfig`, which is the source of truth- # for reads. The Python attributes are underscore-prefixed to discourage direct access — read- # through `self.idp_config` instead — while `db_column` keeps the original column names so no- # schema change is needed. Only the internal sync code (and the dual-write domain serializer)- # touches these directly.- # Normally not good practice to have `null=True` in `CharField` (as you have to nil states now), but creating non-nullable- # attributes locks up tables when migrating. Remove `null=True` on next major release.- _saml_entity_id = models.CharField(max_length=512, blank=True, null=True, db_column="saml_entity_id")- _saml_acs_url = models.CharField(max_length=512, blank=True, null=True, db_column="saml_acs_url")- _saml_x509_cert = models.TextField(blank=True, null=True, db_column="saml_x509_cert")-- _scim_enabled = models.BooleanField(default=False, db_column="scim_enabled")+ # ---- SAML / SCIM / ID-JAG attributes (legacy, frozen) ----+ _saml_entity_id = models.CharField(+ max_length=512, blank=True, null=True, db_column="saml_entity_id"+ ) # deprecated, do not use; see `IdentityProviderConfig`+ _saml_acs_url = models.CharField(+ max_length=512, blank=True, null=True, db_column="saml_acs_url"+ ) # deprecated, do not use; see `IdentityProviderConfig`+ _saml_x509_cert = models.TextField(+ blank=True, null=True, db_column="saml_x509_cert"+ ) # deprecated, do not use; see `IdentityProviderConfig`++ _scim_enabled = models.BooleanField(+ default=False, db_column="scim_enabled"+ ) # deprecated, do not use; see `IdentityProviderConfig`_scim_bearer_token = models.CharField(max_length=255,blank=True,null=True,help_text="Hashed bearer token for SCIM authentication",db_column="scim_bearer_token",- )+ ) # deprecated, do not use; see `IdentityProviderConfig`_id_jag_issuer_url = models.CharField(max_length=512,@@ -217,7 +215,8 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):null=True,help_text="Trusted IdP issuer URL for ID-JAG. Required to enable ID-JAG on this domain.",db_column="id_jag_issuer_url",- )+ ) # deprecated, do not use; see `IdentityProviderConfig`+# Defaults to `{id_jag_issuer_url}/.well-known/openid-configuration`._id_jag_jwks_url = models.CharField(max_length=512,@@ -225,7 +224,7 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):null=True,help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",db_column="id_jag_jwks_url",- )+ ) # deprecated, do not use; see `IdentityProviderConfig`_id_jag_allowed_clients = ArrayField(models.CharField(max_length=256),default=list,@@ -233,14 +232,12 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):null=True,help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",db_column="id_jag_allowed_clients",- )+ ) # deprecated, do not use; see `IdentityProviderConfig`- # ---- IdP config (new home for SAML/SCIM/ID-JAG settings) ----- # Temporary foreign key to the backing `IdentityProviderConfig` model. Eventually- # will be removed once the migration is complete.- # The IdP fields above are being migrated to `IdentityProviderConfig`, which can be- # shared by multiple domains. Until reads are switched over, this model remains the- # source of truth and `save()` mirrors the fields into the linked config.+ # ---- IdP config (home for SAML/SCIM/ID-JAG settings) ----+ # `IdentityProviderConfig` is the source of truth for SAML/SCIM/ID-JAG settings and can be+ # shared by multiple domains. All reads and writes of those settings go through the linked+ # config (`self.idp_config`); the FK link itself is still writable via this domain.identity_provider_config = models.ForeignKey(IdentityProviderConfig,on_delete=models.SET_NULL,@@ -253,45 +250,11 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):class Meta:verbose_name = "domain"- def save(self, *args, **kwargs) -> None:- # Atomic so the domain write and the mirrored IdP config write cannot diverge.- with transaction.atomic():- # When a brand-new domain is linked to an already-populated config, adopt the config's- # values onto the domain's columns first. Otherwise the forward mirror would see the- # new domain's empty columns as a "change" and blank the (possibly shared) config. This- # mirrors the adopt-on-link the serializer does for updates; here it covers creation- # (including direct ORM creates).- if self._state.adding and self.identity_provider_config_id is not None:- config = self.identity_provider_config- for field in IDP_CONFIG_SYNCED_FIELDS:- setattr(self, f"_{field}", getattr(config, field))- super().save(*args, **kwargs)- sync_identity_provider_config_from_domain(self)-- def clean(self) -> None:- # Validate ID-JAG IdP URLs at write time as a UX guard against the- # common admin mistake of pointing them at an internal/loopback/- # metadata host. This is best-effort — DNS rebinding and post-write- # config changes can still produce an unsafe URL at fetch time, so- # `posthog.api.id_jag._get_jwks_client` re-validates before every- # network call. Callers must invoke `full_clean()` (or use a- # ModelForm / DRF serializer that does) for this to take effect.- # Imported lazily to keep this app's import graph free of security/.- from django.core.exceptions import ValidationError-- from posthog.security.url_validation import is_url_allowed-+ def _validate_identity_provider_config_organization(self) -> dict[str, str]:+ # A linked IdP config must belong to the same organization as the domain. Without this,+ # an admin could link a domain to another org's config and have that org's IdP settings+ # exposed on this domain (SCIM/ID-JAG auth resolve through `self.idp_config`).errors: dict[str, str] = {}- for field_name in ("_id_jag_issuer_url", "_id_jag_jwks_url"):- url = getattr(self, field_name, None)- if not url:- continue- allowed, reason = is_url_allowed(url)- if not allowed:- errors[field_name] = f"URL is not allowed: {reason}"- # A linked IdP config must belong to the same organization as the domain. Without- # this, an admin could link a domain to another org's config and have its IdP- # settings silently overwritten on save (see `sync_identity_provider_config_from_domain`).if self.identity_provider_config_id is not None:try:config = self.identity_provider_config@@ -303,10 +266,23 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):errors["identity_provider_config"] = ("IdP configuration must belong to the same organization as the domain.")+ return errors++ def clean(self) -> None:+ errors = self._validate_identity_provider_config_organization()if errors:raise ValidationError(errors)super().clean()+ def save(self, *args: Any, **kwargs: Any) -> None:+ # `clean()` isn't called by plain `.save()`/`.objects.create()`, so this check has to be+ # always-on here too — otherwise a direct ORM write (not going through a form/serializer)+ # could silently persist a cross-organization IdP link.+ errors = self._validate_identity_provider_config_organization()+ if errors:+ raise ValidationError(errors)+ super().save(*args, **kwargs)+@propertydef is_verified(self) -> bool:"""diff --git a/posthog/test/activity_logging/test_identity_provider_config_activity_logging.py b/posthog/test/activity_logging/test_identity_provider_config_activity_logging.pynew file mode 100644index 000000000000..e012756fb1a6--- /dev/null+++ b/posthog/test/activity_logging/test_identity_provider_config_activity_logging.py@@ -0,0 +1,69 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized++from posthog.models import IdentityProviderConfig, OrganizationMembership+from posthog.models.activity_logging.activity_log import ActivityLog+++class TestIdentityProviderConfigActivityLogging(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def _create_config(self, name="Okta production"):+ response = self.client.post(+ "/api/organizations/@current/identity_provider_configs/",+ {"name": name},+ )+ self.assertEqual(response.status_code, 201)+ config = IdentityProviderConfig.objects.get(id=response.json()["id"])+ ActivityLog.objects.filter(+ organization_id=self.organization.id,+ scope="IdentityProviderConfig",+ ).delete()+ return config++ @parameterized.expand(+ [+ (+ "saml-entity-id",+ "saml_entity_id",+ "https://idp.example.com",+ "SAML entity ID",+ "https://idp.example.com",+ ),+ (+ "saml-acs-url",+ "saml_acs_url",+ "https://idp.example.com/acs",+ "SAML ACS URL",+ "https://idp.example.com/acs",+ ),+ ("saml-x509-cert", "saml_x509_cert", "MIID...cert", "SAML X.509 certificate", "masked"),+ ]+ )+ def test_identity_provider_config_update_activity_logging(+ self, name_prefix, field, value, expected_field_name, expected_logged_value+ ):+ config = self._create_config(f"{name_prefix} config")++ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {field: value},+ )+ self.assertEqual(response.status_code, 200)++ log = ActivityLog.objects.filter(+ organization_id=self.organization.id,+ scope="IdentityProviderConfig",+ activity="updated",+ ).first()++ assert log is not None+ assert log.detail is not None+ changes = log.detail.get("changes", [])+ field_change = next((c for c in changes if c["field"] == expected_field_name), None)+ assert field_change is not None, f"Expected change for '{expected_field_name}' not found in {changes}"+ self.assertEqual(field_change["after"], expected_logged_value)diff --git a/posthog/test/activity_logging/test_organization_domain_activity_logging.py b/posthog/test/activity_logging/test_organization_domain_activity_logging.pyindex da9aaacaf5f1..e1e2a7f4bd0c 100644--- a/posthog/test/activity_logging/test_organization_domain_activity_logging.py+++ b/posthog/test/activity_logging/test_organization_domain_activity_logging.py@@ -89,23 +89,6 @@ class TestOrganizationDomainActivityLogging(APIBaseTest):@parameterized.expand([("sso-enforcement", "sso_enforcement", "google-oauth2", "SSO enforcement", None, "google-oauth2"),- (- "saml-entity-id",- "saml_entity_id",- "https://idp.example.com",- "SAML entity ID",- None,- "https://idp.example.com",- ),- (- "saml-acs-url",- "saml_acs_url",- "https://idp.example.com/acs",- "SAML ACS URL",- None,- "https://idp.example.com/acs",- ),- ("saml-x509-cert", "saml_x509_cert", "MIID...cert", "SAML X.509 certificate", None, "masked"),("jit-provisioning","jit_provisioning_enabled",diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex a749139e346c..ec54856892df 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -6,6 +6,7 @@model_activity:posthog.models.activity_logging.signal_handlers.handle_experiment_holdout_changemodel_activity:posthog.models.activity_logging.signal_handlers.handle_experiment_saved_metric_changemodel_activity:posthog.models.activity_logging.signal_handlers.handle_experiment_to_saved_metric_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_identity_provider_config_changemodel_activity:posthog.models.activity_logging.signal_handlers.handle_oauth_application_scopes_changemodel_activity:posthog.models.activity_logging.signal_handlers.handle_organization_changemodel_activity:posthog.models.activity_logging.signal_handlers.handle_organization_domain_changediff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.pyindex 72ca4472816c..2e20bc7e94cf 100644--- a/posthog/test/test_identity_provider_config.py+++ b/posthog/test/test_identity_provider_config.py@@ -2,115 +2,68 @@ import pytestfrom posthog.test.base import BaseTestfrom django.core.exceptions import ValidationError-from django.core.management import call_commandfrom posthog.models import IdentityProviderConfig, Organization, OrganizationDomain-from posthog.models.identity_provider_config import (- IDP_CONFIG_SYNCED_FIELDS,- sync_domains_from_identity_provider_config,- sync_identity_provider_config_from_domain,-)-from ee.api.scim.utils import disable_scim_for_domain, enable_scim_for_domain, regenerate_scim_token+# Legacy `OrganizationDomain` columns that mirror fields on `IdentityProviderConfig`. Test-only:+# used to build underscore-prefixed kwargs and to guard the two models' field shapes against drift.+_LEGACY_IDP_FIELDS: tuple[str, ...] = (+ "saml_entity_id",+ "saml_acs_url",+ "saml_x509_cert",+ "scim_enabled",+ "scim_bearer_token",+ "id_jag_issuer_url",+ "id_jag_jwks_url",+ "id_jag_allowed_clients",+)def _prefix_idp_kwargs(kwargs: dict) -> dict:- # The domain's IdP columns are underscore-prefixed Python attributes; map the public names.- return {(f"_{k}" if k in IDP_CONFIG_SYNCED_FIELDS else k): v for k, v in kwargs.items()}+ # The domain's legacy IdP columns are underscore-prefixed Python attributes; map the public names.+ return {(f"_{k}" if k in _LEGACY_IDP_FIELDS else k): v for k, v in kwargs.items()}-class TestIdentityProviderConfigSync(BaseTest):+class TestIdentityProviderConfig(BaseTest):def _create_domain(self, domain: str = "posthog.com", **kwargs) -> OrganizationDomain:return OrganizationDomain.objects.create(organization=self.organization, domain=domain, **_prefix_idp_kwargs(kwargs))- def test_domain_without_idp_settings_does_not_create_config(self):- domain = self._create_domain()- assert domain.identity_provider_config is None- assert IdentityProviderConfig.objects.count() == 0-- def test_saving_saml_settings_creates_and_links_config(self):- domain = self._create_domain()- domain._saml_entity_id = "entity-id"- domain._saml_acs_url = "https://idp.example.com/acs"- domain._saml_x509_cert = "cert-contents"+ def _create_linked_config(self, domain: OrganizationDomain, **config_kwargs) -> IdentityProviderConfig:+ config = IdentityProviderConfig.objects.create(organization=self.organization, **config_kwargs)+ domain.identity_provider_config = configdomain.save()+ return config- domain.refresh_from_db()- config = domain.identity_provider_config- assert config is not None- assert config.organization == self.organization- assert config.name == "posthog.com"- assert config.saml_entity_id == "entity-id"- assert config.saml_acs_url == "https://idp.example.com/acs"- assert config.saml_x509_cert == "cert-contents"- assert config.has_saml-- def test_updating_domain_updates_linked_config(self):+ def test_saving_legacy_idp_columns_does_not_create_or_link_config(self):+ # The domain<->config dual-write mirror has been removed: writing the legacy underscore+ # columns must no longer auto-create or link an IdentityProviderConfig.domain = self._create_domain(saml_entity_id="entity-id",saml_acs_url="https://idp.example.com/acs",saml_x509_cert="cert-contents",)- config = domain.identity_provider_config- assert config is not None-- domain._saml_entity_id = "new-entity-id"- domain._id_jag_issuer_url = "https://issuer.example.com"- domain.save()-- config.refresh_from_db()- assert config.saml_entity_id == "new-entity-id"- assert config.id_jag_issuer_url == "https://issuer.example.com"- # Still only one config — updates don't create new rows- assert IdentityProviderConfig.objects.count() == 1-- def test_clearing_idp_settings_clears_linked_config(self):- domain = self._create_domain(- saml_entity_id="entity-id",- saml_acs_url="https://idp.example.com/acs",- saml_x509_cert="cert-contents",- )- domain._saml_entity_id = None- domain._saml_acs_url = None- domain._saml_x509_cert = None- domain.save()-- config = domain.identity_provider_config- assert config is not None- config.refresh_from_db()- assert not config.has_saml- assert config.saml_entity_id is None-- def test_scim_utils_dual_write_to_config(self):- domain = self._create_domain()-- enable_scim_for_domain(domain)domain.refresh_from_db()- config = domain.identity_provider_config- assert config is not None- assert config.scim_enabled is True- assert config.scim_bearer_token == domain._scim_bearer_token- assert config.has_scim+ assert domain.identity_provider_config is None+ assert IdentityProviderConfig.objects.count() == 0- regenerate_scim_token(domain)- config.refresh_from_db()- assert config.scim_bearer_token == domain._scim_bearer_token+ def test_updating_linked_config_does_not_touch_legacy_domain_columns(self):+ # The reverse mirror (config -> domain) has been removed: updating a linked config must+ # not touch the domain's legacy columns anymore.+ domain = self._create_domain()+ config = self._create_linked_config(domain, saml_entity_id="entity-id")- disable_scim_for_domain(domain)- config.refresh_from_db()- assert config.scim_enabled is False+ config.saml_entity_id = "new-entity-id"+ config.save()- def test_sync_is_idempotent(self):- domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")- assert sync_identity_provider_config_from_domain(domain) == "unchanged"- assert IdentityProviderConfig.objects.count() == 1+ domain.refresh_from_db()+ assert domain._saml_entity_id is Nonedef test_synced_fields_match_between_models(self):# Guard against the two models drifting apart. The domain stores these as underscore-prefixed# columns (with the original db_column), the config stores them under the plain name.- for field in IDP_CONFIG_SYNCED_FIELDS:+ for field in _LEGACY_IDP_FIELDS:domain_field = OrganizationDomain._meta.get_field(f"_{field}")config_field = IdentityProviderConfig._meta.get_field(field)assert domain_field.__class__ == config_field.__class__, field@@ -118,138 +71,73 @@ class TestIdentityProviderConfigSync(BaseTest):assert getattr(domain_field, "db_column", None) == field, fielddef test_deleting_domain_keeps_config(self):- domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")- config_id = domain.identity_provider_config_id+ domain = self._create_domain()+ config = self._create_linked_config(domain, saml_entity_id="entity-id")+domain.delete()- assert config_id is not None- assert IdentityProviderConfig.objects.filter(pk=config_id).exists()+ assert IdentityProviderConfig.objects.filter(pk=config.pk).exists()- def test_cross_org_config_link_is_rejected(self):+ def test_cross_org_config_link_fails_validation(self):other_org = Organization.objects.create(name="Other")- other_config = IdentityProviderConfig.objects.create(organization=other_org, saml_entity_id="other-entity")+ other_config = IdentityProviderConfig.objects.create(organization=other_org)domain = self._create_domain()domain.identity_provider_config = other_config- with pytest.raises(ValueError, match="different organization"):- domain.save()-- # The cross-org config's settings must remain untouched- other_config.refresh_from_db()- assert other_config.saml_entity_id == "other-entity"+ with pytest.raises(ValidationError) as exc_info:+ domain.full_clean()+ assert "identity_provider_config" in exc_info.value.message_dict- def test_cross_org_config_link_fails_validation(self):+ def test_cross_org_config_link_fails_on_direct_save(self):+ # `clean()`/`full_clean()` aren't invoked by plain `.save()`/`.objects.create()`, so the+ # cross-org guard must also be enforced from `save()` itself.other_org = Organization.objects.create(name="Other")other_config = IdentityProviderConfig.objects.create(organization=other_org)domain = self._create_domain()domain.identity_provider_config = other_configwith pytest.raises(ValidationError) as exc_info:- domain.full_clean()+ domain.save()+ assert "identity_provider_config" in exc_info.value.message_dict++ def test_cross_org_config_link_fails_on_create(self):+ other_org = Organization.objects.create(name="Other")+ other_config = IdentityProviderConfig.objects.create(organization=other_org)++ with pytest.raises(ValidationError) as exc_info:+ OrganizationDomain.objects.create(+ organization=self.organization, domain="posthog.com", identity_provider_config=other_config+ )assert "identity_provider_config" in exc_info.value.message_dictdef test_dangling_config_link_fails_validation(self):- domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")- config_id = domain.identity_provider_config_id- assert config_id is not None- # Delete the row out from under the FK without nulling the link- IdentityProviderConfig.objects.filter(pk=config_id).delete()+ domain = self._create_domain()+ config = self._create_linked_config(domain)+ # Delete the row out from under the FK without nulling the link on the in-memory instance.+ IdentityProviderConfig.objects.filter(pk=config.pk).delete()with pytest.raises(ValidationError) as exc_info:domain.full_clean()assert "identity_provider_config" in exc_info.value.message_dictdef test_deleting_config_nulls_domain_link(self):- domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")- assert domain.identity_provider_config is not None- domain.identity_provider_config.delete()- domain.refresh_from_db()- assert domain.identity_provider_config is None-- def test_config_save_syncs_to_linked_domain(self):- domain = self._create_domain(- saml_entity_id="entity-id",- saml_acs_url="https://idp.example.com/acs",- saml_x509_cert="cert-contents",- )- config = domain.identity_provider_config- assert config is not None-- config.saml_entity_id = "new-entity-id"- config.save()-- domain.refresh_from_db()- assert domain._saml_entity_id == "new-entity-id"-- def test_config_save_with_no_linked_domains_is_noop(self):- config = IdentityProviderConfig.objects.create(organization=self.organization, saml_entity_id="entity-id")- assert sync_domains_from_identity_provider_config(config) == 0-- def test_linking_populated_config_to_new_domain_does_not_clobber(self):- # A new domain linked to an already-populated config must adopt the config's values, not- # blank the (potentially shared) config via the forward mirror.- config = IdentityProviderConfig.objects.create(- organization=self.organization,- saml_entity_id="entity-id",- saml_acs_url="https://idp.example.com/acs",- saml_x509_cert="cert",- scim_enabled=True,- scim_bearer_token="hashed",- )- domain = OrganizationDomain.objects.create(- organization=self.organization, domain="new.example.com", identity_provider_config=config- )-- config.refresh_from_db()- assert config.saml_entity_id == "entity-id"- assert config.scim_enabled is True- assert config.scim_bearer_token == "hashed"- # The new domain adopts the config's values (config is the source of truth for reads).- assert domain.has_saml- assert domain._saml_entity_id == "entity-id"-- def test_domain_save_does_not_clobber_config_written_directly(self):- domain = self._create_domain(- saml_entity_id="entity-id",- saml_acs_url="https://idp.example.com/acs",- saml_x509_cert="cert-contents",- )- config = domain.identity_provider_config- assert config is not None-- # Write via the config (the source of truth)- config.saml_entity_id = "config-owned-entity"- config.save()-- # An unrelated domain save must not revert the config to a stale value- domain.refresh_from_db()- domain.jit_provisioning_enabled = True- domain.save()+ domain = self._create_domain()+ config = self._create_linked_config(domain)- config.refresh_from_db()+ config.delete()domain.refresh_from_db()- assert config.saml_entity_id == "config-owned-entity"- assert domain._saml_entity_id == "config-owned-entity"+ assert domain.identity_provider_config is None- def test_has_saml_reads_from_config_not_domain_columns(self):- domain = self._create_domain(+ def test_has_saml_reads_from_linked_config_not_legacy_domain_columns(self):+ domain = self._create_domain() # legacy columns stay empty throughout+ config = self._create_linked_config(+ domain,saml_entity_id="entity-id",saml_acs_url="https://idp.example.com/acs",saml_x509_cert="cert-contents",)- config = domain.identity_provider_config- assert config is not None- assert domain.has_saml-- # Blank the domain's own columns without touching the config (bypass sync via queryset update)- OrganizationDomain.objects.filter(pk=domain.pk).update(_saml_entity_id="", _saml_acs_url="", _saml_x509_cert="")- domain.refresh_from_db()- # Reads resolve from the config, which still has SAMLassert domain.has_saml- # Clearing the config flips the readconfig.saml_entity_id = None- config.saml_acs_url = None- config.saml_x509_cert = Noneconfig.save()domain.refresh_from_db()assert not domain.has_saml@@ -260,76 +148,3 @@ class TestIdentityProviderConfigSync(BaseTest):assert not domain.has_samlassert not domain.has_scimassert not domain.has_id_jag---class TestSyncIdentityProviderConfigsCommand(BaseTest):- def _create_unsynced_domain(self, domain: str, **kwargs) -> OrganizationDomain:- # Bypass `OrganizationDomain.save()` dual-write to simulate pre-existing rows- instance = OrganizationDomain(organization=self.organization, domain=domain, **_prefix_idp_kwargs(kwargs))- instance.save()- OrganizationDomain.objects.filter(pk=instance.pk).update(identity_provider_config=None)- IdentityProviderConfig.objects.all().delete()- instance.refresh_from_db()- return instance-- def test_command_backfills_configs(self):- saml_domain = self._create_unsynced_domain(- "saml.example.com",- saml_entity_id="entity-id",- saml_acs_url="https://idp.example.com/acs",- saml_x509_cert="cert-contents",- )- plain_domain = self._create_unsynced_domain("plain.example.com")-- call_command("sync_identity_provider_configs")-- saml_domain.refresh_from_db()- plain_domain.refresh_from_db()- assert saml_domain.identity_provider_config is not None- assert saml_domain.identity_provider_config.saml_entity_id == "entity-id"- assert plain_domain.identity_provider_config is None- assert IdentityProviderConfig.objects.count() == 1-- def test_command_resyncs_drifted_configs(self):- domain = OrganizationDomain.objects.create(- organization=self.organization,- domain="saml.example.com",- _id_jag_issuer_url="https://issuer.example.com",- )- config = domain.identity_provider_config- assert config is not None- # Simulate drift in the mirror- IdentityProviderConfig.objects.filter(pk=config.pk).update(id_jag_issuer_url="https://stale.example.com")-- call_command("sync_identity_provider_configs")-- config.refresh_from_db()- assert config.id_jag_issuer_url == "https://issuer.example.com"-- def test_command_dry_run_makes_no_changes(self):- self._create_unsynced_domain(- "saml.example.com",- saml_entity_id="entity-id",- saml_acs_url="https://idp.example.com/acs",- saml_x509_cert="cert-contents",- )-- call_command("sync_identity_provider_configs", "--dry-run")-- assert IdentityProviderConfig.objects.count() == 0-- def test_command_filters_by_organization(self):- other_org = Organization.objects.create(name="Other")- other_domain = OrganizationDomain.objects.create(- organization=other_org, domain="other.example.com", _id_jag_issuer_url="https://issuer.example.com"- )- # `_create_unsynced_domain` wipes all configs, leaving both domains unsynced- domain = self._create_unsynced_domain("mine.example.com", id_jag_issuer_url="https://issuer.example.com")-- call_command("sync_identity_provider_configs", f"--organization-id={self.organization.id}")-- domain.refresh_from_db()- other_domain.refresh_from_db()- assert domain.identity_provider_config is not None- assert other_domain.identity_provider_config is None- assert IdentityProviderConfig.objects.count() == 1diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex ca4b0ef076dc..d6e0ceabb6dd 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -959,6 +959,7 @@ export type ActivityLogListParams = {* * `LegalDocument` - LegalDocument* * `Organization` - Organization* * `OrganizationDomain` - OrganizationDomain+ * * `IdentityProviderConfig` - IdentityProviderConfig* * `OrganizationMembership` - OrganizationMembership* * `Role` - Role* * `UserGroup` - UserGroup@@ -1043,6 +1044,7 @@ export const ActivityLogListScope = {LegalDocument: 'LegalDocument',Organization: 'Organization',OrganizationDomain: 'OrganizationDomain',+ IdentityProviderConfig: 'IdentityProviderConfig',OrganizationMembership: 'OrganizationMembership',Role: 'Role',UserGroup: 'UserGroup',@@ -1114,6 +1116,7 @@ export const ActivityLogListScope = {* * `LegalDocument` - LegalDocument* * `Organization` - Organization* * `OrganizationDomain` - OrganizationDomain+ * * `IdentityProviderConfig` - IdentityProviderConfig* * `OrganizationMembership` - OrganizationMembership* * `Role` - Role* * `UserGroup` - UserGroup@@ -1186,6 +1189,7 @@ export const ActivityLogListScopesItem = {LegalDocument: 'LegalDocument',Organization: 'Organization',OrganizationDomain: 'OrganizationDomain',+ IdentityProviderConfig: 'IdentityProviderConfig',OrganizationMembership: 'OrganizationMembership',Role: 'Role',UserGroup: 'UserGroup',diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 2ea93206d140..88ccd5ec7db3 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -256,9 +256,6 @@ tools:domains-scim-logs-retrieve:operation: domains_scim_logs_retrieveenabled: false- domains-scim-token-create:- operation: domains_scim_token_create- enabled: falsedomains-update:operation: domains_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ac1bbb5bdc61..108874e3f74a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -33330,50 +33330,12 @@ export namespace Schemas {sso_enforcement?: string;/** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */readonly has_saml: boolean;- /**- * SAML IdP entity ID (issuer).- * @maxLength 512- * @nullable- */- saml_entity_id?: string | null;- /**- * SAML single sign-on (ACS) URL.- * @maxLength 512- * @nullable- */- saml_acs_url?: string | null;- /**- * SAML IdP X.509 signing certificate (PEM).- * @nullable- */- saml_x509_cert?: string | null;/** Returns whether SCIM is configured and enabled for this domain. */readonly has_scim: boolean;- /** Whether SCIM provisioning is enabled for this domain. */- scim_enabled?: boolean;/** @nullable */readonly scim_base_url: string | null;- /** @nullable */- readonly scim_bearer_token: string | null;/** Returns whether ID-JAG (XAA) is configured for this domain. */readonly has_id_jag: boolean;- /**- * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.- * @maxLength 512- * @nullable- */- id_jag_issuer_url?: string | null;- /**- * Override JWKS URL. Defaults to OIDC discovery on the issuer URL.- * @maxLength 512- * @nullable- */- id_jag_jwks_url?: string | null;- /**- * Allowed ID-JAG client IDs. Empty list allows any client_id.- * @items.maxLength 256- */- id_jag_allowed_clients?: string[];/*** Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.* @nullable@@ -42132,50 +42094,12 @@ export namespace Schemas {sso_enforcement?: string;/** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */readonly has_saml?: boolean;- /**- * SAML IdP entity ID (issuer).- * @maxLength 512- * @nullable- */- saml_entity_id?: string | null;- /**- * SAML single sign-on (ACS) URL.- * @maxLength 512- * @nullable- */- saml_acs_url?: string | null;- /**- * SAML IdP X.509 signing certificate (PEM).- * @nullable- */- saml_x509_cert?: string | null;/** Returns whether SCIM is configured and enabled for this domain. */readonly has_scim?: boolean;- /** Whether SCIM provisioning is enabled for this domain. */- scim_enabled?: boolean;/** @nullable */readonly scim_base_url?: string | null;- /** @nullable */- readonly scim_bearer_token?: string | null;/** Returns whether ID-JAG (XAA) is configured for this domain. */readonly has_id_jag?: boolean;- /**- * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG on this domain.- * @maxLength 512- * @nullable- */- id_jag_issuer_url?: string | null;- /**- * Override JWKS URL. Defaults to OIDC discovery on the issuer URL.- * @maxLength 512- * @nullable- */- id_jag_jwks_url?: string | null;- /**- * Allowed ID-JAG client IDs. Empty list allows any client_id.- * @items.maxLength 256- */- id_jag_allowed_clients?: string[];/*** Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.* @nullable@@ -65635,6 +65559,7 @@ export namespace Schemas {* * `LegalDocument` - LegalDocument* * `Organization` - Organization* * `OrganizationDomain` - OrganizationDomain+ * * `IdentityProviderConfig` - IdentityProviderConfig* * `OrganizationMembership` - OrganizationMembership* * `Role` - Role* * `UserGroup` - UserGroup@@ -65720,6 +65645,7 @@ export namespace Schemas {LegalDocument: 'LegalDocument',Organization: 'Organization',OrganizationDomain: 'OrganizationDomain',+ IdentityProviderConfig: 'IdentityProviderConfig',OrganizationMembership: 'OrganizationMembership',Role: 'Role',UserGroup: 'UserGroup',@@ -65791,6 +65717,7 @@ export namespace Schemas {* * `LegalDocument` - LegalDocument* * `Organization` - Organization* * `OrganizationDomain` - OrganizationDomain+ * * `IdentityProviderConfig` - IdentityProviderConfig* * `OrganizationMembership` - OrganizationMembership* * `Role` - Role* * `UserGroup` - UserGroup@@ -65864,6 +65791,7 @@ export namespace Schemas {LegalDocument: 'LegalDocument',Organization: 'Organization',OrganizationDomain: 'OrganizationDomain',+ IdentityProviderConfig: 'IdentityProviderConfig',OrganizationMembership: 'OrganizationMembership',Role: 'Role',UserGroup: 'UserGroup',