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.

fix(workflows): clean up SES identity on every deletion path (#68200)

Harley Alexanderc9370b406978
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 9a38c61411a7..7b87374e49b5 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -976,17 +976,6 @@ class IntegrationViewSet(
stripe_integration.clear_posthog_secrets()
except Exception as e:
capture_exception(e)
- elif instance.kind == "email" and instance.config.get("provider") == "ses":
- domain = instance.config.get("domain")
- if (
- domain
- and not Integration.objects.filter(kind="email", config__domain=domain).exclude(pk=instance.pk).exists()
- ):
- try:
- EmailIntegration(instance).ses_provider.delete_identity(domain)
- except Exception as e:
- capture_exception(e)
-
if instance.kind == "github" and instance.integration_id:
# Team integrations own the installation; personal ones are subordinate. When the
# last team integration for an installation is removed, tear it down everywhere:
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 6d9909765e7a..77db5aea3ec4 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -21,6 +21,7 @@ if TYPE_CHECKING:
from django.conf import settings
from django.db import models, transaction
from django.db.models import Q
+from django.dispatch import receiver
from django.http import HttpRequest
from django.utils import timezone
@@ -3927,3 +3928,22 @@ class PostgreSQLIntegration:
else:
# Preserve the default ssl_root_cert if one was not provided
return TLS(ssl_mode=self.integration.config["ssl_mode"])
+
+
+@receiver(models.signals.post_delete, sender=Integration)
+def cleanup_ses_identity_on_integration_delete(sender: Any, instance: Integration, **kwargs: Any) -> None:
+ # A post_delete signal (rather than viewset perform_destroy) so SES identities are
+ # also cleaned up when integrations die via cascade, e.g. project or org deletion.
+ # Leaving the identity behind permanently blocks the domain for every other
+ # organization via the foreign-tenant guard in SESProvider.create_email_domain.
+ if instance.kind != "email" or instance.config.get("provider") != "ses":
+ return
+ domain = instance.config.get("domain")
+ if not domain:
+ return
+
+ from posthog.tasks.integrations import (
+ delete_ses_identity_if_unused, # noqa: PLC0415 - breaks circular import with the tasks module
+ )
+
+ transaction.on_commit(lambda: delete_ses_identity_if_unused.delay(domain))
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 9238f8925527..f2472bc478bf 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -2671,7 +2671,8 @@ class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):
created_by=self.user,
)
- IntegrationViewSet().perform_destroy(integration)
+ with self.captureOnCommitCallbacks(execute=True):
+ IntegrationViewSet().perform_destroy(integration)
mock_delete_identity.assert_called_once_with("partner.com")
assert not Integration.objects.filter(pk=integration.pk).exists()
@@ -2698,7 +2699,8 @@ class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):
created_by=self.user,
)
- IntegrationViewSet().perform_destroy(integration)
+ with self.captureOnCommitCallbacks(execute=True):
+ IntegrationViewSet().perform_destroy(integration)
assert mock_delete_identity.call_count == 0
@@ -2741,7 +2743,8 @@ class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):
created_by=self.user,
)
with patch("products.workflows.backend.providers.SESProvider.delete_identity") as mock_delete:
- IntegrationViewSet().perform_destroy(integration_a)
+ with self.captureOnCommitCallbacks(execute=True):
+ IntegrationViewSet().perform_destroy(integration_a)
mock_delete.assert_called_once_with("partner.com")
integration_b = EmailIntegration.create_native_integration(
@@ -2773,6 +2776,38 @@ class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):
assert provider.sts_client.get_caller_identity.call_count == 1
+class TestEmailIntegrationSESCleanupOnDelete(BaseTest):
+ def _create_email_integration(self, email: str, team_id: int, organization_id: str) -> Integration:
+ with patch("products.workflows.backend.providers.SESProvider.create_email_domain"):
+ return EmailIntegration.create_native_integration(
+ {"email": email, "name": "Test"},
+ team_id=team_id,
+ organization_id=organization_id,
+ created_by=self.user,
+ )
+
+ @patch("products.workflows.backend.providers.SESProvider.delete_identity")
+ def test_team_cascade_delete_cleans_up_ses_identity(self, mock_delete_identity):
+ team = Team.objects.create(organization=self.organization, name="doomed team")
+ self._create_email_integration("[email protected]", team.id, str(self.organization.id))
+
+ with self.captureOnCommitCallbacks(execute=True):
+ team.delete()
+
+ mock_delete_identity.assert_called_once_with("partner.com")
+
+ @patch("products.workflows.backend.providers.SESProvider.delete_identity")
+ def test_cascade_delete_skips_ses_cleanup_while_domain_still_in_use(self, mock_delete_identity):
+ team = Team.objects.create(organization=self.organization, name="doomed team")
+ self._create_email_integration("[email protected]", team.id, str(self.organization.id))
+ self._create_email_integration("[email protected]", self.team.id, str(self.organization.id))
+
+ with self.captureOnCommitCallbacks(execute=True):
+ team.delete()
+
+ mock_delete_identity.assert_not_called()
+
+
class TestGitLabIntegrationSSRFProtection:
"""Test SSRF protections in GitLabIntegration."""
diff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.py
index fe7d16343665..df3863c68822 100644
--- a/posthog/tasks/integrations.py
+++ b/posthog/tasks/integrations.py
@@ -9,6 +9,8 @@ from posthog.models.integration import (
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
+from products.workflows.backend.providers import SESProvider
+
@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)
@skip_team_scope_audit
@@ -84,6 +86,25 @@ def refresh_integration(id: int) -> int:
return 0
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.INTEGRATIONS.value,
+ autoretry_for=(Exception,),
+ retry_backoff=True,
+ max_retries=5,
+)
+@skip_team_scope_audit
+def delete_ses_identity_if_unused(domain: str) -> None:
+ from posthog.models.integration import Integration
+
+ # Re-check at execution time: the domain may have been re-added since this
+ # task was enqueued, and deleting the identity would break the new sender.
+ if Integration.objects.filter(kind="email", config__domain=domain).exists():
+ return
+
+ SESProvider().delete_identity(domain)
+
+
@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)
@skip_team_scope_audit
def push_vercel_secrets(team_id: int) -> None:
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index a6ca0a287fe5..0c0ba250fc88 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -70,6 +70,7 @@
'posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_without_cohorts_cache_task',
'posthog.tasks.hypercache_verification.verify_and_fix_flags_cache_task',
'posthog.tasks.hypercache_verification.verify_and_fix_team_metadata_cache_task',
+ 'posthog.tasks.integrations.delete_ses_identity_if_unused',
'posthog.tasks.integrations.push_vercel_secrets',
'posthog.tasks.integrations.refresh_integration',
'posthog.tasks.integrations.refresh_integrations',
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 4d3fd586bb09..ba2a1cfc5bcd 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -42,6 +42,7 @@ post_delete:posthog.caching.organization_serializer_cache._connect_invalidation.
post_delete:posthog.models.event_ingestion_restriction_config.delete_redis_cache_with_config
post_delete:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__init_subclass__.<locals>._file_system_post_delete
post_delete:posthog.models.file_system.file_system_view_log._drop_view_logs_when_file_deleted
+post_delete:posthog.models.integration.cleanup_ses_identity_on_integration_delete
post_delete:posthog.models.oauth._block_cimd_url_on_application_delete
post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removal
post_delete:posthog.models.organization.sync_billing_on_membership_removal
diff --git a/products/workflows/backend/management/commands/delete_stale_ses_identity.py b/products/workflows/backend/management/commands/delete_stale_ses_identity.py
new file mode 100644
index 000000000000..388f837b98ac
--- /dev/null
+++ b/products/workflows/backend/management/commands/delete_stale_ses_identity.py
@@ -0,0 +1,31 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.models.integration import Integration
+
+from products.workflows.backend.providers import SESProvider
+
+
+class Command(BaseCommand):
+ help = (
+ "Delete an SES email identity that no longer has a matching email integration. "
+ "Support remediation for domains orphaned in SES (e.g. the owning project or org "
+ "was deleted before identity cleanup existed), which blocks any other organization "
+ "from verifying the domain via the foreign-tenant guard."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("domain", type=str, help="The email domain whose SES identity should be deleted")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ domain = options["domain"].lower()
+ in_use = Integration.objects.filter(kind="email", config__domain=domain)
+ if in_use.exists():
+ team_ids = sorted(in_use.values_list("team_id", flat=True))
+ raise CommandError(
+ f"Refusing to delete: domain {domain} is still used by email integration(s) on team(s) {team_ids}"
+ )
+
+ SESProvider().delete_identity(domain)
+ self.stdout.write(self.style.SUCCESS(f"Deleted SES identity for {domain}"))
diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.py
index 2142503b08a4..4dfcdd69871a 100644
--- a/products/workflows/backend/providers/ses.py
+++ b/products/workflows/backend/providers/ses.py
@@ -339,9 +339,17 @@ class SESProvider:
def delete_identity(self, identity: str):
"""
- Delete an identity from SES
+ Delete an identity from SES, removing its tenant associations first
+ (SES refuses to delete an identity that still has tenant associations)
"""
try:
+ arn = self._identity_arn(identity)
+ for tenant_name in self._list_identity_tenants(identity):
+ try:
+ self.ses_v2_client.delete_tenant_resource_association(TenantName=tenant_name, ResourceArn=arn)
+ except ClientError as e:
+ if e.response["Error"]["Code"] != "NotFoundException":
+ raise
self.ses_client.delete_identity(Identity=identity)
logger.info(f"Identity {identity} deleted from SES")
except (ClientError, BotoCoreError) as e:
diff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.py
index 62c16c4afb17..a7f9ffd54558 100644
--- a/products/workflows/backend/test/test_ses_provider.py
+++ b/products/workflows/backend/test/test_ses_provider.py
@@ -2,7 +2,7 @@ from typing import Optional
import pytest
from unittest import TestCase
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
from django.test import override_settings
@@ -388,3 +388,30 @@ class TestSESResponseShapeContract(TestCase):
}
tenants = provider._list_identity_tenants("test.posthog.com")
assert tenants == {"team-1", "team-2"}
+
+ def test_delete_identity_removes_tenant_associations_first(self):
+ # SES rejects DeleteIdentity while tenant associations exist, so the
+ # associations must be removed before the identity delete is attempted.
+ provider = SESProvider()
+ with (
+ override_settings(SES_REGION="us-east-1"),
+ patch.object(provider.sts_client, "get_caller_identity", return_value={"Account": "123456789012"}),
+ patch.object(
+ provider.ses_v2_client,
+ "list_resource_tenants",
+ return_value={"ResourceTenants": [{"TenantName": "team-1", "TenantId": "t1", "ResourceArn": "arn"}]},
+ ),
+ patch.object(provider.ses_v2_client, "delete_tenant_resource_association") as mock_delete_association,
+ patch.object(provider.ses_client, "delete_identity") as mock_delete_identity,
+ ):
+ manager = MagicMock()
+ manager.attach_mock(mock_delete_association, "delete_association")
+ manager.attach_mock(mock_delete_identity, "delete_identity")
+
+ provider.delete_identity(TEST_DOMAIN)
+
+ arn = f"arn:aws:ses:us-east-1:123456789012:identity/{TEST_DOMAIN}"
+ assert manager.mock_calls == [
+ call.delete_association(TenantName="team-1", ResourceArn=arn),
+ call.delete_identity(Identity=TEST_DOMAIN),
+ ]