:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore: decouple idp config from org domain model (#62762)
Reece Jones1862022f6453
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex a228b7b24fee..115502704a15 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -594,6 +594,7 @@ rules:regex: |(?x)(CIMDVerificationToken+ |IdentityProviderConfig|LegalDocument|OrganizationMembership|OrganizationDomain@@ -661,6 +662,7 @@ rules:regex: |(?x)(CIMDVerificationToken+ |IdentityProviderConfig|LegalDocument|OrganizationMembership|OrganizationDomaindiff --git a/posthog/admin/admins/identity_provider_config_admin.py b/posthog/admin/admins/identity_provider_config_admin.pynew file mode 100644index 000000000000..7673e1da17ef--- /dev/null+++ b/posthog/admin/admins/identity_provider_config_admin.py@@ -0,0 +1,46 @@+from django.contrib import admin+from django.urls import reverse+from django.utils.html import format_html++from posthog.models import IdentityProviderConfig++[email protected](IdentityProviderConfig)+class IdentityProviderConfigAdmin(admin.ModelAdmin):+ list_display = (+ "name",+ "organization_link",+ "saml_status",+ "scim_enabled",+ "id_jag_issuer_url",+ "created_at",+ )+ list_filter = ("scim_enabled",)+ search_fields = ("name", "organization__name", "domains__domain")+ readonly_fields = ("id", "created_at", "updated_at", "linked_domains")+ autocomplete_fields = ["organization"]+ fieldsets = (+ (None, {"fields": ("id", "organization", "name", "created_at", "updated_at", "linked_domains")}),+ ("SAML Configuration", {"fields": ("saml_entity_id", "saml_acs_url", "saml_x509_cert")}),+ ("SCIM Configuration", {"fields": ("scim_enabled", "scim_bearer_token")}),+ ("ID-JAG (XAA) Configuration", {"fields": ("id_jag_issuer_url", "id_jag_jwks_url", "id_jag_allowed_clients")}),+ )+ ordering = ("-created_at",)++ @admin.display(description="Organization", ordering="organization__name")+ def organization_link(self, obj):+ if obj.organization:+ url = reverse("admin:posthog_organization_change", args=[obj.organization.pk])+ return format_html('<a href="{}">{}</a>', url, obj.organization.name)+ return "-"++ @admin.display(description="SAML Status")+ def saml_status(self, obj):+ if obj.has_saml:+ return format_html('<span style="color: green;">✓ Configured</span>')+ return format_html('<span style="color: gray;">Not Configured</span>')++ @admin.display(description="Linked domains")+ def linked_domains(self, obj):+ domains = list(obj.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.pyindex 3bcd2d1f82e3..125bb708734e 100644--- a/posthog/admin/admins/organization_domain_admin.py+++ b/posthog/admin/admins/organization_domain_admin.py@@ -28,9 +28,9 @@ class OrganizationDomainAdmin(admin.ModelAdmin):"verification_challenge","last_verification_retry",)- autocomplete_fields = ["organization"]+ autocomplete_fields = ["organization", "identity_provider_config"]fieldsets = (- (None, {"fields": ("id", "organization", "domain")}),+ (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")}),diff --git a/posthog/management/commands/sync_identity_provider_configs.py b/posthog/management/commands/sync_identity_provider_configs.pynew file mode 100644index 000000000000..c987229e1464--- /dev/null+++ b/posthog/management/commands/sync_identity_provider_configs.py@@ -0,0 +1,62 @@+from collections import Counter+from typing import Any++from django.core.management.base import BaseCommand++import structlog++from posthog.models.identity_provider_config import sync_identity_provider_config_from_domain+from posthog.models.organization_domain import OrganizationDomain++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = (+ "Backfill and sync IdentityProviderConfig rows from OrganizationDomain (the current "+ "source of truth for SAML/SCIM/XAA settings). Creates a config for every domain with "+ "IdP settings and links it; re-running updates any drifted configs. Idempotent."+ )++ def add_arguments(self, parser) -> None:+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Report what would change without writing anything.",+ )+ parser.add_argument(+ "--organization-id",+ type=str,+ default=None,+ help="Only sync domains belonging to this organization ID.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ dry_run: bool = options["dry_run"]+ organization_id: str | None = options["organization_id"]++ queryset = OrganizationDomain.objects.select_related("identity_provider_config").order_by(+ "organization_id", "domain"+ )+ if organization_id:+ queryset = queryset.filter(organization_id=organization_id)++ counts: Counter[str] = Counter()+ for domain in queryset.iterator(chunk_size=500):+ action = sync_identity_provider_config_from_domain(domain, dry_run=dry_run)+ counts[action] += 1+ if action in ("created", "updated"):+ self.stdout.write(+ f"{'[DRY RUN] would have ' if dry_run else ''}{action}: domain={domain.domain} "+ f"organization={domain.organization_id} config={domain.identity_provider_config_id or '<new>'}"+ )++ total = sum(counts.values())+ prefix = "[DRY RUN] " if dry_run else ""+ self.stdout.write(+ self.style.SUCCESS(+ f"{prefix}Processed {total} domain(s): "+ f"{counts['created']} created, {counts['updated']} updated, "+ f"{counts['unchanged']} unchanged, {counts['skipped']} skipped (no IdP settings)"+ )+ )diff --git a/posthog/migrations/1226_identityproviderconfig_and_more.py b/posthog/migrations/1226_identityproviderconfig_and_more.pynew file mode 100644index 000000000000..71ec2cc76efc--- /dev/null+++ b/posthog/migrations/1226_identityproviderconfig_and_more.py@@ -0,0 +1,112 @@+# Generated by Django 5.2.14 on 2026-06-10 14:33++import django.db.models.deletion+import django.contrib.postgres.fields+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1225_team_llm_gateway_overspend_allowance_usd"),+ ]++ operations = [+ migrations.CreateModel(+ name="IdentityProviderConfig",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "name",+ models.CharField(+ blank=True,+ default="",+ help_text="Display name for this IdP configuration (e.g. 'Okta production').",+ max_length=255,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "saml_entity_id",+ models.CharField(blank=True, max_length=512, null=True),+ ),+ (+ "saml_acs_url",+ models.CharField(blank=True, max_length=512, null=True),+ ),+ ("saml_x509_cert", models.TextField(blank=True, null=True)),+ ("scim_enabled", models.BooleanField(default=False)),+ (+ "scim_bearer_token",+ models.CharField(+ blank=True,+ help_text="Hashed bearer token for SCIM authentication",+ max_length=255,+ null=True,+ ),+ ),+ (+ "id_jag_issuer_url",+ models.CharField(+ blank=True,+ help_text="Trusted IdP issuer URL for ID-JAG. Required to enable ID-JAG.",+ max_length=512,+ null=True,+ ),+ ),+ (+ "id_jag_jwks_url",+ models.CharField(+ blank=True,+ help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ max_length=512,+ null=True,+ ),+ ),+ (+ "id_jag_allowed_clients",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=256),+ blank=True,+ default=list,+ help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ null=True,+ size=None,+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="identity_provider_configs",+ to="posthog.organization",+ ),+ ),+ ],+ options={+ "verbose_name": "identity provider config",+ },+ ),+ migrations.AddField(+ model_name="organizationdomain",+ name="identity_provider_config",+ field=models.ForeignKey(+ blank=True,+ help_text="IdP configuration (SAML/SCIM/XAA) backing this domain.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="domains",+ to="posthog.identityproviderconfig",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 272a07911099..264b2eb06df5 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1225_team_llm_gateway_overspend_allowance_usd+1226_identityproviderconfig_and_morediff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex d57436384f00..51ec2ccb9f0c 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -38,6 +38,7 @@ from .group_usage_metric import GroupUsageMetricfrom .group_type_mapping import GroupTypeMappingfrom .host_definition import HostDefinitionfrom .health_issue import HealthIssue+from .identity_provider_config import IdentityProviderConfigfrom .instance_setting import InstanceSettingfrom .integration import Integrationfrom .integration_repository_cache import IntegrationRepositoryCacheEntry@@ -125,6 +126,7 @@ __all__ = ["GroupTypeMapping","HealthIssue","HostDefinition",+ "IdentityProviderConfig","InstanceSetting","Integration","IntegrationRepositoryCacheEntry",diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex e0cc6bcd8317..110b844f5e25 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -387,6 +387,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {"OrganizationDomain": ["organization","scim_provisioned_users",+ # Internal link to the IdP config mirror; the mirrored fields themselves are already logged+ "identity_provider_config",],"Subscription": [# Scheduler-derived field; keep it out of user-facing change diffs even when anotherdiff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.pynew file mode 100644index 000000000000..6d746bbf8c3a--- /dev/null+++ b/posthog/models/identity_provider_config.py@@ -0,0 +1,185 @@+from typing import TYPE_CHECKING, Any++from django.contrib.postgres.fields import ArrayField+from django.db import models++import structlog++from posthog.models.utils import UUIDModel++if TYPE_CHECKING:+ from posthog.models.organization_domain import OrganizationDomain++logger = structlog.get_logger(__name__)++# IdP-specific fields that are mirrored between `OrganizationDomain` (current source of+# truth) and `IdentityProviderConfig`. Used by the dual-write hook in+# `OrganizationDomain.save()` and the `sync_identity_provider_configs` management command.+IDP_CONFIG_SYNCED_FIELDS: tuple[str, ...] = (+ "saml_entity_id",+ "saml_acs_url",+ "saml_x509_cert",+ "scim_enabled",+ "scim_bearer_token",+ "id_jag_issuer_url",+ "id_jag_jwks_url",+ "id_jag_allowed_clients",+)+++class IdentityProviderConfig(UUIDModel):+ """+ Identity provider (IdP) configuration for an organization.++ 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.++ NOTE: While the migration to this model is in flight, `OrganizationDomain` remains the+ source of truth. Writes to a domain's IdP fields are mirrored here automatically by+ `OrganizationDomain.save()` (see `sync_identity_provider_config_from_domain`), so the+ data is consistent when reads are switched over.+ """++ organization = models.ForeignKey(+ "posthog.Organization", on_delete=models.CASCADE, related_name="identity_provider_configs"+ )+ name = models.CharField(+ max_length=255,+ blank=True,+ default="",+ help_text="Display name for this IdP configuration (e.g. 'Okta production').",+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ # ---- SAML attributes ----+ # Field shapes intentionally mirror `OrganizationDomain` (including nullability) so+ # values can be copied verbatim while domains remain the source of truth.+ saml_entity_id = models.CharField(max_length=512, blank=True, null=True)+ saml_acs_url = models.CharField(max_length=512, blank=True, null=True)+ saml_x509_cert = models.TextField(blank=True, null=True)++ # ---- SCIM attributes ----+ scim_enabled = models.BooleanField(default=False)+ scim_bearer_token = models.CharField(+ max_length=255, blank=True, null=True, help_text="Hashed bearer token for SCIM authentication"+ )++ # ---- ID-JAG (XAA) attributes ----+ id_jag_issuer_url = models.CharField(+ max_length=512,+ blank=True,+ null=True,+ help_text="Trusted IdP issuer URL for ID-JAG. Required to enable ID-JAG.",+ )+ # Defaults to `{id_jag_issuer_url}/.well-known/openid-configuration`.+ id_jag_jwks_url = models.CharField(+ max_length=512,+ blank=True,+ null=True,+ help_text="Override JWKS URL. Defaults to OIDC discovery on the issuer URL.",+ )+ id_jag_allowed_clients = ArrayField(+ models.CharField(max_length=256),+ default=list,+ blank=True,+ null=True,+ help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",+ )++ class Meta:+ verbose_name = "identity provider config"++ def __str__(self) -> str:+ return self.name or str(self.id)++ @property+ def has_saml(self) -> bool:+ """+ Returns whether SAML is configured. Does not validate the organization has the required license.+ """+ return bool(self.saml_entity_id) and bool(self.saml_acs_url) and bool(self.saml_x509_cert)++ @property+ def has_scim(self) -> bool:+ """+ Returns whether SCIM is configured and enabled.+ """+ return self.scim_enabled and bool(self.scim_bearer_token)++ @property+ def has_id_jag(self) -> bool:+ """+ Returns whether ID-JAG (XAA) is configured.+ """+ return bool(self.id_jag_issuer_url)+++def _domain_has_any_idp_config(domain: "OrganizationDomain") -> bool:+ return (+ domain.has_saml+ or domain.scim_enabled+ or bool(domain.scim_bearer_token)+ or bool(domain.id_jag_issuer_url)+ or bool(domain.id_jag_jwks_url)+ or bool(domain.id_jag_allowed_clients)+ )+++def sync_identity_provider_config_from_domain(domain: "OrganizationDomain", dry_run: bool = False) -> str:+ """+ Mirror a domain's IdP fields into its linked `IdentityProviderConfig`, creating and+ linking one if needed. `OrganizationDomain` is the source of truth until reads are+ switched over to the config model.++ Returns the action taken: "created", "updated", "unchanged", or "skipped" (domain has+ no IdP configuration and no linked config).+ """+ # Imported here to avoid a circular import with `organization_domain`, which calls+ # this function from `save()`.+ from posthog.models.organization_domain import OrganizationDomain # noqa: PLC0415++ config = domain.identity_provider_config++ # Fail closed on a cross-org link: never mirror one organization's IdP settings into+ # another organization's config. A linked config must belong to the same organization+ # as the domain, otherwise saving the domain (or the backfill command) would silently+ # overwrite the other org's SAML/SCIM/XAA settings — an authentication-bypass vector.+ if config is not None and config.organization_id != domain.organization_id:+ raise ValueError(+ f"OrganizationDomain {domain.pk} (organization {domain.organization_id}) is linked to "+ f"IdentityProviderConfig {config.pk} owned by a different organization "+ f"({config.organization_id}); refusing to mirror IdP settings across organizations."+ )++ if config is None:+ if not _domain_has_any_idp_config(domain):+ return "skipped"+ if dry_run:+ return "created"+ config = IdentityProviderConfig.objects.create(+ organization_id=domain.organization_id,+ name=domain.domain,+ **{field: getattr(domain, field) for field in IDP_CONFIG_SYNCED_FIELDS},+ )+ # Link via a queryset update to avoid recursing into `OrganizationDomain.save()`+ # (and to avoid emitting a second activity log entry for the same write).+ OrganizationDomain.objects.filter(pk=domain.pk).update(identity_provider_config=config)+ domain.identity_provider_config = config+ return "created"++ changed_fields: dict[str, Any] = {+ field: getattr(domain, field)+ for field in IDP_CONFIG_SYNCED_FIELDS+ if getattr(config, field) != getattr(domain, field)+ }+ if not changed_fields:+ return "unchanged"+ if dry_run:+ return "updated"+ for field, value in changed_fields.items():+ setattr(config, field, value)+ config.save(update_fields=[*changed_fields.keys(), "updated_at"])+ return "updated"diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.pyindex 6477e22e1c1e..1b8f34a3ffe6 100644--- a/posthog/models/organization_domain.py+++ b/posthog/models/organization_domain.py@@ -2,7 +2,7 @@ import secretsfrom typing import Optionalfrom django.contrib.postgres.fields import ArrayField-from django.db import models+from django.db import models, transactionfrom django.utils import timezoneimport structlog@@ -11,6 +11,7 @@ import dns.resolverfrom posthog.constants import AvailableFeaturefrom posthog.models import Organizationfrom posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.identity_provider_config import IdentityProviderConfig, sync_identity_provider_config_from_domainfrom posthog.models.utils import UUIDTModelfrom posthog.utils import get_instance_available_sso_providers@@ -215,9 +216,30 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",)+ # ---- IdP config (new home for SAML/SCIM/ID-JAG settings) ----+ # Temporary foreign key to the backing `IdentityProviderConfig` model. Eventually+ # will be removed once the migration is complete.+ # The IdP fields above are being migrated to `IdentityProviderConfig`, which can be+ # shared by multiple domains. Until reads are switched over, this model remains the+ # source of truth and `save()` mirrors the fields into the linked config.+ 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.",+ )+class Meta:verbose_name = "domain"+ def save(self, *args, **kwargs) -> None:+ # Atomic so the domain write and the mirrored IdP config write cannot diverge.+ with transaction.atomic():+ super().save(*args, **kwargs)+ sync_identity_provider_config_from_domain(self)+def clean(self) -> None:# Validate ID-JAG IdP URLs at write time as a UX guard against the# common admin mistake of pointing them at an internal/loopback/@@ -239,6 +261,20 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):allowed, reason = is_url_allowed(url)if not allowed:errors[field_name] = f"URL is not allowed: {reason}"+ # A linked IdP config must belong to the same organization as the domain. Without+ # this, an admin could link a domain to another org's config and have its IdP+ # settings silently overwritten on save (see `sync_identity_provider_config_from_domain`).+ if self.identity_provider_config_id is not None:+ try:+ config = self.identity_provider_config+ 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."+ )if errors:raise ValidationError(errors)super().clean()diff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.pynew file mode 100644index 000000000000..57acbd063bdb--- /dev/null+++ b/posthog/test/test_identity_provider_config.py@@ -0,0 +1,226 @@+import pytest+from posthog.test.base import BaseTest++from django.core.exceptions import ValidationError+from django.core.management import call_command++from posthog.models import IdentityProviderConfig, Organization, OrganizationDomain+from posthog.models.identity_provider_config import IDP_CONFIG_SYNCED_FIELDS, sync_identity_provider_config_from_domain++from ee.api.scim.utils import disable_scim_for_domain, enable_scim_for_domain, regenerate_scim_token+++class TestIdentityProviderConfigSync(BaseTest):+ def _create_domain(self, domain: str = "posthog.com", **kwargs) -> OrganizationDomain:+ return OrganizationDomain.objects.create(organization=self.organization, domain=domain, **kwargs)++ def test_domain_without_idp_settings_does_not_create_config(self):+ domain = self._create_domain()+ assert domain.identity_provider_config is None+ assert IdentityProviderConfig.objects.count() == 0++ def test_saving_saml_settings_creates_and_links_config(self):+ domain = self._create_domain()+ domain.saml_entity_id = "entity-id"+ domain.saml_acs_url = "https://idp.example.com/acs"+ domain.saml_x509_cert = "cert-contents"+ domain.save()++ domain.refresh_from_db()+ config = domain.identity_provider_config+ assert config is not None+ assert config.organization == self.organization+ assert config.name == "posthog.com"+ assert config.saml_entity_id == "entity-id"+ assert config.saml_acs_url == "https://idp.example.com/acs"+ assert config.saml_x509_cert == "cert-contents"+ assert config.has_saml++ def test_updating_domain_updates_linked_config(self):+ domain = self._create_domain(+ saml_entity_id="entity-id",+ saml_acs_url="https://idp.example.com/acs",+ saml_x509_cert="cert-contents",+ )+ config = domain.identity_provider_config+ assert config is not None++ domain.saml_entity_id = "new-entity-id"+ domain.id_jag_issuer_url = "https://issuer.example.com"+ domain.save()++ config.refresh_from_db()+ assert config.saml_entity_id == "new-entity-id"+ assert config.id_jag_issuer_url == "https://issuer.example.com"+ # Still only one config — updates don't create new rows+ assert IdentityProviderConfig.objects.count() == 1++ def test_clearing_idp_settings_clears_linked_config(self):+ domain = self._create_domain(+ saml_entity_id="entity-id",+ saml_acs_url="https://idp.example.com/acs",+ saml_x509_cert="cert-contents",+ )+ domain.saml_entity_id = None+ domain.saml_acs_url = None+ domain.saml_x509_cert = None+ domain.save()++ config = domain.identity_provider_config+ assert config is not None+ config.refresh_from_db()+ assert not config.has_saml+ assert config.saml_entity_id is None++ def test_scim_utils_dual_write_to_config(self):+ domain = self._create_domain()++ enable_scim_for_domain(domain)+ domain.refresh_from_db()+ config = domain.identity_provider_config+ assert config is not None+ assert config.scim_enabled is True+ assert config.scim_bearer_token == domain.scim_bearer_token+ assert config.has_scim++ regenerate_scim_token(domain)+ config.refresh_from_db()+ assert config.scim_bearer_token == domain.scim_bearer_token++ disable_scim_for_domain(domain)+ config.refresh_from_db()+ assert config.scim_enabled is False++ def test_sync_is_idempotent(self):+ domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")+ assert sync_identity_provider_config_from_domain(domain) == "unchanged"+ assert IdentityProviderConfig.objects.count() == 1++ def test_synced_fields_match_between_models(self):+ # Guard against the two models drifting apart while domains remain the source of truth+ for field in IDP_CONFIG_SYNCED_FIELDS:+ domain_field = OrganizationDomain._meta.get_field(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++ def test_deleting_domain_keeps_config(self):+ domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")+ config_id = domain.identity_provider_config_id+ domain.delete()+ assert config_id is not None+ assert IdentityProviderConfig.objects.filter(pk=config_id).exists()++ def test_cross_org_config_link_is_rejected(self):+ other_org = Organization.objects.create(name="Other")+ other_config = IdentityProviderConfig.objects.create(organization=other_org, saml_entity_id="other-entity")+ domain = self._create_domain()+ domain.identity_provider_config = other_config++ with pytest.raises(ValueError, match="different organization"):+ domain.save()++ # The cross-org config's settings must remain untouched+ other_config.refresh_from_db()+ assert other_config.saml_entity_id == "other-entity"++ 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_dangling_config_link_fails_validation(self):+ domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")+ config_id = domain.identity_provider_config_id+ assert config_id is not None+ # Delete the row out from under the FK without nulling the link+ IdentityProviderConfig.objects.filter(pk=config_id).delete()++ with pytest.raises(ValidationError) as exc_info:+ domain.full_clean()+ assert "identity_provider_config" in exc_info.value.message_dict++ def test_deleting_config_nulls_domain_link(self):+ domain = self._create_domain(id_jag_issuer_url="https://issuer.example.com")+ assert domain.identity_provider_config is not None+ domain.identity_provider_config.delete()+ domain.refresh_from_db()+ assert domain.identity_provider_config is None+++class TestSyncIdentityProviderConfigsCommand(BaseTest):+ def _create_unsynced_domain(self, domain: str, **kwargs) -> OrganizationDomain:+ # Bypass `OrganizationDomain.save()` dual-write to simulate pre-existing rows+ instance = OrganizationDomain(organization=self.organization, domain=domain, **kwargs)+ instance.save()+ OrganizationDomain.objects.filter(pk=instance.pk).update(identity_provider_config=None)+ IdentityProviderConfig.objects.all().delete()+ instance.refresh_from_db()+ return instance++ def test_command_backfills_configs(self):+ saml_domain = self._create_unsynced_domain(+ "saml.example.com",+ saml_entity_id="entity-id",+ saml_acs_url="https://idp.example.com/acs",+ saml_x509_cert="cert-contents",+ )+ plain_domain = self._create_unsynced_domain("plain.example.com")++ call_command("sync_identity_provider_configs")++ saml_domain.refresh_from_db()+ plain_domain.refresh_from_db()+ assert saml_domain.identity_provider_config is not None+ assert saml_domain.identity_provider_config.saml_entity_id == "entity-id"+ assert plain_domain.identity_provider_config is None+ assert IdentityProviderConfig.objects.count() == 1++ def test_command_resyncs_drifted_configs(self):+ domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="saml.example.com",+ id_jag_issuer_url="https://issuer.example.com",+ )+ config = domain.identity_provider_config+ assert config is not None+ # Simulate drift in the mirror+ IdentityProviderConfig.objects.filter(pk=config.pk).update(id_jag_issuer_url="https://stale.example.com")++ call_command("sync_identity_provider_configs")++ config.refresh_from_db()+ assert config.id_jag_issuer_url == "https://issuer.example.com"++ def test_command_dry_run_makes_no_changes(self):+ self._create_unsynced_domain(+ "saml.example.com",+ saml_entity_id="entity-id",+ saml_acs_url="https://idp.example.com/acs",+ saml_x509_cert="cert-contents",+ )++ call_command("sync_identity_provider_configs", "--dry-run")++ assert IdentityProviderConfig.objects.count() == 0++ def test_command_filters_by_organization(self):+ other_org = Organization.objects.create(name="Other")+ other_domain = OrganizationDomain.objects.create(+ organization=other_org, domain="other.example.com", id_jag_issuer_url="https://issuer.example.com"+ )+ # `_create_unsynced_domain` wipes all configs, leaving both domains unsynced+ domain = self._create_unsynced_domain("mine.example.com", id_jag_issuer_url="https://issuer.example.com")++ call_command("sync_identity_provider_configs", f"--organization-id={self.organization.id}")++ domain.refresh_from_db()+ other_domain.refresh_from_db()+ assert domain.identity_provider_config is not None+ assert other_domain.identity_provider_config is None+ assert IdentityProviderConfig.objects.count() == 1