: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(workflows): associate SES configuration sets with tenants (#75863)
Meikel Ratzf6d3c647d541
diff --git a/posthog/management/commands/migrate_ses_tenants.py b/posthog/management/commands/migrate_ses_tenants.pyindex 51ce66566103..5939ed945be1 100644--- a/posthog/management/commands/migrate_ses_tenants.py+++ b/posthog/management/commands/migrate_ses_tenants.py@@ -2,7 +2,7 @@ import loggingfrom collections.abc import Iterablefrom django.conf import settings-from django.core.management.base import BaseCommand+from django.core.management.base import BaseCommand, CommandErrorfrom django.core.paginator import Paginatorfrom django.db.models import Q@@ -25,15 +25,18 @@ def _batched(iterable: Iterable, size: int) -> Iterable[list]:yield batch-def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool = False):+def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool = False) -> dict[str, int]:"""- Ensure existing SES email identities have SES Tenants and Tenant Resource Associations.+ Ensure existing SES email identities have SES Tenants and Tenant Resource Associations+ (the identity plus every configuration set sends reference).- The command is idempotent.+ Idempotent. Returns counts so callers can tell a complete pass from a partial one:+ {"tenants": ..., "associations_ok": ..., "tenant_failures": ..., "association_failures": ...}."""+ counts = {"tenants": 0, "associations_ok": 0, "tenant_failures": 0, "association_failures": 0}if team_ids and domains:print("Please provide either team_ids or domains, not both") # noqa: T201- return+ return countsquery = (Integration.objects.filter(kind="email")@@ -70,7 +73,7 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =if not pairs:print("No SES email identities found to migrate.") # noqa: T201- return+ return countssts_client = boto3.client("sts",@@ -84,7 +87,8 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =except (ClientError, BotoCoreError) as e:logger.exception("Failed to get AWS account id for SES tenant association: %s", e)print("Error determining AWS account ID. Aborting.") # noqa: T201- return+ counts["tenant_failures"] = len(pairs)+ return countsfor batch in _batched(pairs, 50):for team_id, domain in batch:@@ -110,33 +114,45 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =except (ClientError, BotoCoreError) as e:logger.exception("Error creating SES tenant '%s': %s", tenant_name, e)print(f"Error creating tenant '{tenant_name}': {e}") # noqa: T201+ counts["tenant_failures"] += 1continue-- # Create association if missing- try:- if dry_run:- print(f"[DRY-RUN] Would associate identity '{identity_arn}' with tenant '{tenant_name}'") # noqa: T201- else:- try:- tenant_client.create_tenant_resource_association(- TenantName=tenant_name,- ResourceArn=identity_arn,- )- print(f"Associated identity '{domain}' with tenant '{tenant_name}'") # noqa: T201- except ClientError as e:- if e.response.get("Error", {}).get("Code") == "AlreadyExistsException":- print(f"Association already exists for '{domain}' and tenant '{tenant_name}'") # noqa: T201- else:- raise- except (ClientError, BotoCoreError) as e:- logger.exception(- "Error creating SES tenant_resource_association for '%s' on '%s': %s",- domain,- tenant_name,- e,- )- print(f"Error creating tenant_resource_association for '{domain}' on '{tenant_name}': {e}") # noqa: T201- continue+ counts["tenants"] += 1++ # Associate the identity plus the configuration sets sends reference — an attributed+ # send fails unless EVERY resource it uses is associated with the tenant.+ resource_arns = [identity_arn] + [+ f"arn:aws:ses:{settings.SES_REGION}:{aws_account_id}:configuration-set/{config_set}"+ for config_set in settings.SES_TENANT_CONFIGURATION_SETS+ ]+ for resource_arn in resource_arns:+ try:+ if dry_run:+ print(f"[DRY-RUN] Would associate '{resource_arn}' with tenant '{tenant_name}'") # noqa: T201+ else:+ try:+ tenant_client.create_tenant_resource_association(+ TenantName=tenant_name,+ ResourceArn=resource_arn,+ )+ print(f"Associated '{resource_arn}' with tenant '{tenant_name}'") # noqa: T201+ except ClientError as e:+ if e.response.get("Error", {}).get("Code") == "AlreadyExistsException":+ print(f"Association already exists for '{resource_arn}' and tenant '{tenant_name}'") # noqa: T201+ else:+ raise+ counts["associations_ok"] += 1+ except (ClientError, BotoCoreError) as e:+ logger.exception(+ "Error creating SES tenant_resource_association for '%s' on '%s': %s",+ resource_arn,+ tenant_name,+ e,+ )+ print(f"Error creating tenant_resource_association for '{resource_arn}' on '{tenant_name}': {e}") # noqa: T201+ counts["association_failures"] += 1+ continue++ return countsclass Command(BaseCommand):@@ -167,4 +183,16 @@ class Command(BaseCommand):team_ids = [int(x) for x in team_ids_opt.split(",")] if team_ids_opt else []domains = [x.strip() for x in domains_opt.split(",")] if domains_opt else []- migrate_ses_tenants(team_ids=team_ids, domains=domains, dry_run=dry_run)+ counts = migrate_ses_tenants(team_ids=team_ids, domains=domains, dry_run=dry_run)++ self.stdout.write(+ f"Summary: {counts['tenants']} tenants processed, "+ f"{counts['associations_ok']} associations ensured, "+ f"{counts['tenant_failures']} tenant failures, "+ f"{counts['association_failures']} association failures"+ )+ failures = counts["tenant_failures"] + counts["association_failures"]+ if failures:+ # Non-zero exit: an incomplete pass must not read as a successful rollout step —+ # tenants missing an association fail attributed sends. Rerun for the logged tenants.+ raise CommandError(f"{failures} SES tenant migration step(s) failed — rerun after fixing; see logs above.")diff --git a/posthog/management/commands/test/test_migrate_ses_tenants.py b/posthog/management/commands/test/test_migrate_ses_tenants.pyindex 75ed170895ae..c2533a837dc5 100644--- a/posthog/management/commands/test/test_migrate_ses_tenants.py+++ b/posthog/management/commands/test/test_migrate_ses_tenants.py@@ -87,10 +87,18 @@ class TestMigrateSESTenants(BaseTest):migrate_ses_tenants(team_ids=[self.team.id], domains=[], dry_run=False)- # Deduped: only one tenant and one association for (team, example.com)+ # Deduped: one tenant, and one association per resource (identity + the configuration+ # sets sends reference) for (team, example.com)assert sesv2.created_tenants == [f"team-{self.team.id}"]- expected_arn = f"arn:aws:ses:us-east-1:123456789012:identity/example.com"- assert sesv2.associations == [(f"team-{self.team.id}", expected_arn)]+ expected = [+ (f"team-{self.team.id}", f"arn:aws:ses:us-east-1:123456789012:identity/example.com"),+ (f"team-{self.team.id}", "arn:aws:ses:us-east-1:123456789012:configuration-set/posthog-messaging"),+ (+ f"team-{self.team.id}",+ "arn:aws:ses:us-east-1:123456789012:configuration-set/posthog-messaging-untracked",+ ),+ ]+ assert sesv2.associations == expected@override_settings(SES_ACCESS_KEY_ID="test", SES_SECRET_ACCESS_KEY="test", SES_REGION="eu-west-1", SES_ENDPOINT="")@patch("posthog.management.commands.migrate_ses_tenants.boto3.client")@@ -102,8 +110,15 @@ class TestMigrateSESTenants(BaseTest):migrate_ses_tenants(team_ids=[], domains=["example.com"], dry_run=False)assert sesv2.created_tenants == [f"team-{self.team.id}"]- expected_arn = f"arn:aws:ses:eu-west-1:123456789012:identity/example.com"- assert sesv2.associations == [(f"team-{self.team.id}", expected_arn)]+ expected = [+ (f"team-{self.team.id}", f"arn:aws:ses:eu-west-1:123456789012:identity/example.com"),+ (f"team-{self.team.id}", "arn:aws:ses:eu-west-1:123456789012:configuration-set/posthog-messaging"),+ (+ f"team-{self.team.id}",+ "arn:aws:ses:eu-west-1:123456789012:configuration-set/posthog-messaging-untracked",+ ),+ ]+ assert sesv2.associations == expected@override_settings(SES_ACCESS_KEY_ID="test", SES_SECRET_ACCESS_KEY="test", SES_REGION="us-east-1", SES_ENDPOINT="")@patch("posthog.management.commands.migrate_ses_tenants.boto3.client")@@ -116,7 +131,34 @@ class TestMigrateSESTenants(BaseTest):# Second run should hit AlreadyExistsException internally and not errormigrate_ses_tenants(team_ids=[self.team.id], domains=[], dry_run=False)- # Still only one tenant and association recorded+ # Still only one tenant and one association per resource recordedassert sesv2.created_tenants == [f"team-{self.team.id}"]- expected_arn = f"arn:aws:ses:us-east-1:123456789012:identity/example.com"- assert sesv2.associations == [(f"team-{self.team.id}", expected_arn)]+ expected = [+ (f"team-{self.team.id}", f"arn:aws:ses:us-east-1:123456789012:identity/example.com"),+ (f"team-{self.team.id}", "arn:aws:ses:us-east-1:123456789012:configuration-set/posthog-messaging"),+ (+ f"team-{self.team.id}",+ "arn:aws:ses:us-east-1:123456789012:configuration-set/posthog-messaging-untracked",+ ),+ ]+ assert sesv2.associations == expected++ @override_settings(SES_ACCESS_KEY_ID="test", SES_SECRET_ACCESS_KEY="test", SES_REGION="us-east-1", SES_ENDPOINT="")+ @patch("posthog.management.commands.migrate_ses_tenants.boto3.client")+ def test_returns_counts_including_association_failures(self, mock_boto_client):+ class _ConfigSetFailingClient(_FakeSESv2Client):+ def create_tenant_resource_association(self, TenantName: str, ResourceArn: str): # noqa: N803+ if "configuration-set" in ResourceArn:+ from botocore.exceptions import ClientError++ raise ClientError({"Error": {"Code": "NotFoundException"}}, "CreateTenantResourceAssociation")+ return super().create_tenant_resource_association(TenantName=TenantName, ResourceArn=ResourceArn)++ sesv2 = _ConfigSetFailingClient()+ mock_boto_client.side_effect = lambda service, **kwargs: sesv2++ counts = migrate_ses_tenants(team_ids=[self.team.id], domains=[], dry_run=False)++ # The identity succeeded; both config-set associations failed and must be reported so the+ # rollout can't mistake a partial pass for a complete one+ assert counts == {"tenants": 1, "associations_ok": 1, "tenant_failures": 0, "association_failures": 2}diff --git a/posthog/settings/ses.py b/posthog/settings/ses.pyindex 91f636f4289a..6d3f3e34da2c 100644--- a/posthog/settings/ses.py+++ b/posthog/settings/ses.py@@ -13,3 +13,16 @@ else:SES_SECRET_ACCESS_KEY = os.getenv("SES_SECRET_ACCESS_KEY", "") or NoneSES_REGION = os.getenv("SES_REGION", "us-east-1")++# Configuration sets referenced by workflow email sends. With tenant attribution, SES requires+# every resource a send references — the configuration set included, not just the sending+# identity — to be associated with the tenant, so provisioning associates these with each tenant.+# KEEP IN SYNC with the Node email worker's SES_TRACKED_CONFIGURATION_SET /+# SES_UNTRACKED_CONFIGURATION_SET (nodejs/src/cdp/config.ts and the cdp-cyclotron-worker-email+# chart): there is no shared config between the two services, so a set the worker sends through+# but which is missing here never gets associated and attributed sends through it fail.+SES_TENANT_CONFIGURATION_SETS: list[str] = [+ cs.strip()+ for cs in os.getenv("SES_TENANT_CONFIGURATION_SETS", "posthog-messaging,posthog-messaging-untracked").split(",")+ if cs.strip()+]diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.pyindex 53b629e7519b..71f120fc5f4a 100644--- a/products/workflows/backend/providers/ses.py+++ b/products/workflows/backend/providers/ses.py@@ -118,6 +118,16 @@ class SESProvider:def _identity_arn(self, domain: str) -> str:return f"arn:aws:ses:{settings.SES_REGION}:{self._aws_account_id}:identity/{domain}"+ def _configuration_set_arn(self, name: str) -> str:+ return f"arn:aws:ses:{settings.SES_REGION}:{self._aws_account_id}:configuration-set/{name}"++ def _associate_tenant_resource(self, tenant_name: str, resource_arn: str) -> None:+ try:+ self.ses_v2_client.create_tenant_resource_association(TenantName=tenant_name, ResourceArn=resource_arn)+ except ClientError as e:+ if e.response["Error"]["Code"] != "AlreadyExistsException":+ raise+def _list_identity_tenants(self, domain: str) -> set[str]:try:resp = self.ses_v2_client.list_resource_tenants(ResourceArn=self._identity_arn(domain))@@ -158,15 +168,20 @@ class SESProvider:if e.response["Error"]["Code"] != "AlreadyExistsException":raise- # Associate the new domain identity with the tenant- try:- self.ses_v2_client.create_tenant_resource_association(- TenantName=expected_tenant,- ResourceArn=self._identity_arn(domain),- )- except ClientError as e:- if e.response["Error"]["Code"] != "AlreadyExistsException":- raise+ # Associate the new domain identity with the tenant, plus the configuration sets sends+ # reference — an attributed send fails unless EVERY resource it uses is associated.+ self._associate_tenant_resource(expected_tenant, self._identity_arn(domain))+ for config_set in settings.SES_TENANT_CONFIGURATION_SETS:+ # Unlike the identity (created moments ago in this same call), config sets are+ # provisioned externally — a missing or drifted one must not fail the customer's+ # add-domain request. The gap is caught by migrate_ses_tenants / at attributed send+ # time instead.+ try:+ self._associate_tenant_resource(expected_tenant, self._configuration_set_arn(config_set))+ except (ClientError, BotoCoreError):+ logger.exception(+ "Failed to associate configuration set '%s' with tenant '%s'", config_set, expected_tenant+ )def verify_email_domain(self, domain: str, mail_from_subdomain: str, team_id: int):# Validate the domain contains valid characters for a domain namediff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.pyindex a469c3743bf9..a81f8285d610 100644--- a/products/workflows/backend/test/test_ses_provider.py+++ b/products/workflows/backend/test/test_ses_provider.py@@ -94,6 +94,26 @@ class TestSESProvider(TestCase):provider.create_email_domain(TEST_DOMAIN, mail_from_subdomain="mail", team_id=1)+ # Attributed sends fail unless every referenced resource is tenant-associated, so the+ # configuration set must be associated alongside the identity.+ associated = {+ call.kwargs["ResourceArn"]+ for call in mock_ses_v2_client.create_tenant_resource_association.call_args_list+ }+ 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)++ # An unprovisioned config set must not fail the customer's add-domain request —+ # only the identity association (self-created above) is allowed to raise.+ def fail_config_set_associations(TenantName: str, ResourceArn: str) -> dict:+ if "configuration-set" in ResourceArn:+ raise ClientError({"Error": {"Code": "NotFoundException"}}, "CreateTenantResourceAssociation")+ return {}++ 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)+@patch("products.workflows.backend.providers.ses.boto3.client")def test_create_email_domain_invalid_domain(self, mock_boto_client):with override_settings(