Skip to content

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

chore: use `LinkedIdentityProviderConfig` as source of truth for idp config lookups (#84673)

Reece Jones88e1728f2a78
diff --git a/ee/api/authentication.py b/ee/api/authentication.py
index b81ce0f82e6c..a2f44e154347 100644
--- a/ee/api/authentication.py
+++ b/ee/api/authentication.py
@@ -35,7 +35,7 @@ from social_django.utils import load_backend, load_strategy
from posthog.cloud_utils import get_cached_instance_license
from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
-from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.identity_provider_config import IdentityProviderConfig, has_verified_organization_domain_q
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -132,8 +132,8 @@ class MultitenantSAMLAuth(SAMLAuth):
configs = list(
# nosemgrep: idor-lookup-without-org (pre-auth SAML routing by IdP entity id; the assertion signature is verified afterwards)
IdentityProviderConfig.objects.filter(
+ has_verified_organization_domain_q(),
saml_entity_id=issuer,
- domains__verified_at__isnull=False,
).distinct()
)
if len(configs) != 1:
@@ -168,8 +168,8 @@ class MultitenantSAMLAuth(SAMLAuth):
# nosemgrep: idor-lookup-without-org (pre-auth SAML routing check by IdP config identifier)
return (
IdentityProviderConfig.objects.filter(
+ has_verified_organization_domain_q(),
saml_relay_state=candidate,
- domains__verified_at__isnull=False,
)
.distinct()
.exists()
@@ -196,14 +196,19 @@ class MultitenantSAMLAuth(SAMLAuth):
raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")
if isinstance(organization_domain_or_id, OrganizationDomain):
- idp_config = organization_domain_or_id.idp_config
+ try:
+ idp_config = organization_domain_or_id.saml_identity_provider_configs.get()
+ except IdentityProviderConfig.DoesNotExist:
+ raise AuthFailed(self, "SAML not configured for this domain.")
+ except IdentityProviderConfig.MultipleObjectsReturned:
+ raise AuthFailed(self, "Multiple SAML configurations apply to this domain.")
else:
try:
# nosemgrep: idor-lookup-without-org (pre-auth SAML flow, lookup by config identifier on verified configs)
idp_config = (
IdentityProviderConfig.objects.filter(
+ has_verified_organization_domain_q(),
saml_relay_state=organization_domain_or_id,
- domains__verified_at__isnull=False,
)
.distinct()
.get()
@@ -250,7 +255,7 @@ class MultitenantSAMLAuth(SAMLAuth):
instance = OrganizationDomain.objects.get_verified_for_email_address(email=email)
- if not instance or not instance.has_saml:
+ if not instance or not instance.saml_identity_provider_configs.exists():
saml_logger.warning("saml_not_configured", **_saml_log_context(email))
raise AuthFailed(self, "SAML not configured for this user.")
@@ -260,7 +265,8 @@ class MultitenantSAMLAuth(SAMLAuth):
organization_id=str(instance.organization_id),
**_saml_log_context(email, instance.organization_id),
)
- auth = self._create_saml_auth(idp=self.get_idp(instance))
+ identity_provider = self.get_idp(instance)
+ auth = self._create_saml_auth(idp=identity_provider)
# `return_to` sets the RelayState, a value the IdP echoes back in its POST to the
# (shared) auth_complete URL. The session cookie is SameSite=Lax and so is dropped on
# the IdP's cross-site POST, which would otherwise lose `next` and send the user to `/`;
@@ -269,7 +275,7 @@ class MultitenantSAMLAuth(SAMLAuth):
# We deliberately omit the session key that upstream `SAMLAuth.auth_url` also packs into
# RelayState: it would be disclosed to the (potentially attacker-controlled) IdP in the
# redirect, and `next` alone is enough to recover the redirect without it.
- relay_state = {"idp": instance.idp_config.saml_relay_state, "next": self.data.get("next")}
+ relay_state = {"idp": identity_provider.name, "next": self.data.get("next")}
return auth.login(return_to=json.dumps(relay_state))
def _get_attr(
@@ -373,7 +379,9 @@ class MultitenantSAMLAuth(SAMLAuth):
# A config can back several verified domains, and an assertion is valid for any of them.
configured_domains = {
domain.lower()
- for domain in idp_config.domains.filter(verified_at__isnull=False).values_list("domain", flat=True)
+ for domain in idp_config.organization_domains.filter(verified_at__isnull=False).values_list(
+ "domain", flat=True
+ )
}
if email.rsplit("@", 1)[-1].lower() in configured_domains:
return
diff --git a/ee/api/scim/auth.py b/ee/api/scim/auth.py
index f11162888c14..f681b29d36c4 100644
--- a/ee/api/scim/auth.py
+++ b/ee/api/scim/auth.py
@@ -60,7 +60,11 @@ class SCIMBearerTokenAuthentication(BaseAuthentication):
# SCIM stays gated behind domain verification, which the config API doesn't check. Any of the
# config's verified domains admits the request — it names a config, not one of the domains
# behind it — so the config, and its organization, is what scopes the request from here.
- if not config.has_scim or not hashed_token or not config.domains.filter(verified_at__isnull=False).exists():
+ if (
+ not config.has_scim
+ or not hashed_token
+ or not config.organization_domains.filter(verified_at__isnull=False).exists()
+ ):
raise exceptions.AuthenticationFailed("SCIM is not enabled on a verified domain for this configuration")
if not config.organization.is_feature_available(AvailableFeature.SCIM):
diff --git a/ee/api/scim/test/test_groups_api.py b/ee/api/scim/test/test_groups_api.py
index 97cbbc2da55c..3feb3c710801 100644
--- a/ee/api/scim/test/test_groups_api.py
+++ b/ee/api/scim/test/test_groups_api.py
@@ -6,6 +6,7 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, User
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from ee.api.scim.auth import generate_scim_token
@@ -41,8 +42,9 @@ class TestSCIMGroupsAPI(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
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.py
index ceeaa2b18969..67344ca7b6c9 100644
--- a/ee/api/scim/test/test_scim_api.py
+++ b/ee/api/scim/test/test_scim_api.py
@@ -5,6 +5,7 @@ from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from ee.api.scim.auth import generate_scim_token
@@ -40,8 +41,9 @@ class TestSCIMAPI(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}
@@ -52,11 +54,13 @@ class TestSCIMAPI(APILicensedTest):
def test_scim_uses_config_slug(self):
self.config.scim_slug = "custom-scim-slug"
self.config.save(update_fields=["scim_slug"])
- OrganizationDomain.objects.create(
+ second_domain = OrganizationDomain.objects.create(
organization=self.organization,
domain="example.co.uk",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=second_domain, identity_provider_config=self.config
)
self.client.credentials(**self.scim_headers)
@@ -101,7 +105,7 @@ class TestSCIMAPI(APILicensedTest):
domain="no-config.example.com",
verified_at="2024-01-01T00:00:00Z",
)
- assert unconfigured.identity_provider_config is None
+ assert not unconfigured.identity_provider_configs.exists()
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
@@ -119,9 +123,8 @@ class TestSCIMAPI(APILicensedTest):
config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- unverified.identity_provider_config = config
- unverified.save()
- assert unverified.has_scim # config is SCIM-enabled with a token
+ LinkedIdentityProviderConfig.objects.create(organization_domain=unverified, identity_provider_config=config)
+ assert config.has_scim
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {plain_token}")
response = self.client.get(f"/scim/v2/{unverified.id}/Users")
@@ -318,8 +321,9 @@ class TestSCIMEmailDomainValidation(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}
@@ -559,8 +563,9 @@ class TestSCIMAuditLogging(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}
@@ -657,8 +662,9 @@ class TestSCIMGroupAuditLogging(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}
diff --git a/ee/api/scim/test/test_scim_legacy_records.py b/ee/api/scim/test/test_scim_legacy_records.py
index 0d4ed993b62e..460904e10038 100644
--- a/ee/api/scim/test/test_scim_legacy_records.py
+++ b/ee/api/scim/test/test_scim_legacy_records.py
@@ -1,25 +1,16 @@
-from importlib import import_module
-from types import SimpleNamespace
-
-from django.apps import apps
-from django.db import connection
-
from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, User
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from ee.api.scim.auth import generate_scim_token
from ee.api.test.base import APILicensedTest
from ee.models.scim_provisioned_user import SCIMProvisionedUser
-backfill_scim_provisioned_user_config = import_module(
- "ee.migrations.0058_backfill_scim_provisioned_user_config"
-).backfill_scim_provisioned_user_config
-
class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):
# SCIM used to be addressed per domain, so provisioning records were keyed on the domain. Those
@@ -41,8 +32,9 @@ class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
self.provisioned = User.objects.create_user(
@@ -52,7 +44,7 @@ class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):
user=self.provisioned, organization=self.organization, level=OrganizationMembership.Level.MEMBER
)
self.legacy_record = self._provision_keyed_on_domain(self.provisioned, "already.okta.username", self.domain)
- backfill_scim_provisioned_user_config(apps, SimpleNamespace(connection=connection))
+ SCIMProvisionedUser.objects.filter(pk=self.legacy_record.pk).update(identity_provider_config=self.config)
assert self.config.scim_slug != self.domain.id
self.scim_url = f"/scim/v2/{self.config.scim_slug}"
@@ -179,8 +171,10 @@ class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):
scim_enabled=True,
scim_bearer_token=second_token.hashed,
)
- self.domain.identity_provider_config = second_config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.filter(organization_domain=self.domain).delete()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=second_config
+ )
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {second_token.plain}")
read = self.client.get(f"/scim/v2/{second_config.scim_slug}/Users/{self.provisioned.id}")
@@ -199,7 +193,9 @@ class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):
organization=self.organization,
domain="partner.example.com",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=second_domain, identity_provider_config=self.config
)
sibling = self._provision_keyed_on_domain(self.provisioned, "already.partner.username", second_domain)
SCIMProvisionedUser.objects.filter(pk=self.legacy_record.pk).update(identity_provider_config=self.config)
@@ -230,7 +226,9 @@ class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):
organization=self.organization,
domain="partner.example.com",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=second_domain, identity_provider_config=self.config
)
skipped = self._provision_keyed_on_domain(self.provisioned, "already.partner.username", second_domain)
diff --git a/ee/api/scim/test/test_scim_request_log.py b/ee/api/scim/test/test_scim_request_log.py
index 2fe035daab12..b3ae15021bfb 100644
--- a/ee/api/scim/test/test_scim_request_log.py
+++ b/ee/api/scim/test/test_scim_request_log.py
@@ -11,6 +11,7 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import Organization
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -41,8 +42,9 @@ class TestSCIMRequestLogCapture(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
def test_get_request_creates_log(self):
@@ -120,7 +122,9 @@ class TestSCIMRequestLogCleanup(TestCase):
organization=self.organization,
domain="cleanup-test.com",
verified_at=timezone.now(),
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
)
def _create_log(self, age_days: int) -> SCIMRequestLog:
@@ -184,7 +188,9 @@ class TestSCIMLogsEndpoint(APILicensedTest):
organization=self.organization,
domain="example.com",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
)
def _create_log(self, **kwargs) -> SCIMRequestLog:
diff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.py
index 380ff1ddf332..1cd92f55d13e 100644
--- a/ee/api/scim/test/test_users_api.py
+++ b/ee/api/scim/test/test_users_api.py
@@ -4,6 +4,7 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, User
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from ee.api.scim.auth import generate_scim_token
@@ -39,8 +40,9 @@ class TestSCIMUsersAPI(APILicensedTest):
self.config = IdentityProviderConfig.objects.create(
organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
- self.domain.identity_provider_config = self.config
- self.domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
+ )
self.config.refresh_from_db()
self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}
@@ -277,11 +279,13 @@ class TestSCIMUsersAPI(APILicensedTest):
== status.HTTP_201_CREATED
)
- OrganizationDomain.objects.create(
+ partner_domain = OrganizationDomain.objects.create(
organization=self.organization,
domain="partner.example.com",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=partner_domain, identity_provider_config=self.config
)
response = self.client.post(
diff --git a/ee/api/scim/views.py b/ee/api/scim/views.py
index 4c0fe65371dd..15d7e291110a 100644
--- a/ee/api/scim/views.py
+++ b/ee/api/scim/views.py
@@ -388,7 +388,7 @@ class SCIMUserDetailView(SCIMBaseView):
user = User.objects.filter(
Q(organization_membership__organization=config.organization)
| Q(scim_provisions__identity_provider_config=config)
- | Q(scim_provisions__organization_domain__identity_provider_config=config),
+ | Q(scim_provisions__organization_domain__in=config.organization_domains),
id=user_id,
).first()
if not user:
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index 39b5450d246d..30aefc458247 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -25,6 +25,7 @@ from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from ee.api.authentication import CustomGoogleOAuth2, MultitenantSAMLAuth
@@ -495,7 +496,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
organization=cls.organization,
jit_provisioning_enabled=True,
)
- cls.organization_domain.identity_provider_config = IdentityProviderConfig.objects.create(
+ config = IdentityProviderConfig.objects.create(
organization=cls.organization,
saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",
saml_acs_url="https://idp.hogflix.io/saml",
@@ -517,7 +518,9 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
dcKmj4EG6bfcI3KY6wK46JoogXZdHDaFP+WOJNj/pJ165hYsYLcqkJktj/rEgGQmqAXWPOXHmFJb
5FPleoJTchctnzUw+QfmSsLWQ838/lUQsN7FsQ==""",
)
- cls.organization_domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=cls.organization_domain, identity_provider_config=config
+ )
def _assert_saml_login_social_failure_redirect(self, response, error_detail_substring: str) -> None:
"""SocialAuthExceptionMiddleware catches AuthFailed and redirects instead of propagating."""
@@ -587,15 +590,15 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
def test_saml_config_can_back_multiple_verified_domains(self):
self._grant_saml()
- config = self.organization_domain.identity_provider_config
+ config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.refresh_from_db()
- OrganizationDomain.objects.create(
+ second_domain = OrganizationDomain.objects.create(
domain="posthog.co.uk",
verified_at=timezone.now(),
organization=self.organization,
- identity_provider_config=config,
)
+ LinkedIdentityProviderConfig.objects.create(organization_domain=second_domain, identity_provider_config=config)
auth = object.__new__(MultitenantSAMLAuth)
idp = auth.get_idp(config.saml_relay_state)
@@ -604,7 +607,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
def test_relay_state_minted_before_the_move_to_configs_still_resolves(self):
self._grant_saml()
- config = self.organization_domain.identity_provider_config
+ config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.saml_relay_state = str(self.organization_domain.id)
config.save(update_fields=["saml_relay_state"])
@@ -619,15 +622,15 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
# the config backs. Checking the email against a single one of them locks out everyone on the
# others.
self._grant_saml()
- config = self.organization_domain.identity_provider_config
+ config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.refresh_from_db()
- OrganizationDomain.objects.create(
+ second_domain = OrganizationDomain.objects.create(
domain="posthog.co.uk",
verified_at=timezone.now(),
organization=self.organization,
- identity_provider_config=config,
)
+ LinkedIdentityProviderConfig.objects.create(organization_domain=second_domain, identity_provider_config=config)
auth = object.__new__(MultitenantSAMLAuth)
details = auth.get_user_details(
@@ -656,7 +659,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
)
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
- config = self.organization_domain.identity_provider_config
+ config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.refresh_from_db()
relay_state = json.loads(parse_qs(urlparse(response.headers["Location"]).query)["RelayState"][0])
@@ -903,7 +906,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
@freeze_time("2021-08-25T22:09:14.252Z")
def test_cannot_login_with_improperly_signed_payload(self):
- config = self.organization_domain.identity_provider_config
+ config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.saml_x509_cert = """MIIDPjCCAiYCCQC864/0fftWQTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJV
UzELMAkGA1UECAwCVVMxCzAJBgNVBAcMAlVTMQswCQYDVQQKDAJVUzELMAkGA1UE
@@ -1188,7 +1191,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
organization=other_org,
jit_provisioning_enabled=True,
)
- my_config = self.organization_domain.identity_provider_config
+ my_config = self.organization_domain.saml_identity_provider_configs.first()
assert my_config is not None
other_config = IdentityProviderConfig.objects.create(
organization=other_org,
@@ -1196,8 +1199,9 @@ YotAcSbU3p5bzd11wpyebYHB"""
saml_acs_url=my_config.saml_acs_url,
saml_x509_cert=my_config.saml_x509_cert,
)
- other_domain.identity_provider_config = other_config
- other_domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=other_domain, identity_provider_config=other_config
+ )
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
@@ -1427,7 +1431,7 @@ class TestSSOEnforcement(APILicensedTest):
verified_at=timezone.now(),
sso_enforcement="google-oauth2",
)
- org_domain_saml.identity_provider_config = IdentityProviderConfig.objects.create(
+ config = IdentityProviderConfig.objects.create(
organization=self.organization,
saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",
saml_acs_url="https://my.posthog.app/complete/saml/",
@@ -1449,7 +1453,9 @@ jSjV4Oxsv3ogajnnGYGv22iBgS1qccK/cg41YkpgfP36HbiwA10xjUMv5zs97Ljep4ejp6yoKrGL
dcKmj4EG6bfcI3KY6wK46JoogXZdHDaFP+WOJNj/pJ165hYsYLcqkJktj/rEgGQmqAXWPOXHmFJb
5FPleoJTchctnzUw+QfmSsLWQ838/lUQsN7FsQ==""",
)
- org_domain_saml.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=org_domain_saml, identity_provider_config=config
+ )
# Set the SAML state in session (required for SAML authentication)
_session = self.client.session
diff --git a/ee/management/commands/backfill_scim_request_log_config.py b/ee/management/commands/backfill_scim_request_log_config.py
index a6b08abf960c..6e5ac01854ad 100644
--- a/ee/management/commands/backfill_scim_request_log_config.py
+++ b/ee/management/commands/backfill_scim_request_log_config.py
@@ -26,7 +26,7 @@ from django.db.models import OuterRef, Subquery
import structlog
-from posthog.models.organization_domain import OrganizationDomain
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from ee.models.scim_request_log import SCIMRequestLog
@@ -77,7 +77,7 @@ class Command(BaseCommand):
pending = SCIMRequestLog.objects.filter(
identity_provider_config__isnull=True,
- organization_domain__identity_provider_config__isnull=False,
+ organization_domain__linked_identity_provider_configs__isnull=False,
)
if organization_id:
pending = pending.filter(organization_domain__organization_id=organization_id)
@@ -88,9 +88,9 @@ class Command(BaseCommand):
return
config_of_domain = Subquery(
- OrganizationDomain.objects.filter(pk=OuterRef("organization_domain_id")).values(
- "identity_provider_config_id"
- )[:1]
+ LinkedIdentityProviderConfig.objects.filter(
+ organization_domain_id=OuterRef("organization_domain_id")
+ ).values("identity_provider_config_id")[:1]
)
started_at = time.monotonic()
@@ -129,7 +129,7 @@ class Command(BaseCommand):
# reachable through the domain, which is why the SCIM log endpoint still matches both keys.
orphaned = SCIMRequestLog.objects.filter(
identity_provider_config__isnull=True,
- organization_domain__identity_provider_config__isnull=True,
+ organization_domain__linked_identity_provider_configs__isnull=True,
)
if organization_id:
orphaned = orphaned.filter(organization_domain__organization_id=organization_id)
diff --git a/ee/management/commands/test/test_backfill_scim_request_log_config.py b/ee/management/commands/test/test_backfill_scim_request_log_config.py
index 96c58b57c1a6..57c3c02303ee 100644
--- a/ee/management/commands/test/test_backfill_scim_request_log_config.py
+++ b/ee/management/commands/test/test_backfill_scim_request_log_config.py
@@ -6,6 +6,7 @@ from django.core.management import call_command
from posthog.models import Organization
from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from ee.models.scim_request_log import SCIMRequestLog
@@ -19,7 +20,9 @@ class TestBackfillSCIMRequestLogConfig(BaseTest):
organization=self.organization,
domain="example.com",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=self.domain, identity_provider_config=self.config
)
self.unlinked_domain = OrganizationDomain.objects.create(
organization=self.organization,
@@ -89,7 +92,9 @@ class TestBackfillSCIMRequestLogConfig(BaseTest):
organization=other_organization,
domain="other.example.com",
verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=other_config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=other_domain, identity_provider_config=other_config
)
mine = self._create_log(self.domain)
theirs = self._create_log(other_domain)
diff --git a/ee/models/scim_provisioned_user.py b/ee/models/scim_provisioned_user.py
index 0b045c920ad9..696a51574feb 100644
--- a/ee/models/scim_provisioned_user.py
+++ b/ee/models/scim_provisioned_user.py
@@ -25,7 +25,7 @@ class SCIMProvisionedUserManager(models.Manager["SCIMProvisionedUser"]):
models.Q(identity_provider_config=config)
| models.Q(
identity_provider_config__isnull=True,
- organization_domain__identity_provider_config=config,
+ organization_domain__in=config.organization_domains,
)
)
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f7cdeecbb211..ef640352dda6 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -163,19 +163,8 @@ export interface OrganizationDomainApi {
jit_provisioning_enabled?: boolean
/** @maxLength 28 */
sso_enforcement?: string
- /** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */
- readonly has_saml: boolean
- /** Returns whether SCIM is configured and enabled for this domain. */
- readonly has_scim: boolean
/** @nullable */
readonly scim_base_url: string | null
- /** Returns whether ID-JAG (XAA) is configured for this domain. */
- readonly has_id_jag: boolean
- /**
- * 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 {
@@ -199,21 +188,34 @@ export interface PatchedOrganizationDomainApi {
jit_provisioning_enabled?: boolean
/** @maxLength 28 */
sso_enforcement?: string
- /** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */
- readonly has_saml?: boolean
- /** Returns whether SCIM is configured and enabled for this domain. */
- readonly has_scim?: boolean
/** @nullable */
readonly scim_base_url?: string | null
- /** Returns whether ID-JAG (XAA) is configured for this domain. */
- readonly has_id_jag?: boolean
- /**
- * Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.
- * @nullable
- */
- identity_provider_config?: string | null
}
+/**
+ * * `all` - All
+ * * `selected` - Selected
+ */
+export type DomainScopeEnumApi = (typeof DomainScopeEnumApi)[keyof typeof DomainScopeEnumApi]
+
+export const DomainScopeEnumApi = {
+ All: 'all',
+ Selected: 'selected',
+} as const
+
+/**
+ * * `saml` - Saml
+ * * `scim` - Scim
+ * * `xaa` - Xaa
+ */
+export type ConfigScopeEnumApi = (typeof ConfigScopeEnumApi)[keyof typeof ConfigScopeEnumApi]
+
+export const ConfigScopeEnumApi = {
+ Saml: 'saml',
+ Scim: 'scim',
+ Xaa: 'xaa',
+} as const
+
export interface IdentityProviderConfigApi {
readonly id: string
/**
@@ -221,6 +223,19 @@ export interface IdentityProviderConfigApi {
* @maxLength 255
*/
name?: string
+ /** Domains this configuration applies to. An unset value behaves like selected domains.
+ *
+ * * `all` - All
+ * * `selected` - Selected */
+ domain_scope?: DomainScopeEnumApi | BlankEnumApi | null
+ /** Feature configured by this identity provider configuration.
+ *
+ * * `saml` - Saml
+ * * `scim` - Scim
+ * * `xaa` - Xaa */
+ config_scope?: ConfigScopeEnumApi | BlankEnumApi | null
+ /** Organization domain IDs that this identity provider configuration applies to. */
+ organization_domain_ids?: string[]
readonly created_at: string
readonly updated_at: string
/** Whether SAML is fully configured on this config. */
@@ -290,6 +305,19 @@ export interface PatchedIdentityProviderConfigApi {
* @maxLength 255
*/
name?: string
+ /** Domains this configuration applies to. An unset value behaves like selected domains.
+ *
+ * * `all` - All
+ * * `selected` - Selected */
+ domain_scope?: DomainScopeEnumApi | BlankEnumApi | null
+ /** Feature configured by this identity provider configuration.
+ *
+ * * `saml` - Saml
+ * * `scim` - Scim
+ * * `xaa` - Xaa */
+ config_scope?: ConfigScopeEnumApi | BlankEnumApi | null
+ /** Organization domain IDs that this identity provider configuration applies to. */
+ organization_domain_ids?: string[]
readonly created_at?: string
readonly updated_at?: string
/** Whether SAML is fully configured on this config. */
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index fb21335b2589..c090de42d7ac 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -86,12 +86,6 @@ export const DomainsCreateBody = /* @__PURE__ */ zod.object({
domain: zod.string().max(domainsCreateBodyDomainMax),
jit_provisioning_enabled: zod.boolean().optional(),
sso_enforcement: zod.string().max(domainsCreateBodySsoEnforcementMax).optional(),
- 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
@@ -102,12 +96,6 @@ export const DomainsUpdateBody = /* @__PURE__ */ zod.object({
domain: zod.string().max(domainsUpdateBodyDomainMax),
jit_provisioning_enabled: zod.boolean().optional(),
sso_enforcement: zod.string().max(domainsUpdateBodySsoEnforcementMax).optional(),
- 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
@@ -118,12 +106,6 @@ 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(),
- 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
@@ -134,12 +116,6 @@ export const DomainsVerifyCreateBody = /* @__PURE__ */ zod.object({
domain: zod.string().max(domainsVerifyCreateBodyDomainMax),
jit_provisioning_enabled: zod.boolean().optional(),
sso_enforcement: zod.string().max(domainsVerifyCreateBodySsoEnforcementMax).optional(),
- 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
@@ -160,6 +136,30 @@ export const IdentityProviderConfigsCreateBody = /* @__PURE__ */ zod.object({
.max(identityProviderConfigsCreateBodyNameMax)
.optional()
.describe("Display name for this IdP configuration (e.g. 'Okta production')."),
+ domain_scope: zod
+ .union([
+ zod.enum(['all', 'selected']).describe('\* `all` - All\n\* `selected` - Selected'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Domains this configuration applies to. An unset value behaves like selected domains.\n\n\* `all` - All\n\* `selected` - Selected'
+ ),
+ config_scope: zod
+ .union([
+ zod.enum(['saml', 'scim', 'xaa']).describe('\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'
+ ),
+ organization_domain_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe('Organization domain IDs that this identity provider configuration applies to.'),
saml_entity_id: zod
.string()
.max(identityProviderConfigsCreateBodySamlEntityIdMax)
@@ -211,6 +211,30 @@ export const IdentityProviderConfigsUpdateBody = /* @__PURE__ */ zod.object({
.max(identityProviderConfigsUpdateBodyNameMax)
.optional()
.describe("Display name for this IdP configuration (e.g. 'Okta production')."),
+ domain_scope: zod
+ .union([
+ zod.enum(['all', 'selected']).describe('\* `all` - All\n\* `selected` - Selected'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Domains this configuration applies to. An unset value behaves like selected domains.\n\n\* `all` - All\n\* `selected` - Selected'
+ ),
+ config_scope: zod
+ .union([
+ zod.enum(['saml', 'scim', 'xaa']).describe('\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'
+ ),
+ organization_domain_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe('Organization domain IDs that this identity provider configuration applies to.'),
saml_entity_id: zod
.string()
.max(identityProviderConfigsUpdateBodySamlEntityIdMax)
@@ -262,6 +286,30 @@ export const IdentityProviderConfigsPartialUpdateBody = /* @__PURE__ */ zod.obje
.max(identityProviderConfigsPartialUpdateBodyNameMax)
.optional()
.describe("Display name for this IdP configuration (e.g. 'Okta production')."),
+ domain_scope: zod
+ .union([
+ zod.enum(['all', 'selected']).describe('\* `all` - All\n\* `selected` - Selected'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Domains this configuration applies to. An unset value behaves like selected domains.\n\n\* `all` - All\n\* `selected` - Selected'
+ ),
+ config_scope: zod
+ .union([
+ zod.enum(['saml', 'scim', 'xaa']).describe('\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'
+ ),
+ organization_domain_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe('Organization domain IDs that this identity provider configuration applies to.'),
saml_entity_id: zod
.string()
.max(identityProviderConfigsPartialUpdateBodySamlEntityIdMax)
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
index 08e2619a94d0..95988ea17fa9 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
@@ -49,10 +49,7 @@ const VERIFIED_DOMAIN_WITH_SAML_SCIM: OrganizationDomainType = {
verification_challenge: 'abc',
jit_provisioning_enabled: true,
sso_enforcement: 'google-oauth2',
- has_saml: true,
- has_scim: true,
scim_base_url: 'https://posthog.com/scim/v2',
- has_id_jag: true,
}
const VERIFIED_DOMAIN_NO_SAML_SCIM: OrganizationDomainType = {
@@ -63,9 +60,6 @@ const VERIFIED_DOMAIN_NO_SAML_SCIM: OrganizationDomainType = {
verification_challenge: 'def',
jit_provisioning_enabled: false,
sso_enforcement: '',
- has_saml: false,
- has_scim: false,
- has_id_jag: false,
}
const UNVERIFIED_DOMAIN: OrganizationDomainType = {
@@ -76,9 +70,6 @@ const UNVERIFIED_DOMAIN: OrganizationDomainType = {
verification_challenge: 'ghi',
jit_provisioning_enabled: false,
sso_enforcement: '',
- has_saml: false,
- has_scim: false,
- has_id_jag: false,
}
const ALL_FEATURES = [
@@ -105,6 +96,21 @@ const meta: Meta<typeof App> = {
'/_preflight': CLOUD_PREFLIGHT,
'/api/projects/:id/integrations': { results: [] },
'/api/organizations/:id/integrations': { results: [] },
+ '/api/organizations/:id/identity_provider_configs': {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ {
+ id: 'idp-config',
+ config_scope: null,
+ organization_domain_ids: ['1'],
+ has_saml: true,
+ has_scim: true,
+ has_id_jag: true,
+ },
+ ],
+ },
'/api/environments/:team_id/conversations/': { results: [] },
'/api/user_home_settings/@me/': {},
},
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
index 577adf664eab..49e7f43e5ccd 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
@@ -19,6 +19,7 @@ import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
+import { ConfigScopeEnumApi } from '~/generated/core/api.schemas'
import { ProductKey } from '~/queries/schema/schema-general'
import { AvailableFeature, OrganizationDomainType } from '~/types'
@@ -30,7 +31,7 @@ import { ScimLogsModal } from './ScimLogsModal'
import { SSOSelect } from './SSOSelect'
import { verifiedDomainImpactLogic } from './verifiedDomainImpactLogic'
import { RemoveDomainModal } from './VerifiedDomainImpactModals'
-import { verifiedDomainsLogic } from './verifiedDomainsLogic'
+import { getIdentityProviderConfigForDomain, verifiedDomainsLogic } from './verifiedDomainsLogic'
import { VerifyDomainModal } from './VerifyDomainModal'
// One distinctive icon per integration type, reused across each integration's status badges.
@@ -104,12 +105,14 @@ function VerifiedDomainsTable(): JSX.Element {
const {
verifiedDomains,
verifiedDomainsLoading,
+ identityProviderConfigsLoading,
updatingDomainLoading,
isSSOEnforcementAvailable,
isSAMLAvailable,
isSCIMAvailable,
isXAAAuthenticationAvailable,
ownVerifiedDomain,
+ identityProviderConfigs,
} = useValues(verifiedDomainsLogic)
const { currentOrganization } = useValues(organizationLogic)
const {
@@ -193,7 +196,10 @@ function VerifiedDomainsTable(): JSX.Element {
</Tooltip>
</div>
),
- render: function SSOEnforcement(_, { sso_enforcement, id, has_saml }) {
+ render: function SSOEnforcement(_, { sso_enforcement, id }) {
+ const hasSaml = Boolean(
+ getIdentityProviderConfigForDomain(identityProviderConfigs, id, ConfigScopeEnumApi.Saml)?.has_saml
+ )
if (!isSSOEnforcementAvailable) {
return (
<Link
@@ -209,7 +215,7 @@ function VerifiedDomainsTable(): JSX.Element {
value={sso_enforcement}
loading={updatingDomainLoading}
onChange={(val) => updateDomain({ id, sso_enforcement: val })}
- samlAvailable={has_saml}
+ samlAvailable={hasSaml}
disabledReason={restrictionReason}
/>
)
@@ -218,7 +224,22 @@ function VerifiedDomainsTable(): JSX.Element {
{
key: 'integrations',
title: 'Integrations',
- render: function Integrations(_, { has_saml, has_scim, has_id_jag }) {
+ render: function Integrations(_, { id }) {
+ const samlConfig = getIdentityProviderConfigForDomain(
+ identityProviderConfigs,
+ id,
+ ConfigScopeEnumApi.Saml
+ )
+ const scimConfig = getIdentityProviderConfigForDomain(
+ identityProviderConfigs,
+ id,
+ ConfigScopeEnumApi.Scim
+ )
+ const idJagConfig = getIdentityProviderConfigForDomain(
+ identityProviderConfigs,
+ id,
+ ConfigScopeEnumApi.Xaa
+ )
const billingLink = urls.organizationBilling([ProductKey.PLATFORM_AND_SUPPORT])
const badges: JSX.Element[] = []
@@ -233,7 +254,7 @@ function VerifiedDomainsTable(): JSX.Element {
to={billingLink}
/>
)
- } else if (has_saml) {
+ } else if (samlConfig?.has_saml) {
badges.push(
<IntegrationBadge
key="saml"
@@ -266,7 +287,7 @@ function VerifiedDomainsTable(): JSX.Element {
to={billingLink}
/>
)
- } else if (has_scim) {
+ } else if (scimConfig?.has_scim) {
badges.push(
<IntegrationBadge
key="scim"
@@ -288,7 +309,7 @@ function VerifiedDomainsTable(): JSX.Element {
)
}
- if (showXAAControls && has_id_jag) {
+ if (showXAAControls && idJagConfig?.has_id_jag) {
badges.push(
<IntegrationBadge
key="xaa"
@@ -440,7 +461,7 @@ function VerifiedDomainsTable(): JSX.Element {
<LemonTable
dataSource={verifiedDomainsList}
columns={verifiedColumns}
- loading={verifiedDomainsLoading}
+ loading={verifiedDomainsLoading || identityProviderConfigsLoading}
rowKey="id"
emptyState="You haven't registered any authentication domains yet."
/>
@@ -450,7 +471,7 @@ function VerifiedDomainsTable(): JSX.Element {
<LemonTable
dataSource={unverifiedDomainsList}
columns={unverifiedColumns}
- loading={verifiedDomainsLoading}
+ loading={verifiedDomainsLoading || identityProviderConfigsLoading}
rowKey="id"
/>
</>
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
index 14e88bcdf740..5e97028b27bf 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
@@ -25,6 +25,16 @@ exports[`verifiedDomainsLogic values has proper defaults 1`] = `
"id_jag_issuer_url": undefined,
"id_jag_jwks_url": undefined,
},
+ "identityProviderConfigs": [
+ {
+ "config_scope": null,
+ "id": "config_will_be_deleted",
+ "organization_domain_ids": [
+ "id_will_be_deleted",
+ ],
+ },
+ ],
+ "identityProviderConfigsLoading": false,
"isIdJagConfigSubmitting": false,
"isIdJagConfigValid": true,
"isSAMLAvailable": false,
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts
index 943b4ef5c8d5..0ce34b311f60 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts
@@ -2,12 +2,13 @@ import { expectLogic } from 'kea-test-utils'
import { userLogic } from 'scenes/userLogic'
+import { ConfigScopeEnumApi } from '~/generated/core/api.schemas'
import { useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { AvailableFeature } from '~/types'
-import { isSecureURL, verifiedDomainsLogic } from './verifiedDomainsLogic'
+import { getIdentityProviderConfigForDomain, isSecureURL, verifiedDomainsLogic } from './verifiedDomainsLogic'
describe('verifiedDomainsLogic', () => {
let logic: ReturnType<typeof verifiedDomainsLogic.build>
@@ -17,6 +18,18 @@ describe('verifiedDomainsLogic', () => {
useAvailableFeatures([AvailableFeature.SSO_ENFORCEMENT, AvailableFeature.SAML])
useMocks({
get: {
+ '/api/organizations/:organization/identity_provider_configs/': {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ {
+ id: 'config_will_be_deleted',
+ config_scope: null,
+ organization_domain_ids: ['id_will_be_deleted'],
+ },
+ ],
+ },
'/api/organizations/:organization/domains': {
count: 1,
next: null,
@@ -65,11 +78,11 @@ describe('verifiedDomainsLogic', () => {
sso_enforcement: 'google-oauth2',
is_verified: true,
verified_at: '2022-01-01T23:59:59',
- identity_provider_config: '4aa1f0dc-a0ab-490a-9037-14f3358a81bc',
},
},
delete: {
'/api/organizations/:organization/domains/:id/': {},
+ '/api/organizations/:organization/identity_provider_configs/:id/': {},
},
})
initKeaTests()
@@ -101,6 +114,59 @@ describe('verifiedDomainsLogic', () => {
})
})
+ describe('identity provider config resolution', () => {
+ it('selects the config matching the domain', () => {
+ const configs = [
+ {
+ id: 'other-domain-config',
+ config_scope: null,
+ organization_domain_ids: ['other-domain'],
+ created_at: '2024-01-01',
+ updated_at: '2024-01-01',
+ saml_relay_state: 'relay-state',
+ has_saml: false,
+ has_scim: true,
+ scim_bearer_token: null,
+ has_id_jag: false,
+ },
+ {
+ id: 'selected-config',
+ config_scope: ConfigScopeEnumApi.Saml,
+ organization_domain_ids: ['domain-id'],
+ created_at: '2024-01-01',
+ updated_at: '2024-01-01',
+ saml_relay_state: 'relay-state',
+ has_saml: true,
+ has_scim: false,
+ scim_bearer_token: null,
+ has_id_jag: false,
+ },
+ {
+ id: 'selected-scim-config',
+ config_scope: ConfigScopeEnumApi.Scim,
+ organization_domain_ids: ['domain-id'],
+ created_at: '2024-01-01',
+ updated_at: '2024-01-01',
+ saml_relay_state: 'relay-state',
+ has_saml: false,
+ has_scim: true,
+ scim_bearer_token: null,
+ has_id_jag: false,
+ },
+ ]
+
+ expect(getIdentityProviderConfigForDomain(configs, 'domain-id', ConfigScopeEnumApi.Saml)?.id).toBe(
+ 'selected-config'
+ )
+ expect(getIdentityProviderConfigForDomain(configs, 'domain-id', ConfigScopeEnumApi.Scim)?.id).toBe(
+ 'selected-scim-config'
+ )
+ expect(getIdentityProviderConfigForDomain(configs, 'other-domain', ConfigScopeEnumApi.Xaa)?.id).toBe(
+ 'other-domain-config'
+ )
+ })
+ })
+
describe('values', () => {
it('has proper defaults', async () => {
await expectLogic(userlogic).toFinishAllListeners()
@@ -116,9 +182,6 @@ describe('verifiedDomainsLogic', () => {
logic.actions[openModal]('8db3b0c2-a0ab-490a-9037-14f3358a81bc')
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.verifiedDomains[0].identity_provider_config).toEqual(
- '4aa1f0dc-a0ab-490a-9037-14f3358a81bc'
- )
if (openModal === 'setConfigureSAMLModalId') {
expect(logic.values.samlConfig.saml_relay_state).toEqual('6969b120-a0ab-490a-9037-14f3358a81bc')
}
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
index 2161780fee0a..a7d296764d40 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
@@ -11,41 +11,47 @@ import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'
import {
- domainsPartialUpdate,
+ domainsDestroy,
identityProviderConfigsCreate,
identityProviderConfigsDestroy,
+ identityProviderConfigsList,
identityProviderConfigsPartialUpdate,
- identityProviderConfigsRetrieve,
identityProviderConfigsScimTokenCreate,
} from '~/generated/core/api'
-import { IdentityProviderConfigApi } from '~/generated/core/api.schemas'
+import { ConfigScopeEnumApi, IdentityProviderConfigApi } from '~/generated/core/api.schemas'
import { AvailableFeature, OrganizationDomainType, PaginatedSCIMRequestLogs, UserType } from '~/types'
/**
- * 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 sole read/write interface
- * for SAML/SCIM/ID-JAG settings, so all IdP-config CRUD targets it rather than the domain.
- * If linking fails, the freshly created config is deleted so we don't leave an orphan behind.
+ * Resolve the identity provider configuration for a domain, creating one through the
+ * configuration API when needed so the join table remains the only mapping source.
*/
+export function getIdentityProviderConfigForDomain(
+ configs: IdentityProviderConfigApi[],
+ domainId: string,
+ configScope: ConfigScopeEnumApi
+): IdentityProviderConfigApi | undefined {
+ const linkedConfigs = configs.filter((config) => config.organization_domain_ids?.includes(domainId))
+ return (
+ linkedConfigs.find((config) => config.config_scope === configScope) ??
+ linkedConfigs.find((config) => config.config_scope == null)
+ )
+}
+
async function ensureIdpConfig(
organizationId: string,
domain: OrganizationDomainType,
- replaceDomain: (domain: OrganizationDomainType) => void
+ configScope: ConfigScopeEnumApi
): Promise<IdentityProviderConfigApi> {
- if (domain.identity_provider_config) {
- return identityProviderConfigsRetrieve(organizationId, domain.identity_provider_config)
- }
- const config = await identityProviderConfigsCreate(organizationId, { name: domain.domain })
- try {
- const linkedDomain = await domainsPartialUpdate(organizationId, domain.id, {
- identity_provider_config: config.id,
- })
- replaceDomain(linkedDomain as OrganizationDomainType)
- } catch (error) {
- await identityProviderConfigsDestroy(organizationId, config.id).catch(() => undefined)
- throw error
+ const configs = (await identityProviderConfigsList(organizationId)).results
+ const existingConfig = getIdentityProviderConfigForDomain(configs, domain.id, configScope)
+ if (existingConfig) {
+ return existingConfig
}
- return config
+ return identityProviderConfigsCreate(organizationId, {
+ name: domain.domain,
+ config_scope: configScope,
+ organization_domain_ids: [domain.id],
+ })
}
/** Re-fetch a single domain and replace it in local state (e.g. after linking/updating its IdP config). */
@@ -129,6 +135,8 @@ export interface verifiedDomainsLogicValues {
>,
ValidationErrorType
>
+ identityProviderConfigs: IdentityProviderConfigApi[]
+ identityProviderConfigsLoading: boolean
isIdJagConfigSubmitting: boolean
isIdJagConfigValid: boolean
isSAMLAvailable: boolean
@@ -273,6 +281,21 @@ export interface verifiedDomainsLogicActions {
hideAddDomainModal: () => {
value: true
}
+ loadIdentityProviderConfigs: () => any
+ loadIdentityProviderConfigsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadIdentityProviderConfigsSuccess: (
+ identityProviderConfigs: IdentityProviderConfigApi[],
+ payload?: any
+ ) => {
+ identityProviderConfigs: IdentityProviderConfigApi[]
+ payload?: any
+ }
loadScimConfig: (domainId: string) => string
loadScimConfigFailure: (
error: string,
@@ -771,6 +794,13 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
],
}),
loaders(({ values, actions }) => ({
+ identityProviderConfigs: [
+ [] as IdentityProviderConfigApi[],
+ {
+ loadIdentityProviderConfigs: async () =>
+ (await identityProviderConfigsList(values.currentOrganizationId)).results,
+ },
+ ],
verifiedDomains: [
[] as OrganizationDomainType[],
{
@@ -787,7 +817,15 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
return [...values.verifiedDomains, response]
},
deleteVerifiedDomain: async (id: string) => {
- await api.delete(`api/organizations/${values.currentOrganizationId}/domains/${id}`)
+ const configs = values.identityProviderConfigs.filter(
+ (config) =>
+ config.organization_domain_ids?.length === 1 && config.organization_domain_ids[0] === id
+ )
+ await domainsDestroy(values.currentOrganizationId, id)
+ await Promise.all(
+ configs.map((config) => identityProviderConfigsDestroy(values.currentOrganizationId, config.id))
+ )
+ actions.loadIdentityProviderConfigs()
return values.verifiedDomains.filter((domain) => domain.id !== id)
},
},
@@ -832,7 +870,7 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
const config = await ensureIdpConfig(
values.currentOrganizationId as string,
domain,
- actions.replaceDomain
+ ConfigScopeEnumApi.Scim
)
return {
id: domainId,
@@ -846,11 +884,11 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
if (!domain) {
return values.scimConfig
}
- const ensuredConfig = await ensureIdpConfig(orgId, domain, actions.replaceDomain)
+ const ensuredConfig = await ensureIdpConfig(orgId, domain, ConfigScopeEnumApi.Scim)
const config = await identityProviderConfigsPartialUpdate(orgId, ensuredConfig.id, {
scim_enabled: true,
})
- // Refresh the domain so its SCIM base URL and identity_provider_config link are current.
+ actions.loadIdentityProviderConfigs()
const refreshed = await refreshDomain(orgId, domainId, actions.replaceDomain)
lemonToast.success('SCIM enabled successfully!')
return {
@@ -866,10 +904,11 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
if (!domain) {
return values.scimConfig
}
- const ensuredConfig = await ensureIdpConfig(orgId, domain, actions.replaceDomain)
+ const ensuredConfig = await ensureIdpConfig(orgId, domain, ConfigScopeEnumApi.Scim)
const config = await identityProviderConfigsPartialUpdate(orgId, ensuredConfig.id, {
scim_enabled: false,
})
+ actions.loadIdentityProviderConfigs()
const refreshed = await refreshDomain(orgId, domainId, actions.replaceDomain)
lemonToast.success('SCIM disabled successfully!')
return {
@@ -881,13 +920,17 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
regenerateScimToken: async (domainId: string) => {
const orgId = values.currentOrganizationId as string
const domain = values.verifiedDomains.find(({ id }) => id === domainId)
- if (!domain?.identity_provider_config) {
+ const config = domain
+ ? getIdentityProviderConfigForDomain(
+ values.identityProviderConfigs,
+ domain.id,
+ ConfigScopeEnumApi.Scim
+ )
+ : undefined
+ if (!domain || !config) {
return values.scimConfig
}
- const response = await identityProviderConfigsScimTokenCreate(
- orgId,
- domain.identity_provider_config
- )
+ const response = await identityProviderConfigsScimTokenCreate(orgId, config.id)
lemonToast.success('SCIM token regenerated successfully!')
return {
id: domainId,
@@ -939,7 +982,7 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
const config = await ensureIdpConfig(
values.currentOrganizationId as string,
domain,
- actions.replaceDomain
+ ConfigScopeEnumApi.Saml
)
actions.setSamlConfigValues({
id,
@@ -963,7 +1006,7 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
const config = await ensureIdpConfig(
values.currentOrganizationId as string,
domain,
- actions.replaceDomain
+ ConfigScopeEnumApi.Xaa
)
actions.setIdJagConfigValues({
id,
@@ -1047,7 +1090,10 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
hasAvailableFeature(AvailableFeature.XAA_AUTHENTICATION),
],
}),
- afterMount(({ actions }) => actions.loadVerifiedDomains()),
+ afterMount(({ actions }) => {
+ actions.loadIdentityProviderConfigs()
+ actions.loadVerifiedDomains()
+ }),
bindModalToUrl({
urlKey: 'add-domain',
openActionKey: 'showAddDomainModal',
@@ -1073,12 +1119,13 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
if (!domain) {
return
}
- const config = await ensureIdpConfig(orgId, domain, actions.replaceDomain)
+ const config = await ensureIdpConfig(orgId, domain, ConfigScopeEnumApi.Saml)
await identityProviderConfigsPartialUpdate(orgId, config.id, {
saml_acs_url,
saml_entity_id,
saml_x509_cert,
})
+ actions.loadIdentityProviderConfigs()
breakpoint()
const refreshed = await refreshDomain(orgId, id, actions.replaceDomain)
actions.setConfigureSAMLModalId(null)
@@ -1108,12 +1155,13 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
if (!domain) {
return
}
- const config = await ensureIdpConfig(orgId, domain, actions.replaceDomain)
+ const config = await ensureIdpConfig(orgId, domain, ConfigScopeEnumApi.Xaa)
await identityProviderConfigsPartialUpdate(orgId, config.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 ?? [],
})
+ actions.loadIdentityProviderConfigs()
breakpoint()
const refreshed = await refreshDomain(orgId, id, actions.replaceDomain)
actions.setConfigureIdJagModalId(null)
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 69877fcd0140..900becaee451 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -609,12 +609,7 @@ export interface OrganizationDomainType {
verification_challenge: string
jit_provisioning_enabled: boolean
sso_enforcement: SSOProvider | ''
- has_saml: boolean
- has_scim?: boolean
scim_base_url?: string
- has_id_jag?: boolean
- /** Linked IdP config (SAML/SCIM/XAA) — the sole read/write interface for those settings. */
- identity_provider_config?: string | null
}
export interface SCIMRequestLogType {
diff --git a/posthog/admin/admins/identity_provider_config_admin.py b/posthog/admin/admins/identity_provider_config_admin.py
index 7673e1da17ef..443bc008482f 100644
--- a/posthog/admin/admins/identity_provider_config_admin.py
+++ b/posthog/admin/admins/identity_provider_config_admin.py
@@ -16,7 +16,7 @@ class IdentityProviderConfigAdmin(admin.ModelAdmin):
"created_at",
)
list_filter = ("scim_enabled",)
- search_fields = ("name", "organization__name", "domains__domain")
+ search_fields = ("name", "organization__name", "linked_identity_provider_configs__organization_domain__domain")
readonly_fields = ("id", "created_at", "updated_at", "linked_domains")
autocomplete_fields = ["organization"]
fieldsets = (
@@ -42,5 +42,5 @@ class IdentityProviderConfigAdmin(admin.ModelAdmin):
@admin.display(description="Linked domains")
def linked_domains(self, obj):
- domains = list(obj.domains.order_by("domain").values_list("domain", flat=True))
+ domains = list(obj.organization_domains.order_by("domain").values_list("domain", flat=True))
return ", ".join(domains) if domains else "-"
diff --git a/posthog/admin/admins/organization_domain_admin.py b/posthog/admin/admins/organization_domain_admin.py
index e20d77cfee21..0129598b7857 100644
--- a/posthog/admin/admins/organization_domain_admin.py
+++ b/posthog/admin/admins/organization_domain_admin.py
@@ -28,16 +28,21 @@ class OrganizationDomainAdmin(admin.ModelAdmin):
"verification_challenge",
"last_verification_retry",
# Legacy, frozen columns — edit SAML settings via IdentityProviderConfigAdmin instead.
+ "_identity_provider_config",
"_saml_entity_id",
"_saml_acs_url",
"_saml_x509_cert",
+ "_scim_enabled",
+ "_scim_bearer_token",
+ "_id_jag_issuer_url",
+ "_id_jag_jwks_url",
+ "_id_jag_allowed_clients",
)
- autocomplete_fields = ["organization", "identity_provider_config"]
+ autocomplete_fields = ["organization"]
fieldsets = (
- (None, {"fields": ("id", "organization", "domain", "identity_provider_config")}),
+ (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")}),
)
list_display_links = ("domain",)
ordering = ("domain",)
@@ -53,6 +58,6 @@ class OrganizationDomainAdmin(admin.ModelAdmin):
@admin.display(description="SAML Status")
def saml_status(self, obj):
"""Display SAML configuration status"""
- if obj.has_saml:
+ if obj.saml_identity_provider_configs.exists():
return format_html('<span style="color: green;">✓ Configured</span>')
return format_html('<span style="color: gray;">Not Configured</span>')
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index 07d57637f3dc..8021c4fc0d34 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -269,18 +269,19 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
id_jag_email = unverified_claims.get("email") or unverified_claims.get("sub") or ""
- org_domain, error = OrganizationDomain.objects.get_verified_for_email_address_and_issuer(id_jag_email, issuer)
- if org_domain is None or error:
+ resolution = OrganizationDomain.objects.get_verified_for_email_address_and_issuer(id_jag_email, issuer)
+ if resolution.organization_domain is None or resolution.identity_provider_config is None or resolution.error:
# Do not echo the specific reason — see GENERIC_ID_JAG_REJECTION.
logger.info(
"id_jag_token_rejected",
- reason=error or "ID-JAG configuration is invalid",
+ reason=resolution.error or "ID-JAG configuration is invalid",
issuer=issuer,
stage="pre_signature_domain_lookup",
)
raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)
- idp_config = org_domain.idp_config
+ org_domain = resolution.organization_domain
+ idp_config = resolution.identity_provider_config
expected_issuer = (idp_config.id_jag_issuer_url or "").rstrip("/")
provider_name = org_domain.domain
diff --git a/posthog/api/identity_provider_config.py b/posthog/api/identity_provider_config.py
index 00ed87371c77..37e2d015a79b 100644
--- a/posthog/api/identity_provider_config.py
+++ b/posthog/api/identity_provider_config.py
@@ -1,5 +1,7 @@
from typing import Any, cast
+from django.db import transaction
+
import posthoganalytics
from drf_spectacular.utils import extend_schema
from rest_framework import exceptions, request, response, serializers, status
@@ -7,11 +9,14 @@ from rest_framework.request import Request
from rest_framework.viewsets import ModelViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.scoped_related_fields import OrgScopedPrimaryKeyRelatedField
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.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization import Organization
+from posthog.models.organization_domain import OrganizationDomain
from posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission
from posthog.security.url_validation import is_url_allowed
@@ -30,6 +35,10 @@ def _capture_idp_config_event(
)
+class _OrgScopedOrganizationDomainField(OrgScopedPrimaryKeyRelatedField):
+ scope_field = "organization"
+
+
class IdentityProviderConfigSerializer(serializers.ModelSerializer):
saml_relay_state = serializers.CharField(
read_only=True,
@@ -51,12 +60,22 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
has_id_jag = serializers.BooleanField(
read_only=True, help_text="Whether ID-JAG (XAA) is configured on this config."
)
+ organization_domain_ids = _OrgScopedOrganizationDomainField(
+ source="organization_domains",
+ many=True,
+ queryset=OrganizationDomain.objects.all(),
+ required=False,
+ help_text="Organization domain IDs that this identity provider configuration applies to.",
+ )
class Meta:
model = IdentityProviderConfig
fields = (
"id",
"name",
+ "domain_scope",
+ "config_scope",
+ "organization_domain_ids",
"created_at",
"updated_at",
"has_saml",
@@ -74,6 +93,16 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
)
extra_kwargs = {
"name": {"help_text": "Display name for this IdP configuration (e.g. 'Okta production')."},
+ "domain_scope": {
+ "required": False,
+ "allow_null": True,
+ "help_text": "Domains this configuration applies to. An unset value behaves like selected domains.",
+ },
+ "config_scope": {
+ "required": False,
+ "allow_null": True,
+ "help_text": "Feature configured by this identity provider configuration.",
+ },
"created_at": {"read_only": True},
"updated_at": {"read_only": True},
"saml_entity_id": {
@@ -158,20 +187,40 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
return attrs
+ @staticmethod
+ def _sync_organization_domains(
+ instance: IdentityProviderConfig, organization_domains: list[OrganizationDomain]
+ ) -> None:
+ LinkedIdentityProviderConfig.objects.filter(identity_provider_config=instance).delete()
+ LinkedIdentityProviderConfig.objects.bulk_create(
+ [
+ LinkedIdentityProviderConfig(
+ identity_provider_config=instance,
+ organization_domain=organization_domain,
+ )
+ for organization_domain in organization_domains
+ ]
+ )
+
+ @transaction.atomic
def create(self, validated_data: dict[str, Any]) -> IdentityProviderConfig:
validated_data["organization"] = self.context["view"].organization
scim_enabled = validated_data.pop("scim_enabled", None)
+ organization_domains = validated_data.pop("organization_domains", [])
validated_data.pop("scim_bearer_token", None)
instance: IdentityProviderConfig = super().create(validated_data)
+ self._sync_organization_domains(instance, organization_domains)
if scim_enabled:
self._scim_plain_token = enable_scim_for_config(instance)
return instance
+ @transaction.atomic
def update(self, instance: IdentityProviderConfig, validated_data: dict[str, Any]) -> IdentityProviderConfig:
scim_enabled = validated_data.pop("scim_enabled", None)
+ organization_domains = validated_data.pop("organization_domains", None)
validated_data.pop("scim_bearer_token", None)
scim_plain_token: str | None = None
@@ -186,6 +235,8 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
disable_scim_for_config(instance)
instance = super().update(instance, validated_data)
+ if organization_domains is not None:
+ self._sync_organization_domains(instance, organization_domains)
self._scim_plain_token = scim_plain_token
return instance
@@ -226,9 +277,9 @@ class IdentityProviderConfigViewSet(TeamAndOrgViewSetMixin, ModelViewSet):
# immutable-id mapping for those users — the next sync provisions everyone again. Make that
# reachable only after the domain is explicitly unlinked, so it can't ride along on a
# misdirected request against a live configuration.
- if config.domains.exists():
+ if config.organization_domains.exists():
raise exceptions.ValidationError(
- "This configuration is linked to a domain. Unlink it from the domain before deleting it.",
+ "This configuration is mapped to an organization domain. Remove its domain mappings before deleting it.",
code="linked_to_domain",
)
return super().destroy(request, *args, **kwargs)
diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.py
index 36cf666b504b..1961e575af83 100644
--- a/posthog/api/organization_domain.py
+++ b/posthog/api/organization_domain.py
@@ -12,13 +12,12 @@ from rest_framework.request import Request
from rest_framework.viewsets import ModelViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.scoped_related_fields import OrgScopedPrimaryKeyRelatedField
from posthog.api.utils import action
from posthog.cloud_utils import is_cloud
from posthog.constants import AvailableFeature
from posthog.event_usage import groups
from posthog.models import OrganizationDomain, User
-from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.identity_provider_config import ConfigScope
from posthog.models.organization import Organization, OrganizationMembership
from posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission
@@ -28,12 +27,6 @@ from ee.models.scim_request_log import SCIMRequestLog
DOMAIN_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 = {}
@@ -60,13 +53,9 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):
"sso_enforcement": "sso_enforcement",
}
- scim_base_url = 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.",
- )
+ scim_base_url = (
+ serializers.SerializerMethodField()
+ ) # TODO: remove this from the org domain api and have the frontend use the idp config api to get the scim base url
class Meta:
model = OrganizationDomain
@@ -78,20 +67,13 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):
"verification_challenge",
"jit_provisioning_enabled",
"sso_enforcement",
- "has_saml",
- "has_scim",
"scim_base_url",
- "has_id_jag",
- "identity_provider_config",
)
extra_kwargs = {
"verified_at": {"read_only": True},
"verification_challenge": {"read_only": True},
"is_verified": {"read_only": True},
- "has_saml": {"read_only": True},
- "has_scim": {"read_only": True},
"scim_base_url": {"read_only": True},
- "has_id_jag": {"read_only": True},
}
def get_fields(self):
@@ -143,10 +125,10 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):
return super().update(instance, validated_data)
def get_scim_base_url(self, obj: OrganizationDomain) -> str | None:
- config = obj.identity_provider_config
- if config is None or not config.has_scim or not config.scim_slug:
+ configs = list(obj.identity_provider_configs_for_scope(ConfigScope.SCIM).filter(scim_enabled=True)[:2])
+ if len(configs) != 1 or not configs[0].has_scim or not configs[0].scim_slug:
return None
- return get_scim_base_url(config)
+ return get_scim_base_url(configs[0])
class SCIMRequestLogSerializer(serializers.ModelSerializer):
@@ -209,8 +191,7 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):
scope_object = "organization"
serializer_class = OrganizationDomainSerializer
permission_classes = [OrganizationAdminWritePermissions, TimeSensitiveActionPermission]
- # Every serialized domain reads its linked config (SAML/SCIM/ID-JAG state, SCIM base URL).
- queryset = OrganizationDomain.objects.select_related("identity_provider_config").order_by("domain").all()
+ queryset = OrganizationDomain.objects.order_by("domain").all()
@action(methods=["POST"], detail=True)
def verify(self, request: request.Request, **kw) -> response.Response:
@@ -277,17 +258,18 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):
code="would_block_self",
)
+ identity_provider_configs = list(instance.identity_provider_configs)
_capture_domain_event(
request,
instance,
"deleted",
properties={
"is_verified": instance.is_verified,
- "had_saml": instance.has_saml,
+ "had_saml": any(config.has_saml for config in identity_provider_configs),
"had_jit_provisioning": instance.jit_provisioning_enabled,
"had_sso_enforcement": bool(instance.sso_enforcement),
- "had_scim": instance.has_scim,
- "had_id_jag": instance.has_id_jag,
+ "had_scim": any(config.has_scim for config in identity_provider_configs),
+ "had_id_jag": any(config.has_id_jag for config in identity_provider_configs),
},
)
@@ -307,9 +289,7 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):
# config. Match the domain too: rows logged before the move carry only that until the
# `backfill_scim_request_log_config` command reaches them, and a domain that was later
# unlinked from its config keeps nothing else to find its history by.
- scope = Q(organization_domain=domain)
- if domain.identity_provider_config_id is not None:
- scope |= Q(identity_provider_config_id=domain.identity_provider_config_id)
+ scope = Q(organization_domain=domain) | Q(identity_provider_config__in=domain.identity_provider_configs)
queryset = SCIMRequestLog.objects.filter(scope)
queryset = SCIMRequestLogFilter(request.query_params, queryset=queryset).qs
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index e3e0b6e6d87d..008149938bfe 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -35,7 +35,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import EmailValidationHelper, reject_plus_addressed_email, validate_display_name
from posthog.helpers.verified_domain_enforcement import resolve_login_organization
from posthog.models import InviteExpiredException, Organization, OrganizationDomain, OrganizationInvite, Team, User
-from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfig
from posthog.models.organization_invite import INVITE_DAYS_VALIDITY
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.permissions import CanCreateOrg
@@ -893,12 +893,15 @@ def process_social_domain_jit_provisioning_signup(
)
return user
else:
+ scim_enabled = (
+ domain_instance.identity_provider_configs_for_scope(ConfigScope.SCIM).filter(scim_enabled=True).exists()
+ )
logger.info(
f"process_social_domain_jit_provisioning_signup_domain_exists",
domain=domain,
is_verified=domain_instance.is_verified,
jit_provisioning_enabled=domain_instance.jit_provisioning_enabled,
- scim_enabled=domain_instance.idp_config.scim_enabled,
+ scim_enabled=scim_enabled,
)
if domain_instance.is_verified and domain_instance.jit_provisioning_enabled:
if not user:
@@ -949,7 +952,7 @@ def process_social_domain_jit_provisioning_signup(
domain=domain,
user=user.email,
organization=domain_instance.organization_id,
- scim_enabled=domain_instance.idp_config.scim_enabled,
+ scim_enabled=scim_enabled,
)
return user
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index e6507502bd43..6ee814f0a231 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -36,7 +36,8 @@ from posthog.api.id_jag import (
)
from posthog.auth import IDJagAccessTokenAuthentication
from posthog.constants import AvailableFeature
-from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User as UserModel
@@ -123,10 +124,8 @@ class TestIdJagTokenEndpoint(APIBaseTest):
domain=_VERIFIED_DOMAIN,
verified_at=timezone.now(),
)
- domain.identity_provider_config = IdentityProviderConfig.objects.create(
- organization=cls.organization, id_jag_issuer_url=_IDP_ISSUER
- )
- domain.save()
+ config = IdentityProviderConfig.objects.create(organization=cls.organization, id_jag_issuer_url=_IDP_ISSUER)
+ LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
def setUp(self) -> None:
super().setUp()
@@ -469,10 +468,12 @@ class TestIdJagTokenEndpoint(APIBaseTest):
domain="bigco.example",
verified_at=timezone.now(),
)
- attacker_domain.identity_provider_config = IdentityProviderConfig.objects.create(
+ attacker_config = IdentityProviderConfig.objects.create(
organization=attacker_org, id_jag_issuer_url=_IDP_ISSUER
)
- attacker_domain.save()
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=attacker_domain, identity_provider_config=attacker_config
+ )
# Victim user whose email is on the attacker's verified domain but who
# belongs to a completely unrelated org.
@@ -634,7 +635,7 @@ 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)
- config = domain.identity_provider_config
+ config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
config.id_jag_issuer_url = None
config.save()
@@ -650,7 +651,7 @@ 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)
- config = domain.identity_provider_config
+ config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
config.id_jag_issuer_url = "https://idp.example.com"
config.save()
@@ -668,7 +669,7 @@ 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)
- config = domain.identity_provider_config
+ config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
config.id_jag_issuer_url = _IDP_ISSUER
config.save()
@@ -682,7 +683,7 @@ 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)
- config = domain.identity_provider_config
+ config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
config.id_jag_jwks_url = "https://idp.example.com/keys.json"
config.save()
@@ -702,7 +703,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
def test_allowed_clients_permits_listed_client_id(self) -> None:
domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)
- config = domain.identity_provider_config
+ config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
config.id_jag_allowed_clients = ["client_first", "client_second"]
config.save()
@@ -712,7 +713,7 @@ class TestIdJagTokenEndpoint(APIBaseTest):
def test_allowed_clients_rejects_unlisted_client_id(self) -> None:
domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)
- config = domain.identity_provider_config
+ config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
config.id_jag_allowed_clients = ["client_first", "client_second"]
config.save()
diff --git a/posthog/api/test/test_identity_provider_config.py b/posthog/api/test/test_identity_provider_config.py
index 4b05eb2d4c25..f25ced205453 100644
--- a/posthog/api/test/test_identity_provider_config.py
+++ b/posthog/api/test/test_identity_provider_config.py
@@ -5,7 +5,13 @@ from django.utils import timezone
from rest_framework import status
from posthog.constants import AvailableFeature
-from posthog.models import IdentityProviderConfig, Organization, OrganizationDomain, OrganizationMembership
+from posthog.models import (
+ IdentityProviderConfig,
+ LinkedIdentityProviderConfig,
+ Organization,
+ OrganizationDomain,
+ OrganizationMembership,
+)
class TestIdentityProviderConfigAPI(APIBaseTest):
@@ -35,17 +41,67 @@ class TestIdentityProviderConfigAPI(APIBaseTest):
# Create & permissions
- def test_admin_can_create_config(self):
+ def test_admin_can_create_config_with_selected_domains(self):
self._make_admin()
+ domain = OrganizationDomain.objects.create(organization=self.organization, domain="example.com")
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"},
+ {
+ "name": "Okta production",
+ "domain_scope": "selected",
+ "organization_domain_ids": [str(domain.id)],
+ "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")
+ self.assertEqual(response.json()["domain_scope"], "selected")
+ self.assertEqual(response.json()["organization_domain_ids"], [str(domain.id)])
self.assertEqual(response.json()["saml_relay_state"], str(config.saml_relay_state))
+ self.assertTrue(
+ LinkedIdentityProviderConfig.objects.filter(
+ identity_provider_config=config, organization_domain=domain
+ ).exists()
+ )
+
+ def test_updating_selected_domains_replaces_links(self):
+ self._make_admin()
+ first_domain = OrganizationDomain.objects.create(organization=self.organization, domain="first.example.com")
+ second_domain = OrganizationDomain.objects.create(organization=self.organization, domain="second.example.com")
+ config = IdentityProviderConfig.objects.create(organization=self.organization)
+ LinkedIdentityProviderConfig.objects.create(identity_provider_config=config, organization_domain=first_domain)
+
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",
+ {"organization_domain_ids": [str(second_domain.id)]},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["organization_domain_ids"], [str(second_domain.id)])
+ self.assertEqual(
+ list(
+ LinkedIdentityProviderConfig.objects.filter(identity_provider_config=config).values_list(
+ "organization_domain_id", flat=True
+ )
+ ),
+ [second_domain.id],
+ )
+
+ def test_cannot_map_config_to_another_organizations_domain(self):
+ self._make_admin()
+ other_organization = Organization.objects.create(name="Other")
+ other_domain = OrganizationDomain.objects.create(organization=other_organization, domain="other.example.com")
+
+ response = self.client.post(
+ "/api/organizations/@current/identity_provider_configs/",
+ {"organization_domain_ids": [str(other_domain.id)]},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "organization_domain_ids")
def test_member_cannot_create_config(self):
self.organization_membership.level = OrganizationMembership.Level.MEMBER
@@ -174,12 +230,12 @@ class TestIdentityProviderConfigAPI(APIBaseTest):
# IdP's immutable-id mapping. That has to take an explicit unlink first.
self._make_admin()
config = IdentityProviderConfig.objects.create(organization=self.organization)
- OrganizationDomain.objects.create(
+ domain = OrganizationDomain.objects.create(
organization=self.organization,
domain="linked.example.com",
verified_at=timezone.now(),
- identity_provider_config=config,
)
+ LinkedIdentityProviderConfig.objects.create(identity_provider_config=config, organization_domain=domain)
response = self.client.delete(f"/api/organizations/@current/identity_provider_configs/{config.id}/")
@@ -194,10 +250,9 @@ class TestIdentityProviderConfigAPI(APIBaseTest):
organization=self.organization,
domain="unlinked.example.com",
verified_at=timezone.now(),
- identity_provider_config=config,
)
- domain.identity_provider_config = None
- domain.save()
+ link = LinkedIdentityProviderConfig.objects.create(identity_provider_config=config, organization_domain=domain)
+ link.delete()
response = self.client.delete(f"/api/organizations/@current/identity_provider_configs/{config.id}/")
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index 0958d35063f4..9afd0a65eb37 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -25,6 +25,7 @@ from posthog.constants import AvailableFeature
from posthog.models import Organization, Team, User
from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.instance_setting import override_instance_config
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.organization_invite import INVITE_DAYS_VALIDITY, OrganizationInvite
@@ -1044,10 +1045,8 @@ class TestSignupAPI(APIBaseTest):
jit_provisioning_enabled=True,
organization=new_org,
)
- domain.identity_provider_config = IdentityProviderConfig.objects.create(
- organization=new_org, scim_enabled=True
- )
- domain.save()
+ config = IdentityProviderConfig.objects.create(organization=new_org, scim_enabled=True)
+ LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
Team.objects.create(organization=new_org, name="Test Project")
response = self.client.get(reverse("social:begin", kwargs={"backend": "google-oauth2"}))
@@ -1090,10 +1089,8 @@ class TestSignupAPI(APIBaseTest):
jit_provisioning_enabled=True,
organization=new_org,
)
- domain.identity_provider_config = IdentityProviderConfig.objects.create(
- organization=new_org, scim_enabled=True
- )
- domain.save()
+ config = IdentityProviderConfig.objects.create(organization=new_org, scim_enabled=True)
+ LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
Team.objects.create(organization=new_org, name="Test Project")
response = self.client.get(reverse("social:begin", kwargs={"backend": "google-oauth2"}))
@@ -3384,11 +3381,13 @@ class TestSAMLInviteLookup(APIBaseTest):
organization=self.organization, saml_entity_id="e", saml_acs_url="a", saml_x509_cert="c"
)
for domain in domains:
- OrganizationDomain.objects.create(
+ organization_domain = OrganizationDomain.objects.create(
organization=self.organization,
domain=domain,
verified_at=timezone.now(),
- identity_provider_config=config,
+ )
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=organization_domain, identity_provider_config=config
)
config.refresh_from_db()
assert config.saml_relay_state is not None
diff --git a/posthog/migrations/1316_deprecate_organization_domain_idp_config.py b/posthog/migrations/1316_deprecate_organization_domain_idp_config.py
new file mode 100644
index 000000000000..b693cdaeafe2
--- /dev/null
+++ b/posthog/migrations/1316_deprecate_organization_domain_idp_config.py
@@ -0,0 +1,30 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1315_githubinstallrequest_account")]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RenameField(
+ model_name="organizationdomain",
+ old_name="identity_provider_config",
+ new_name="_identity_provider_config",
+ ),
+ migrations.AlterField(
+ model_name="organizationdomain",
+ name="_identity_provider_config",
+ field=models.ForeignKey(
+ blank=True,
+ db_column="identity_provider_config_id",
+ null=True,
+ on_delete=models.SET_NULL,
+ related_name="+",
+ to="posthog.identityproviderconfig",
+ ),
+ ),
+ ],
+ database_operations=[],
+ )
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 2b22f030134a..d481c119b0ae 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1315_githubinstallrequest_account
+1316_deprecate_organization_domain_idp_config
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 5f45d2d682ee..42fa9b655aa0 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -548,13 +548,12 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"scim_provisioned_users",
"scim_request_logs",
# Internal link to the IdP config mirror; the mirrored fields themselves are already logged
- "identity_provider_config",
+ "_identity_provider_config",
],
"IdentityProviderConfig": [
"organization",
# Reverse relations, not plain field diffs — and diffing them reads every related row, which
# for SCIM request logs is the tenant's whole request history.
- "domains",
"linked_identity_provider_configs",
"scim_provisioned_users",
"scim_request_logs",
diff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.py
index 3b463ff1e7a6..9dbdbc93e10f 100644
--- a/posthog/models/identity_provider_config.py
+++ b/posthog/models/identity_provider_config.py
@@ -1,4 +1,5 @@
import uuid
+from typing import TYPE_CHECKING, cast
from django.contrib.postgres.fields import ArrayField
from django.db import models
@@ -8,6 +9,9 @@ import structlog
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import UUIDModel
+if TYPE_CHECKING:
+ from posthog.models.organization_domain import OrganizationDomain
+
logger = structlog.get_logger(__name__)
@@ -16,10 +20,33 @@ class DomainScope(models.TextChoices):
SELECTED = "selected"
+DEFAULT_DOMAIN_SCOPE = DomainScope.SELECTED
+
+
+def has_verified_organization_domain_q() -> models.Q:
+ return models.Q(linked_identity_provider_configs__organization_domain__verified_at__isnull=False) | models.Q(
+ domain_scope=DomainScope.ALL, organization__domains__verified_at__isnull=False
+ )
+
+
class ConfigScope(models.TextChoices):
SAML = "saml"
SCIM = "scim"
- XAA = "xaa"
+ ID_JAG = (
+ "xaa",
+ "Xaa",
+ ) # TODO: before letting people put data here, let's widen the column to 6 chars and rename this to `id_jag`
+
+
+def saml_configured_q() -> models.Q:
+ return ~models.Q(
+ models.Q(saml_entity_id="")
+ | models.Q(saml_entity_id__isnull=True)
+ | models.Q(saml_acs_url="")
+ | models.Q(saml_acs_url__isnull=True)
+ | models.Q(saml_x509_cert="")
+ | models.Q(saml_x509_cert__isnull=True)
+ )
class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
@@ -28,8 +55,8 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
Groups IdP-specific settings — SAML, SCIM, and ID-JAG (XAA) today, custom SSO in the
future — in one place, decoupled from any single domain. One config can be mapped to
- multiple `OrganizationDomain` rows (via `OrganizationDomain.identity_provider_config`),
- and an organization can have zero, one, or many configs.
+ multiple `OrganizationDomain` rows through `LinkedIdentityProviderConfig`, and an
+ organization can have zero, one, or many configs.
This model is the sole read/write interface for IdP settings (SAML/SCIM/ID-JAG). The legacy
IdP columns on `OrganizationDomain` are no longer written to — they're frozen.
@@ -107,6 +134,24 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
def __str__(self) -> str:
return self.name or str(self.id)
+ @property
+ def effective_domain_scope(self) -> str:
+ return self.domain_scope or DEFAULT_DOMAIN_SCOPE
+
+ @property
+ def applies_to_all_domains(self) -> bool:
+ return self.effective_domain_scope == DomainScope.ALL
+
+ @property
+ def organization_domains(self) -> models.QuerySet["OrganizationDomain"]:
+ organization_domain_model = cast(
+ type["OrganizationDomain"], self._meta.apps.get_model("posthog", "OrganizationDomain")
+ )
+ domains = organization_domain_model.objects.filter(organization_id=self.organization_id)
+ if self.applies_to_all_domains:
+ return domains
+ return domains.filter(linked_identity_provider_configs__identity_provider_config=self)
+
@property
def has_saml(self) -> bool:
"""
diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.py
index 3c56e98bed0a..0c95e7ec97f1 100644
--- a/posthog/models/organization_domain.py
+++ b/posthog/models/organization_domain.py
@@ -1,21 +1,19 @@
import secrets
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Optional
from django.contrib.postgres.fields import ArrayField
-from django.core.exceptions import ValidationError
-from django.db import models, transaction
-from django.db.models.signals import post_delete
-from django.dispatch import receiver
+from django.db import models
from django.utils import timezone
import structlog
import dns.resolver
from posthog.constants import AvailableFeature
+from posthog.dataclasses import frozen
from posthog.dns_utils import dnssec_resolver
from posthog.models import Organization
from posthog.models.activity_logging.model_activity import ModelActivityMixin
-from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.identity_provider_config import ConfigScope, DomainScope, IdentityProviderConfig, saml_configured_q
from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.utils import UUIDTModel
from posthog.utils import get_instance_available_sso_providers
@@ -30,6 +28,23 @@ def generate_verification_challenge() -> str:
return secrets.token_urlsafe(32)
+@frozen
+class IDJagIdentityProviderResolution:
+ organization_domain: Optional["OrganizationDomain"]
+ identity_provider_config: Optional[IdentityProviderConfig]
+ error: Optional[str]
+
+
+def resolves_to_identity_provider_config_q(
+ configs: models.QuerySet[IdentityProviderConfig],
+) -> models.Q:
+ explicitly_linked = LinkedIdentityProviderConfig.objects.filter(
+ organization_domain=models.OuterRef("pk"), identity_provider_config__in=configs
+ )
+ organization_wide = configs.filter(domain_scope=DomainScope.ALL, organization_id=models.OuterRef("organization_id"))
+ return models.Q(models.Exists(explicitly_linked)) | models.Q(models.Exists(organization_wide))
+
+
class OrganizationDomainManager(models.Manager):
def verified_domains(self):
# TODO: Verification becomes stale on Cloud if not reverified after a certain period.
@@ -37,9 +52,7 @@ class OrganizationDomainManager(models.Manager):
# has `enforce_verified_domains` on — the domain would drop out of the enforcement
# allow-list and lock out every member on it at once, admins included. Suspend or flag
# instead of clearing.
- # `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")
+ return self.exclude(verified_at__isnull=True)
def get_verified_for_email_address(self, email: str) -> Optional["OrganizationDomain"]:
"""
@@ -49,68 +62,75 @@ class OrganizationDomainManager(models.Manager):
domain = email[email.index("@") + 1 :]
return self.verified_domains().filter(domain__iexact=domain).first()
- def get_verified_for_email_address_and_issuer(
- self, email: str, issuer: str
- ) -> tuple[Optional["OrganizationDomain"], Optional[str]]:
- """
- Resolve the `OrganizationDomain` that should authorize an ID-JAG
- assertion for `email` signed by `issuer`. Returns
- `(org_domain, error)` where `error` is `None` on success or a
- human-readable description of the failure mode otherwise.
-
- Lookup is by `(domain, issuer)` (not `.first()`) so the chosen org is
- deterministic and cannot be steered by row ordering when multiple
- organizations have verified the same domain. The returned org is the
- one whose IdP signed the assertion — callers should scope the issued
- access token to that org and require user membership there.
- """
+ def get_verified_for_email_address_and_issuer(self, email: str, issuer: str) -> IDJagIdentityProviderResolution:
if "@" not in email:
- return None, "ID-JAG sub email domain is not a verified domain for any PostHog organization"
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG sub email domain is not a verified domain for any PostHog organization",
+ )
domain = email[email.index("@") + 1 :].lower()
normalized_issuer = (issuer or "").rstrip("/")
verified_for_domain = list(self.verified_domains().filter(domain__iexact=domain))
if not verified_for_domain:
- return None, "ID-JAG sub email domain is not a verified domain for any PostHog organization"
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG sub email domain is not a verified domain for any PostHog organization",
+ )
- configured = [d for d in verified_for_domain if (d.idp_config.id_jag_issuer_url or "").rstrip("/")]
+ configured = [
+ (organization_domain, config)
+ for organization_domain in verified_for_domain
+ for config in organization_domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG)
+ if (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)"
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG is not configured for this domain (id_jag_issuer_url is unset)",
+ )
- matching = [d for d in configured if (d.idp_config.id_jag_issuer_url or "").rstrip("/") == normalized_issuer]
+ matching = [
+ (organization_domain, config)
+ for organization_domain, config in configured
+ if (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"
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG iss does not match the IdP configured for this email's domain",
+ )
if len(matching) > 1:
- # Ambiguous config — multiple orgs verified the same domain AND
- # configured the same IdP issuer. This is a case that will rqeuire
- # manual intervention to resolve since it is not clear if one of
- # or both of the org domains are valid
- return None, "ID-JAG configuration is ambiguous: multiple OrganizationDomains share this (domain, issuer)"
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG configuration is ambiguous: multiple OrganizationDomains share this (domain, issuer)",
+ )
- return matching[0], None
+ organization_domain, config = matching[0]
+ return IDJagIdentityProviderResolution(
+ organization_domain=organization_domain,
+ identity_provider_config=config,
+ error=None,
+ )
def get_is_saml_available_for_email(self, email: str) -> bool:
"""
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.
+ saml_configs = IdentityProviderConfig.objects.filter(
+ models.Q(config_scope=ConfigScope.SAML) | models.Q(config_scope__isnull=True)
+ ).filter(saml_configured_q())
query = (
self.verified_domains()
.filter(domain__iexact=domain)
- .exclude(
- 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(
- 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(identity_provider_config__saml_acs_url__isnull=True)
- | models.Q(identity_provider_config__saml_x509_cert__isnull=True)
- )
+ .filter(resolves_to_identity_provider_config_q(saml_configs))
.values_list("organization__available_product_features", flat=True)
.first()
)
@@ -273,64 +293,18 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):
db_column="id_jag_allowed_clients",
) # deprecated, do not use; see `IdentityProviderConfig`
- # ---- IdP config (home for SAML/SCIM/ID-JAG settings) ----
- # `IdentityProviderConfig` is the source of truth for SAML/SCIM/ID-JAG settings and can be
- # shared by multiple domains. All reads and writes of those settings go through the linked
- # config (`self.idp_config`); the FK link itself is still writable via this domain.
- identity_provider_config = models.ForeignKey(
+ _identity_provider_config = models.ForeignKey(
IdentityProviderConfig,
on_delete=models.SET_NULL,
null=True,
blank=True,
- related_name="domains",
- help_text="IdP configuration (SAML/SCIM/XAA) backing this domain.",
- )
+ related_name="+",
+ db_column="identity_provider_config_id",
+ ) # deprecated, do not use; see `LinkedIdentityProviderConfig`
class Meta:
verbose_name = "domain"
- def _validate_identity_provider_config_organization(self) -> dict[str, str]:
- # A linked IdP config must belong to the same organization as the domain. Without this,
- # an admin could link a domain to another org's config and have that org's IdP settings
- # exposed on this domain (SCIM/ID-JAG auth resolve through `self.idp_config`).
- errors: dict[str, str] = {}
- if self.identity_provider_config_id is not None:
- try:
- config = self.identity_provider_config
- except IdentityProviderConfig.DoesNotExist:
- config = None
- if config is None:
- errors["identity_provider_config"] = "IdP configuration does not exist."
- elif config.organization_id != self.organization_id:
- errors["identity_provider_config"] = (
- "IdP configuration must belong to the same organization as the domain."
- )
- return errors
-
- def clean(self) -> None:
- errors = self._validate_identity_provider_config_organization()
- if errors:
- raise ValidationError(errors)
- super().clean()
-
- def save(self, *args: Any, **kwargs: Any) -> None:
- # `clean()` isn't called by plain `.save()`/`.objects.create()`, so this check has to be
- # always-on here too — otherwise a direct ORM write (not going through a form/serializer)
- # could silently persist a cross-organization IdP link.
- errors = self._validate_identity_provider_config_organization()
- if errors:
- raise ValidationError(errors)
-
- with transaction.atomic():
- super().save(*args, **kwargs)
- if self.identity_provider_config_id is None:
- return
-
- LinkedIdentityProviderConfig.objects.get_or_create(
- organization_domain=self,
- identity_provider_config_id=self.identity_provider_config_id,
- )
-
@property
def is_verified(self) -> bool:
"""
@@ -340,34 +314,30 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):
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()
-
- @property
- def 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 self.idp_config.has_saml
+ def identity_provider_configs(self) -> models.QuerySet[IdentityProviderConfig]:
+ if self._state.adding:
+ return IdentityProviderConfig.objects.none()
+ return (
+ IdentityProviderConfig.objects.filter(organization_id=self.organization_id)
+ .annotate(
+ is_explicitly_linked=models.Exists(
+ LinkedIdentityProviderConfig.objects.filter(
+ organization_domain=self, identity_provider_config=models.OuterRef("pk")
+ )
+ )
+ )
+ .filter(models.Q(is_explicitly_linked=True) | models.Q(domain_scope=DomainScope.ALL))
+ .order_by("-is_explicitly_linked", "created_at", "id")
+ )
- @property
- def has_scim(self) -> bool:
- """
- Returns whether SCIM is configured and enabled for this domain.
- """
- return self.idp_config.has_scim
+ def identity_provider_configs_for_scope(self, config_scope: str) -> models.QuerySet[IdentityProviderConfig]:
+ return self.identity_provider_configs.filter(
+ models.Q(config_scope=config_scope) | models.Q(config_scope__isnull=True)
+ )
@property
- def has_id_jag(self) -> bool:
- """
- Returns whether ID-JAG (XAA) is configured for this domain.
- """
- return self.idp_config.has_id_jag
+ def saml_identity_provider_configs(self) -> models.QuerySet[IdentityProviderConfig]:
+ return self.identity_provider_configs_for_scope(ConfigScope.SAML).filter(saml_configured_q())
def _complete_verification(self) -> tuple["OrganizationDomain", bool]:
self.last_verification_retry = None
@@ -391,15 +361,3 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):
self.last_verification_retry = timezone.now()
self.save()
return (self, False)
-
-
-@receiver(post_delete, sender=OrganizationDomain)
-def delete_orphaned_identity_provider_config(
- sender: type[OrganizationDomain], instance: OrganizationDomain, **kwargs: Any
-) -> None:
- """
- Note: This is temporary. In the future IDP configs will be explicitly managed in the UI. However, they are currently implicitly
- managed by their relationship to the org domains so we need to make sure they get cleaned up when all linked org domains are deleted
- """
- if instance.identity_provider_config_id is not None:
- IdentityProviderConfig.objects.filter(pk=instance.identity_provider_config_id, domains__isnull=True).delete()
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index adcaefe24c40..c8084c1f2dcb 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -59,7 +59,6 @@ post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membersh
post_delete:posthog.models.organization.clean_up_event_streams_on_membership_removal
post_delete:posthog.models.organization.pause_loops_on_membership_removal
post_delete:posthog.models.organization.sync_billing_on_membership_removal
-post_delete:posthog.models.organization_domain.delete_orphaned_identity_provider_config
post_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_delete
post_delete:posthog.models.remote_config.product_tour_deleted
post_delete:posthog.models.remote_config.push_integration_changed
diff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.py
index 2f3c39184aac..ab5fd6c6e198 100644
--- a/posthog/test/test_identity_provider_config.py
+++ b/posthog/test/test_identity_provider_config.py
@@ -1,193 +1,116 @@
import uuid
-import pytest
from posthog.test.base import BaseTest
-from django.core.exceptions import ValidationError
+from parameterized import parameterized
+from posthog.constants import AvailableFeature
from posthog.models import IdentityProviderConfig, LinkedIdentityProviderConfig, Organization, OrganizationDomain
-
-# Legacy `OrganizationDomain` columns that mirror fields on `IdentityProviderConfig`. Test-only:
-# used to build underscore-prefixed kwargs and to guard the two models' field shapes against drift.
-_LEGACY_IDP_FIELDS: tuple[str, ...] = (
- "saml_entity_id",
- "saml_acs_url",
- "saml_x509_cert",
- "scim_enabled",
- "scim_bearer_token",
- "id_jag_issuer_url",
- "id_jag_jwks_url",
- "id_jag_allowed_clients",
-)
-
-
-def _prefix_idp_kwargs(kwargs: dict) -> dict:
- # The domain's legacy IdP columns are underscore-prefixed Python attributes; map the public names.
- return {(f"_{k}" if k in _LEGACY_IDP_FIELDS else k): v for k, v in kwargs.items()}
+from posthog.models.identity_provider_config import ConfigScope, DomainScope
class TestIdentityProviderConfig(BaseTest):
- def _create_domain(self, domain: str = "posthog.com", **kwargs) -> OrganizationDomain:
- return OrganizationDomain.objects.create(
- organization=self.organization, domain=domain, **_prefix_idp_kwargs(kwargs)
+ SAML_CONFIG = {
+ "saml_entity_id": "entity-id",
+ "saml_acs_url": "https://idp.example.com/acs",
+ "saml_x509_cert": "cert-contents",
+ }
+
+ def _create_domain(self, domain: str = "posthog.com") -> OrganizationDomain:
+ return OrganizationDomain.objects.create(organization=self.organization, domain=domain)
+
+ def _create_config(self, **kwargs: object) -> IdentityProviderConfig:
+ return IdentityProviderConfig.objects.create(organization=self.organization, **kwargs)
+
+ def _link(self, domain: OrganizationDomain, config: IdentityProviderConfig) -> None:
+ LinkedIdentityProviderConfig.objects.create(
+ organization_domain=domain,
+ identity_provider_config=config,
)
- def _create_linked_config(self, domain: OrganizationDomain, **config_kwargs) -> IdentityProviderConfig:
- config = IdentityProviderConfig.objects.create(organization=self.organization, **config_kwargs)
- domain.identity_provider_config = config
- domain.save()
- return config
-
- def test_creating_config_populates_uuid_identifiers(self):
- config = IdentityProviderConfig.objects.create(organization=self.organization)
+ def test_creating_config_populates_uuid_identifiers(self) -> None:
+ config = self._create_config()
assert uuid.UUID(str(config.saml_relay_state))
assert uuid.UUID(str(config.scim_slug))
assert config.saml_relay_state != config.scim_slug
- def test_creating_domain_with_idp_config_creates_link(self):
- config = IdentityProviderConfig.objects.create(organization=self.organization)
- identifiers = (str(config.saml_relay_state), str(config.scim_slug))
- domain = self._create_domain(identity_provider_config=config)
-
- assert LinkedIdentityProviderConfig.objects.filter(
- organization_domain=domain, identity_provider_config=config
- ).exists()
- config.refresh_from_db()
- assert (config.saml_relay_state, config.scim_slug) == identifiers
-
- def test_updating_domain_idp_config_creates_link(self):
- domain = self._create_domain()
- config = IdentityProviderConfig.objects.create(organization=self.organization)
- identifiers = (str(config.saml_relay_state), str(config.scim_slug))
- domain.identity_provider_config = config
- domain.save()
-
- assert LinkedIdentityProviderConfig.objects.filter(
- organization_domain=domain, identity_provider_config=config
- ).exists()
- config.refresh_from_db()
- assert (config.saml_relay_state, config.scim_slug) == identifiers
-
- def test_saving_legacy_idp_columns_does_not_create_or_link_config(self):
- # The domain<->config dual-write mirror has been removed: writing the legacy underscore
- # columns must no longer auto-create or link an IdentityProviderConfig.
- domain = self._create_domain(
- saml_entity_id="entity-id",
- saml_acs_url="https://idp.example.com/acs",
- saml_x509_cert="cert-contents",
+ def test_deprecated_domain_foreign_key_does_not_create_a_link(self) -> None:
+ config = self._create_config(**self.SAML_CONFIG)
+ domain = OrganizationDomain.objects.create(
+ organization=self.organization,
+ domain="posthog.com",
+ _identity_provider_config=config,
)
- domain.refresh_from_db()
- assert domain.identity_provider_config is None
- assert IdentityProviderConfig.objects.count() == 0
-
- def test_updating_linked_config_does_not_touch_legacy_domain_columns(self):
- # The reverse mirror (config -> domain) has been removed: updating a linked config must
- # not touch the domain's legacy columns anymore.
- domain = self._create_domain()
- config = self._create_linked_config(domain, saml_entity_id="entity-id")
-
- config.saml_entity_id = "new-entity-id"
- config.save()
-
- domain.refresh_from_db()
- assert domain._saml_entity_id is None
- def test_synced_fields_match_between_models(self):
- # Guard against the two models drifting apart. The domain stores these as underscore-prefixed
- # columns (with the original db_column), the config stores them under the plain name.
- for field in _LEGACY_IDP_FIELDS:
- domain_field = OrganizationDomain._meta.get_field(f"_{field}")
- config_field = IdentityProviderConfig._meta.get_field(field)
- assert domain_field.__class__ == config_field.__class__, field
- assert getattr(domain_field, "max_length", None) == getattr(config_field, "max_length", None), field
- assert getattr(domain_field, "db_column", None) == field, field
+ assert not LinkedIdentityProviderConfig.objects.filter(organization_domain=domain).exists()
+ assert domain.saml_identity_provider_configs.first() is None
- def test_deleting_domain_deletes_orphaned_config(self):
+ def test_deleting_domain_does_not_delete_config(self) -> None:
+ config = self._create_config()
domain = self._create_domain()
- config = self._create_linked_config(domain, saml_entity_id="entity-id")
+ self._link(domain, config)
domain.delete()
- assert not IdentityProviderConfig.objects.filter(pk=config.pk).exists()
- def test_deleting_domain_keeps_config_linked_to_another_domain(self):
- domain = self._create_domain()
- other_domain = self._create_domain(domain="other.posthog.com")
- config = self._create_linked_config(domain, saml_entity_id="entity-id")
- other_domain.identity_provider_config = config
- other_domain.save()
-
- domain.delete()
assert IdentityProviderConfig.objects.filter(pk=config.pk).exists()
- def test_cross_org_config_link_fails_validation(self):
- other_org = Organization.objects.create(name="Other")
- other_config = IdentityProviderConfig.objects.create(organization=other_org)
- domain = self._create_domain()
- domain.identity_provider_config = other_config
-
- with pytest.raises(ValidationError) as exc_info:
- domain.full_clean()
- assert "identity_provider_config" in exc_info.value.message_dict
-
- def test_cross_org_config_link_fails_on_direct_save(self):
- # `clean()`/`full_clean()` aren't invoked by plain `.save()`/`.objects.create()`, so the
- # cross-org guard must also be enforced from `save()` itself.
- other_org = Organization.objects.create(name="Other")
- other_config = IdentityProviderConfig.objects.create(organization=other_org)
+ @parameterized.expand([(None,), (DomainScope.SELECTED,)])
+ def test_selected_scope_only_resolves_explicit_links(self, domain_scope: str | None) -> None:
+ config = self._create_config(domain_scope=domain_scope)
+ linked_domain = self._create_domain()
+ unlinked_domain = self._create_domain("other.posthog.com")
+ self._link(linked_domain, config)
+
+ assert list(config.organization_domains) == [linked_domain]
+ assert list(linked_domain.identity_provider_configs) == [config]
+ assert list(unlinked_domain.identity_provider_configs) == []
+
+ def test_all_scope_resolves_every_domain_in_the_organization(self) -> None:
+ config = self._create_config(domain_scope=DomainScope.ALL, **self.SAML_CONFIG)
+ first_domain = self._create_domain()
+ second_domain = self._create_domain("other.posthog.com")
+ other_organization = Organization.objects.create(name="Other")
+ other_domain = OrganizationDomain.objects.create(organization=other_organization, domain="example.com")
+
+ assert set(config.organization_domains) == {first_domain, second_domain}
+ assert first_domain.saml_identity_provider_configs.first() == config
+ assert second_domain.saml_identity_provider_configs.first() == config
+ assert list(other_domain.identity_provider_configs) == []
+
+ def test_config_scope_selects_the_matching_config(self) -> None:
domain = self._create_domain()
- domain.identity_provider_config = other_config
-
- with pytest.raises(ValidationError) as exc_info:
- domain.save()
- assert "identity_provider_config" in exc_info.value.message_dict
-
- def test_cross_org_config_link_fails_on_create(self):
- other_org = Organization.objects.create(name="Other")
- other_config = IdentityProviderConfig.objects.create(organization=other_org)
+ saml_config = self._create_config(config_scope=ConfigScope.SAML, **self.SAML_CONFIG)
+ second_saml_config = self._create_config(config_scope=ConfigScope.SAML, **self.SAML_CONFIG)
+ xaa_config = self._create_config(
+ config_scope=ConfigScope.ID_JAG,
+ id_jag_issuer_url="https://idp.example.com",
+ )
+ self._link(domain, saml_config)
+ self._link(domain, second_saml_config)
+ self._link(domain, xaa_config)
- with pytest.raises(ValidationError) as exc_info:
- OrganizationDomain.objects.create(
- organization=self.organization, domain="posthog.com", identity_provider_config=other_config
- )
- assert "identity_provider_config" in exc_info.value.message_dict
+ assert list(domain.saml_identity_provider_configs) == [saml_config, second_saml_config]
+ assert list(domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG)) == [xaa_config]
- def test_dangling_config_link_fails_validation(self):
+ def test_explicit_config_takes_precedence_over_all_scope(self) -> None:
+ organization_config = self._create_config(domain_scope=DomainScope.ALL, **self.SAML_CONFIG)
+ selected_config = self._create_config(**self.SAML_CONFIG)
domain = self._create_domain()
- config = self._create_linked_config(domain)
- # Delete the row out from under the FK without nulling the link on the in-memory instance.
- IdentityProviderConfig.objects.filter(pk=config.pk).delete()
+ self._link(domain, selected_config)
- with pytest.raises(ValidationError) as exc_info:
- domain.full_clean()
- assert "identity_provider_config" in exc_info.value.message_dict
+ assert list(domain.identity_provider_configs) == [selected_config, organization_config]
+ assert domain.saml_identity_provider_configs.first() == selected_config
- def test_deleting_config_nulls_domain_link(self):
+ def test_saml_availability_resolves_through_join_table(self) -> None:
+ self.organization.available_product_features = [{"key": AvailableFeature.SAML, "name": "SAML"}]
+ self.organization.save()
+ config = self._create_config(**self.SAML_CONFIG)
domain = self._create_domain()
- config = self._create_linked_config(domain)
-
- config.delete()
- domain.refresh_from_db()
- assert domain.identity_provider_config is None
-
- def test_has_saml_reads_from_linked_config_not_legacy_domain_columns(self):
- domain = self._create_domain() # legacy columns stay empty throughout
- config = self._create_linked_config(
- domain,
- saml_entity_id="entity-id",
- saml_acs_url="https://idp.example.com/acs",
- saml_x509_cert="cert-contents",
- )
- assert domain.has_saml
+ domain._complete_verification()
+ self._link(domain, config)
- config.saml_entity_id = None
- config.save()
- domain.refresh_from_db()
- assert not domain.has_saml
+ assert OrganizationDomain.objects.get_is_saml_available_for_email("[email protected]")
- 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
+ LinkedIdentityProviderConfig.objects.filter(organization_domain=domain).delete()
+ assert not OrganizationDomain.objects.get_is_saml_available_for_email("[email protected]")
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7c6ba28cb670..c0b7b8077fe5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18353,6 +18353,20 @@ export namespace Schemas {
results: ConfigVersion[];
}
+ /**
+ * * `saml` - Saml
+ * * `scim` - Scim
+ * * `xaa` - Xaa
+ */
+ export type ConfigScopeEnum = typeof ConfigScopeEnum[keyof typeof ConfigScopeEnum];
+
+
+ export const ConfigScopeEnum = {
+ Saml: 'saml',
+ Scim: 'scim',
+ Xaa: 'xaa',
+ } as const;
+
/**
* * `posthog_code` - posthog_code
*/
@@ -28310,6 +28324,18 @@ export namespace Schemas {
version?: number | null;
}
+ /**
+ * * `all` - All
+ * * `selected` - Selected
+ */
+ export type DomainScopeEnum = typeof DomainScopeEnum[keyof typeof DomainScopeEnum];
+
+
+ export const DomainScopeEnum = {
+ All: 'all',
+ Selected: 'selected',
+ } as const;
+
export interface DraftCustomManifestRequest {
/** Optional human name of the API being connected (e.g. 'Acme CRM'). Used only to orient the model. */
source_name?: string;
@@ -44061,6 +44087,19 @@ export namespace Schemas {
* @maxLength 255
*/
name?: string;
+ /** Domains this configuration applies to. An unset value behaves like selected domains.
+ *
+ * * `all` - All
+ * * `selected` - Selected */
+ domain_scope?: DomainScopeEnum | BlankEnum | null;
+ /** Feature configured by this identity provider configuration.
+ *
+ * * `saml` - Saml
+ * * `scim` - Scim
+ * * `xaa` - Xaa */
+ config_scope?: ConfigScopeEnum | BlankEnum | null;
+ /** Organization domain IDs that this identity provider configuration applies to. */
+ organization_domain_ids?: string[];
readonly created_at: string;
readonly updated_at: string;
/** Whether SAML is fully configured on this config. */
@@ -50676,19 +50715,8 @@ export namespace Schemas {
jit_provisioning_enabled?: boolean;
/** @maxLength 28 */
sso_enforcement?: string;
- /** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */
- readonly has_saml: boolean;
- /** Returns whether SCIM is configured and enabled for this domain. */
- readonly has_scim: boolean;
/** @nullable */
readonly scim_base_url: string | null;
- /** Returns whether ID-JAG (XAA) is configured for this domain. */
- readonly has_id_jag: boolean;
- /**
- * 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 {
@@ -60560,6 +60588,19 @@ export namespace Schemas {
* @maxLength 255
*/
name?: string;
+ /** Domains this configuration applies to. An unset value behaves like selected domains.
+ *
+ * * `all` - All
+ * * `selected` - Selected */
+ domain_scope?: DomainScopeEnum | BlankEnum | null;
+ /** Feature configured by this identity provider configuration.
+ *
+ * * `saml` - Saml
+ * * `scim` - Scim
+ * * `xaa` - Xaa */
+ config_scope?: ConfigScopeEnum | BlankEnum | null;
+ /** Organization domain IDs that this identity provider configuration applies to. */
+ organization_domain_ids?: string[];
readonly created_at?: string;
readonly updated_at?: string;
/** Whether SAML is fully configured on this config. */
@@ -61608,19 +61649,8 @@ export namespace Schemas {
jit_provisioning_enabled?: boolean;
/** @maxLength 28 */
sso_enforcement?: string;
- /** Returns whether SAML is configured for the instance. Does not validate the user has the required license (that check is performed in other places). */
- readonly has_saml?: boolean;
- /** Returns whether SCIM is configured and enabled for this domain. */
- readonly has_scim?: boolean;
/** @nullable */
readonly scim_base_url?: string | null;
- /** Returns whether ID-JAG (XAA) is configured for this domain. */
- readonly has_id_jag?: boolean;
- /**
- * Linked IdP configuration (SAML/SCIM/XAA) that backs this domain. Must belong to the same organization.
- * @nullable
- */
- identity_provider_config?: string | null;
}
/**