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): fix SES stuff (#62290)

Meikel Ratzeb85f6c7df1d
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index ee4dd82fb1b3..d1d9f0acf6b9 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -633,6 +633,16 @@ 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)
super().perform_destroy(instance)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index fa83e60154af..66f4336f79ea 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -303,7 +303,10 @@ class TestEmailIntegration:
assert integration.created_by == self.user
mock_client.create_email_domain.assert_called_once_with(
- "posthog.com", mail_from_subdomain="youmustnothavelikedmyemail", team_id=self.team.id
+ "posthog.com",
+ mail_from_subdomain="youmustnothavelikedmyemail",
+ team_id=self.team.id,
+ org_team_ids=[self.team.id],
)
@patch("posthog.models.integration.SESProvider")
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index c64ceaa8fc40..6d09b657ff4e 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -43,6 +43,7 @@ from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError
from posthog.models.instance_setting import get_instance_settings
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import IntegrityError, generate_random_oauth_access_token, generate_random_oauth_refresh_token
from posthog.plugins.plugin_server_api import reload_integrations_on_workers
@@ -2012,7 +2013,13 @@ class EmailIntegration:
# Create domain in the appropriate provider
if provider == "ses":
ses = SESProvider()
- ses.create_email_domain(domain, mail_from_subdomain=mail_from_subdomain, team_id=team_id)
+ org_team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))
+ ses.create_email_domain(
+ domain,
+ mail_from_subdomain=mail_from_subdomain,
+ team_id=team_id,
+ org_team_ids=org_team_ids,
+ )
elif provider == "maildev" and settings.DEBUG:
pass
else:
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 820b6f81cab1..534570c694df 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -43,6 +43,8 @@ from posthog.models.integration import (
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+from products.workflows.backend.providers import SESProvider
+
def get_db_field_value(field, model_id):
cursor = connection.cursor()
@@ -2222,6 +2224,169 @@ class TestEmailIntegrationDomainValidation(BaseTest):
assert "not supported" in str(exc.value)
+class TestEmailIntegrationCrossTenantStaleVerification(BaseTest):
+ def _build_ses_provider(self, tenants_for_domain: dict[str, list[str]] | None = None) -> SESProvider:
+ patcher = patch("products.workflows.backend.providers.ses.boto3.client")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ provider = SESProvider()
+ provider.ses_client = MagicMock()
+ provider.ses_v2_client = MagicMock()
+ provider.sts_client = MagicMock()
+ provider.sts_client.get_caller_identity.return_value = {"Account": "123456789012"}
+
+ provider.ses_client.verify_domain_identity.return_value = {"VerificationToken": "tok"}
+ provider.ses_client.verify_domain_dkim.return_value = {"DkimTokens": ["t1", "t2", "t3"]}
+ provider.ses_client.set_identity_mail_from_domain.return_value = {}
+
+ def _list_resource_tenants(ResourceArn: str) -> dict:
+ domain = ResourceArn.split("/")[-1]
+ return {"Tenants": [{"TenantName": t} for t in (tenants_for_domain or {}).get(domain, [])]}
+
+ provider.ses_v2_client.list_resource_tenants.side_effect = _list_resource_tenants
+ return provider
+
+ def _set_global_ses_success(self, provider, domain: str) -> None:
+ provider.ses_client.get_identity_verification_attributes.return_value = {
+ "VerificationAttributes": {domain: {"VerificationStatus": "Success"}}
+ }
+ provider.ses_client.get_identity_dkim_attributes.return_value = {
+ "DkimAttributes": {domain: {"DkimVerificationStatus": "Success"}}
+ }
+ provider.ses_client.get_identity_mail_from_domain_attributes.return_value = {
+ "MailFromDomainAttributes": {domain: {"MailFromDomainStatus": "Success"}}
+ }
+
+ @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")
+ def test_verify_email_domain_requires_team_tenant_association(self, mock_resolver_cls):
+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})
+ self._set_global_ses_success(provider, "partner.com")
+ dmarc_answer = MagicMock()
+ dmarc_answer.strings = [b"v=DMARC1; p=none;"]
+ mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]
+
+ result_team_a = provider.verify_email_domain("partner.com", "feedback", team_id=1)
+ result_team_b = provider.verify_email_domain("partner.com", "feedback", team_id=999)
+
+ assert result_team_a["status"] == "success"
+ assert result_team_b["status"] == "pending"
+
+ @patch("products.workflows.backend.providers.SESProvider.delete_identity")
+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")
+ def test_destroy_email_integration_deletes_ses_identity(self, mock_create_email_domain, mock_delete_identity):
+ from posthog.api.integration import IntegrationViewSet
+
+ mock_create_email_domain.return_value = {"status": "success"}
+ integration = EmailIntegration.create_native_integration(
+ {"email": "[email protected]", "name": "Owner"},
+ team_id=self.team.id,
+ organization_id=str(self.organization.id),
+ created_by=self.user,
+ )
+
+ IntegrationViewSet().perform_destroy(integration)
+
+ mock_delete_identity.assert_called_once_with("partner.com")
+ assert not Integration.objects.filter(pk=integration.pk).exists()
+
+ @patch("products.workflows.backend.providers.SESProvider.delete_identity")
+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")
+ def test_destroy_email_integration_skips_ses_delete_when_sibling_exists(
+ self, mock_create_email_domain, mock_delete_identity
+ ):
+ from posthog.api.integration import IntegrationViewSet
+
+ mock_create_email_domain.return_value = {"status": "success"}
+ sibling_team = Team.objects.create(organization=self.organization, name="sibling team")
+ EmailIntegration.create_native_integration(
+ {"email": "[email protected]", "name": "Sibling"},
+ team_id=sibling_team.id,
+ organization_id=str(self.organization.id),
+ created_by=self.user,
+ )
+ integration = EmailIntegration.create_native_integration(
+ {"email": "[email protected]", "name": "Owner"},
+ team_id=self.team.id,
+ organization_id=str(self.organization.id),
+ created_by=self.user,
+ )
+
+ IntegrationViewSet().perform_destroy(integration)
+
+ assert mock_delete_identity.call_count == 0
+
+ def test_create_email_domain_rejects_foreign_tenant_owner(self):
+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})
+
+ with pytest.raises(Exception) as exc:
+ provider.create_email_domain("partner.com", "feedback", team_id=999, org_team_ids=[999])
+ assert "already associated with another organization" in str(exc.value)
+
+ def test_create_email_domain_allows_sibling_team_in_same_org(self):
+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": ["team-1"]})
+
+ provider.create_email_domain(
+ "partner.com",
+ "feedback",
+ team_id=2,
+ org_team_ids=[1, 2, 3, 4, 5],
+ )
+
+ @patch("products.workflows.backend.providers.ses.dns.resolver.Resolver")
+ @patch("products.workflows.backend.providers.SESProvider.create_email_domain")
+ def test_takeover_after_owner_deletes_integration_is_blocked(self, mock_create_email_domain, mock_resolver_cls):
+ from posthog.api.integration import IntegrationViewSet
+
+ mock_create_email_domain.return_value = {"status": "success"}
+ dmarc_answer = MagicMock()
+ dmarc_answer.strings = [b"v=DMARC1; p=none;"]
+ mock_resolver_cls.return_value.resolve.return_value = [dmarc_answer]
+
+ org_a = Organization.objects.create(name="org a")
+ team_a = Team.objects.create(organization=org_a, name="team a")
+ org_b = Organization.objects.create(name="org b")
+ team_b = Team.objects.create(organization=org_b, name="team b")
+
+ integration_a = EmailIntegration.create_native_integration(
+ {"email": "[email protected]", "name": "Owner A"},
+ team_id=team_a.id,
+ organization_id=str(org_a.id),
+ created_by=self.user,
+ )
+ with patch("products.workflows.backend.providers.SESProvider.delete_identity") as mock_delete:
+ IntegrationViewSet().perform_destroy(integration_a)
+ mock_delete.assert_called_once_with("partner.com")
+
+ integration_b = EmailIntegration.create_native_integration(
+ {"email": "[email protected]", "name": "Attacker B"},
+ team_id=team_b.id,
+ organization_id=str(org_b.id),
+ created_by=self.user,
+ )
+
+ provider = self._build_ses_provider(tenants_for_domain={"partner.com": []})
+ self._set_global_ses_success(provider, "partner.com")
+
+ email_b = EmailIntegration(integration_b)
+ with patch.object(type(email_b), "ses_provider", new=provider):
+ result = email_b.verify()
+
+ assert result["status"] == "pending"
+ integration_b.refresh_from_db()
+ assert integration_b.config.get("verified") is False
+
+ def test_aws_account_id_is_cached_per_provider(self):
+ provider = self._build_ses_provider()
+ provider.sts_client.get_caller_identity.reset_mock()
+
+ for _ in range(5):
+ provider._identity_arn("partner.com")
+ provider._identity_arn("other.com")
+
+ assert provider.sts_client.get_caller_identity.call_count == 1
+
+
class TestGitLabIntegrationSSRFProtection:
"""Test SSRF protections in GitLabIntegration."""
diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.py
index 7ffc40d7ec44..361fd6efc3a7 100644
--- a/products/workflows/backend/providers/ses.py
+++ b/products/workflows/backend/providers/ses.py
@@ -1,5 +1,7 @@
import re
import logging
+from collections.abc import Iterable
+from functools import cached_property
from django.conf import settings
@@ -34,14 +36,49 @@ class SESProvider:
region_name=settings.SES_REGION,
)
- def create_email_domain(self, domain: str, mail_from_subdomain: str, team_id: int):
+ def _tenant_name_for_team(self, team_id: int) -> str:
+ return f"team-{team_id}"
+
+ @cached_property
+ def _aws_account_id(self) -> str:
+ return self.sts_client.get_caller_identity()["Account"]
+
+ def _identity_arn(self, domain: str) -> str:
+ return f"arn:aws:ses:{settings.SES_REGION}:{self._aws_account_id}:identity/{domain}"
+
+ def _list_identity_tenants(self, domain: str) -> set[str]:
+ try:
+ resp = self.ses_v2_client.list_resource_tenants(ResourceArn=self._identity_arn(domain))
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "NotFoundException":
+ return set()
+ raise
+ return {t.get("TenantName") for t in resp.get("Tenants", []) if t.get("TenantName")}
+
+ def create_email_domain(
+ self,
+ domain: str,
+ mail_from_subdomain: str,
+ team_id: int,
+ org_team_ids: Iterable[int] | None = None,
+ ):
+ expected_tenant = self._tenant_name_for_team(team_id)
+ friendly_tenants = {self._tenant_name_for_team(t) for t in (org_team_ids or [team_id])}
+ foreign_tenants = self._list_identity_tenants(domain) - friendly_tenants
+ if foreign_tenants:
+ raise exceptions.ValidationError(
+ "This domain is already associated with another organization in SES. "
+ "Please contact support if you believe this is a mistake."
+ )
+
# NOTE: For sesv1, domain Identity creation is done through verification
self.verify_email_domain(domain, mail_from_subdomain, team_id)
# Create a tenant for the domain if not exists
- tenant_name = f"team-{team_id}"
try:
- self.ses_v2_client.create_tenant(TenantName=tenant_name, Tags=[{"Key": "team_id", "Value": str(team_id)}])
+ self.ses_v2_client.create_tenant(
+ TenantName=expected_tenant, Tags=[{"Key": "team_id", "Value": str(team_id)}]
+ )
except ClientError as e:
if e.response["Error"]["Code"] != "AlreadyExistsException":
raise
@@ -49,8 +86,8 @@ class SESProvider:
# Associate the new domain identity with the tenant
try:
self.ses_v2_client.create_tenant_resource_association(
- TenantName=tenant_name,
- ResourceArn=f"arn:aws:ses:{settings.SES_REGION}:{self.sts_client.get_caller_identity()['Account']}:identity/{domain}",
+ TenantName=expected_tenant,
+ ResourceArn=self._identity_arn(domain),
)
except ClientError as e:
if e.response["Error"]["Code"] != "AlreadyExistsException":
@@ -216,6 +253,11 @@ class SESProvider:
else:
overall = "pending"
+ if overall == "success":
+ expected_tenant = self._tenant_name_for_team(team_id)
+ if expected_tenant not in self._list_identity_tenants(domain):
+ overall = "pending"
+
# Upgrade per-record statuses if SES reports success
# - Domain verification TXT is considered verified when VerificationStatus == Success
# - DKIM CNAMEs considered verified when DkimVerificationStatus == Success
diff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.py
index e557ce650d6b..1c0c8f09d590 100644
--- a/products/workflows/backend/test/test_ses_provider.py
+++ b/products/workflows/backend/test/test_ses_provider.py
@@ -209,6 +209,7 @@ class TestSESProvider(TestCase):
patch.object(provider.ses_client, "get_identity_verification_attributes") as mock_verif_attrs,
patch.object(provider.ses_client, "get_identity_dkim_attributes") as mock_dkim_attrs,
patch.object(provider.ses_client, "get_identity_mail_from_domain_attributes") as mock_mail_from_attrs,
+ patch.object(provider.ses_v2_client, "list_resource_tenants") as mock_list_tenants,
):
mock_verif_attrs.return_value = {
"VerificationAttributes": {
@@ -222,6 +223,7 @@ class TestSESProvider(TestCase):
mock_mail_from_attrs.return_value = {
"MailFromDomainAttributes": {TEST_DOMAIN: {"MailFromDomainStatus": "Success"}}
}
+ mock_list_tenants.return_value = {"Tenants": [{"TenantName": "team-1"}]}
result = provider.verify_email_domain(TEST_DOMAIN, mail_from_subdomain="mail", team_id=1)