:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(idp): move SCIM and SAML config from OrganizationDomain to IdentityProviderConfig (#65614)
Reece Jones4339f4438704
diff --git a/ee/api/authentication.py b/ee/api/authentication.pyindex b1107573d865..c2e2b0388bc2 100644--- a/ee/api/authentication.py+++ b/ee/api/authentication.py@@ -127,12 +127,13 @@ class MultitenantSAMLAuth(SAMLAuth):"Your organization does not have the required license to use SAML.",)+ idp_config = organization_domain.idp_configreturn SAMLIdentityProvider(self,str(organization_domain.id),- entity_id=organization_domain.saml_entity_id,- url=organization_domain.saml_acs_url,- x509cert=organization_domain.saml_x509_cert,+ entity_id=idp_config.saml_entity_id,+ url=idp_config.saml_acs_url,+ x509cert=idp_config.saml_x509_cert,)def auth_url(self):diff --git a/ee/api/scim/auth.py b/ee/api/scim/auth.pyindex 3148450481ac..c97f80760cef 100644--- a/ee/api/scim/auth.py+++ b/ee/api/scim/auth.py@@ -50,18 +50,26 @@ class SCIMBearerTokenAuthentication(BaseAuthentication):try:# nosemgrep: idor-lookup-without-org (SCIM bearer token auth, domain_id is tenant identifier)- domain = OrganizationDomain.objects.get(id=domain_id)+ domain = OrganizationDomain.objects.select_related("identity_provider_config").get(id=domain_id)except OrganizationDomain.DoesNotExist:raise exceptions.AuthenticationFailed("Invalid organization domain")- if not domain.has_scim:+ # Read the linked IdP config directly (the source of truth) rather than through the+ # empty-config fallback, so a domain with no config fails clearly here instead of falling+ # through to a misleading "Invalid bearer token" on a null hash below.+ #+ # The domain must also be verified: SCIM can be enabled on a config independently of any+ # domain (the config API has no verification gate), so re-check verification here to keep+ # provisioning gated behind a verified domain.+ config = domain.identity_provider_config+ if not domain.is_verified or config is None or not config.has_scim:raise exceptions.AuthenticationFailed("SCIM not configured for this domain")if not domain.organization.is_feature_available(AvailableFeature.SCIM):raise exceptions.AuthenticationFailed("Your organization does not have the required license to use SCIM")- # Verify the bearer token matches the stored hashed token- if not check_password(token, domain.scim_bearer_token):+ # Verify the bearer token matches the stored hashed token (sourced from the IdP config)+ if not check_password(token, config.scim_bearer_token):raise exceptions.AuthenticationFailed("Invalid bearer token")return (SCIMAuthToken(domain), domain)diff --git a/ee/api/scim/test/test_groups_api.py b/ee/api/scim/test/test_groups_api.pyindex 2b7a3b8bad51..e2589f313fc0 100644--- a/ee/api/scim/test/test_groups_api.py+++ b/ee/api/scim/test/test_groups_api.py@@ -35,8 +35,8 @@ 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+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.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 be10d04b89c7..642d4585c9b8 100644--- a/ee/api/scim/test/test_scim_api.py+++ b/ee/api/scim/test/test_scim_api.py@@ -33,8 +33,8 @@ 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+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -49,6 +49,37 @@ class TestSCIMAPI(APILicensedTest):assert data["status"] == 403assert "detail" in data+ def test_domain_without_idp_config_is_rejected(self):+ # A domain with no linked IdP config must be rejected by SCIM auth (the no-config case is+ # handled explicitly, not by falling through to check_password against a null hash).+ unconfigured = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="no-config.example.com",+ verified_at="2024-01-01T00:00:00Z",+ )+ assert unconfigured.identity_provider_config is None+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.plain_token}")+ response = self.client.get(f"/scim/v2/{unconfigured.id}/Users")+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_unverified_domain_is_rejected(self):+ # SCIM can be enabled on a config independently of any domain, so an unverified domain with+ # a SCIM-enabled config must still be rejected — provisioning stays gated behind verification.+ plain_token, hashed_token = generate_scim_token()+ unverified = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="unverified.example.com",+ verified_at=None,+ )+ unverified._scim_enabled = True+ unverified._scim_bearer_token = hashed_token+ unverified.save()+ assert unverified.has_scim # config is SCIM-enabled with a token++ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {plain_token}")+ response = self.client.get(f"/scim/v2/{unverified.id}/Users")+ assert response.status_code == status.HTTP_403_FORBIDDEN+def test_no_token(self):response = self.client.get(f"/scim/v2/{self.domain.id}/Users")assert response.status_code == status.HTTP_401_UNAUTHORIZED@@ -236,8 +267,8 @@ class TestSCIMEmailDomainValidation(APILicensedTest):)self.plain_token, hashed_token = generate_scim_token()- self.domain.scim_enabled = True- self.domain.scim_bearer_token = hashed_token+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -473,8 +504,8 @@ class TestSCIMAuditLogging(APILicensedTest):)self.plain_token, hashed_token = generate_scim_token()- self.domain.scim_enabled = True- self.domain.scim_bearer_token = hashed_token+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.domain.save()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -567,8 +598,8 @@ class TestSCIMGroupAuditLogging(APILicensedTest):)self.plain_token, hashed_token = generate_scim_token()- self.domain.scim_enabled = True- self.domain.scim_bearer_token = hashed_token+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.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 ac829bf5dcee..b532ced75361 100644--- a/ee/api/scim/test/test_scim_request_log.py+++ b/ee/api/scim/test/test_scim_request_log.py@@ -36,8 +36,8 @@ 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+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.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 c1b75b923883..eb875883d411 100644--- a/ee/api/scim/test/test_users_api.py+++ b/ee/api/scim/test/test_users_api.py@@ -33,8 +33,8 @@ 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+ self.domain._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.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 eadb8affae5f..caf0b84bd8d4 100644--- a/ee/api/scim/utils.py+++ b/ee/api/scim/utils.py@@ -2,6 +2,7 @@ from typing import Anyfrom rest_framework.request import Request+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomainfrom ee.models.scim_provisioned_user import SCIMProvisionedUser@@ -94,8 +95,8 @@ def enable_scim_for_domain(domain: OrganizationDomain) -> str:"""plain_token, hashed_token = generate_scim_token()- domain.scim_enabled = True- domain.scim_bearer_token = hashed_token+ domain._scim_enabled = True+ domain._scim_bearer_token = hashed_tokendomain.save()return plain_token@@ -105,8 +106,8 @@ def disable_scim_for_domain(domain: OrganizationDomain) -> None:"""Disable SCIM for an OrganizationDomain."""- domain.scim_enabled = False- domain.scim_bearer_token = None+ domain._scim_enabled = False+ domain._scim_bearer_token = Nonedomain.save()@@ -117,12 +118,48 @@ def regenerate_scim_token(domain: OrganizationDomain) -> str:"""plain_token, hashed_token = generate_scim_token()- domain.scim_bearer_token = hashed_token+ domain._scim_bearer_token = hashed_tokendomain.save()return plain_token+def enable_scim_for_config(config: IdentityProviderConfig) -> str:+ """+ Enable SCIM for an IdentityProviderConfig and generate a new bearer token.+ Returns the plain text token (only shown once).+ """+ plain_token, hashed_token = generate_scim_token()++ config.scim_enabled = True+ config.scim_bearer_token = hashed_token+ config.save()++ return plain_token+++def disable_scim_for_config(config: IdentityProviderConfig) -> None:+ """+ Disable SCIM for an IdentityProviderConfig.+ """+ config.scim_enabled = False+ config.scim_bearer_token = None+ config.save()+++def regenerate_scim_token_for_config(config: IdentityProviderConfig) -> str:+ """+ Regenerate SCIM bearer token for an IdentityProviderConfig.+ Returns the new plain text token (only shown once).+ """+ plain_token, hashed_token = generate_scim_token()++ config.scim_bearer_token = hashed_token+ config.save()++ return plain_token++def get_scim_base_url(domain: OrganizationDomain, request=None) -> str:"""Get the SCIM base URL for a domain.diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex fd95d78c0132..e2d1e4e4ed58 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -303,9 +303,9 @@ 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+ _saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",+ _saml_acs_url="https://idp.hogflix.io/saml",+ _saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEUMBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEcMBoGCSqGSIb3DQEJARYNaW5mb0Bva3RhLmNvbTAeFw0yMTA4MjExMTIyMjNaFw0zMTA4MjExMTIzMjNaMIGUMQswCQYD@@ -553,7 +553,7 @@ 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+ self.organization_domain._saml_x509_cert = """MIIDPjCCAiYCCQC864/0fftWQTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJVUzELMAkGA1UECAwCVVMxCzAJBgNVBAcMAlVTMQswCQYDVQQKDAJVUzELMAkGA1UECwwCVVMxCzAJBgNVBAMMAlVTMREwDwYJKoZIhvcNAQkBFgJVUzAeFw0yMTA4MjYwMDAxMzNaFw0zMTA4MjYwMDAxMzNaMGExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJV@@ -821,9 +821,9 @@ 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,+ _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,)response = self.client.get("/login/saml/[email protected]")@@ -987,9 +987,9 @@ 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",+ _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@@ -1056,9 +1056,9 @@ 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+ _saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",+ _saml_acs_url="https://my.posthog.app/complete/saml/",+ _saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEUMBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEcMBoGCSqGSIb3DQEJARYNaW5mb0Bva3RhLmNvbTAeFw0yMTA4MjExMTIyMjNaFw0zMTA4MjExMTIzMjNaMIGUMQswCQYDdiff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 96f999deb8aa..04160d2eac7d 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -118,19 +118,25 @@ export interface OrganizationDomainApi {/** 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- /** @nullable */+ /**+ * 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@@ -155,6 +161,11 @@ export interface OrganizationDomainApi {* @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+ */+ identity_provider_config?: string | null}export interface PaginatedOrganizationDomainListApi {@@ -181,19 +192,25 @@ export interface PatchedOrganizationDomainApi {/** 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- /** @nullable */+ /**+ * 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@@ -218,6 +235,143 @@ export interface PatchedOrganizationDomainApi {* @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+ */+ identity_provider_config?: string | null+}++export interface IdentityProviderConfigApi {+ readonly id: string+ /**+ * Display name for this IdP configuration (e.g. 'Okta production').+ * @maxLength 255+ */+ name?: string+ readonly created_at: string+ readonly updated_at: string+ /** Whether SAML is fully configured on this config. */+ readonly has_saml: boolean+ /**+ * SAML IdP entity ID (issuer).+ * @maxLength 512+ * @nullable+ */+ saml_entity_id?: string | null+ /**+ * SAML single sign-on (ACS) URL the IdP redirects to.+ * @maxLength 512+ * @nullable+ */+ saml_acs_url?: string | null+ /**+ * SAML IdP X.509 signing certificate (PEM).+ * @nullable+ */+ saml_x509_cert?: string | null+ /** Whether SCIM is enabled and a bearer token is set on this config. */+ readonly has_scim: boolean+ /** Whether SCIM provisioning is enabled. Setting this true generates a bearer token (returned once); setting it false clears the token. */+ scim_enabled?: boolean+ /**+ * Plaintext SCIM bearer token. Only returned once, immediately after SCIM is enabled or the token is regenerated; null otherwise.+ * @nullable+ */+ readonly scim_bearer_token: string | null+ /** Whether ID-JAG (XAA) is configured on this config. */+ readonly has_id_jag: boolean+ /**+ * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.+ * @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[]+}++export interface PaginatedIdentityProviderConfigListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: IdentityProviderConfigApi[]+}++export interface PatchedIdentityProviderConfigApi {+ readonly id?: string+ /**+ * Display name for this IdP configuration (e.g. 'Okta production').+ * @maxLength 255+ */+ name?: string+ readonly created_at?: string+ readonly updated_at?: string+ /** Whether SAML is fully configured on this config. */+ readonly has_saml?: boolean+ /**+ * SAML IdP entity ID (issuer).+ * @maxLength 512+ * @nullable+ */+ saml_entity_id?: string | null+ /**+ * SAML single sign-on (ACS) URL the IdP redirects to.+ * @maxLength 512+ * @nullable+ */+ saml_acs_url?: string | null+ /**+ * SAML IdP X.509 signing certificate (PEM).+ * @nullable+ */+ saml_x509_cert?: string | null+ /** Whether SCIM is enabled and a bearer token is set on this config. */+ readonly has_scim?: boolean+ /** Whether SCIM provisioning is enabled. Setting this true generates a bearer token (returned once); setting it false clears the token. */+ scim_enabled?: boolean+ /**+ * Plaintext SCIM bearer token. Only returned once, immediately after SCIM is enabled or the token is regenerated; null otherwise.+ * @nullable+ */+ readonly scim_bearer_token?: string | null+ /** Whether ID-JAG (XAA) is configured on this config. */+ readonly has_id_jag?: boolean+ /**+ * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.+ * @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[]+}++export interface SCIMTokenResponseApi {+ /** Whether SCIM is enabled for this config. */+ scim_enabled: boolean+ /** Newly generated plaintext SCIM bearer token. Only returned once. */+ scim_bearer_token: string}/**@@ -3785,6 +3939,17 @@ export type DomainsListParams = {offset?: number}+export type IdentityProviderConfigsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type InvitesListParams = {/*** Number of results to return per page.diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 2a91b8dd9c12..faf84d73a073 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -33,6 +33,8 @@ import type {GitHubBranchesResponseApi,GitHubReposRefreshResponseApi,GitHubReposResponseApi,+ IdentityProviderConfigApi,+ IdentityProviderConfigsListParams,InvitesListParams,OauthApplicationsListParams,OnboardingSkipRequestApi,@@ -46,6 +48,7 @@ import type {PaginatedFileSystemListApi,PaginatedFileSystemShortcutListApi,PaginatedFolderInstructionsVersionListApi,+ PaginatedIdentityProviderConfigListApi,PaginatedOrganizationDomainListApi,PaginatedOrganizationInviteListApi,PaginatedOrganizationOAuthApplicationListApi,@@ -58,6 +61,7 @@ import type {PatchedFileSystemApi,PatchedFileSystemShortcutApi,PatchedFolderInstructionsPublishApi,+ PatchedIdentityProviderConfigApi,PatchedOrganizationDomainApi,PatchedProjectBackwardCompatApi,PatchedProjectSecretAPIKeyApi,@@ -67,6 +71,7 @@ import type {ProjectSecretApiKeysListParams,PropertyDefinitionsListParams,RevokeOtherSessionsResponseApi,+ SCIMTokenResponseApi,SharingConfigurationApi,UserApi,UserAuthSessionApi,@@ -381,6 +386,140 @@ export const domainsVerifyCreate = async (})}+export const getIdentityProviderConfigsListUrl = (+ organizationId: string,+ params?: IdentityProviderConfigsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/identity_provider_configs/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/identity_provider_configs/`+}++export const identityProviderConfigsList = async (+ organizationId: string,+ params?: IdentityProviderConfigsListParams,+ options?: RequestInit+): Promise<PaginatedIdentityProviderConfigListApi> => {+ return apiMutator<PaginatedIdentityProviderConfigListApi>(+ getIdentityProviderConfigsListUrl(organizationId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getIdentityProviderConfigsCreateUrl = (organizationId: string) => {+ return `/api/organizations/${organizationId}/identity_provider_configs/`+}++export const identityProviderConfigsCreate = async (+ organizationId: string,+ identityProviderConfigApi?: NonReadonly<IdentityProviderConfigApi>,+ options?: RequestInit+): Promise<IdentityProviderConfigApi> => {+ return apiMutator<IdentityProviderConfigApi>(getIdentityProviderConfigsCreateUrl(organizationId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(identityProviderConfigApi),+ })+}++export const getIdentityProviderConfigsRetrieveUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/identity_provider_configs/${id}/`+}++export const identityProviderConfigsRetrieve = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<IdentityProviderConfigApi> => {+ return apiMutator<IdentityProviderConfigApi>(getIdentityProviderConfigsRetrieveUrl(organizationId, id), {+ ...options,+ method: 'GET',+ })+}++export const getIdentityProviderConfigsUpdateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/identity_provider_configs/${id}/`+}++export const identityProviderConfigsUpdate = async (+ organizationId: string,+ id: string,+ identityProviderConfigApi?: NonReadonly<IdentityProviderConfigApi>,+ options?: RequestInit+): Promise<IdentityProviderConfigApi> => {+ return apiMutator<IdentityProviderConfigApi>(getIdentityProviderConfigsUpdateUrl(organizationId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(identityProviderConfigApi),+ })+}++export const getIdentityProviderConfigsPartialUpdateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/identity_provider_configs/${id}/`+}++export const identityProviderConfigsPartialUpdate = async (+ organizationId: string,+ id: string,+ patchedIdentityProviderConfigApi?: NonReadonly<PatchedIdentityProviderConfigApi>,+ options?: RequestInit+): Promise<IdentityProviderConfigApi> => {+ return apiMutator<IdentityProviderConfigApi>(getIdentityProviderConfigsPartialUpdateUrl(organizationId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedIdentityProviderConfigApi),+ })+}++export const getIdentityProviderConfigsDestroyUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/identity_provider_configs/${id}/`+}++export const identityProviderConfigsDestroy = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getIdentityProviderConfigsDestroyUrl(organizationId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getIdentityProviderConfigsScimTokenCreateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/identity_provider_configs/${id}/scim/token/`+}++/**+ * Regenerate the SCIM bearer token for this IdP config.+ */+export const identityProviderConfigsScimTokenCreate = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<SCIMTokenResponseApi> => {+ return apiMutator<SCIMTokenResponseApi>(getIdentityProviderConfigsScimTokenCreateUrl(organizationId, id), {+ ...options,+ method: 'POST',+ })+}+export const getInvitesListUrl = (organizationId: string, params?: InvitesListParams) => {const normalizedParams = new URLSearchParams()diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 38093a3d7995..151bbac810aa 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -44,10 +44,14 @@ 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(),- saml_acs_url: zod.string().max(domainsCreateBodySamlAcsUrlMax).nullish(),- saml_x509_cert: zod.string().nullish(),- scim_enabled: zod.boolean().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)@@ -62,6 +66,12 @@ export const DomainsCreateBody = /* @__PURE__ */ zod.object({.array(zod.string().max(domainsCreateBodyIdJagAllowedClientsItemMax)).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.'+ ),})export const domainsUpdateBodyDomainMax = 128@@ -82,10 +92,14 @@ 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(),- saml_acs_url: zod.string().max(domainsUpdateBodySamlAcsUrlMax).nullish(),- saml_x509_cert: zod.string().nullish(),- scim_enabled: zod.boolean().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)@@ -100,6 +114,12 @@ export const DomainsUpdateBody = /* @__PURE__ */ zod.object({.array(zod.string().max(domainsUpdateBodyIdJagAllowedClientsItemMax)).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.'+ ),})export const domainsPartialUpdateBodyDomainMax = 128@@ -120,10 +140,18 @@ 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(),- saml_acs_url: zod.string().max(domainsPartialUpdateBodySamlAcsUrlMax).nullish(),- saml_x509_cert: zod.string().nullish(),- scim_enabled: zod.boolean().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)@@ -138,6 +166,12 @@ export const DomainsPartialUpdateBody = /* @__PURE__ */ zod.object({.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.'+ ),})/**@@ -161,10 +195,18 @@ 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(),- saml_acs_url: zod.string().max(domainsScimTokenCreateBodySamlAcsUrlMax).nullish(),- saml_x509_cert: zod.string().nullish(),- scim_enabled: zod.boolean().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)@@ -179,6 +221,12 @@ export const DomainsScimTokenCreateBody = /* @__PURE__ */ zod.object({.array(zod.string().max(domainsScimTokenCreateBodyIdJagAllowedClientsItemMax)).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.'+ ),})export const domainsVerifyCreateBodyDomainMax = 128@@ -199,10 +247,18 @@ 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(),- saml_acs_url: zod.string().max(domainsVerifyCreateBodySamlAcsUrlMax).nullish(),- saml_x509_cert: zod.string().nullish(),- scim_enabled: zod.boolean().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)@@ -217,6 +273,165 @@ export const DomainsVerifyCreateBody = /* @__PURE__ */ zod.object({.array(zod.string().max(domainsVerifyCreateBodyIdJagAllowedClientsItemMax)).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.'+ ),+})++export const identityProviderConfigsCreateBodyNameMax = 255++export const identityProviderConfigsCreateBodySamlEntityIdMax = 512++export const identityProviderConfigsCreateBodySamlAcsUrlMax = 512++export const identityProviderConfigsCreateBodyIdJagIssuerUrlMax = 512++export const identityProviderConfigsCreateBodyIdJagJwksUrlMax = 512++export const identityProviderConfigsCreateBodyIdJagAllowedClientsItemMax = 256++export const IdentityProviderConfigsCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(identityProviderConfigsCreateBodyNameMax)+ .optional()+ .describe("Display name for this IdP configuration (e.g. 'Okta production')."),+ saml_entity_id: zod+ .string()+ .max(identityProviderConfigsCreateBodySamlEntityIdMax)+ .nullish()+ .describe('SAML IdP entity ID (issuer).'),+ saml_acs_url: zod+ .string()+ .max(identityProviderConfigsCreateBodySamlAcsUrlMax)+ .nullish()+ .describe('SAML single sign-on (ACS) URL the IdP redirects to.'),+ 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. Setting this true generates a bearer token (returned once); setting it false clears the token.'+ ),+ id_jag_issuer_url: zod+ .string()+ .max(identityProviderConfigsCreateBodyIdJagIssuerUrlMax)+ .nullish()+ .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.'),+ id_jag_jwks_url: zod+ .string()+ .max(identityProviderConfigsCreateBodyIdJagJwksUrlMax)+ .nullish()+ .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),+ id_jag_allowed_clients: zod+ .array(zod.string().max(identityProviderConfigsCreateBodyIdJagAllowedClientsItemMax))+ .optional()+ .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),+})++export const identityProviderConfigsUpdateBodyNameMax = 255++export const identityProviderConfigsUpdateBodySamlEntityIdMax = 512++export const identityProviderConfigsUpdateBodySamlAcsUrlMax = 512++export const identityProviderConfigsUpdateBodyIdJagIssuerUrlMax = 512++export const identityProviderConfigsUpdateBodyIdJagJwksUrlMax = 512++export const identityProviderConfigsUpdateBodyIdJagAllowedClientsItemMax = 256++export const IdentityProviderConfigsUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(identityProviderConfigsUpdateBodyNameMax)+ .optional()+ .describe("Display name for this IdP configuration (e.g. 'Okta production')."),+ saml_entity_id: zod+ .string()+ .max(identityProviderConfigsUpdateBodySamlEntityIdMax)+ .nullish()+ .describe('SAML IdP entity ID (issuer).'),+ saml_acs_url: zod+ .string()+ .max(identityProviderConfigsUpdateBodySamlAcsUrlMax)+ .nullish()+ .describe('SAML single sign-on (ACS) URL the IdP redirects to.'),+ 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. Setting this true generates a bearer token (returned once); setting it false clears the token.'+ ),+ id_jag_issuer_url: zod+ .string()+ .max(identityProviderConfigsUpdateBodyIdJagIssuerUrlMax)+ .nullish()+ .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.'),+ id_jag_jwks_url: zod+ .string()+ .max(identityProviderConfigsUpdateBodyIdJagJwksUrlMax)+ .nullish()+ .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),+ id_jag_allowed_clients: zod+ .array(zod.string().max(identityProviderConfigsUpdateBodyIdJagAllowedClientsItemMax))+ .optional()+ .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),+})++export const identityProviderConfigsPartialUpdateBodyNameMax = 255++export const identityProviderConfigsPartialUpdateBodySamlEntityIdMax = 512++export const identityProviderConfigsPartialUpdateBodySamlAcsUrlMax = 512++export const identityProviderConfigsPartialUpdateBodyIdJagIssuerUrlMax = 512++export const identityProviderConfigsPartialUpdateBodyIdJagJwksUrlMax = 512++export const identityProviderConfigsPartialUpdateBodyIdJagAllowedClientsItemMax = 256++export const IdentityProviderConfigsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(identityProviderConfigsPartialUpdateBodyNameMax)+ .optional()+ .describe("Display name for this IdP configuration (e.g. 'Okta production')."),+ saml_entity_id: zod+ .string()+ .max(identityProviderConfigsPartialUpdateBodySamlEntityIdMax)+ .nullish()+ .describe('SAML IdP entity ID (issuer).'),+ saml_acs_url: zod+ .string()+ .max(identityProviderConfigsPartialUpdateBodySamlAcsUrlMax)+ .nullish()+ .describe('SAML single sign-on (ACS) URL the IdP redirects to.'),+ 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. Setting this true generates a bearer token (returned once); setting it false clears the token.'+ ),+ id_jag_issuer_url: zod+ .string()+ .max(identityProviderConfigsPartialUpdateBodyIdJagIssuerUrlMax)+ .nullish()+ .describe('Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.'),+ id_jag_jwks_url: zod+ .string()+ .max(identityProviderConfigsPartialUpdateBodyIdJagJwksUrlMax)+ .nullish()+ .describe('Override JWKS URL. Defaults to OIDC discovery on the issuer URL.'),+ id_jag_allowed_clients: zod+ .array(zod.string().max(identityProviderConfigsPartialUpdateBodyIdJagAllowedClientsItemMax))+ .optional()+ .describe('Allowed ID-JAG client IDs. Empty list allows any client_id.'),})export const invitesCreateBodyTargetEmailMax = 254diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.tsindex 1f6a4a6dffa6..d25446786e74 100644--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts@@ -9,10 +9,52 @@ import { bindModalToUrl } from 'lib/logic/bindModalToUrl'import { organizationLogic } from 'scenes/organizationLogic'import { userLogic } from 'scenes/userLogic'+import {+ identityProviderConfigsCreate,+ identityProviderConfigsDestroy,+ identityProviderConfigsPartialUpdate,+ identityProviderConfigsScimTokenCreate,+} from '~/generated/core/api'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.+ * 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> {+ if (domain.identity_provider_config) {+ return domain.identity_provider_config+ }+ const config = await identityProviderConfigsCreate(organizationId, { name: domain.domain })+ try {+ await api.update(`api/organizations/${organizationId}/domains/${domain.id}`, {+ identity_provider_config: config.id,+ })+ } catch (error) {+ await identityProviderConfigsDestroy(organizationId, config.id).catch(() => undefined)+ throw error+ }+ return config.id+}++/** Re-fetch a single domain and replace it in local state, reflecting reverse-synced IdP columns. */+async function refreshDomain(+ organizationId: string,+ domainId: string,+ replaceDomain: (domain: OrganizationDomainType) => void+): Promise<OrganizationDomainType> {+ const domain = await api.get<OrganizationDomainType>(`api/organizations/${organizationId}/domains/${domainId}`)+ replaceDomain(domain)+ return domain+}+export type OrganizationDomainUpdatePayload = Partial<Pick<OrganizationDomainType, 'jit_provisioning_enabled' | 'sso_enforcement'>> &@@ -195,38 +237,56 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([}},enableScim: async (domainId: string) => {- const domain = await api.update<OrganizationDomainType>(- `api/organizations/${values.currentOrganizationId}/domains/${domainId}`,- { scim_enabled: true }- )- actions.replaceDomain({ ...domain, scim_bearer_token: undefined })+ const orgId = values.currentOrganizationId as string+ const domain = values.verifiedDomains.find(({ id }) => id === domainId)+ if (!domain) {+ return values.scimConfig+ }+ 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.+ const refreshed = await refreshDomain(orgId, domainId, actions.replaceDomain)lemonToast.success('SCIM enabled successfully!')return {id: domainId,- scim_enabled: domain.scim_enabled,- scim_base_url: domain.scim_base_url,- scim_bearer_token: domain.scim_bearer_token,+ scim_enabled: config.scim_enabled,+ scim_base_url: refreshed.scim_base_url,+ scim_bearer_token: config.scim_bearer_token ?? undefined,}},disableScim: async (domainId: string) => {- const domain = await api.update<OrganizationDomainType>(- `api/organizations/${values.currentOrganizationId}/domains/${domainId}`,- { scim_enabled: false }- )- actions.replaceDomain({ ...domain, scim_bearer_token: undefined })+ const orgId = values.currentOrganizationId as string+ const domain = values.verifiedDomains.find(({ id }) => id === domainId)+ if (!domain) {+ return values.scimConfig+ }+ const configId = await ensureIdpConfigId(orgId, domain)+ const config = await identityProviderConfigsPartialUpdate(orgId, configId, { scim_enabled: false })+ const refreshed = await refreshDomain(orgId, domainId, actions.replaceDomain)lemonToast.success('SCIM disabled successfully!')return {id: domainId,- scim_enabled: domain.scim_enabled,- scim_base_url: domain.scim_base_url,+ scim_enabled: config.scim_enabled,+ scim_base_url: refreshed.scim_base_url,}},regenerateScimToken: async (domainId: string) => {- const response = await api.create<SCIMConfigType>(- `api/organizations/${values.currentOrganizationId}/domains/${domainId}/scim/token`+ const orgId = values.currentOrganizationId as string+ const domain = values.verifiedDomains.find(({ id }) => id === domainId)+ if (!domain?.identity_provider_config) {+ return values.scimConfig+ }+ const response = await identityProviderConfigsScimTokenCreate(+ orgId,+ domain.identity_provider_config)lemonToast.success('SCIM token regenerated successfully!')- return { ...response, id: domainId }+ return {+ id: domainId,+ scim_enabled: response.scim_enabled,+ scim_base_url: domain.scim_base_url,+ scim_bearer_token: response.scim_bearer_token,+ }},},],@@ -352,21 +412,26 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([: undefined,}),submit: async (payload, breakpoint) => {- const { id, ...updateParams } = payload+ const { id, saml_acs_url, saml_entity_id, saml_x509_cert } = payloadif (!id) {return}- const response = await api.update<OrganizationDomainType>(- `api/organizations/${values.currentOrganizationId}/domains/${payload.id}`,- {- ...updateParams,- }- )+ const orgId = values.currentOrganizationId as string+ const domain = values.verifiedDomains.find(({ id: _id }) => _id === id)+ if (!domain) {+ return+ }+ const configId = await ensureIdpConfigId(orgId, domain)+ await identityProviderConfigsPartialUpdate(orgId, configId, {+ saml_acs_url,+ saml_entity_id,+ saml_x509_cert,+ })breakpoint()- actions.replaceDomain(response)+ const refreshed = await refreshDomain(orgId, id, actions.replaceDomain)actions.setConfigureSAMLModalId(null)actions.setSamlConfigValues({})- lemonToast.success(`SAML configuration for ${response.domain} updated successfully.`)+ lemonToast.success(`SAML configuration for ${refreshed.domain} updated successfully.`)},},idJagConfig: {@@ -386,19 +451,22 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([if (!id) {return}- const response = await api.update<OrganizationDomainType>(- `api/organizations/${values.currentOrganizationId}/domains/${id}`,- {- id_jag_issuer_url: id_jag_issuer_url?.trim() || null,- id_jag_jwks_url: id_jag_jwks_url?.trim() || null,- id_jag_allowed_clients: id_jag_allowed_clients ?? [],- }- )+ const orgId = values.currentOrganizationId as string+ const domain = values.verifiedDomains.find(({ id: _id }) => _id === id)+ if (!domain) {+ return+ }+ const configId = await ensureIdpConfigId(orgId, domain)+ await identityProviderConfigsPartialUpdate(orgId, configId, {+ id_jag_issuer_url: id_jag_issuer_url?.trim() || null,+ id_jag_jwks_url: id_jag_jwks_url?.trim() || null,+ id_jag_allowed_clients: id_jag_allowed_clients ?? [],+ })breakpoint()- actions.replaceDomain(response)+ const refreshed = await refreshDomain(orgId, id, actions.replaceDomain)actions.setConfigureIdJagModalId(null)actions.setIdJagConfigValues({})- lemonToast.success(`XAA configuration for ${response.domain} updated successfully.`)+ lemonToast.success(`XAA configuration for ${refreshed.domain} updated successfully.`)},},})),diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex c6a78163e318..b2bb30d026f1 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -582,6 +582,8 @@ export interface OrganizationDomainType {id_jag_issuer_url?: string | nullid_jag_jwks_url?: string | nullid_jag_allowed_clients?: string[]+ /** Linked IdP config (SAML/SCIM/XAA), the source of truth for those settings. */+ identity_provider_config?: string | null}export interface SCIMRequestLogType {diff --git a/posthog/admin/admins/organization_domain_admin.py b/posthog/admin/admins/organization_domain_admin.pyindex 125bb708734e..b6e42c8b20a2 100644--- a/posthog/admin/admins/organization_domain_admin.py+++ b/posthog/admin/admins/organization_domain_admin.py@@ -33,7 +33,7 @@ class OrganizationDomainAdmin(admin.ModelAdmin):(None, {"fields": ("id", "organization", "domain", "identity_provider_config")}),("Verification", {"fields": ("verification_challenge", "verified_at", "last_verification_retry")}),("Access Control", {"fields": ("jit_provisioning_enabled", "sso_enforcement")}),- ("SAML Configuration", {"fields": ("saml_entity_id", "saml_acs_url", "saml_x509_cert")}),+ ("SAML Configuration", {"fields": ("_saml_entity_id", "_saml_acs_url", "_saml_x509_cert")}),)list_display_links = ("domain",)ordering = ("domain",)diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.pyindex afe6ae421059..07d57637f3dc 100644--- a/posthog/api/id_jag.py+++ b/posthog/api/id_jag.py@@ -147,8 +147,8 @@ def get_allowed_resources() -> list[str]:def _get_jwks_client(issuer: str, jwks_url: str | None = None) -> jwt.PyJWKClient:"""Resolve a `PyJWKClient` for the given IdP issuer.- If `jwks_url` is provided (set on the `OrganizationDomain.id_jag_jwks_url`- field), skip OIDC discovery and point PyJWKClient at it directly. Otherwise+ If `jwks_url` is provided (from the linked `IdentityProviderConfig.id_jag_jwks_url`),+ skip OIDC discovery and point PyJWKClient at it directly. Otherwisedo OIDC discovery against `<issuer>/.well-known/openid-configuration` andcache the resulting `jwks_uri` for `ID_JAG_JWKS_CACHE_TTL_SECONDS`. Wedon't cache the `PyJWKClient` object itself because it already does@@ -280,11 +280,12 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,)raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)- expected_issuer = (org_domain.id_jag_issuer_url or "").rstrip("/")+ idp_config = org_domain.idp_config+ expected_issuer = (idp_config.id_jag_issuer_url or "").rstrip("/")provider_name = org_domain.domaintry:- jwks_client = _get_jwks_client(expected_issuer, jwks_url=org_domain.id_jag_jwks_url or None)+ jwks_client = _get_jwks_client(expected_issuer, jwks_url=idp_config.id_jag_jwks_url or None)signing_key = jwks_client.get_signing_key_from_jwt(assertion)except jwt.PyJWTError as e:raise InvalidGrantError(f"ID-JAG signing key resolution failed: {e}")@@ -354,7 +355,7 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,raise InvalidGrantError("ID-JAG is missing the client_id claim")# validate allowed clients if set in config- if org_domain.id_jag_allowed_clients and client_id not in org_domain.id_jag_allowed_clients:+ if idp_config.id_jag_allowed_clients and client_id not in idp_config.id_jag_allowed_clients:raise InvalidClientError(f"client_id {client_id!r} is not allowed for this domain")# prevent replayed tokens from being used againdiff --git a/posthog/api/identity_provider_config.py b/posthog/api/identity_provider_config.pynew file mode 100644index 000000000000..6659101129e2--- /dev/null+++ b/posthog/api/identity_provider_config.py@@ -0,0 +1,233 @@+from typing import Any, cast++import posthoganalytics+from drf_spectacular.utils import extend_schema+from rest_framework import exceptions, request, response, serializers, status+from rest_framework.request import Request+from rest_framework.viewsets import ModelViewSet++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import action+from posthog.constants import AvailableFeature+from posthog.event_usage import groups+from posthog.models.identity_provider_config import IdentityProviderConfig+from posthog.models.organization import Organization+from posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission+from posthog.security.url_validation import is_url_allowed++from ee.api.scim.utils import disable_scim_for_config, enable_scim_for_config, regenerate_scim_token_for_config+++def _capture_idp_config_event(+ request: Request, config: IdentityProviderConfig, event_type: str, properties: dict | None = None+) -> None:+ properties = {**(properties or {}), "identity_provider_config_id": str(config.id)}+ posthoganalytics.capture(+ event=f"organization idp config {event_type}",+ distinct_id=str(request.user.distinct_id), # type: ignore[union-attr]+ properties=properties,+ groups=groups(config.organization),+ )+++class IdentityProviderConfigSerializer(serializers.ModelSerializer):+ scim_bearer_token = serializers.SerializerMethodField(+ help_text="Plaintext SCIM bearer token. Only returned once, immediately after SCIM is enabled or the token is regenerated; null otherwise."+ )+ id_jag_allowed_clients = serializers.ListField(+ child=serializers.CharField(max_length=256),+ required=False,+ allow_empty=True,+ help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ )+ has_saml = serializers.BooleanField(read_only=True, help_text="Whether SAML is fully configured on this config.")+ has_scim = serializers.BooleanField(+ read_only=True, help_text="Whether SCIM is enabled and a bearer token is set on this config."+ )+ has_id_jag = serializers.BooleanField(+ read_only=True, help_text="Whether ID-JAG (XAA) is configured on this config."+ )++ class Meta:+ model = IdentityProviderConfig+ fields = (+ "id",+ "name",+ "created_at",+ "updated_at",+ "has_saml",+ "saml_entity_id",+ "saml_acs_url",+ "saml_x509_cert",+ "has_scim",+ "scim_enabled",+ "scim_bearer_token",+ "has_id_jag",+ "id_jag_issuer_url",+ "id_jag_jwks_url",+ "id_jag_allowed_clients",+ )+ extra_kwargs = {+ "name": {"help_text": "Display name for this IdP configuration (e.g. 'Okta production')."},+ "created_at": {"read_only": True},+ "updated_at": {"read_only": True},+ "saml_entity_id": {+ "required": False,+ "allow_null": True,+ "allow_blank": True,+ "help_text": "SAML IdP entity ID (issuer).",+ },+ "saml_acs_url": {+ "required": False,+ "allow_null": True,+ "allow_blank": True,+ "help_text": "SAML single sign-on (ACS) URL the IdP redirects to.",+ },+ "saml_x509_cert": {+ "required": False,+ "allow_null": True,+ "allow_blank": True,+ "help_text": "SAML IdP X.509 signing certificate (PEM).",+ },+ "scim_enabled": {+ "required": False,+ "help_text": "Whether SCIM provisioning is enabled. Setting this true generates a bearer token (returned once); setting it false clears the token.",+ },+ "id_jag_issuer_url": {+ "required": False,+ "allow_null": True,+ "allow_blank": True,+ "help_text": "Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.",+ },+ "id_jag_jwks_url": {+ "required": False,+ "allow_null": True,+ "allow_blank": True,+ "help_text": "Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ },+ }++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._scim_plain_token: str | None = None++ @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_url(self, value: str | None) -> str | None:+ normalized = self._normalize_optional_url(value)+ if normalized:+ allowed, reason = is_url_allowed(normalized)+ if not allowed:+ raise serializers.ValidationError(f"URL is not allowed: {reason}")+ return normalized++ def validate_id_jag_issuer_url(self, value: str | None) -> str | None:+ return self._validate_id_jag_url(value)++ def validate_id_jag_jwks_url(self, value: str | None) -> str | None:+ return self._validate_id_jag_url(value)++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ organization: Organization = self.context["view"].organization++ if attrs.get("scim_enabled") is not None and 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 attrs.get("id_jag_issuer_url") and not organization.is_feature_available(+ AvailableFeature.XAA_AUTHENTICATION+ ):+ raise serializers.ValidationError(+ {"id_jag_issuer_url": "XAA (ID-JAG) is not available for this organization."},+ code="feature_not_available",+ )++ return attrs++ def create(self, validated_data: dict[str, Any]) -> IdentityProviderConfig:+ validated_data["organization"] = self.context["view"].organization+ scim_enabled = validated_data.pop("scim_enabled", None)+ validated_data.pop("scim_bearer_token", None)++ instance: IdentityProviderConfig = super().create(validated_data)++ if scim_enabled:+ self._scim_plain_token = enable_scim_for_config(instance)++ return instance++ def update(self, instance: IdentityProviderConfig, validated_data: dict[str, Any]) -> IdentityProviderConfig:+ scim_enabled = validated_data.pop("scim_enabled", None)+ validated_data.pop("scim_bearer_token", None)++ scim_plain_token: str | None = None++ # Generate a new token when enabling SCIM, clear it when disabling.+ if scim_enabled is not None:+ if scim_enabled:+ if not instance.scim_enabled:+ scim_plain_token = enable_scim_for_config(instance)+ else:+ if instance.scim_enabled:+ disable_scim_for_config(instance)++ instance = super().update(instance, validated_data)+ self._scim_plain_token = scim_plain_token++ return instance++ def get_scim_bearer_token(self, obj: IdentityProviderConfig) -> str | None:+ return self._scim_plain_token+++class SCIMTokenResponseSerializer(serializers.Serializer):+ scim_enabled = serializers.BooleanField(help_text="Whether SCIM is enabled for this config.")+ scim_bearer_token = serializers.CharField(+ help_text="Newly generated plaintext SCIM bearer token. Only returned once."+ )+++@extend_schema(extensions={"x-product": "core"})+class IdentityProviderConfigViewSet(TeamAndOrgViewSetMixin, ModelViewSet):+ scope_object = "organization"+ serializer_class = IdentityProviderConfigSerializer+ permission_classes = [OrganizationAdminWritePermissions, TimeSensitiveActionPermission]+ queryset = IdentityProviderConfig.objects.order_by("created_at")++ def create(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ instance = serializer.save()+ _capture_idp_config_event(request, instance, "created")+ return response.Response(serializer.data, status=status.HTTP_201_CREATED)++ def update(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ res = super().update(request, *args, **kwargs)+ _capture_idp_config_event(request, self.get_object(), "updated", {"fields": sorted(request.data.keys())})+ return res++ @extend_schema(request=None, responses=SCIMTokenResponseSerializer)+ @action(methods=["POST"], detail=True, url_path="scim/token")+ def scim_token(self, request: Request, **kwargs: Any) -> response.Response:+ """Regenerate the SCIM bearer token for this IdP config."""+ config = cast(IdentityProviderConfig, self.get_object())++ if not config.organization.is_feature_available(AvailableFeature.SCIM):+ raise exceptions.PermissionDenied("SCIM is not available for this organization")++ if not config.scim_enabled:+ return response.Response(+ {"detail": "SCIM is not enabled for this config"}, status=status.HTTP_400_BAD_REQUEST+ )++ plain_token = regenerate_scim_token_for_config(config)+ return response.Response({"scim_enabled": True, "scim_bearer_token": plain_token})diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.pyindex 0a2afeb36b02..1e1ca2144925 100644--- a/posthog/api/organization_domain.py+++ b/posthog/api/organization_domain.py@@ -13,11 +13,13 @@ from rest_framework.request import Requestfrom rest_framework.viewsets import ModelViewSetfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.scoped_related_fields import OrgScopedPrimaryKeyRelatedFieldfrom posthog.api.utils import actionfrom 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, IdentityProviderConfigfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission@@ -34,6 +36,12 @@ from ee.models.scim_request_log import SCIMRequestLogDOMAIN_REGEX = r"^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"+class _OrgScopedIdentityProviderConfigField(OrgScopedPrimaryKeyRelatedField):+ # IdentityProviderConfig has a direct `organization` FK (not via team), so scope on it+ # directly. Scoping prevents linking a domain to (or probing) another org's config.+ scope_field = "organization"++def _capture_domain_event(request, domain: OrganizationDomain, event_type: str, properties: dict | None = None) -> None:if not properties:properties = {}@@ -53,18 +61,72 @@ def _capture_domain_event(request, domain: OrganizationDomain, event_type: str,class OrganizationDomainSerializer(serializers.ModelSerializer):- UPDATE_ONLY_WHEN_VERIFIED = [- "jit_provisioning_enabled",- "sso_enforcement",- "scim_enabled",- "id_jag_issuer_url",- "id_jag_jwks_url",- "id_jag_allowed_clients",- ]+ # 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.+ 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,@@ -93,6 +155,7 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):"id_jag_issuer_url","id_jag_jwks_url","id_jag_allowed_clients",+ "identity_provider_config",)extra_kwargs = {"verified_at": {"read_only": True},@@ -103,18 +166,6 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):"scim_base_url": {"read_only": True},"scim_bearer_token": {"read_only": True},"has_id_jag": {"read_only": True},- "id_jag_issuer_url": {- "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": {- "required": False,- "allow_null": True,- "allow_blank": True,- "help_text": "Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",- },}def __init__(self, *args, **kwargs):@@ -136,11 +187,10 @@ 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("scim_bearer_token", 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)+ 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@@ -170,10 +220,10 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):organization: Organization = self.context["view"].organizationif instance and not instance.verified_at:- for protected_attr in self.UPDATE_ONLY_WHEN_VERIFIED:- if protected_attr in attrs:+ for source_attr, public_name in self.UPDATE_ONLY_WHEN_VERIFIED.items():+ if source_attr in attrs:raise serializers.ValidationError(- {protected_attr: "This attribute cannot be updated until the domain is verified."},+ {public_name: "This attribute cannot be updated until the domain is verified."},code="verification_required",)if instance and attrs.get("jit_provisioning_enabled", None):@@ -183,14 +233,14 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):code="feature_not_available",)- if instance and attrs.get("scim_enabled") is not None:+ 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 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."},@@ -201,30 +251,42 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):def 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)- validated_data.pop("scim_bearer_token", None)+ scim_enabled = validated_data.pop("_scim_enabled", None)- scim_plain_token: str | None = 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))- # Generate new token when enabling SCIM, clear when disabling+ 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 = Noneif scim_enabled is not None:if scim_enabled:- if not instance.scim_enabled:+ if not instance._scim_enabled:scim_plain_token = enable_scim_for_domain(instance)else:- if instance.scim_enabled:+ if instance._scim_enabled:disable_scim_for_domain(instance)- instance = super().update(instance, validated_data)-self._scim_plain_token = scim_plain_token- id_jag_fields = {"id_jag_issuer_url", "id_jag_jwks_url", "id_jag_allowed_clients"}+ 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:- raise serializers.ValidationError(e.message_dict) from 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 ereturn instance@@ -377,7 +439,7 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):if not domain.organization.is_feature_available(AvailableFeature.SCIM):raise exceptions.PermissionDenied("SCIM is not available for this organization")- if not domain.scim_enabled:+ if not domain.has_scim:return response.Response({"detail": "SCIM is not enabled for this domain"}, status=status.HTTP_400_BAD_REQUEST)diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.pyindex 5ebabf3a08d9..b7f6a7708bdf 100644--- a/posthog/api/rest_router.py+++ b/posthog/api/rest_router.py@@ -38,6 +38,7 @@ from . import (event_schema,health_issue,hog,+ identity_provider_config,ingestion_warnings,instance_settings,instance_status,@@ -333,6 +334,12 @@ organizations_router.register("organization_domains",["organization_id"],)+organizations_router.register(+ r"identity_provider_configs",+ identity_provider_config.IdentityProviderConfigViewSet,+ "organization_identity_provider_configs",+ ["organization_id"],+)organizations_router.register(r"personal_api_keys",organization_personal_api_key.OrganizationPersonalAPIKeyViewSet,diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 0a943703193d..99ec31cfb4dd 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -853,7 +853,7 @@ def process_social_domain_jit_provisioning_signup(domain=domain,is_verified=domain_instance.is_verified,jit_provisioning_enabled=domain_instance.jit_provisioning_enabled,- scim_enabled=domain_instance.scim_enabled,+ scim_enabled=domain_instance.idp_config.scim_enabled,)if domain_instance.is_verified and domain_instance.jit_provisioning_enabled:if not user:@@ -904,7 +904,7 @@ def process_social_domain_jit_provisioning_signup(domain=domain,user=user.email,organization=domain_instance.organization_id,- scim_enabled=domain_instance.scim_enabled,+ scim_enabled=domain_instance.idp_config.scim_enabled,)return userdiff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex c8ebb12418cf..6ad4eaf80950 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -120,7 +120,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):organization=cls.organization,domain=_VERIFIED_DOMAIN,verified_at=timezone.now(),- id_jag_issuer_url=_IDP_ISSUER,+ _id_jag_issuer_url=_IDP_ISSUER,)def setUp(self) -> None:@@ -463,7 +463,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):organization=attacker_org,domain="bigco.example",verified_at=timezone.now(),- id_jag_issuer_url=_IDP_ISSUER,+ _id_jag_issuer_url=_IDP_ISSUER,)# Victim user whose email is on the attacker's verified domain but who@@ -626,8 +626,8 @@ 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"])+ domain._id_jag_issuer_url = None+ domain.save(update_fields=["_id_jag_issuer_url"])assertion = _make_id_jag()resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -641,8 +641,8 @@ 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"])+ domain._id_jag_issuer_url = "https://idp.example.com"+ domain.save(update_fields=["_id_jag_issuer_url"])assertion = _make_id_jag(issuer="https://other-idp.example.com")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -658,8 +658,8 @@ 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"])+ domain._id_jag_issuer_url = _IDP_ISSUER+ domain.save(update_fields=["_id_jag_issuer_url"])assertion = _make_id_jag(issuer=_IDP_ISSUER + "/")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -671,8 +671,8 @@ 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"])+ domain._id_jag_jwks_url = "https://idp.example.com/keys.json"+ domain.save(update_fields=["_id_jag_jwks_url"])# Re-patch to capture call args; the base setUp patch doesn't expose# them in a way that survives across multiple tests.@@ -690,8 +690,8 @@ 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"])+ domain._id_jag_allowed_clients = ["client_first", "client_second"]+ domain.save(update_fields=["_id_jag_allowed_clients"])assertion = _make_id_jag(client_id="client_second")resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})@@ -699,8 +699,8 @@ 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"])+ domain._id_jag_allowed_clients = ["client_first", "client_second"]+ domain.save(update_fields=["_id_jag_allowed_clients"])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_identity_provider_config.py b/posthog/api/test/test_identity_provider_config.pynew file mode 100644index 000000000000..22d6fad187a3--- /dev/null+++ b/posthog/api/test/test_identity_provider_config.py@@ -0,0 +1,165 @@+from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import IdentityProviderConfig, Organization, OrganizationMembership+++class TestIdentityProviderConfigAPI(APIBaseTest):+ def _make_admin(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def _enable_features(self, *features: str) -> None:+ self.organization.available_product_features = [{"key": f, "name": f} for f in features]+ self.organization.save()++ # List & retrieve++ def test_member_can_list_configs(self):+ IdentityProviderConfig.objects.create(organization=self.organization, name="Okta")+ response = self.client.get("/api/organizations/@current/identity_provider_configs")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)+ self.assertEqual(response.json()["results"][0]["name"], "Okta")++ def test_cannot_retrieve_config_from_other_org(self):+ self._make_admin()+ other_org = Organization.objects.create(name="Other")+ other_config = IdentityProviderConfig.objects.create(organization=other_org, name="Other Okta")+ response = self.client.get(f"/api/organizations/@current/identity_provider_configs/{other_config.id}")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ # Create & permissions++ def test_admin_can_create_config(self):+ self._make_admin()+ response = self.client.post(+ "/api/organizations/@current/identity_provider_configs/",+ {"name": "Okta production", "saml_entity_id": "entity", "saml_acs_url": "https://idp.example.com/acs"},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ config = IdentityProviderConfig.objects.get(id=response.json()["id"])+ self.assertEqual(config.organization, self.organization)+ self.assertEqual(config.saml_entity_id, "entity")++ def test_member_cannot_create_config(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ response = self.client.post(+ "/api/organizations/@current/identity_provider_configs/",+ {"name": "Okta"},+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ # SAML++ def test_can_configure_saml(self):+ self._make_admin()+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {+ "saml_entity_id": "entity-id",+ "saml_acs_url": "https://idp.example.com/acs",+ "saml_x509_cert": "cert",+ },+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["has_saml"])+ config.refresh_from_db()+ self.assertEqual(config.saml_entity_id, "entity-id")++ # SCIM++ def test_enable_scim_returns_token_once(self):+ self._make_admin()+ self._enable_features(AvailableFeature.SCIM)+ config = IdentityProviderConfig.objects.create(organization=self.organization)++ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {"scim_enabled": True},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["scim_enabled"])+ self.assertIsNotNone(response.json()["scim_bearer_token"])++ config.refresh_from_db()+ self.assertTrue(config.scim_enabled)+ self.assertIsNotNone(config.scim_bearer_token)++ # A subsequent read never returns the plaintext token+ read = self.client.get(f"/api/organizations/@current/identity_provider_configs/{config.id}")+ self.assertIsNone(read.json()["scim_bearer_token"])++ def test_cannot_enable_scim_without_feature(self):+ self._make_admin()+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {"scim_enabled": True},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "scim_enabled")++ def test_regenerate_scim_token(self):+ self._make_admin()+ self._enable_features(AvailableFeature.SCIM)+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ enable = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {"scim_enabled": True},+ )+ original_token = enable.json()["scim_bearer_token"]++ response = self.client.post(f"/api/organizations/@current/identity_provider_configs/{config.id}/scim/token")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["scim_enabled"])+ self.assertNotEqual(response.json()["scim_bearer_token"], original_token)++ def test_regenerate_scim_token_requires_scim_enabled(self):+ self._make_admin()+ self._enable_features(AvailableFeature.SCIM)+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ response = self.client.post(f"/api/organizations/@current/identity_provider_configs/{config.id}/scim/token")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ # ID-JAG (XAA)++ def test_can_configure_id_jag(self):+ self._make_admin()+ self._enable_features(AvailableFeature.XAA_AUTHENTICATION)+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {+ "id_jag_issuer_url": "https://example.com/",+ "id_jag_jwks_url": "https://example.com/keys.json",+ "id_jag_allowed_clients": ["client-a"],+ },+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["id_jag_issuer_url"], "https://example.com")+ self.assertTrue(response.json()["has_id_jag"])++ def test_cannot_configure_id_jag_without_feature(self):+ self._make_admin()+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {"id_jag_issuer_url": "https://example.com"},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "id_jag_issuer_url")++ def test_id_jag_url_must_be_allowed(self):+ self._make_admin()+ self._enable_features(AvailableFeature.XAA_AUTHENTICATION)+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ response = self.client.patch(+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",+ {"id_jag_issuer_url": "http://169.254.169.254/latest/meta-data"},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/posthog/api/test/test_organization_domain.py b/posthog/api/test/test_organization_domain.pyindex f9fc40da2627..8b6eca08078d 100644--- a/posthog/api/test/test_organization_domain.py+++ b/posthog/api/test/test_organization_domain.py@@ -17,6 +17,7 @@ from rest_framework import serializers, statusfrom posthog.api.organization_domain import OrganizationDomainSerializer, OrganizationDomainViewsetfrom 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@@ -123,7 +124,7 @@ 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)+ self.assertEqual(instance._scim_enabled, False)# Verify the domain creation capture event was calledmock_capture.assert_any_call(@@ -551,8 +552,38 @@ class TestOrganizationDomainsAPI(APIBaseTest):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)+ 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@@ -613,8 +644,8 @@ class TestOrganizationDomainsAPI(APIBaseTest):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)+ 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@@ -650,8 +681,8 @@ class TestOrganizationDomainsAPI(APIBaseTest):# 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._scim_enabled = True+ self.domain._scim_bearer_token = hashed_tokenself.domain.save()# Remove feature@@ -689,9 +720,9 @@ class TestOrganizationDomainsAPI(APIBaseTest):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"])+ 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@@ -720,7 +751,7 @@ class TestOrganizationDomainsAPI(APIBaseTest):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()self.domain.verified_at = timezone.now()- self.domain.id_jag_issuer_url = "https://example.com"+ self.domain._id_jag_issuer_url = "https://example.com"self.domain.save()response = self.client.patch(@@ -732,7 +763,7 @@ class TestOrganizationDomainsAPI(APIBaseTest):self.assertIsNone(response.json()["id_jag_issuer_url"])self.domain.refresh_from_db()- self.assertIsNone(self.domain.id_jag_issuer_url)+ 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@@ -788,7 +819,7 @@ class TestSCIMRequestLogsAPI(APILicensedTest):organization=self.organization,domain="logs-test.com",verified_at=timezone.now(),- scim_enabled=True,+ _scim_enabled=True,)def _create_log(self, **kwargs):diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex ef104e7ee760..6d7653099bb5 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -996,7 +996,7 @@ class TestSignupAPI(APIBaseTest):domain="posthog.net",verified_at=timezone.now(),jit_provisioning_enabled=True,- scim_enabled=True,+ _scim_enabled=True,organization=new_org,)Team.objects.create(organization=new_org, name="Test Project")@@ -1039,7 +1039,7 @@ class TestSignupAPI(APIBaseTest):domain="posthog.net",verified_at=timezone.now(),jit_provisioning_enabled=True,- scim_enabled=True,+ _scim_enabled=True,organization=new_org,)Team.objects.create(organization=new_org, name="Test Project")diff --git a/posthog/migrations/1246_alter_organizationdomain_id_jag_allowed_clients_and_more.py b/posthog/migrations/1246_alter_organizationdomain_id_jag_allowed_clients_and_more.pynew file mode 100644index 000000000000..b104cf7d8d2c--- /dev/null+++ b/posthog/migrations/1246_alter_organizationdomain_id_jag_allowed_clients_and_more.py@@ -0,0 +1,130 @@+# Generated by Django 5.2.14 on 2026-06-23 18:30++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1245_duckgres_sink_schema_state"),+ ]++ # Pure state-only migration: the IdP fields on OrganizationDomain are renamed to+ # underscore-prefixed Python attributes while `db_column` keeps the original column names, so+ # there is NO database change. Wrapping the renames in SeparateDatabaseAndState with empty+ # `database_operations` makes that explicit — Django updates its migration state, runs zero SQL,+ # and the migration risk analyzer correctly treats it as safe (RenameField/AlterField here do+ # not touch the database).+ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="organizationdomain",+ name="id_jag_allowed_clients",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=256),+ blank=True,+ db_column="id_jag_allowed_clients",+ default=list,+ help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ null=True,+ size=None,+ ),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="id_jag_allowed_clients",+ new_name="_id_jag_allowed_clients",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="id_jag_issuer_url",+ field=models.CharField(+ blank=True,+ db_column="id_jag_issuer_url",+ help_text="Trusted IdP issuer URL for ID-JAG. Required to enable ID-JAG on this domain.",+ max_length=512,+ null=True,+ ),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="id_jag_issuer_url",+ new_name="_id_jag_issuer_url",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="id_jag_jwks_url",+ field=models.CharField(+ blank=True,+ db_column="id_jag_jwks_url",+ help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ max_length=512,+ null=True,+ ),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="id_jag_jwks_url",+ new_name="_id_jag_jwks_url",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="saml_acs_url",+ field=models.CharField(blank=True, db_column="saml_acs_url", max_length=512, null=True),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="saml_acs_url",+ new_name="_saml_acs_url",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="saml_entity_id",+ field=models.CharField(blank=True, db_column="saml_entity_id", max_length=512, null=True),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="saml_entity_id",+ new_name="_saml_entity_id",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="saml_x509_cert",+ field=models.TextField(blank=True, db_column="saml_x509_cert", null=True),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="saml_x509_cert",+ new_name="_saml_x509_cert",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="scim_bearer_token",+ field=models.CharField(+ blank=True,+ db_column="scim_bearer_token",+ help_text="Hashed bearer token for SCIM authentication",+ max_length=255,+ null=True,+ ),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="scim_bearer_token",+ new_name="_scim_bearer_token",+ ),+ migrations.AlterField(+ model_name="organizationdomain",+ name="scim_enabled",+ field=models.BooleanField(db_column="scim_enabled", default=False),+ ),+ migrations.RenameField(+ model_name="organizationdomain",+ old_name="scim_enabled",+ new_name="_scim_enabled",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 66a71b80d784..643ce2e13a87 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1245_duckgres_sink_schema_state+1246_alter_organizationdomain_id_jag_allowed_clients_and_morediff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 4448046fac57..763b45626e71 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -252,9 +252,9 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {"job_inputs",],"OrganizationDomain": [- "scim_bearer_token",+ "_scim_bearer_token","verification_challenge",- "saml_x509_cert",+ "_saml_x509_cert",],"User": ["email",@@ -297,10 +297,10 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {"OrganizationDomain": {"jit_provisioning_enabled": "just-in-time provisioning","sso_enforcement": "SSO enforcement",- "saml_entity_id": "SAML entity ID",- "saml_acs_url": "SAML ACS URL",- "saml_x509_cert": "SAML X.509 certificate",- "scim_enabled": "SCIM provisioning",+ "_saml_entity_id": "SAML entity ID",+ "_saml_acs_url": "SAML ACS URL",+ "_saml_x509_cert": "SAML X.509 certificate",+ "_scim_enabled": "SCIM provisioning","verified_at": "domain verification",},}diff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.pyindex 6d746bbf8c3a..808534c34212 100644--- a/posthog/models/identity_provider_config.py+++ b/posthog/models/identity_provider_config.py@@ -1,7 +1,7 @@from typing import TYPE_CHECKING, Anyfrom django.contrib.postgres.fields import ArrayField-from django.db import models+from django.db import models, transactionimport structlog@@ -36,10 +36,12 @@ class IdentityProviderConfig(UUIDModel):multiple `OrganizationDomain` rows (via `OrganizationDomain.identity_provider_config`),and an organization can have zero, one, or many configs.- NOTE: While the migration to this model is in flight, `OrganizationDomain` remains the- source of truth. Writes to a domain's IdP fields are mirrored here automatically by- `OrganizationDomain.save()` (see `sync_identity_provider_config_from_domain`), so the- data is consistent when reads are switched over.+ 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()`."""organization = models.ForeignKey(@@ -95,6 +97,12 @@ 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:"""@@ -118,13 +126,16 @@ class IdentityProviderConfig(UUIDModel):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 (- domain.has_saml- 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)+ (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))@@ -162,7 +173,8 @@ def sync_identity_provider_config_from_domain(domain: "OrganizationDomain", dry_config = IdentityProviderConfig.objects.create(organization_id=domain.organization_id,name=domain.domain,- **{field: getattr(domain, field) for field in IDP_CONFIG_SYNCED_FIELDS},+ # 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).@@ -171,9 +183,9 @@ def sync_identity_provider_config_from_domain(domain: "OrganizationDomain", dry_return "created"changed_fields: dict[str, Any] = {- field: getattr(domain, field)+ field: getattr(domain, f"_{field}")for field in IDP_CONFIG_SYNCED_FIELDS- if getattr(config, field) != getattr(domain, field)+ if getattr(config, field) != getattr(domain, f"_{field}")}if not changed_fields:return "unchanged"@@ -183,3 +195,22 @@ def sync_identity_provider_config_from_domain(domain: "OrganizationDomain", dry_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 1b8f34a3ffe6..e52204291176 100644--- a/posthog/models/organization_domain.py+++ b/posthog/models/organization_domain.py@@ -11,7 +11,11 @@ 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 IdentityProviderConfig, sync_identity_provider_config_from_domain+from posthog.models.identity_provider_config import (+ IDP_CONFIG_SYNCED_FIELDS,+ IdentityProviderConfig,+ sync_identity_provider_config_from_domain,+)from posthog.models.utils import UUIDTModelfrom posthog.utils import get_instance_available_sso_providers@@ -25,7 +29,9 @@ def generate_verification_challenge() -> str:class OrganizationDomainManager(models.Manager):def verified_domains(self):# TODO: Verification becomes stale on Cloud if not reverified after a certain period.- return self.exclude(verified_at__isnull=True)+ # `select_related` the IdP config since reads of SAML/SCIM/ID-JAG settings resolve through+ # it (`OrganizationDomain.idp_config`) in the hot auth paths.+ return self.exclude(verified_at__isnull=True).select_related("identity_provider_config")def get_verified_for_email_address(self, email: str) -> Optional["OrganizationDomain"]:"""@@ -59,11 +65,11 @@ class OrganizationDomainManager(models.Manager):if not verified_for_domain:return None, "ID-JAG sub email domain is not a verified domain for any PostHog organization"- configured = [d for d in verified_for_domain if (d.id_jag_issuer_url or "").rstrip("/")]+ configured = [d for d in verified_for_domain if (d.idp_config.id_jag_issuer_url or "").rstrip("/")]if not configured:return None, "ID-JAG is not configured for this domain (id_jag_issuer_url is unset)"- matching = [d for d in configured if (d.id_jag_issuer_url or "").rstrip("/") == normalized_issuer]+ matching = [d for d in configured if (d.idp_config.id_jag_issuer_url or "").rstrip("/") == normalized_issuer]if not matching:return None, "ID-JAG iss does not match the IdP configured for this email's domain"@@ -81,18 +87,21 @@ class OrganizationDomainManager(models.Manager):Returns whether SAML is available for a specific email address."""domain = email[email.index("@") + 1 :]+ # SAML config is read from the linked `IdentityProviderConfig`. A domain with no linked+ # config produces NULLs across the LEFT JOIN, so the `__isnull=True` excludes drop it.query = (self.verified_domains().filter(domain__iexact=domain).exclude(- models.Q(saml_entity_id="")- | models.Q(saml_acs_url="")- | models.Q(saml_x509_cert="")+ models.Q(identity_provider_config__saml_entity_id="")+ | models.Q(identity_provider_config__saml_acs_url="")+ | models.Q(identity_provider_config__saml_x509_cert="")+ | models.Q(identity_provider_config__isnull=True)| models.Q(- saml_entity_id__isnull=True+ identity_provider_config__saml_entity_id__isnull=True) # normally we would have just a nil state (i.e. ""), but to avoid migration locks we had to introduce this- | models.Q(saml_acs_url__isnull=True)- | models.Q(saml_x509_cert__isnull=True)+ | models.Q(identity_provider_config__saml_acs_url__isnull=True)+ | models.Q(identity_provider_config__saml_x509_cert__isnull=True)).values_list("organization__available_product_features", flat=True).first()@@ -181,39 +190,49 @@ 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 attributes ----+ # ---- 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)- saml_acs_url = models.CharField(max_length=512, blank=True, null=True)- saml_x509_cert = models.TextField(blank=True, null=True)-- # ---- SCIM attributes ----- scim_enabled = models.BooleanField(default=False)- scim_bearer_token = models.CharField(- max_length=255, blank=True, null=True, help_text="Hashed bearer token for SCIM authentication"+ _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")+ _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",)- # ---- ID-JAG attributes ----- id_jag_issuer_url = models.CharField(+ _id_jag_issuer_url = models.CharField(max_length=512,blank=True,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",)# Defaults to `{id_jag_issuer_url}/.well-known/openid-configuration`.- id_jag_jwks_url = models.CharField(+ _id_jag_jwks_url = models.CharField(max_length=512,blank=True,null=True,help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ db_column="id_jag_jwks_url",)- id_jag_allowed_clients = ArrayField(+ _id_jag_allowed_clients = ArrayField(models.CharField(max_length=256),default=list,blank=True,null=True,help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ db_column="id_jag_allowed_clients",)# ---- IdP config (new home for SAML/SCIM/ID-JAG settings) ----@@ -237,6 +256,15 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):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)@@ -254,7 +282,7 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):from posthog.security.url_validation import is_url_allowederrors: dict[str, str] = {}- for field_name in ("id_jag_issuer_url", "id_jag_jwks_url"):+ for field_name in ("_id_jag_issuer_url", "_id_jag_jwks_url"):url = getattr(self, field_name, None)if not url:continue@@ -287,26 +315,35 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):# TODO: Verification becomes stale on Cloud if not reverified after a certain period.return bool(self.verified_at)+ @property+ def idp_config(self) -> IdentityProviderConfig:+ """+ The linked `IdentityProviderConfig` (source of truth for SAML/SCIM/ID-JAG reads), or an+ empty in-memory config when none is linked yet so reads resolve to safe empty values+ without null-guards.+ """+ return self.identity_provider_config or IdentityProviderConfig()+@propertydef has_saml(self) -> bool:"""Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places)."""- return bool(self.saml_entity_id) and bool(self.saml_acs_url) and bool(self.saml_x509_cert)+ return self.idp_config.has_saml@propertydef has_scim(self) -> bool:"""Returns whether SCIM is configured and enabled for this domain."""- return self.scim_enabled and bool(self.scim_bearer_token)+ return self.idp_config.has_scim@propertydef has_id_jag(self) -> bool:"""Returns whether ID-JAG (XAA) is configured for this domain."""- return bool(self.id_jag_issuer_url)+ return self.idp_config.has_id_jagdef _complete_verification(self) -> tuple["OrganizationDomain", bool]:self.last_verification_retry = Nonediff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.pyindex 57acbd063bdb..72ca4472816c 100644--- a/posthog/test/test_identity_provider_config.py+++ b/posthog/test/test_identity_provider_config.py@@ -5,14 +5,25 @@ from django.core.exceptions import ValidationErrorfrom django.core.management import call_commandfrom posthog.models import IdentityProviderConfig, Organization, OrganizationDomain-from posthog.models.identity_provider_config import IDP_CONFIG_SYNCED_FIELDS, sync_identity_provider_config_from_domain+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+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()}++class TestIdentityProviderConfigSync(BaseTest):def _create_domain(self, domain: str = "posthog.com", **kwargs) -> OrganizationDomain:- return OrganizationDomain.objects.create(organization=self.organization, domain=domain, **kwargs)+ 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()@@ -21,9 +32,9 @@ class TestIdentityProviderConfigSync(BaseTest):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"+ domain._saml_entity_id = "entity-id"+ domain._saml_acs_url = "https://idp.example.com/acs"+ domain._saml_x509_cert = "cert-contents"domain.save()domain.refresh_from_db()@@ -45,8 +56,8 @@ class TestIdentityProviderConfigSync(BaseTest):config = domain.identity_provider_configassert config is not None- domain.saml_entity_id = "new-entity-id"- domain.id_jag_issuer_url = "https://issuer.example.com"+ domain._saml_entity_id = "new-entity-id"+ domain._id_jag_issuer_url = "https://issuer.example.com"domain.save()config.refresh_from_db()@@ -61,9 +72,9 @@ class TestIdentityProviderConfigSync(BaseTest):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._saml_entity_id = None+ domain._saml_acs_url = None+ domain._saml_x509_cert = Nonedomain.save()config = domain.identity_provider_config@@ -80,12 +91,12 @@ class TestIdentityProviderConfigSync(BaseTest):config = domain.identity_provider_configassert config is not Noneassert config.scim_enabled is True- assert config.scim_bearer_token == domain.scim_bearer_token+ assert config.scim_bearer_token == domain._scim_bearer_tokenassert config.has_scimregenerate_scim_token(domain)config.refresh_from_db()- assert config.scim_bearer_token == domain.scim_bearer_token+ assert config.scim_bearer_token == domain._scim_bearer_tokendisable_scim_for_domain(domain)config.refresh_from_db()@@ -97,12 +108,14 @@ class TestIdentityProviderConfigSync(BaseTest):assert IdentityProviderConfig.objects.count() == 1def test_synced_fields_match_between_models(self):- # Guard against the two models drifting apart while domains remain the source of truth+ # 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:- domain_field = OrganizationDomain._meta.get_field(field)+ domain_field = OrganizationDomain._meta.get_field(f"_{field}")config_field = IdentityProviderConfig._meta.get_field(field)assert domain_field.__class__ == config_field.__class__, fieldassert getattr(domain_field, "max_length", None) == getattr(config_field, "max_length", None), field+ 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")@@ -152,11 +165,107 @@ class TestIdentityProviderConfigSync(BaseTest):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()++ config.refresh_from_db()+ domain.refresh_from_db()+ assert config.saml_entity_id == "config-owned-entity"+ assert domain._saml_entity_id == "config-owned-entity"++ def test_has_saml_reads_from_config_not_domain_columns(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+ 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 SAML+ assert domain.has_saml++ # Clearing the config flips the read+ config.saml_entity_id = None+ config.saml_acs_url = None+ config.saml_x509_cert = None+ config.save()+ domain.refresh_from_db()+ assert not domain.has_saml++ def test_domain_without_config_has_no_idp_reads(self):+ domain = self._create_domain()+ assert domain.identity_provider_config is None+ assert not domain.has_saml+ assert not domain.has_scim+ assert 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, **kwargs)+ 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()@@ -185,7 +294,7 @@ class TestSyncIdentityProviderConfigsCommand(BaseTest):domain = OrganizationDomain.objects.create(organization=self.organization,domain="saml.example.com",- id_jag_issuer_url="https://issuer.example.com",+ _id_jag_issuer_url="https://issuer.example.com",)config = domain.identity_provider_configassert config is not None@@ -212,7 +321,7 @@ class TestSyncIdentityProviderConfigsCommand(BaseTest):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"+ organization=other_org, domain="other.example.com", _id_jag_issuer_url="https://issuer.example.com")# `_create_unsynced_domain` wipes all configs, leaving both domains unsynceddomain = self._create_unsynced_domain("mine.example.com", id_jag_issuer_url="https://issuer.example.com")diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex d1eccb44767d..d95dd4a691ee 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -343,6 +343,27 @@ tools:generate-conversations-public-token-create:operation: organizations_projects_generate_conversations_public_token_createenabled: false+ identity-provider-configs-create:+ operation: identity_provider_configs_create+ enabled: false+ identity-provider-configs-destroy:+ operation: identity_provider_configs_destroy+ enabled: false+ identity-provider-configs-list:+ operation: identity_provider_configs_list+ enabled: false+ identity-provider-configs-partial-update:+ operation: identity_provider_configs_partial_update+ enabled: false+ identity-provider-configs-retrieve:+ operation: identity_provider_configs_retrieve+ enabled: false+ identity-provider-configs-scim-token-create:+ operation: identity_provider_configs_scim_token_create+ enabled: false+ identity-provider-configs-update:+ operation: identity_provider_configs_update+ enabled: falseinsights-sharing-list:operation: insights_sharing_listenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fa567dd128c7..774235e8bc04 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27151,6 +27151,64 @@ export namespace Schemas {results: IdentityMatchingRun[];}+ export interface IdentityProviderConfig {+ readonly id: string;+ /**+ * Display name for this IdP configuration (e.g. 'Okta production').+ * @maxLength 255+ */+ name?: string;+ readonly created_at: string;+ readonly updated_at: string;+ /** Whether SAML is fully configured on this config. */+ readonly has_saml: boolean;+ /**+ * SAML IdP entity ID (issuer).+ * @maxLength 512+ * @nullable+ */+ saml_entity_id?: string | null;+ /**+ * SAML single sign-on (ACS) URL the IdP redirects to.+ * @maxLength 512+ * @nullable+ */+ saml_acs_url?: string | null;+ /**+ * SAML IdP X.509 signing certificate (PEM).+ * @nullable+ */+ saml_x509_cert?: string | null;+ /** Whether SCIM is enabled and a bearer token is set on this config. */+ readonly has_scim: boolean;+ /** Whether SCIM provisioning is enabled. Setting this true generates a bearer token (returned once); setting it false clears the token. */+ scim_enabled?: boolean;+ /**+ * Plaintext SCIM bearer token. Only returned once, immediately after SCIM is enabled or the token is regenerated; null otherwise.+ * @nullable+ */+ readonly scim_bearer_token: string | null;+ /** Whether ID-JAG (XAA) is configured on this config. */+ readonly has_id_jag: boolean;+ /**+ * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.+ * @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[];+ }+/*** * `trends` - trends* * `funnel` - funnel@@ -30379,19 +30437,25 @@ export namespace Schemas {/** 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;- /** @nullable */+ /**+ * 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;@@ -30416,6 +30480,11 @@ export namespace Schemas {* @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+ */+ identity_provider_config?: string | null;}export interface OrganizationFeatureFlagRow {@@ -31477,6 +31546,15 @@ export namespace Schemas {results: HogFunctionTemplate[];}+ export interface PaginatedIdentityProviderConfigList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: IdentityProviderConfig[];+ }+export interface PaginatedInsightList {count: number;/** @nullable */@@ -37848,6 +37926,64 @@ export namespace Schemas {orders?: PatchedHogFunctionRearrangeOrders;}+ export interface PatchedIdentityProviderConfig {+ readonly id?: string;+ /**+ * Display name for this IdP configuration (e.g. 'Okta production').+ * @maxLength 255+ */+ name?: string;+ readonly created_at?: string;+ readonly updated_at?: string;+ /** Whether SAML is fully configured on this config. */+ readonly has_saml?: boolean;+ /**+ * SAML IdP entity ID (issuer).+ * @maxLength 512+ * @nullable+ */+ saml_entity_id?: string | null;+ /**+ * SAML single sign-on (ACS) URL the IdP redirects to.+ * @maxLength 512+ * @nullable+ */+ saml_acs_url?: string | null;+ /**+ * SAML IdP X.509 signing certificate (PEM).+ * @nullable+ */+ saml_x509_cert?: string | null;+ /** Whether SCIM is enabled and a bearer token is set on this config. */+ readonly has_scim?: boolean;+ /** Whether SCIM provisioning is enabled. Setting this true generates a bearer token (returned once); setting it false clears the token. */+ scim_enabled?: boolean;+ /**+ * Plaintext SCIM bearer token. Only returned once, immediately after SCIM is enabled or the token is regenerated; null otherwise.+ * @nullable+ */+ readonly scim_bearer_token?: string | null;+ /** Whether ID-JAG (XAA) is configured on this config. */+ readonly has_id_jag?: boolean;+ /**+ * Trusted IdP issuer URL for ID-JAG (XAA). Required to enable ID-JAG.+ * @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[];+ }+/*** @nullable*/@@ -38583,19 +38719,25 @@ export namespace Schemas {/** 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;- /** @nullable */+ /**+ * 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;@@ -38620,6 +38762,11 @@ export namespace Schemas {* @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+ */+ identity_provider_config?: string | null;}/**@@ -47053,6 +47200,13 @@ export namespace Schemas {fields: S3PresignedPostFields;}+ export interface SCIMTokenResponse {+ /** Whether SCIM is enabled for this config. */+ scim_enabled: boolean;+ /** Newly generated plaintext SCIM bearer token. Only returned once. */+ scim_bearer_token: string;+ }+/*** * `action` - action* * `dashboard` - dashboard@@ -59196,6 +59350,17 @@ export namespace Schemas {team_ids?: number[];};+ export type IdentityProviderConfigsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type OrgOrganizationsIntegrationsListParams = {/*** Number of results to return per page.