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: prevent inbound email echo loop (#62756)

Alex V44463ddc0f42
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index 488160e8fabd..7f75665dbbc1 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -394,6 +394,7 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
item_context = {
"author_type": "support" if is_team_member else "customer",
"is_private": False,
+ "from_email": True,
"email_from": sender_email,
"email_from_name": sender_name,
"email_message_id": email_message_id,
diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.py
index 3d81da393cbd..9cd51c1b98cf 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -814,6 +814,53 @@ class TestSendEmailReplyMultiConfig(BaseTest):
config.refresh_from_db()
assert config.domain_verified is (not flips_domain_verified)
+ @patch("products.conversations.backend.tasks.send_mime")
+ def test_send_email_reply_delivers_to_team_member_ticket(self, mock_send_mime: MagicMock):
+ """An in-app agent reply on a ticket opened by a team member (e.g. dogfooding
+ the support inbox) must still be delivered to them."""
+ config = self._create_config("[email protected]", "aaa111")
+ ticket = self._create_ticket(config)
+ ticket.email_from = self.user.email
+ ticket.save(update_fields=["email_from"])
+
+ _, outbox = self._run_reply(ticket)
+
+ mock_send_mime.assert_called_once()
+ assert mock_send_mime.call_args[1]["recipients"] == [self.user.email]
+ assert outbox.status == EmailOutboxMessage.Status.SENT
+
+ @patch("products.conversations.backend.tasks.send_mime")
+ def test_send_email_reply_skips_comment_from_inbound_email(self, mock_send_mime: MagicMock):
+ """Last-mile echo guard: an outbox row pointing at a comment that itself arrived
+ via inbound email must never be sent, even if a regression enqueues one."""
+ from products.conversations.backend.tasks import send_email_reply
+
+ config = self._create_config("[email protected]", "aaa111")
+ ticket = self._create_ticket(config)
+ comment = Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="Inbound team-member email",
+ created_by=self.user,
+ item_context={"author_type": "support", "from_email": True},
+ )
+ # The signal guard skips outbox creation; create the row explicitly to
+ # simulate a regression in enqueueing.
+ outbox = EmailOutboxMessage.objects.create(
+ team=self.team,
+ ticket=ticket,
+ comment=comment,
+ message_id="<[email protected]>",
+ )
+
+ send_email_reply(str(outbox.id))
+ outbox.refresh_from_db()
+
+ mock_send_mime.assert_not_called()
+ assert outbox.status == EmailOutboxMessage.Status.FAILED_PERMANENT
+ assert outbox.last_error == "comment originated from inbound email"
+
@patch("products.conversations.backend.tasks.send_mime")
def test_send_email_reply_transient_error_schedules_retry(self, mock_send_mime: MagicMock):
"""Transient errors must NOT be dropped or raised — the row stays pending with a
@@ -1121,6 +1168,53 @@ class TestEmailInboundTeamMemberDetection(BaseTest):
ticket.refresh_from_db()
assert ticket.unread_team_count == 1
+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)
+ def test_team_member_inbound_stamps_from_email_and_no_outbox(self, _mock_sig: MagicMock):
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "from": "Customer <[email protected]>",
+ "Message-Id": "<[email protected]>",
+ "subject": "Help please",
+ "stripped-text": "Need help",
+ }
+ )
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "sender": self.user.email,
+ "from": f"{self.user.first_name} <{self.user.email}>",
+ "Message-Id": "<[email protected]>",
+ "In-Reply-To": "<[email protected]>",
+ "stripped-text": "I will look into this",
+ "X-Mailgun-Spf": "Pass",
+ }
+ )
+
+ support_comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]
+
+ assert isinstance(support_comment.item_context, dict)
+ assert support_comment.item_context["from_email"] is True
+ assert support_comment.item_context["author_type"] == "support"
+ assert EmailOutboxMessage.objects.filter(comment=support_comment).count() == 0
+
+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)
+ def test_customer_inbound_stamps_from_email(self, _mock_sig: MagicMock):
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "from": "Customer <[email protected]>",
+ "Message-Id": "<[email protected]>",
+ "subject": "Question",
+ "stripped-text": "Hello",
+ }
+ )
+
+ comment = Comment.objects.get(team=self.team, scope="conversations_ticket")
+ assert isinstance(comment.item_context, dict)
+ assert comment.item_context["from_email"] is True
+ assert comment.item_context["author_type"] == "customer"
+
@patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)
def test_no_spf_treated_as_customer(self, _mock_sig: MagicMock):
"""From header matches a team member but no SPF pass → customer."""
diff --git a/products/conversations/backend/api/tests/test_signals.py b/products/conversations/backend/api/tests/test_signals.py
index 9bed583ac814..7e817b0479af 100644
--- a/products/conversations/backend/api/tests/test_signals.py
+++ b/products/conversations/backend/api/tests/test_signals.py
@@ -9,7 +9,7 @@ from parameterized import parameterized
from posthog.models.comment import Comment
-from products.conversations.backend.models import Ticket
+from products.conversations.backend.models import EmailChannel, EmailOutboxMessage, Ticket
from products.conversations.backend.models.constants import Channel
@@ -417,3 +417,51 @@ class TestTicketCreatedEventSignal(BaseTest):
assert ticket.id is not None
mock_capture.assert_called_once()
+
+
[email protected](transaction, "on_commit", side_effect=immediate_on_commit)
+class TestEmailReplySignalGuard(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.team.conversations_settings = {"email_enabled": True}
+ self.team.save()
+ self.config = EmailChannel.objects.create(
+ team=self.team,
+ inbound_token="signal0test1",
+ from_email="[email protected]",
+ from_name="Support",
+ domain="example.com",
+ domain_verified=True,
+ )
+ self.email_ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.EMAIL,
+ email_config=self.config,
+ widget_session_id="",
+ distinct_id="[email protected]",
+ email_from="[email protected]",
+ email_subject="Help",
+ )
+
+ @parameterized.expand(
+ [
+ ("inbound_team_email_blocked", "support", True, True, 0),
+ ("in_app_agent_reply_sent", "support", False, True, 1),
+ ("customer_email_blocked", "customer", True, True, 0),
+ ]
+ )
+ def test_email_outbox_guard(self, _mock_on_commit, _name, author_type, from_email, has_created_by, expected_count):
+ ctx: dict = {"author_type": author_type, "is_private": False}
+ if from_email:
+ ctx["from_email"] = True
+
+ Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(self.email_ticket.id),
+ content="test message",
+ created_by=self.user if has_created_by else None,
+ item_context=ctx,
+ )
+
+ assert EmailOutboxMessage.objects.filter(ticket=self.email_ticket).count() == expected_count
diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.py
index e735896f522b..3603072e1c85 100644
--- a/products/conversations/backend/signals.py
+++ b/products/conversations/backend/signals.py
@@ -355,6 +355,10 @@ def send_email_reply_on_team_message(sender, instance: Comment, created: bool, *
if author_type == "customer":
return
+ # Don't echo messages that originated from email back via email
+ if isinstance(item_context, dict) and item_context.get("from_email"):
+ return
+
team_id = instance.team_id
item_id = instance.item_id
comment = instance
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index f95a645d1dc3..5a11f5f31879 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -518,6 +518,13 @@ def _process_outbox_row(outbox: EmailOutboxMessage) -> None:
_mark_outbox_failed(outbox, "no customer email")
return
+ # Defense-in-depth: never send out a comment that itself arrived via inbound
+ # email — mirrors the from_email signal guard at the last mile, so a future
+ # regression in outbox enqueueing can't echo inbound mail back to recipients.
+ if isinstance(comment.item_context, dict) and comment.item_context.get("from_email"):
+ _mark_outbox_failed(outbox, "comment originated from inbound email")
+ return
+
author_name = ""
if comment.created_by:
author_name = (