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.

feat(workflows): reject off-domain custom sender addresses at save time (#85217)

Harley Alexandercd92a3a9a775
diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.py
index 7ec16176e1a3..20ae3964e705 100644
--- a/posthog/cdp/test/test_validation.py
+++ b/posthog/cdp/test/test_validation.py
@@ -16,19 +16,20 @@ from posthog.cdp.validation import (
compile_hog,
generate_template_bytecode,
)
+from posthog.models.integration import Integration
from products.messaging.backend.api.design_validation import validate_design
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
-def validate_inputs(schema, inputs, function_type="destination", is_dwh_source=False):
+def validate_inputs(schema, inputs, function_type="destination", is_dwh_source=False, context_extra=None):
serializer = MappingsSerializer(
data={
"inputs_schema": schema,
"inputs": inputs,
},
- context={"function_type": function_type, "is_dwh_source": is_dwh_source},
+ context={"function_type": function_type, "is_dwh_source": is_dwh_source, **(context_extra or {})},
)
serializer.is_valid(raise_exception=True)
return serializer.validated_data["inputs"]
@@ -551,6 +552,159 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
validate_inputs(inputs_schema, {"email": {"value": value}})
assert "At most 10 email senders are allowed." in str(ctx.value.detail)
+ def _create_email_integration(self, domain="posthog.com"):
+ return Integration.objects.create(
+ team=self.team,
+ kind="email",
+ config={"email": f"sender@{domain}", "name": "Sender", "domain": domain, "verified": True},
+ )
+
+ def _validate_email_from(self, from_value, existing_from=None, get_team=True, cache=None):
+ inputs_schema = [{"key": "email", "type": "native_email", "required": True, "templating": "liquid"}]
+ value = {"from": from_value, "to": "[email protected]", "subject": "hi", "text": "hi"}
+ context_extra = {"existing_email_from": existing_from}
+ if get_team:
+ context_extra["get_team"] = lambda: self.team
+ if cache is not None:
+ context_extra["email_integration_domain_cache"] = cache
+ return validate_inputs(inputs_schema, {"email": {"value": value}}, context_extra=context_extra)
+
+ @parameterized.expand(
+ [
+ ("off_domain", "[email protected]", 'is not on the verified domain "posthog.com"'),
+ ("planted_placeholder", "[email protected]", 'is not on the verified domain "posthog.com"'),
+ ("not_an_email", "not-an-email", "is not a valid email address"),
+ ("address_list", "[email protected], [email protected]", "is not a valid email address"),
+ ]
+ )
+ def test_email_literal_sender_override_rejected_at_save(self, _name, address, expected):
+ # A literal override that the runtime would refuse (or silently fall back from) must be
+ # rejected when the workflow is saved, while the author can still act on it.
+ integration = self._create_email_integration()
+
+ with pytest.raises(ValidationError) as ctx:
+ self._validate_email_from({"integrationId": integration.id, "email": address})
+ assert expected in str(ctx.value.detail)
+
+ @parameterized.expand(
+ [
+ ("on_domain", "[email protected]"),
+ ("case_insensitive", "[email protected]"),
+ ("liquid_template", "{{ event.properties.sender }}"),
+ ("hog_template", "{event.properties.sender}"),
+ ("empty_means_integration_default", ""),
+ ]
+ )
+ def test_email_sender_override_accepted_at_save(self, _name, address):
+ integration = self._create_email_integration()
+
+ validated = self._validate_email_from({"integrationId": integration.id, "email": address})
+ assert validated["email"]["value"]["from"]["email"] == address
+
+ def test_email_sender_override_unchanged_stored_value_is_not_revalidated(self):
+ # Workflows written before June 2026 carry a placeholder address the author never typed.
+ # Re-saving one of them must not fail on that stored value; only a newly written address
+ # is held to the domain rule. The stored placeholders are removed by a separate backfill.
+ integration = self._create_email_integration()
+
+ self._validate_email_from(
+ {"integrationId": integration.id, "email": "[email protected]"},
+ existing_from={"integrationId": integration.id, "email": "[email protected]"},
+ )
+
+ def test_email_sender_override_changed_value_is_validated(self):
+ integration = self._create_email_integration()
+
+ with pytest.raises(ValidationError) as ctx:
+ self._validate_email_from(
+ {"integrationId": integration.id, "email": "[email protected]"},
+ existing_from={"integrationId": integration.id, "email": "[email protected]"},
+ )
+ assert 'is not on the verified domain "posthog.com"' in str(ctx.value.detail)
+
+ def test_email_sender_override_kept_address_with_changed_sender_is_validated(self):
+ # Selecting a different sender re-runs the domain check even when the address is kept.
+ # Grandfathering on the address alone let a sender change save an off-domain pair that
+ # silently falls back at send time - the failure this validation exists to surface.
+ posthog_integration = self._create_email_integration("posthog.com")
+ other_integration = self._create_email_integration("example.dev")
+
+ with pytest.raises(ValidationError) as ctx:
+ self._validate_email_from(
+ {"integrationId": other_integration.id, "email": "[email protected]"},
+ existing_from={"integrationId": posthog_integration.id, "email": "[email protected]"},
+ )
+ assert 'is not on the verified domain "example.dev"' in str(ctx.value.detail)
+
+ def test_email_sender_override_added_rotation_sender_is_validated(self):
+ # Adding a rotation sender keeps the stored address, so an address-only grandfather
+ # would skip the multi-sender domain loop entirely.
+ posthog_integration = self._create_email_integration("posthog.com")
+ other_integration = self._create_email_integration("example.dev")
+
+ with pytest.raises(ValidationError) as ctx:
+ self._validate_email_from(
+ {
+ "integrationId": posthog_integration.id,
+ "integrationIds": [posthog_integration.id, other_integration.id],
+ "email": "[email protected]",
+ },
+ existing_from={"integrationId": posthog_integration.id, "email": "[email protected]"},
+ )
+ assert 'is not on the verified domain "example.dev"' in str(ctx.value.detail)
+
+ def test_email_sender_override_grandfathers_either_live_or_draft_value(self):
+ # A raw-API live save is compared against both stored variants: an address unchanged
+ # from the live value must not be blocked because a divergent draft exists.
+ integration = self._create_email_integration()
+
+ self._validate_email_from(
+ {"integrationId": integration.id, "email": "[email protected]"},
+ existing_from=[
+ {"integrationId": integration.id, "email": "[email protected]"},
+ {"integrationId": integration.id, "email": "[email protected]"},
+ ],
+ )
+
+ def test_email_sender_domain_lookup_is_cached_per_save(self):
+ # A drip sequence validates one action at a time, so each email step re-queries the
+ # same sender row unless the domain lookup shares a request-scoped cache (mirrors
+ # _message_template_cache).
+ integration = self._create_email_integration()
+ cache: dict = {}
+
+ self._validate_email_from({"integrationId": integration.id, "email": "[email protected]"}, cache=cache)
+ with self.assertNumQueries(0):
+ self._validate_email_from({"integrationId": integration.id, "email": "[email protected]"}, cache=cache)
+
+ def test_email_sender_override_must_be_on_every_rotation_domain(self):
+ # Sender rotation picks one integration per send, so a literal address that is off-domain
+ # for any of them would make a fraction of sends fall back to a different sender.
+ posthog_integration = self._create_email_integration("posthog.com")
+ other_integration = self._create_email_integration("example.dev")
+
+ with pytest.raises(ValidationError) as ctx:
+ self._validate_email_from(
+ {
+ "integrationId": posthog_integration.id,
+ "integrationIds": [posthog_integration.id, other_integration.id],
+ "email": "[email protected]",
+ }
+ )
+ assert 'is not on the verified domain "example.dev"' in str(ctx.value.detail)
+
+ @parameterized.expand(
+ [
+ ("no_team_in_context", False, 1),
+ ("unknown_integration", True, 999999),
+ ]
+ )
+ def test_email_sender_override_skips_when_domain_is_unresolvable(self, _name, get_team, integration_id):
+ # Internal re-saves run without a request (no get_team), and an integration id that does
+ # not resolve has no domain to compare against. Both must not block the save; the runtime
+ # still enforces the domain at send time.
+ self._validate_email_from({"integrationId": integration_id, "email": "[email protected]"}, get_team=get_team)
+
@parameterized.expand(
[
("person", "{person?.id}"),
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.py
index 173a31ba4750..91cd2c47be8e 100644
--- a/posthog/cdp/validation.py
+++ b/posthog/cdp/validation.py
@@ -15,6 +15,7 @@ from posthog.hogql.parser import parse_program, parse_string_template
from posthog.hogql.visitor import TraversingVisitor
from posthog.cdp.filters import compile_filters_bytecode, compile_filters_expr
+from posthog.models.integration import Integration
from products.cdp.backend.models.hog_functions.hog_function import (
TYPES_WITH_JAVASCRIPT_SOURCE,
@@ -30,6 +31,89 @@ logger = logging.getLogger(__name__)
CORE_SUPPORTED_FUNCTIONS = {"fetch", "postHogCapture"}
MAX_WORKFLOW_EMAIL_SENDERS = 10
+# Mirrors FROM_OVERRIDE_EMAIL_REGEX in nodejs/src/cdp/services/messaging/email.service.ts, which
+# is what the send path enforces after rendering. Keep the two in sync.
+FROM_OVERRIDE_EMAIL_REGEX = re.compile(r'^[^\s@"<>,;]+@[^\s@"<>,;]+\.[^\s@"<>,;]+$')
+
+
+def _sender_integration_ids(from_value: dict) -> set[int]:
+ return {
+ integration_id
+ for integration_id in [from_value.get("integrationId"), *(from_value.get("integrationIds") or [])]
+ if isinstance(integration_id, int) and not isinstance(integration_id, bool)
+ }
+
+
+def _validate_email_sender_override(from_value: dict, context: dict) -> None:
+ """Reject a literal custom sender address the send path would refuse.
+
+ The runtime only sends from an address on the selected integration's verified domain; an
+ off-domain override is discarded at send time with a run-log warning the author never sees.
+ Catching it at save time puts the error in front of the person who can fix it. Only newly
+ written sender configurations are checked: templated addresses resolve at render time, and a
+ value already stored on the workflow (live or draft) is grandfathered so legacy placeholder
+ data (cleaned up by a separate backfill) does not block unrelated edits.
+ """
+ override = (from_value.get("email") or "").strip()
+ # A brace means a Liquid or Hog template that only resolves at send time.
+ if not override or "{" in override:
+ return
+
+ existing = context.get("existing_email_from") or []
+ # Grandfather only a fully unchanged sender configuration: the address AND the selected
+ # sender set must match a stored variant. Keeping the address while switching senders must
+ # re-check it against the new sender's domain, or the pair silently falls back at send time.
+ for stored in existing if isinstance(existing, list) else [existing]:
+ if not isinstance(stored, dict):
+ continue
+ if override == (stored.get("email") or "").strip() and _sender_integration_ids(
+ from_value
+ ) == _sender_integration_ids(stored):
+ return
+
+ get_team = context.get("get_team")
+ if get_team is None:
+ # No request context (internal re-saves, direct construction); the send path still
+ # enforces the domain.
+ return
+
+ if not FROM_OVERRIDE_EMAIL_REGEX.match(override):
+ raise serializers.ValidationError(
+ {
+ "input": f'The custom sender address "{override}" is not a valid email address. '
+ "Use a single address like [email protected], or a template that resolves to one."
+ }
+ )
+
+ integration_ids = _sender_integration_ids(from_value)
+ if not integration_ids:
+ return
+
+ override_domain = override.split("@")[1].lower()
+ # An empty cached domain means the id resolved to no email integration for this team; the
+ # save is not blocked on it (there is no domain to compare), matching the uncached behavior.
+ shared_cache = context.get("email_integration_domain_cache")
+ domain_cache: dict[int, str] = shared_cache if isinstance(shared_cache, dict) else {}
+ missing_ids = [integration_id for integration_id in integration_ids if integration_id not in domain_cache]
+ if missing_ids:
+ for integration in Integration.objects.filter(team_id=get_team().id, id__in=missing_ids, kind="email"):
+ config = integration.config or {}
+ domain_cache[integration.id] = (config.get("domain") or (config.get("email") or "").split("@")[-1]).lower()
+ for integration_id in missing_ids:
+ domain_cache.setdefault(integration_id, "")
+
+ for integration_id in sorted(integration_ids):
+ integration_domain = domain_cache.get(integration_id) or ""
+ if integration_domain and override_domain != integration_domain:
+ raise serializers.ValidationError(
+ {
+ "input": f'The custom sender address "{override}" is not on the verified domain '
+ f'"{integration_domain}" of the selected sender. Use an address on that domain, '
+ "or select a different sender."
+ }
+ )
+
+
PRODUCT_ASYNC_FUNCTIONS: set[str] = set()
@@ -504,6 +588,8 @@ class InputsItemSerializer(serializers.Serializer):
{"input": "Expected 'from.integrationIds' to be a list of Integration IDs."}
)
+ _validate_email_sender_override(from_value, self.context)
+
if isinstance(value.get("html"), str) and value["html"] and not value.get("design"):
# Programmatically authored emails often supply html without a design, which the
# visual editor can't open. Wrap it so every stored email has an editable design.
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 774475332bb5..3b212b60c0b0 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -740,6 +740,27 @@ def _should_validate_strictly(context: dict, is_draft: Optional[bool]) -> bool:
return source is not None and source != EventSource.WEB
+def _existing_email_from_by_action(instance: "HogFlow") -> dict[str, list[dict]]:
+ """Stored email sender overrides keyed by action id, live and draft variants both kept.
+
+ Which variant a save should be compared against depends on how the request routes (a
+ builder save targets the draft, a raw API write targets live), so validation grandfathers
+ a value matching either - both are values already stored on the workflow.
+ """
+ result: dict[str, list[dict]] = {}
+ draft = instance.draft if isinstance(instance.draft, dict) else {}
+ for actions in (instance.actions, draft.get("actions")):
+ for stored_action in actions or []:
+ if not isinstance(stored_action, dict) or not stored_action.get("id"):
+ continue
+ email_input = ((stored_action.get("config") or {}).get("inputs") or {}).get("email")
+ value = email_input.get("value") if isinstance(email_input, dict) else None
+ from_value = value.get("from") if isinstance(value, dict) else None
+ if isinstance(from_value, dict):
+ result.setdefault(stored_action["id"], []).append(from_value)
+ return result
+
+
def _event_config_has_event_or_action(event_config: dict) -> bool:
# An "events to wait for" / conversion entry that targets neither events nor actions compiles to
# always-true bytecode and would fire on every incoming event. Action-based entries (events empty,
@@ -1251,6 +1272,18 @@ class HogFlowActionSerializer(serializers.Serializer):
# {"secret": true} marker recovers the stored value instead of wiping it.
"encrypted_inputs": (self.context.get("existing_encrypted_inputs") or {}).get(data.get("id"))
or {},
+ # Team plus this action's stored sender override, so a literal custom
+ # sender address is checked against the integration's verified domain at
+ # save time, while an unchanged stored value is grandfathered.
+ "get_team": self.context.get("get_team"),
+ "existing_email_from": (self.context.get("existing_action_email_from") or {}).get(
+ data.get("id")
+ ),
+ # Request-scoped: a drip sequence's steps share senders, and the actions
+ # list validates one action at a time (mirrors _message_template_cache).
+ "email_integration_domain_cache": self.context.setdefault(
+ "_email_integration_domain_cache", {}
+ ),
},
)
@@ -1992,6 +2025,10 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
# Must be set before super() runs, since the nested action serializers validate inside it.
if instance is not None:
self.context["existing_encrypted_inputs"] = existing_secret_map(instance, template_cache={})
+ # Stored sender overrides, keyed by action id, so child action validation only holds
+ # newly written custom sender addresses to the verified-domain rule. Draft wins over
+ # live for the same reason as secrets: it is the value the client last saw.
+ self.context["existing_action_email_from"] = _existing_email_from_by_action(instance)
# Warehouse-table triggers are row-scoped: step inputs may use the `{record.x}` alias for the
# synced row. Flag it before child action validation so function-input compilation rewrites it.
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 06c6632f75ad..51fd561def4a 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -19,6 +19,7 @@ from posthog.constants import AvailableFeature
from posthog.event_usage import EventSource
from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.integration import Integration
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.fixtures import create_app_metric2
@@ -313,6 +314,51 @@ class TestHogFlowAPI(APIBaseTest):
for fragment in fragments:
assert fragment in detail, (fragment, detail)
+ def test_literal_off_domain_sender_override_is_rejected_at_save(self):
+ # The domain rule lived only in the send path, so a bad literal address saved fine and
+ # every send then fell back to the integration's sender with a run-log warning the
+ # author never saw. The save is where the author can still act on it.
+ sync_template_to_db(_email_function_template())
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="email",
+ config={"email": "[email protected]", "name": "Sender", "domain": "posthog.com", "verified": True},
+ )
+ inputs = _valid_email_inputs()
+ inputs["email"]["value"]["from"] = {"integrationId": integration.id, "email": "[email protected]"}
+ hog_flow, action = self._create_hog_flow_with_action({"inputs": inputs})
+ action["type"] = "function_email"
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")
+
+ assert response.status_code == 400, response.json()
+ assert 'is not on the verified domain "posthog.com"' in response.json()["detail"]
+
+ def test_stored_off_domain_sender_override_survives_a_resave(self):
+ # Workflows written before June 2026 carry a placeholder address the author never typed.
+ # Re-sending the stored graph unchanged must not fail on it, or every edit to an affected
+ # workflow is blocked until the placeholder backfill has run.
+ sync_template_to_db(_email_function_template())
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="email",
+ config={"email": "[email protected]", "name": "Sender", "domain": "posthog.com", "verified": True},
+ )
+ inputs = _valid_email_inputs()
+ inputs["email"]["value"]["from"] = {"integrationId": integration.id, "email": "[email protected]"}
+ hog_flow, action = self._create_hog_flow_with_action({"template_id": "template-email", "inputs": inputs})
+ action["type"] = "function_email"
+ stored = HogFlow.objects.create(
+ team=self.team, name="Legacy flow", actions=hog_flow["actions"], status=HogFlow.State.ACTIVE
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{stored.id}",
+ {"actions": hog_flow["actions"]},
+ )
+
+ assert response.status_code == 200, response.json()
+
def test_fixed_template_id_is_inferred_from_step_type(self):
# template_id on fixed-template steps is a constant of the step type; omitting the
# constant used to bounce the create with "Template not found".