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.

chore(workflows): type the SES and Twilio facade contracts (#108318)

Harley Alexanderd500294b27c8
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 9a2403bf36d1..7abdf9c1d7fa 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -84,7 +84,7 @@ from products.batch_exports.backend.facade.contracts import DestinationType
from products.cdp.backend.models import HogFunction
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.tasks.backend.facade.contracts import InProgressGithubRunsDTO
-from products.workflows.backend.facade.contracts import WorkflowSummary
+from products.workflows.backend.facade.contracts import EmailDomainVerification, WorkflowSummary
from products.workflows.backend.facade.testing import create_workflow_for_test
@@ -716,7 +716,7 @@ class TestEmailIntegration:
def test_email_verify_updates_integration(self, mock_create_email_domain, mock_verify_email_domain):
# Mock the verify_email_domain method to return a test result
- expected_result = {
+ expected_result: EmailDomainVerification = {
"status": "success",
"dnsRecords": [],
}
diff --git a/posthog/models/integration/email.py b/posthog/models/integration/email.py
index c4696e2b17c9..269f0df8b7f3 100644
--- a/posthog/models/integration/email.py
+++ b/posthog/models/integration/email.py
@@ -1,6 +1,6 @@
"""Native email-sending integration (SES / maildev) and its cleanup signal."""
-from typing import Any
+from typing import TYPE_CHECKING, Any
from django.conf import settings
from django.db import models, transaction
@@ -16,6 +16,9 @@ from posthog.plugins.plugin_server_api import reload_integrations_on_workers
from . import model
+if TYPE_CHECKING:
+ from products.workflows.backend.facade.contracts import EmailDomainVerification
+
class EmailIntegration:
integration: model.Integration
@@ -119,11 +122,12 @@ class EmailIntegration:
return self.integration
- def verify(self):
+ def verify(self) -> "EmailDomainVerification":
domain = self.integration.config.get("domain")
provider = self.integration.config.get("provider", "ses")
mail_from_subdomain = self.integration.config.get("mail_from_subdomain", "feedback")
+ verification_result: EmailDomainVerification
# Use the appropriate provider for verification
if provider == "ses":
from products.workflows.backend.facade.api import (
diff --git a/posthog/models/integration/twilio.py b/posthog/models/integration/twilio.py
index 8e0e0876425f..2be240e2b9e4 100644
--- a/posthog/models/integration/twilio.py
+++ b/posthog/models/integration/twilio.py
@@ -1,9 +1,14 @@
"""Twilio integration."""
+from typing import TYPE_CHECKING
+
from rest_framework.exceptions import ValidationError
from . import model
+if TYPE_CHECKING:
+ from products.workflows.backend.facade.contracts import TwilioPhoneNumber
+
class TwilioIntegration:
integration: model.Integration
@@ -15,7 +20,7 @@ class TwilioIntegration:
self._account_sid = self.integration.config["account_sid"]
self._auth_token = self.integration.sensitive_config["auth_token"]
- def list_twilio_phone_numbers(self) -> list[dict]:
+ def list_twilio_phone_numbers(self) -> list["TwilioPhoneNumber"]:
from products.workflows.backend.facade.api import (
get_twilio_phone_numbers, # noqa: PLC0415 — keeps the workflows facade off the model import path
)
diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.py
index 9783f3d7242a..387a78e7ee3a 100644
--- a/products/workflows/backend/facade/api.py
+++ b/products/workflows/backend/facade/api.py
@@ -1,5 +1,5 @@
from collections.abc import Iterable
-from typing import Any, cast
+from typing import Any
from uuid import UUID
from django.db.models import F
@@ -9,8 +9,12 @@ from posthog.ingress.contracts import WebhookDelivery
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.workflows.backend.facade.contracts import (
+ EmailDomainDnsRecord,
+ EmailDomainVerification,
RecentWorkflow,
TierDecision,
+ TwilioAccount,
+ TwilioPhoneNumber,
WorkflowActivitySummary,
WorkflowSummary,
)
@@ -265,7 +269,7 @@ def update_ses_mail_from_subdomain(domain: str, *, mail_from_subdomain: str) ->
providers.SESProvider().update_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)
-def verify_ses_email_domain(domain: str, *, mail_from_subdomain: str, team_id: int) -> dict[str, Any]:
+def verify_ses_email_domain(domain: str, *, mail_from_subdomain: str, team_id: int) -> EmailDomainVerification:
from products.workflows.backend import providers # noqa: PLC0415
return providers.SESProvider().verify_email_domain(domain, mail_from_subdomain=mail_from_subdomain, team_id=team_id)
@@ -277,19 +281,19 @@ def delete_ses_identity(identity: str) -> None:
providers.SESProvider().delete_identity(identity)
-def get_maildev_mock_dns_records() -> list[dict[str, Any]]:
+def get_maildev_mock_dns_records() -> list[EmailDomainDnsRecord]:
from products.workflows.backend import providers # noqa: PLC0415
- return cast(list[dict[str, Any]], providers.MAILDEV_MOCK_DNS_RECORDS)
+ return providers.MAILDEV_MOCK_DNS_RECORDS
-def get_twilio_phone_numbers(*, account_sid: str, auth_token: str) -> list[dict]:
+def get_twilio_phone_numbers(*, account_sid: str, auth_token: str) -> list[TwilioPhoneNumber]:
from products.workflows.backend import providers # noqa: PLC0415
return providers.TwilioProvider(account_sid=account_sid, auth_token=auth_token).get_phone_numbers()
-def get_twilio_account_info(*, account_sid: str, auth_token: str) -> dict:
+def get_twilio_account_info(*, account_sid: str, auth_token: str) -> TwilioAccount:
from products.workflows.backend import providers # noqa: PLC0415
return providers.TwilioProvider(account_sid=account_sid, auth_token=auth_token).get_account_info()
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 50e340794d3c..1f67b17da7c1 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Literal, Protocol
+from typing import TYPE_CHECKING, Any, Literal, NotRequired, Protocol, TypedDict
from uuid import UUID
from posthog.dataclasses import frozen
@@ -114,3 +114,39 @@ class EmailSendingSuspensionChange:
changed_at: datetime | None
previously_suspended_at: datetime | None = None
+
+
+# The provider payloads below are TypedDicts, not frozen dataclasses: the email-verify endpoint
+# returns them as JSON without a serializer, so the keys are the API response keys.
+
+EmailDomainVerificationStatus = Literal["success", "failed", "pending"]
+
+
+class EmailDomainDnsRecord(TypedDict):
+ """One DNS record the customer adds before the domain can send email."""
+
+ type: Literal["verification", "dkim", "mail_from", "dmarc"]
+ recordType: Literal["TXT", "CNAME", "MX"]
+ recordHostname: str
+ recordValue: str
+ status: Literal["success", "pending"]
+ priority: NotRequired[int]
+
+
+class EmailDomainVerification(TypedDict):
+ status: EmailDomainVerificationStatus
+ dnsRecords: list[EmailDomainDnsRecord]
+
+
+class TwilioPhoneNumber(TypedDict):
+ """The fields callers read. The Twilio payload has more keys."""
+
+ sid: str
+ phone_number: str
+ friendly_name: str
+
+
+class TwilioAccount(TypedDict, total=False):
+ """Empty when the Twilio request fails."""
+
+ sid: str
diff --git a/products/workflows/backend/providers/maildev.py b/products/workflows/backend/providers/maildev.py
index 087f50ff4a48..2a8025809456 100644
--- a/products/workflows/backend/providers/maildev.py
+++ b/products/workflows/backend/providers/maildev.py
@@ -1,4 +1,6 @@
-MAILDEV_MOCK_DNS_RECORDS = [
+from products.workflows.backend.facade.contracts import EmailDomainDnsRecord
+
+MAILDEV_MOCK_DNS_RECORDS: list[EmailDomainDnsRecord] = [
# Mock DNS records for email domain setup when using local maildev
{
"type": "verification",
diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.py
index 4b7d1a96c689..065b6d4b603b 100644
--- a/products/workflows/backend/providers/ses.py
+++ b/products/workflows/backend/providers/ses.py
@@ -19,6 +19,12 @@ from rest_framework import exceptions
from posthog.dataclasses import frozen
+from products.workflows.backend.facade.contracts import (
+ EmailDomainDnsRecord,
+ EmailDomainVerification,
+ EmailDomainVerificationStatus,
+)
+
if TYPE_CHECKING:
from types_boto3_ses.client import SESClient
from types_boto3_sesv2.client import SESV2Client
@@ -478,13 +484,13 @@ class SESProvider:
"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):
+ 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,}$"
if not re.match(DOMAIN_REGEX, domain):
raise exceptions.ValidationError("Please enter a valid domain or subdomain name.")
- dns_records: list[dict[str, Any]] = []
+ dns_records: list[EmailDomainDnsRecord] = []
# Start/ensure domain verification (TXT at _amazonses.domain) ---
verification_token: str | None = None
@@ -631,6 +637,7 @@ class SESProvider:
all_statuses = [verification_status, dkim_status, mail_from_status]
# Normalize overall status
+ overall: EmailDomainVerificationStatus
if (
verification_status == "Success"
and dkim_status == "Success"
diff --git a/products/workflows/backend/providers/twilio.py b/products/workflows/backend/providers/twilio.py
index 435a85b8445f..08f757d5f7cb 100644
--- a/products/workflows/backend/providers/twilio.py
+++ b/products/workflows/backend/providers/twilio.py
@@ -1,8 +1,11 @@
import logging
+from typing import cast
import requests
from posthoganalytics import capture_exception
+from products.workflows.backend.facade.contracts import TwilioAccount, TwilioPhoneNumber
+
logger = logging.getLogger(__name__)
TWILIO_API_BASE_URL: str = "https://api.twilio.com/2010-04-01"
@@ -26,7 +29,7 @@ class TwilioProvider:
logger.exception(f"Twilio API error: {e}")
raise
- def get_phone_numbers(self) -> list[dict]:
+ def get_phone_numbers(self) -> list[TwilioPhoneNumber]:
"""
Get all phone numbers owned by the account.
"""
@@ -38,14 +41,14 @@ class TwilioProvider:
capture_exception(Exception(f"TwilioIntegration: Failed to list twilio phone numbers: {e}"))
return []
- def get_account_info(self) -> dict:
+ def get_account_info(self) -> TwilioAccount:
"""
Get account info.
"""
try:
endpoint = ".json"
response = self._make_request("GET", endpoint)
- return response
+ return cast(TwilioAccount, response)
except requests.exceptions.HTTPError as e:
capture_exception(Exception(f"TwilioIntegration: Failed to get account info: {e}"))
return {}