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): stop forwarding ses bounce emails to the sender (#113335)

posthog[bot]bd3453c24c89
diff --git a/products/workflows/backend/management/commands/disable_ses_feedback_forwarding.py b/products/workflows/backend/management/commands/disable_ses_feedback_forwarding.py
new file mode 100644
index 000000000000..472298d1b92d
--- /dev/null
+++ b/products/workflows/backend/management/commands/disable_ses_feedback_forwarding.py
@@ -0,0 +1,68 @@
+import logging
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from botocore.exceptions import BotoCoreError, ClientError
+
+from posthog.models.integration import Integration
+
+from products.workflows.backend.providers import SESProvider
+
+logger = logging.getLogger(__name__)
+
+
+def ses_email_domains(domains: list[str]) -> list[str]:
+ query = Integration.objects.filter(kind="email", config__provider="ses")
+ if domains:
+ query = query.filter(config__domain__in=domains)
+ return sorted({domain for domain in query.values_list("config__domain", flat=True) if domain})
+
+
+class Command(BaseCommand):
+ help = (
+ "Disable SES email feedback forwarding on the domain identities of SES email integrations. "
+ "New domains get this during setup. Run this once for domains created before that. Idempotent."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--dry-run", action="store_true", help="Print the domains without changing them")
+ parser.add_argument("--domains", type=str, help="Comma separated list of email domains to update")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ domains_opt = options.get("domains")
+ if domains_opt is None:
+ requested: list[str] = []
+ else:
+ # An omitted option updates every domain. An explicit but empty value is a mistake,
+ # not a request to update every domain, so reject it instead of widening the scope.
+ requested = [d.strip().lower() for d in domains_opt.split(",") if d.strip()]
+ if not requested:
+ raise CommandError("--domains was empty. Omit it to update every domain.")
+ domains = ses_email_domains(requested)
+
+ if options.get("dry_run"):
+ for domain in domains:
+ self.stdout.write(f"[DRY-RUN] Would disable feedback forwarding for {domain}")
+ self.stdout.write(f"Summary: {len(domains)} domain(s) to update")
+ return
+
+ provider = SESProvider()
+ failures: list[str] = []
+ for domain in domains:
+ try:
+ provider.disable_feedback_forwarding(domain)
+ except ClientError as e:
+ # The integration can outlive its SES identity. Nothing forwards for a missing identity.
+ if e.response["Error"]["Code"] == "NotFoundException":
+ self.stdout.write(f"Skipped {domain}: no SES identity")
+ continue
+ logger.exception("Failed to disable SES feedback forwarding for '%s'", domain)
+ failures.append(domain)
+ except BotoCoreError:
+ logger.exception("Failed to disable SES feedback forwarding for '%s'", domain)
+ failures.append(domain)
+
+ self.stdout.write(f"Summary: {len(domains) - len(failures)} domain(s) processed, {len(failures)} failure(s)")
+ if failures:
+ raise CommandError(f"Failed for {', '.join(failures)}. Rerun with --domains after you fix the cause.")
diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.py
index 2b6a4371c9de..5173b5324559 100644
--- a/products/workflows/backend/providers/ses.py
+++ b/products/workflows/backend/providers/ses.py
@@ -486,6 +486,14 @@ class SESProvider:
# NOTE: For sesv1, domain Identity creation is done through verification
self.verify_email_domain(domain, mail_from_subdomain, team_id)
+ # Bounces and complaints already reach the SES webhook through the configuration sets,
+ # so a forwarding failure must not fail the add-domain request. The backfill command
+ # disable_ses_feedback_forwarding repairs a missed identity.
+ try:
+ self.disable_feedback_forwarding(domain)
+ except (ClientError, BotoCoreError):
+ logger.exception("Failed to disable SES feedback forwarding for '%s'", domain)
+
# Create a tenant for the domain if not exists
try:
self.ses_v2_client.create_tenant(
@@ -510,6 +518,14 @@ class SESProvider:
"Failed to associate configuration set '%s' with tenant '%s'", config_set, expected_tenant
)
+ def disable_feedback_forwarding(self, domain: str) -> None:
+ """
+ Stop SES from emailing bounce and complaint notices to the sender address.
+ Sends set that address as FeedbackForwardingEmailAddress, which is often a monitored inbox.
+ SES keeps forwarding anyway when a send has no configuration set that publishes bounces and complaints.
+ """
+ self.ses_v2_client.put_email_identity_feedback_attributes(EmailIdentity=domain, EmailForwardingEnabled=False)
+
def verify_email_domain(self, domain: str, mail_from_subdomain: str, team_id: int) -> EmailDomainVerification:
# Validate the domain contains valid characters for a domain name
DOMAIN_REGEX = r"(?i)^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"
diff --git a/products/workflows/backend/test/test_disable_ses_feedback_forwarding.py b/products/workflows/backend/test/test_disable_ses_feedback_forwarding.py
new file mode 100644
index 000000000000..4a617a51d2a0
--- /dev/null
+++ b/products/workflows/backend/test/test_disable_ses_feedback_forwarding.py
@@ -0,0 +1,45 @@
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from botocore.exceptions import ClientError
+
+from posthog.models.integration import Integration
+
+
+class TestDisableSesFeedbackForwarding(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ for domain, provider in [("ses.com", "ses"), ("gone.com", "ses"), ("broken.com", "ses"), ("mj.com", "mailjet")]:
+ Integration.objects.create(
+ team=self.team,
+ kind="email",
+ integration_id=f"a@{domain}",
+ config={"domain": domain, "provider": provider},
+ )
+
+ @patch("products.workflows.backend.management.commands.disable_ses_feedback_forwarding.SESProvider")
+ def test_updates_ses_domains_and_reports_real_failures(self, mock_provider_cls: MagicMock) -> None:
+ def put(domain: str) -> None:
+ code = {"gone.com": "NotFoundException", "broken.com": "TooManyRequestsException"}.get(domain)
+ if code:
+ raise ClientError({"Error": {"Code": code}}, "PutEmailIdentityFeedbackAttributes")
+
+ mock_provider_cls.return_value.disable_feedback_forwarding.side_effect = put
+
+ with pytest.raises(CommandError, match="broken.com"):
+ call_command("disable_ses_feedback_forwarding")
+
+ called = [c.args[0] for c in mock_provider_cls.return_value.disable_feedback_forwarding.call_args_list]
+ assert called == ["broken.com", "gone.com", "ses.com"]
+
+ @patch("products.workflows.backend.management.commands.disable_ses_feedback_forwarding.SESProvider")
+ def test_rejects_an_explicitly_empty_domains_value(self, mock_provider_cls: MagicMock) -> None:
+ # An empty value must not fall through to updating every domain.
+ with pytest.raises(CommandError, match="empty"):
+ call_command("disable_ses_feedback_forwarding", "--domains", ",")
+
+ mock_provider_cls.return_value.disable_feedback_forwarding.assert_not_called()
diff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.py
index af87522ef152..6eab44e15ddf 100644
--- a/products/workflows/backend/test/test_ses_provider.py
+++ b/products/workflows/backend/test/test_ses_provider.py
@@ -110,6 +110,9 @@ class TestSESProvider(TestCase):
assert any(arn.endswith(f"identity/{TEST_DOMAIN}") for arn in associated)
assert any(arn.endswith("configuration-set/posthog-messaging") for arn in associated)
assert any(arn.endswith("configuration-set/posthog-messaging-untracked") for arn in associated)
+ mock_ses_v2_client.put_email_identity_feedback_attributes.assert_called_with(
+ EmailIdentity=TEST_DOMAIN, EmailForwardingEnabled=False
+ )
# An unprovisioned config set must not fail the customer's add-domain request —
# only the identity association (self-created above) is allowed to raise.
@@ -121,6 +124,12 @@ class TestSESProvider(TestCase):
mock_ses_v2_client.create_tenant_resource_association.side_effect = fail_config_set_associations
provider.create_email_domain(TEST_DOMAIN, mail_from_subdomain="mail", team_id=1)
+ # The configuration sets already report bounces, so a forwarding failure must not fail it either.
+ mock_ses_v2_client.put_email_identity_feedback_attributes.side_effect = ClientError(
+ {"Error": {"Code": "TooManyRequestsException"}}, "PutEmailIdentityFeedbackAttributes"
+ )
+ provider.create_email_domain(TEST_DOMAIN, mail_from_subdomain="mail", team_id=1)
+
@patch("products.workflows.backend.providers.ses.boto3.client")
def test_create_email_domain_invalid_domain(self, mock_boto_client):
with override_settings(