: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
fix: delete orphaned idp configs (#74822)
Reece Jones85b8a059db87
diff --git a/posthog/migrations/1286_cleanup_orphaned_identity_provider_configs.py b/posthog/migrations/1286_cleanup_orphaned_identity_provider_configs.pynew file mode 100644index 000000000000..4abcdf6af4d8--- /dev/null+++ b/posthog/migrations/1286_cleanup_orphaned_identity_provider_configs.py@@ -0,0 +1,29 @@+from datetime import timedelta++from django.db import migrations+from django.utils import timezone++# A config and its domain link are created in two separate requests, so a valid but not-yet-linked+# config can exist while this migration runs. Only sweep configs old enough that no in-flight request+# could still be about to link them.+UNLINKED_GRACE_PERIOD = timedelta(days=1)+++def delete_orphaned_identity_provider_configs(apps, schema_editor):+ IdentityProviderConfig = apps.get_model("posthog", "IdentityProviderConfig")+ IdentityProviderConfig.objects.filter(+ domains__isnull=True, created_at__lt=timezone.now() - UNLINKED_GRACE_PERIOD+ ).delete()+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1285_drop_desktop_file_system"),+ ]++ operations = [+ migrations.RunPython(+ delete_orphaned_identity_provider_configs,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 6ead612b325b..0d28bac85434 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1285_drop_desktop_file_system+1286_cleanup_orphaned_identity_provider_configsdiff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.pyindex da0f31cbb6ee..76937120922e 100644--- a/posthog/models/organization_domain.py+++ b/posthog/models/organization_domain.py@@ -4,6 +4,8 @@ from typing import TYPE_CHECKING, Any, Optionalfrom django.contrib.postgres.fields import ArrayFieldfrom django.core.exceptions import ValidationErrorfrom django.db import models+from django.db.models.signals import post_delete+from django.dispatch import receiverfrom django.utils import timezoneimport structlog@@ -379,3 +381,15 @@ 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/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 94a4dc02f6f2..1a3028a3a55b 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -54,6 +54,7 @@ post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membershpost_delete:posthog.models.organization.clean_up_event_streams_on_membership_removalpost_delete:posthog.models.organization.pause_loops_on_membership_removalpost_delete:posthog.models.organization.sync_billing_on_membership_removal+post_delete:posthog.models.organization_domain.delete_orphaned_identity_provider_configpost_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_deletepost_delete:posthog.models.remote_config.product_tour_deletedpost_delete:posthog.models.remote_config.site_function_changeddiff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.pyindex 2e20bc7e94cf..5aa5fc7f46da 100644--- a/posthog/test/test_identity_provider_config.py+++ b/posthog/test/test_identity_provider_config.py@@ -70,10 +70,20 @@ class TestIdentityProviderConfig(BaseTest):assert getattr(domain_field, "max_length", None) == getattr(config_field, "max_length", None), fieldassert getattr(domain_field, "db_column", None) == field, field- def test_deleting_domain_keeps_config(self):+ def test_deleting_domain_deletes_orphaned_config(self):domain = self._create_domain()config = self._create_linked_config(domain, saml_entity_id="entity-id")+ 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()diff --git a/posthog/test/test_migration_1286.py b/posthog/test/test_migration_1286.pynew file mode 100644index 000000000000..1ff43a191a88--- /dev/null+++ b/posthog/test/test_migration_1286.py@@ -0,0 +1,43 @@+from importlib import import_module++from posthog.test.base import BaseTest++from django.apps import apps+from django.utils import timezone++from posthog.models import IdentityProviderConfig, OrganizationDomain++migration = import_module("posthog.migrations.1286_cleanup_orphaned_identity_provider_configs")+++class TestCleanupOrphanedIdentityProviderConfigs(BaseTest):+ def _backdate(self, config: IdentityProviderConfig) -> None:+ # created_at is auto_now_add, so it has to be rewritten with an update+ IdentityProviderConfig.objects.filter(pk=config.pk).update(+ created_at=timezone.now() - migration.UNLINKED_GRACE_PERIOD * 2+ )++ def test_migration_deletes_only_configs_without_domains(self):+ orphaned_config = IdentityProviderConfig.objects.create(organization=self.organization)+ linked_config = IdentityProviderConfig.objects.create(organization=self.organization)+ self._backdate(orphaned_config)+ self._backdate(linked_config)+ OrganizationDomain.objects.create(+ organization=self.organization,+ domain="linked.posthog.com",+ identity_provider_config=linked_config,+ )++ migration.delete_orphaned_identity_provider_configs(apps, None)++ assert not IdentityProviderConfig.objects.filter(pk=orphaned_config.pk).exists()+ assert IdentityProviderConfig.objects.filter(pk=linked_config.pk).exists()++ def test_migration_keeps_recently_created_unlinked_configs(self):+ # A config created via the standalone create endpoint may not be linked to a domain yet, since+ # the frontend links it in a follow-up request+ in_progress_config = IdentityProviderConfig.objects.create(organization=self.organization)++ migration.delete_orphaned_identity_provider_configs(apps, None)++ assert IdentityProviderConfig.objects.filter(pk=in_progress_config.pk).exists()