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: support email author (#57636)

Alex Vf629bb73f1f4
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index 8e7e8dd22261..25c0dcadfae7 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -13,7 +13,9 @@ from django.views.decorators.csrf import csrf_exempt
import structlog
from posthog.models.comment import Comment
+from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
+from posthog.models.user import User
from products.conversations.backend.mailgun import validate_webhook_signature
from products.conversations.backend.models import Channel, EmailChannel, EmailMessageMapping, Status
@@ -229,6 +231,46 @@ def _recover_dmarc_rewritten_sender(
return sender_email, sender_name
+def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:
+ """Verify the From header domain is authenticated before trusting it for identity.
+
+ We require SPF pass + envelope-to-From domain alignment:
+ - SPF pass means the sending IP is authorized by the envelope sender's
+ domain DNS (X-Mailgun-Spf). An attacker can't pass SPF for posthog.com
+ without controlling posthog.com's DNS records.
+ - Domain alignment means the envelope sender (MAIL FROM) domain matches
+ the From header domain, preventing an attacker from passing SPF on
+ evil.com while forging From: [email protected].
+
+ DKIM alone is insufficient — Mailgun's X-Mailgun-Dkim-Check-Result only
+ confirms a valid signature exists without reporting which domain signed it.
+ An attacker signing with evil.com's key but forging From: [email protected]
+ would still get DKIM Pass.
+ """
+ spf_passed = request.POST.get("X-Mailgun-Spf", "").lower() == "pass"
+ if not spf_passed:
+ return False
+ envelope_sender = request.POST.get("sender", "")
+ envelope_domain = envelope_sender.rsplit("@", 1)[-1].lower() if "@" in envelope_sender else ""
+ from_domain = sender_email.rsplit("@", 1)[-1].lower() if "@" in sender_email else ""
+ return bool(envelope_domain and from_domain and envelope_domain == from_domain)
+
+
+def _resolve_team_member(email: str, team: Team) -> User | None:
+ """Match a sender email to a PostHog user within the team's organization."""
+ if not email:
+ return None
+ membership = (
+ OrganizationMembership.objects.filter(
+ organization_id=team.organization_id,
+ user__email__iexact=email,
+ )
+ .select_related("user")
+ .first()
+ )
+ return membership.user if membership else None
+
+
@csrf_exempt
def email_inbound_handler(request: HttpRequest) -> HttpResponse:
if request.method != "POST":
@@ -310,6 +352,11 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
content = (request.POST.get("stripped-text", "") or request.POST.get("body-plain", ""))[:MAX_EMAIL_BODY_LENGTH]
subject = request.POST.get("subject", "")
+ # 7b. Detect team member sender — only trust From when DKIM passes
+ # AND the envelope-sender domain aligns with the From domain.
+ posthog_user = _resolve_team_member(sender_email, team) if _sender_authenticated(request, sender_email) else None
+ is_team_member = posthog_user is not None
+
# 8. Create ticket/comment/mapping in a transaction
# Attachments are extracted inside the transaction so UploadedMedia rows roll back
# on duplicate-race IntegrityError. Orphaned S3 blobs are acceptable.
@@ -339,13 +386,13 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
email_subject=subject,
email_from=sender_email,
cc_participants=cc_list,
- unread_team_count=1,
+ unread_team_count=0 if is_team_member else 1,
)
assert ticket is not None
item_context = {
- "author_type": "customer",
+ "author_type": "support" if is_team_member else "customer",
"is_private": False,
"email_from": sender_email,
"email_from_name": sender_name,
@@ -360,15 +407,20 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
content=content,
rich_content=rich_content,
item_context=item_context,
+ created_by=posthog_user,
)
if existing_ticket:
qs = Ticket.objects.filter(id=ticket.id, team=team)
- if cc_list:
- merged = list(dict.fromkeys(ticket.cc_participants + cc_list))
- qs.update(unread_team_count=F("unread_team_count") + 1, cc_participants=merged)
- else:
+ if not is_team_member and cc_list:
+ qs.update(
+ unread_team_count=F("unread_team_count") + 1,
+ cc_participants=list(dict.fromkeys(ticket.cc_participants + cc_list)),
+ )
+ elif not is_team_member:
qs.update(unread_team_count=F("unread_team_count") + 1)
+ elif cc_list:
+ qs.update(cc_participants=list(dict.fromkeys(ticket.cc_participants + cc_list)))
EmailMessageMapping.objects.create(
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 05ff5e9eacba..c687b4f6e3d0 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -924,6 +924,119 @@ class TestEmailInboundDmarcRewrite(BaseTest):
assert comment.item_context["email_from_name"] == "Alex Smith"
+class TestEmailInboundTeamMemberDetection(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.client = Client()
+ self.team.conversations_settings = {"email_enabled": True}
+ self.team.save()
+ self.config = EmailChannel.objects.create(
+ team=self.team,
+ inbound_token="ab01cd23ef45",
+ from_email="[email protected]",
+ from_name="Security",
+ domain="posthog.com",
+ domain_verified=True,
+ )
+
+ def _post(self, data: dict[str, str]):
+ return self.client.post("/api/conversations/v1/email/inbound", data)
+
+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)
+ def test_team_member_reply_attribution_and_unread(self, _mock_sig: MagicMock):
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "from": "Customer <[email protected]>",
+ "Message-Id": "<[email protected]>",
+ "subject": "Security question",
+ "stripped-text": "Hello",
+ }
+ )
+ ticket = Ticket.objects.get(team=self.team)
+ assert ticket.email_from == "[email protected]"
+ assert ticket.unread_team_count == 1
+
+ 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": "Looking into this",
+ "X-Mailgun-Spf": "Pass",
+ }
+ )
+
+ comments = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")
+ assert comments.count() == 2
+
+ customer_comment = comments[0]
+ assert customer_comment.item_context["author_type"] == "customer"
+ assert customer_comment.created_by is None
+
+ support_comment = comments[1]
+ assert support_comment.item_context["author_type"] == "support"
+ assert support_comment.created_by_id == self.user.id
+
+ 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_no_spf_treated_as_customer(self, _mock_sig: MagicMock):
+ """From header matches a team member but no SPF pass → customer."""
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "from": "Customer <[email protected]>",
+ "Message-Id": "<[email protected]>",
+ "subject": "Question",
+ "stripped-text": "Hello",
+ }
+ )
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "sender": self.user.email,
+ "from": f"Forged <{self.user.email}>",
+ "Message-Id": "<[email protected]>",
+ "In-Reply-To": "<[email protected]>",
+ "stripped-text": "I am totally a team member",
+ }
+ )
+ forged = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]
+ assert forged.item_context["author_type"] == "customer"
+ assert forged.created_by is None
+
+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)
+ def test_spf_pass_but_mismatched_envelope_treated_as_customer(self, _mock_sig: MagicMock):
+ """SPF passes but envelope sender domain != From domain → customer."""
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "from": "Customer <[email protected]>",
+ "Message-Id": "<[email protected]>",
+ "subject": "Question",
+ "stripped-text": "Hello",
+ }
+ )
+ self._post(
+ {
+ "recipient": "[email protected]",
+ "sender": "[email protected]",
+ "from": f"Forged <{self.user.email}>",
+ "Message-Id": "<[email protected]>",
+ "In-Reply-To": "<[email protected]>",
+ "stripped-text": "Cross-domain forgery attempt",
+ "X-Mailgun-Spf": "Pass",
+ }
+ )
+ forged = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]
+ assert forged.item_context["author_type"] == "customer"
+ assert forged.created_by is None
+
+
class TestEmailInboundCcParticipants(BaseTest):
def setUp(self):
super().setUp()
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 1a74cdad7892..624ed0062805 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -374,12 +374,13 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
} else if (authorType === 'AI') {
displayName = 'PostHog Assistant'
} else if (authorType === 'customer') {
- // For Slack messages, use the per-message author info
const slackAuthorName = message.item_context?.slack_author_name
+ const emailAuthorName = message.item_context?.email_from_name
if (slackAuthorName) {
displayName = slackAuthorName
+ } else if (emailAuthorName) {
+ displayName = emailAuthorName
} else {
- // Fallback to ticket-level info for widget messages
displayName =
ticket?.person?.properties?.name ||
ticket?.person?.properties?.email ||