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): use the root domain for email Domain Connect (#96868)

posthog[bot]cc11db2b90f0
diff --git a/frontend/src/lib/components/DomainConnect/README.md b/frontend/src/lib/components/DomainConnect/README.md
index f81d5491243d..86c65e475587 100644
--- a/frontend/src/lib/components/DomainConnect/README.md
+++ b/frontend/src/lib/components/DomainConnect/README.md
@@ -47,7 +47,8 @@ Single module with all Domain Connect logic:
- **URL building**: `build_sync_apply_url()` — constructs the redirect URL
- **Signing**: `sign_query_string()` — RSA-SHA256 signs the query string (required by Cloudflare)
- **Domain parsing**: `extract_root_domain_and_host()` — splits FQDNs handling multi-part TLDs
-- **Context resolvers**: `resolve_email_context()` / `resolve_proxy_context()` — extracts template variables from the relevant PostHog resource
+- **Context resolvers**: `resolve_email_context()` / `resolve_proxy_context()` — extract template variables from the relevant PostHog resource.
+ Both return a `DomainConnectContext`, which also carries the root domain that discovery runs against and the host that scopes the records to a subdomain.
- **Provider allowlist**: `DOMAIN_CONNECT_PROVIDERS` dict — empty until providers accept our templates
### API endpoints (`posthog/api/integration.py`)
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 632061b246e0..110110da433e 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -2265,14 +2265,12 @@ class IntegrationViewSet(
if provider_endpoint and provider_endpoint not in DOMAIN_CONNECT_PROVIDERS:
raise ValidationError("Unsupported provider endpoint")
- host: str | None = None
-
if context == "email":
integration_id = request.data.get("integration_id")
if not integration_id:
raise ValidationError("integration_id is required for email context")
try:
- domain, service_id, variables = resolve_email_context(integration_id, self.team_id)
+ resolved = resolve_email_context(integration_id, self.team_id)
except ValueError as e:
capture_exception(e, {"integration_id": integration_id, "team_id": self.team_id, "context": context})
raise ValidationError(
@@ -2285,7 +2283,7 @@ class IntegrationViewSet(
raise ValidationError("proxy_record_id is required for proxy context")
organization = self.organization
try:
- domain, service_id, host, variables = resolve_proxy_context(proxy_record_id, str(organization.id))
+ resolved = resolve_proxy_context(proxy_record_id, str(organization.id))
except ValueError as e:
capture_exception(
e, {"proxy_record_id": proxy_record_id, "organization_id": organization.id, "context": context}
@@ -2298,15 +2296,17 @@ class IntegrationViewSet(
try:
url = generate_apply_url(
- domain=domain,
- service_id=service_id,
- variables=variables,
- host=host,
+ domain=resolved.root_domain,
+ service_id=resolved.service_id,
+ variables=resolved.variables,
+ host=resolved.host,
provider_endpoint=provider_endpoint,
redirect_uri=redirect_uri,
)
except DomainConnectSigningKeyMissing as e:
- capture_exception(e, {"context": context, "domain": domain, "provider_endpoint": provider_endpoint})
+ capture_exception(
+ e, {"context": context, "domain": resolved.root_domain, "provider_endpoint": provider_endpoint}
+ )
raise ValidationError(
"Automatic DNS configuration is temporarily unavailable for this provider. "
"Please configure your DNS records manually."
@@ -2316,9 +2316,9 @@ class IntegrationViewSet(
e,
{
"context": context,
- "domain": domain,
- "service_id": service_id,
- "host": host,
+ "domain": resolved.root_domain,
+ "service_id": resolved.service_id,
+ "host": resolved.host,
"provider_endpoint": provider_endpoint,
"redirect_uri": redirect_uri,
},
diff --git a/posthog/domain_connect.py b/posthog/domain_connect.py
index 041a100abc3c..deb967b4afde 100644
--- a/posthog/domain_connect.py
+++ b/posthog/domain_connect.py
@@ -108,8 +108,9 @@ def build_sync_apply_url(
Constructs the URL that the user's browser is redirected to in order to
approve DNS record changes at their provider.
- If host is provided, it is included as a protocol-level parameter (used with
- hostRequired templates to scope the template to a specific subdomain).
+ If host is provided, it is included as a protocol-level parameter. The provider
+ prefixes it to the host of each template record, which scopes the template to a
+ subdomain. Templates that set hostRequired must get one.
If private_key is provided, the query string is signed with RS256 and
sig= / key= parameters are appended (required by providers like Cloudflare).
@@ -203,10 +204,26 @@ def get_available_providers() -> list[dict[str, str]]:
# --- Context resolvers ---
-# Each resolver returns (domain, service_id, variables) for a specific use case.
-def resolve_email_context(integration_id: int, team_id: int) -> tuple[str, str, dict[str, str]]:
+@frozen
+class DomainConnectContext:
+ """The Domain Connect parameters for one use case.
+
+ Discovery and provider settings are always keyed on `root_domain`, because the
+ `_domainconnect` TXT record lives at the registrable domain and never at a
+ subdomain. `host` is the subdomain prefix, which scopes the template records to
+ the part of the zone the user configured. Keep the two apart, or a subdomain
+ fails discovery at its DNS provider.
+ """
+
+ root_domain: str
+ host: str
+ service_id: str
+ variables: dict[str, str]
+
+
+def resolve_email_context(integration_id: int, team_id: int) -> DomainConnectContext:
"""Resolve Domain Connect parameters for an email integration.
Triggers SES verification to get current tokens, then extracts the
@@ -222,7 +239,7 @@ def resolve_email_context(integration_id: int, team_id: int) -> tuple[str, str,
verification_result = email_integration.verify()
dns_records = verification_result.get("dnsRecords", [])
- domain = instance.config.get("domain", "")
+ domain_parts = extract_root_domain_and_host(instance.config.get("domain", ""))
mail_from_subdomain = instance.config.get("mail_from_subdomain", "feedback")
verify_token = ""
@@ -251,15 +268,20 @@ def resolve_email_context(integration_id: int, team_id: int) -> tuple[str, str,
"mailFromSub": mail_from_subdomain,
"sesRegion": ses_region,
}
- return (domain, service_id, variables)
+ # The template variables are bare SES tokens and a subdomain label, so they stay
+ # the same when the records move from the full sender domain to root plus host.
+ return DomainConnectContext(
+ root_domain=domain_parts.root_domain,
+ host=domain_parts.host,
+ service_id=service_id,
+ variables=variables,
+ )
-def resolve_proxy_context(proxy_record_id: str, organization_id: str) -> tuple[str, str, str, dict[str, str]]:
+def resolve_proxy_context(proxy_record_id: str, organization_id: str) -> DomainConnectContext:
"""Resolve Domain Connect parameters for a proxy record.
Extracts the root domain and host from the proxy record's full domain.
- Returns (domain, service_id, host, variables) — host is a protocol-level
- parameter (for hostRequired templates), not a template variable.
"""
from posthog.models import ProxyRecord
@@ -270,7 +292,12 @@ def resolve_proxy_context(proxy_record_id: str, organization_id: str) -> tuple[s
variables = {
"target": record.target_cname,
}
- return (domain_parts.root_domain, service_id, domain_parts.host, variables)
+ return DomainConnectContext(
+ root_domain=domain_parts.root_domain,
+ host=domain_parts.host,
+ service_id=service_id,
+ variables=variables,
+ )
def generate_apply_url(
diff --git a/posthog/test/test_domain_connect.py b/posthog/test/test_domain_connect.py
index 1afd5fe9e150..284ef8a7778f 100644
--- a/posthog/test/test_domain_connect.py
+++ b/posthog/test/test_domain_connect.py
@@ -324,30 +324,39 @@ class TestTemplateResolverAlignment(BaseTest):
mock_proxy_cls.objects.get.return_value = mock_record
with self.settings(CLOUD_DEPLOYMENT=region):
- domain, service_id, host, variables = resolve_proxy_context("test-id", "test-org")
+ resolved = resolve_proxy_context("test-id", "test-org")
- self.assertEqual(set(variables.keys()), expected_vars)
- self.assertEqual(service_id, template["serviceId"])
+ self.assertEqual(set(resolved.variables.keys()), expected_vars)
+ self.assertEqual(resolved.service_id, template["serviceId"])
+ self.assertEqual(resolved.root_domain, "example.com")
+ self.assertEqual(resolved.host, "ph")
if template.get("hostRequired"):
- self.assertTrue(host, "hostRequired template but resolver returned empty host")
+ self.assertTrue(resolved.host, "hostRequired template but resolver returned empty host")
@parameterized.expand(
[
- ("posthog.com.email-verification-us.json", "US"),
- ("posthog.com.email-verification-eu.json", "EU"),
+ ("subdomain sender", "posthog.com.email-verification-us.json", "US", "news.example.com", "news"),
+ ("root domain sender", "posthog.com.email-verification-eu.json", "EU", "example.com", ""),
]
)
@patch("posthog.models.integration.EmailIntegration")
@patch("posthog.models.integration.Integration")
def test_email_resolver_variables_match_template(
- self, template_file: str, region: str, mock_integration_cls: MagicMock, mock_email_cls: MagicMock
+ self,
+ _name: str,
+ template_file: str,
+ region: str,
+ sender_domain: str,
+ expected_host: str,
+ mock_integration_cls: MagicMock,
+ mock_email_cls: MagicMock,
) -> None:
template = _load_template(template_file)
expected_vars = _extract_template_variables(template)
mock_instance = MagicMock()
mock_instance.kind = "email"
- mock_instance.config = {"domain": "example.com", "mail_from_subdomain": "feedback"}
+ mock_instance.config = {"domain": sender_domain, "mail_from_subdomain": "feedback"}
mock_integration_cls.objects.get.return_value = mock_instance
mock_email = MagicMock()
@@ -356,18 +365,23 @@ class TestTemplateResolverAlignment(BaseTest):
{
"type": "verification",
"recordType": "TXT",
- "recordHostname": "_amazonses.example.com",
+ "recordHostname": f"_amazonses.{sender_domain}",
"recordValue": "verify-token-123",
},
- {"type": "dkim", "recordHostname": "aaa._domainkey.example.com"},
- {"type": "dkim", "recordHostname": "bbb._domainkey.example.com"},
- {"type": "dkim", "recordHostname": "ccc._domainkey.example.com"},
+ {"type": "dkim", "recordHostname": f"aaa._domainkey.{sender_domain}"},
+ {"type": "dkim", "recordHostname": f"bbb._domainkey.{sender_domain}"},
+ {"type": "dkim", "recordHostname": f"ccc._domainkey.{sender_domain}"},
]
}
mock_email_cls.return_value = mock_email
with self.settings(CLOUD_DEPLOYMENT=region, SES_REGION="us-east-1"):
- domain, service_id, variables = resolve_email_context(1, 1)
-
- self.assertEqual(set(variables.keys()), expected_vars)
- self.assertEqual(service_id, template["serviceId"])
+ resolved = resolve_email_context(1, 1)
+
+ self.assertEqual(set(resolved.variables.keys()), expected_vars)
+ self.assertEqual(resolved.service_id, template["serviceId"])
+ self.assertEqual(resolved.root_domain, "example.com")
+ self.assertEqual(resolved.host, expected_host)
+ self.assertEqual(resolved.variables["verifyToken"], "verify-token-123")
+ self.assertEqual(resolved.variables["dkim1"], "aaa")
+ self.assertEqual(resolved.variables["mailFromSub"], "feedback")