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(customer-analytics): verify email forwarding (#83174)

Arthur Moreira de Deusb5361a6b2368
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index fa43e4216d1c..528dd6661179 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1520,6 +1520,11 @@ class EmailSendTestThrottle(UserRateThrottle):
rate = "6/minute"
+class EmailForwardingChallengeThrottle(UserRateThrottle):
+ scope = "email_forwarding_challenge"
+ rate = "6/minute"
+
+
class ComposeTicketBurstThrottle(UserRateThrottle):
scope = "compose_ticket_burst"
rate = "10/minute"
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index 9758edf4abcd..327c014fa06e 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -2,6 +2,7 @@
import re
import json
+from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from email.utils import getaddresses, parseaddr, parsedate_to_datetime
from typing import Any, cast
@@ -34,7 +35,13 @@ from products.conversations.backend.services.attachments import (
sanitize_attachment_filename,
save_file_to_uploaded_media,
)
-from products.conversations.backend.services.email_channel_setup import capture_google_forwarding_confirmation
+from products.conversations.backend.services.email_channel_setup import (
+ FORWARDING_CHALLENGE_HEADER,
+ FORWARDING_CHALLENGE_MARKER,
+ ForwardingChallengeResult,
+ capture_google_forwarding_confirmation,
+ process_forwarding_challenges,
+)
from products.conversations.backend.services.email_thread_ingestion import (
EmailAddress,
ParsedInboundEmail,
@@ -48,6 +55,7 @@ INBOUND_TOKEN_PATTERN = re.compile(r"^team-([a-f0-9]+)@")
_VIA_SUFFIX_RE = re.compile(r"\s+via\s+.+$", re.IGNORECASE)
_BASIC_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_MESSAGE_ID_RE = re.compile(r"<[^<>\s]+>")
+_FORWARDING_CHALLENGE_RE = re.compile(rf"{re.escape(FORWARDING_CHALLENGE_MARKER)}(?P<token>[A-Za-z0-9_.:-]{{1,1000}})")
MAX_EMAIL_BODY_LENGTH = 50_000
MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 # 10 MB per file
MAX_ATTACHMENTS = 20
@@ -55,6 +63,7 @@ MAX_ATTACHMENTS = 20
# one becomes a per-recipient participant upsert. Cap the count so one message can't fan out into
# an unbounded batch of queries under the held thread lock.
MAX_RECIPIENTS = 100
+MAX_FORWARDING_CHALLENGE_TOKENS = 10
# The sender controls the Date header, so a far-future value would latch a thread's last_message_at
# and freeze its preview. Reject dates beyond a small clock-skew allowance and fall back to the
# authenticated webhook timestamp (or now) instead.
@@ -278,29 +287,55 @@ def _parse_message_ids(value: str) -> tuple[str, ...]:
return tuple(dict.fromkeys(message_id.strip()[:998] for message_id in message_ids if message_id.strip()))
-def _message_header_values(request: HttpRequest, header_name: str) -> tuple[str, ...]:
- values: list[str] = []
+def _iter_message_header_values(request: HttpRequest, header_name: str) -> Iterator[str]:
direct_value = request.POST.get(header_name, "")
if direct_value:
- values.append(direct_value)
+ yield direct_value
raw_headers = request.POST.get("message-headers", "")
- if raw_headers:
- try:
- parsed_headers = json.loads(raw_headers)
- except (TypeError, ValueError):
- parsed_headers = []
- if isinstance(parsed_headers, list):
- for header in parsed_headers:
- if (
- isinstance(header, list)
- and len(header) == 2
- and isinstance(header[0], str)
- and isinstance(header[1], str)
- and header[0].lower() == header_name.lower()
- ):
- values.append(header[1])
- return tuple(dict.fromkeys(values))
+ if not raw_headers:
+ return
+ try:
+ parsed_headers = json.loads(raw_headers)
+ except (TypeError, ValueError):
+ return
+ if not isinstance(parsed_headers, list):
+ return
+ for header in parsed_headers:
+ if (
+ isinstance(header, list)
+ and len(header) == 2
+ and isinstance(header[0], str)
+ and isinstance(header[1], str)
+ and header[0].lower() == header_name.lower()
+ ):
+ yield header[1]
+
+
+def _message_header_values(request: HttpRequest, header_name: str) -> tuple[str, ...]:
+ return tuple(dict.fromkeys(_iter_message_header_values(request, header_name)))
+
+
+def _forwarding_challenge_tokens(request: HttpRequest) -> tuple[str, ...]:
+ tokens: list[str] = []
+ seen: set[str] = set()
+
+ def append_token(raw_token: str) -> bool:
+ token = raw_token.strip()
+ if not token or len(token) > 1000 or token in seen:
+ return False
+ seen.add(token)
+ tokens.append(token)
+ return len(tokens) >= MAX_FORWARDING_CHALLENGE_TOKENS
+
+ for header_value in _iter_message_header_values(request, FORWARDING_CHALLENGE_HEADER):
+ if append_token(header_value):
+ return tuple(tokens)
+ for field_name in ("body-html", "body-plain", "stripped-text"):
+ for match in _FORWARDING_CHALLENGE_RE.finditer(request.POST.get(field_name, "")):
+ if append_token(match.group("token")):
+ return tuple(tokens)
+ return tuple(tokens)
def _mailgun_authentication_passed(request: HttpRequest, header_name: str) -> bool:
@@ -412,6 +447,7 @@ def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedIn
dkim_signing_domains=_dkim_signing_domains(request),
capture_address=request.POST.get("recipient", "").strip().lower(),
attachments=tuple(attachments),
+ forwarding_challenge_tokens=_forwarding_challenge_tokens(request),
)
@@ -625,6 +661,21 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
return HttpResponse(status=200)
if config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION:
+ challenge_result = process_forwarding_challenges(
+ team_id=config.team_id,
+ channel=config,
+ capture_address=email.capture_address,
+ challenge_tokens=email.forwarding_challenge_tokens,
+ )
+ if challenge_result != ForwardingChallengeResult.NOT_CHALLENGE:
+ logger.info(
+ "customer_email_forwarding_challenge_processed",
+ team_id=config.team_id,
+ config_id=str(config.id),
+ result=challenge_result,
+ )
+ return HttpResponse(status=200)
+
if config.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION:
captured = capture_google_forwarding_confirmation(
team_id=config.team_id,
diff --git a/products/conversations/backend/api/email_settings.py b/products/conversations/backend/api/email_settings.py
index a309a9bc1f78..f496a4dd6157 100644
--- a/products/conversations/backend/api/email_settings.py
+++ b/products/conversations/backend/api/email_settings.py
@@ -2,10 +2,11 @@
import uuid
import secrets
-from datetime import timedelta
from email.utils import formataddr, make_msgid
+from hashlib import sha256
-from django.core import mail
+from django.core import exceptions, mail
+from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.utils import timezone
@@ -17,11 +18,13 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.dataclasses import frozen
+from posthog.email import EmailMessage, is_smtp_email_service_available
from posthog.models.instance_setting import get_instance_setting
from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
from posthog.models.user import User
-from posthog.rate_limit import EmailSendTestThrottle, EmailVerifyDomainThrottle
+from posthog.rate_limit import EmailForwardingChallengeThrottle, EmailSendTestThrottle, EmailVerifyDomainThrottle
from products.conversations.backend.mailgun import (
MailgunDomainConflict,
@@ -47,10 +50,39 @@ from products.conversations.backend.models.team_conversations_email_config impor
MAX_PENDING_CUSTOMER_COMMUNICATION_CHANNELS_PER_OWNER,
)
from products.conversations.backend.permissions import IsConversationsAdmin
+from products.conversations.backend.services.email_channel_setup import (
+ CUSTOMER_EMAIL_SETUP_TTL,
+ FORWARDING_CHALLENGE_HEADER,
+ create_forwarding_challenge,
+)
logger = structlog.get_logger(__name__)
-CUSTOMER_EMAIL_SETUP_TTL = timedelta(hours=24)
+FORWARDING_CHALLENGE_BASE_COOLDOWN_SECONDS = 30
+FORWARDING_CHALLENGE_MAX_COOLDOWN_SECONDS = 60 * 60
+FORWARDING_CHALLENGE_MAX_SEND_ATTEMPTS = 8
+
+
+@frozen
+class ForwardingChallengeRateLimitKeys:
+ cooldown: str
+ attempts: str
+
+
+def _forwarding_challenge_rate_limit_keys(recipient: str) -> ForwardingChallengeRateLimitKeys:
+ recipient_hash = sha256(recipient.strip().lower().encode()).hexdigest()
+ key_prefix = f"customer-email-forwarding-challenge:{recipient_hash}"
+ return ForwardingChallengeRateLimitKeys(
+ cooldown=f"{key_prefix}:cooldown",
+ attempts=f"{key_prefix}:attempts",
+ )
+
+
+def _forwarding_challenge_cooldown_seconds(attempt_count: int) -> int:
+ return min(
+ FORWARDING_CHALLENGE_BASE_COOLDOWN_SECONDS * (2**attempt_count),
+ FORWARDING_CHALLENGE_MAX_COOLDOWN_SECONDS,
+ )
def _get_team_from_request(request: Request) -> tuple[User, Team] | Response:
@@ -369,7 +401,7 @@ class EmailChannelOperationResponseSerializer(serializers.Serializer):
class EmailConfirmForwardingResponseSerializer(EmailChannelOperationResponseSerializer):
confirmation_url = serializers.URLField(
read_only=True,
- help_text="Authenticated Google forwarding confirmation URL.",
+ help_text="Authenticated Google forwarding confirmation URL. Opening it does not verify forwarding to PostHog.",
)
@@ -774,6 +806,132 @@ class EmailSetDefaultView(APIView):
return Response({"ok": True})
+class EmailVerifyForwardingView(APIView):
+ permission_classes = [IsAuthenticated]
+ throttle_classes = [EmailForwardingChallengeThrottle]
+
+ @extend_schema(
+ tags=["conversations"],
+ request=ConfigIdSerializer,
+ responses={
+ 200: EmailChannelOperationResponseSerializer,
+ 400: OpenApiResponse(response=EmailChannelErrorSerializer),
+ 404: OpenApiResponse(response=EmailChannelErrorSerializer),
+ 429: OpenApiResponse(response=EmailChannelErrorSerializer),
+ 502: OpenApiResponse(response=EmailChannelErrorSerializer),
+ 503: OpenApiResponse(response=EmailChannelErrorSerializer),
+ },
+ )
+ def post(self, request: Request, *args, **kwargs) -> Response:
+ result = _get_team_from_request(request)
+ if isinstance(result, Response):
+ return result
+ user, team = result
+
+ id_serializer = ConfigIdSerializer(data=request.data)
+ id_serializer.is_valid(raise_exception=True)
+ config_id = id_serializer.validated_data["config_id"]
+
+ with transaction.atomic():
+ config = (
+ EmailChannel.objects.select_for_update()
+ .filter(
+ id=config_id,
+ team=team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=user,
+ )
+ .first()
+ )
+ if config is None:
+ return Response({"error": "Email config not found"}, status=404)
+ if config.connection_status != EmailChannelConnectionStatus.PENDING_CONFIRMATION:
+ return Response({"error": "This forwarding setup is not pending confirmation."}, status=400)
+
+ setup = EmailChannelSetup.objects.for_team(team.id).select_for_update().filter(channel=config).first()
+ if setup is None:
+ return Response({"error": "This forwarding setup is no longer available."}, status=400)
+ if setup.expires_at <= timezone.now():
+ setup.delete()
+ config.connection_status = EmailChannelConnectionStatus.CONFIRMATION_EXPIRED
+ config.save(update_fields=["connection_status"])
+ return Response({"error": "This forwarding setup expired. Add the email again to restart."}, status=400)
+
+ setup_id = setup.id
+ channel_id = config.id
+ recipient = config.from_email
+
+ if not is_smtp_email_service_available():
+ return Response(
+ {"error": "Email verification is not configured on this PostHog instance."},
+ status=503,
+ )
+
+ rate_limit_keys = _forwarding_challenge_rate_limit_keys(recipient)
+ cached_attempt_count = cache.get(rate_limit_keys.attempts, 0)
+ attempt_count = (
+ cached_attempt_count
+ if isinstance(cached_attempt_count, int)
+ and not isinstance(cached_attempt_count, bool)
+ and cached_attempt_count >= 0
+ else 0
+ )
+ if attempt_count >= FORWARDING_CHALLENGE_MAX_SEND_ATTEMPTS:
+ return Response(
+ {"error": "This email has reached the verification limit. Wait 24 hours before trying again."},
+ status=429,
+ )
+ cooldown_seconds = _forwarding_challenge_cooldown_seconds(attempt_count)
+ if not cache.add(rate_limit_keys.cooldown, True, timeout=cooldown_seconds):
+ return Response(
+ {"error": "A verification email was sent recently. Wait a moment and try again."},
+ status=429,
+ )
+
+ challenge = create_forwarding_challenge(
+ team_id=team.id,
+ channel_id=channel_id,
+ setup_id=setup_id,
+ )
+ try:
+ message = EmailMessage(
+ campaign_key=challenge.campaign_key,
+ subject="Verify email forwarding to PostHog",
+ template_name="customer_email_forwarding_verification",
+ template_context={"forwarding_challenge": challenge.token},
+ headers={FORWARDING_CHALLENGE_HEADER: challenge.token},
+ )
+ message.add_recipient(email=recipient)
+ message.send()
+ except exceptions.ImproperlyConfigured:
+ cache.delete(rate_limit_keys.cooldown)
+ return Response(
+ {"error": "Email verification is not configured on this PostHog instance."},
+ status=503,
+ )
+ except Exception:
+ cache.delete(rate_limit_keys.cooldown)
+ logger.error( # noqa: TRY400 - exception details may contain the signed challenge token
+ "customer_email_forwarding_challenge_enqueue_failed",
+ team_id=team.id,
+ config_id=str(channel_id),
+ )
+ return Response({"error": "Could not send the verification email. Try again."}, status=502)
+
+ cache.set(
+ rate_limit_keys.attempts,
+ attempt_count + 1,
+ timeout=int(CUSTOMER_EMAIL_SETUP_TTL.total_seconds()),
+ )
+ logger.info(
+ "customer_email_forwarding_challenge_enqueued",
+ team_id=team.id,
+ config_id=str(channel_id),
+ user_id=user.id,
+ )
+ return Response({"ok": True})
+
+
class EmailConfirmForwardingView(APIView):
permission_classes = [IsAuthenticated]
@@ -824,13 +982,9 @@ class EmailConfirmForwardingView(APIView):
return Response({"error": "Gmail has not sent a forwarding confirmation yet."}, status=400)
confirmation_url = setup.confirmation_action
- # Google provides no completion callback, so the owner's request for this authenticated action is the activation boundary.
- setup.delete()
- config.connection_status = EmailChannelConnectionStatus.ACTIVE
- config.save(update_fields=["connection_status"])
logger.info(
- "customer_email_forwarding_confirmed",
+ "customer_email_forwarding_confirmation_opened",
team_id=team.id,
config_id=config.id,
user_id=user.id,
diff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
index ddc16e753e87..68af496e1fb5 100644
--- a/products/conversations/backend/api/tests/test_customer_email_ingestion.py
+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
@@ -1,6 +1,9 @@
import json
+from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
+from uuid import uuid4
+from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -13,7 +16,13 @@ from posthog.models.comment import Comment
from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
-from products.conversations.backend.api.email_events import MAX_RECIPIENTS, _parse_addresses, _parse_sent_at
+from products.conversations.backend.api.email_events import (
+ MAX_FORWARDING_CHALLENGE_TOKENS,
+ MAX_RECIPIENTS,
+ _forwarding_challenge_tokens,
+ _parse_addresses,
+ _parse_sent_at,
+)
from products.conversations.backend.models import (
EMAIL_THREAD_COMMENT_SCOPE,
EmailChannel,
@@ -26,6 +35,11 @@ from products.conversations.backend.models import (
EmailThreadMessage,
Ticket,
)
+from products.conversations.backend.services.email_channel_setup import (
+ FORWARDING_CHALLENGE_HEADER,
+ FORWARDING_CHALLENGE_MARKER,
+ create_forwarding_challenge,
+)
class TestCustomerEmailIngestion(BaseTest):
@@ -119,6 +133,109 @@ class TestCustomerEmailIngestion(BaseTest):
assert not Ticket.objects.filter(team=self.team).exists()
assert not EmailOutboxMessage.objects.filter(team=self.team).exists()
+ @parameterized.expand(["message_headers", "body_html"])
+ def test_forwarding_challenge_activates_pending_channel_and_consumes_retries(self, transport: str) -> None:
+ setup = self._start_google_setup()
+ challenge = create_forwarding_challenge(
+ team_id=self.team.id,
+ channel_id=self.channel.id,
+ setup_id=setup.id,
+ )
+ payload: dict[str, str] = {
+ "from": "PostHog <[email protected]>",
+ "sender": "[email protected]",
+ "subject": "Verify email forwarding to PostHog",
+ "body-plain": "PostHog is checking email forwarding.",
+ "stripped-text": "PostHog is checking email forwarding.",
+ }
+ if transport == "message_headers":
+ payload["message-headers"] = json.dumps([[FORWARDING_CHALLENGE_HEADER, challenge.token]])
+ else:
+ payload["body-html"] = f"<p>{FORWARDING_CHALLENGE_MARKER}{challenge.token}</p>"
+
+ first_response = self._post_email(message_id=f"<challenge-{transport}@posthog.com>", **payload)
+ retry_response = self._post_email(message_id=f"<challenge-{transport}[email protected]>", **payload)
+
+ assert first_response.status_code == 200
+ assert retry_response.status_code == 200
+ self.channel.refresh_from_db()
+ assert self.channel.connection_status == EmailChannelConnectionStatus.ACTIVE
+ assert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+ assert not Ticket.objects.filter(team=self.team).exists()
+
+ @parameterized.expand(["wrong_team", "wrong_channel", "wrong_setup"])
+ def test_pending_channel_rejects_signed_challenge_for_another_setup(self, mismatch: str) -> None:
+ setup = self._start_google_setup()
+ challenge = create_forwarding_challenge(
+ team_id=self.team.id + 1 if mismatch == "wrong_team" else self.team.id,
+ channel_id=uuid4() if mismatch == "wrong_channel" else self.channel.id,
+ setup_id=uuid4() if mismatch == "wrong_setup" else setup.id,
+ )
+
+ response = self._post_email(
+ message_id=f"<challenge-{mismatch}@posthog.com>",
+ **{FORWARDING_CHALLENGE_HEADER: challenge.token},
+ )
+
+ assert response.status_code == 200
+ self.channel.refresh_from_db()
+ assert self.channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ def test_active_channel_ingests_email_with_challenge_for_another_channel(self) -> None:
+ challenge = create_forwarding_challenge(
+ team_id=self.team.id,
+ channel_id=uuid4(),
+ setup_id=uuid4(),
+ )
+
+ response = self._post_email(
+ message_id="<[email protected]>",
+ **{FORWARDING_CHALLENGE_HEADER: challenge.token},
+ )
+
+ assert response.status_code == 200
+ thread = EmailThread.objects.for_team(self.team.id).get()
+ message = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get(thread=thread)
+ assert message.comment.content == "Can you help?"
+
+ def test_pending_channel_rejects_expired_signed_challenge(self) -> None:
+ with freeze_time("2026-01-01 00:00:00"):
+ setup = self._start_google_setup(expires_at=timezone.now() + timedelta(hours=48))
+ challenge = create_forwarding_challenge(
+ team_id=self.team.id,
+ channel_id=self.channel.id,
+ setup_id=setup.id,
+ )
+
+ with freeze_time("2026-01-02 00:00:01"):
+ response = self._post_email(
+ message_id="<[email protected]>",
+ **{FORWARDING_CHALLENGE_HEADER: challenge.token},
+ )
+
+ assert response.status_code == 200
+ self.channel.refresh_from_db()
+ assert self.channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ def test_pending_channel_rejects_unsigned_direct_address_challenge(self) -> None:
+ setup = self._start_google_setup()
+
+ response = self._post_email(
+ message_id="<[email protected]>",
+ **{FORWARDING_CHALLENGE_HEADER: "forged-token"},
+ )
+
+ assert response.status_code == 200
+ self.channel.refresh_from_db()
+ assert self.channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
def test_pending_channel_accepts_live_mailgun_confirmation_shape(self) -> None:
setup = self._start_google_setup()
payload = self._valid_google_confirmation()
@@ -312,6 +429,23 @@ class TestCustomerEmailIngestion(BaseTest):
assert not EmailThread.objects.for_team(self.team.id).exists()
+class TestForwardingChallengeTokens(SimpleTestCase):
+ factory = RequestFactory()
+
+ def test_stops_reading_headers_after_reaching_the_token_limit(self) -> None:
+ class HeaderValues(list[list[str]]):
+ def __iter__(self) -> Iterator[list[str]]:
+ for index in range(MAX_FORWARDING_CHALLENGE_TOKENS):
+ yield [FORWARDING_CHALLENGE_HEADER, f"token-{index}"]
+ raise AssertionError("challenge extraction read beyond its limit")
+
+ request = self.factory.post("/", {"message-headers": "[]"})
+ with patch("products.conversations.backend.api.email_events.json.loads", return_value=HeaderValues()):
+ tokens = _forwarding_challenge_tokens(request)
+
+ assert len(tokens) == MAX_FORWARDING_CHALLENGE_TOKENS
+
+
class TestParseAddresses(SimpleTestCase):
def test_recipient_count_is_capped(self) -> None:
header = ", ".join(f"user{index}@example.com" for index in range(MAX_RECIPIENTS + 50))
diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.py
index 1e0f298272ce..c08789753813 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -4,6 +4,7 @@ from io import BytesIO
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, call, patch
+from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client
from django.utils import timezone
@@ -101,6 +102,7 @@ class TestEmailConnectDomainCaseInsensitivity(BaseTest):
class TestEmailChannelPermissions(BaseTest):
def setUp(self):
super().setUp()
+ cache.clear()
self.client.force_login(self.user)
@parameterized.expand(
@@ -222,7 +224,7 @@ class TestEmailChannelPermissions(BaseTest):
assert disconnect_response.status_code == 200
assert not EmailChannel.objects.filter(id=channel.id).exists()
- def test_owner_consumes_confirmation_action_and_activates_channel(self) -> None:
+ def test_owner_opens_confirmation_action_without_activating_channel(self) -> None:
channel = EmailChannel.objects.create(
team=self.team,
kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
@@ -254,10 +256,207 @@ class TestEmailChannelPermissions(BaseTest):
"confirmation_url": "https://mail-settings.google.com/mail/vf-confirmation",
}
channel.refresh_from_db()
- assert channel.connection_status == EmailChannelConnectionStatus.ACTIVE
- assert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ assert channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
- def test_non_owner_cannot_consume_confirmation_action(self) -> None:
+ @patch("products.conversations.backend.api.email_settings.is_smtp_email_service_available", return_value=True)
+ @patch("posthog.email.is_email_available", return_value=True)
+ @patch("products.conversations.backend.api.email_settings.EmailMessage.send", autospec=True)
+ def test_owner_sends_forwarding_challenge_only_to_claimed_mailbox(
+ self,
+ mock_send: MagicMock,
+ _mock_email_available: MagicMock,
+ _mock_smtp_available: MagicMock,
+ ) -> None:
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="challenge-token",
+ from_email="[email protected]",
+ from_name="Customer success",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ setup = EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/verify-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"ok": True}
+ mock_send.assert_called_once()
+ message = mock_send.call_args.args[0]
+ challenge_token = message.headers["X-PostHog-Forwarding-Challenge"]
+ assert message.to == [
+ {
+ "recipient": "[email protected]",
+ "raw_email": "[email protected]",
+ }
+ ]
+ assert f"posthog-forwarding-challenge:{challenge_token}" in message.html_body
+ assert challenge_token not in str(response.json())
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+
+ @patch("products.conversations.backend.api.email_settings.is_smtp_email_service_available", return_value=False)
+ def test_forwarding_challenge_requires_transactional_email(self, _mock_smtp_available: MagicMock) -> None:
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="missing-smtp-token",
+ from_email=self.user.email,
+ from_name="Customer success",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/verify-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 503
+ assert response.json() == {"error": "Email verification is not configured on this PostHog instance."}
+
+ @patch("products.conversations.backend.api.email_settings.cache.delete")
+ @patch("products.conversations.backend.api.email_settings.cache.add", return_value=True)
+ @patch("products.conversations.backend.api.email_settings.is_smtp_email_service_available", return_value=True)
+ @patch(
+ "products.conversations.backend.api.email_settings.EmailMessage",
+ side_effect=RuntimeError("queue unavailable"),
+ )
+ def test_forwarding_challenge_enqueue_failure_releases_cooldown(
+ self,
+ _mock_email_message: MagicMock,
+ _mock_smtp_available: MagicMock,
+ _mock_cache_add: MagicMock,
+ mock_cache_delete: MagicMock,
+ ) -> None:
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="enqueue-failure-token",
+ from_email=self.user.email,
+ from_name="Customer success",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ setup = EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/verify-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 502
+ assert response.json() == {"error": "Could not send the verification email. Try again."}
+ mock_cache_delete.assert_called_once()
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+
+ @patch("products.conversations.backend.api.email_settings.cache.add", side_effect=[True, False])
+ @patch("products.conversations.backend.api.email_settings.is_smtp_email_service_available", return_value=True)
+ @patch("products.conversations.backend.api.email_settings.EmailMessage")
+ def test_forwarding_challenge_resend_respects_channel_cooldown(
+ self,
+ mock_email_message: MagicMock,
+ _mock_smtp_available: MagicMock,
+ _mock_cache_add: MagicMock,
+ ) -> None:
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="cooldown-token",
+ from_email=self.user.email,
+ from_name="Customer success",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ )
+
+ first_response = self.client.post(
+ "/api/conversations/v1/email/verify-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+ second_response = self.client.post(
+ "/api/conversations/v1/email/verify-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert first_response.status_code == 200
+ assert second_response.status_code == 429
+ assert [cache_call.kwargs["timeout"] for cache_call in _mock_cache_add.call_args_list] == [30, 60]
+ assert mock_email_message.call_count == 1
+
+ @patch("products.conversations.backend.api.email_settings.cache.get")
+ @patch("products.conversations.backend.api.email_settings.is_smtp_email_service_available", return_value=True)
+ @patch("products.conversations.backend.api.email_settings.EmailMessage")
+ def test_forwarding_challenge_stops_after_the_address_reaches_its_attempt_limit(
+ self,
+ mock_email_message: MagicMock,
+ _mock_smtp_available: MagicMock,
+ mock_cache_get: MagicMock,
+ ) -> None:
+ mock_cache_get.side_effect = lambda key, default=None: 8 if key.endswith(":attempts") else default
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="attempt-limit-token",
+ from_email=self.user.email,
+ from_name="Customer success",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/verify-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 429
+ assert "verification limit" in response.json()["error"]
+ mock_email_message.assert_not_called()
+
+ @parameterized.expand(["confirm-forwarding", "verify-forwarding"])
+ def test_non_owner_cannot_access_forwarding_setup_action(self, endpoint: str) -> None:
owner = User.objects.create(email="[email protected]")
OrganizationMembership.objects.create(
organization=self.organization,
@@ -283,7 +482,7 @@ class TestEmailChannelPermissions(BaseTest):
)
response = self.client.post(
- "/api/conversations/v1/email/confirm-forwarding",
+ f"/api/conversations/v1/email/{endpoint}",
{"config_id": str(channel.id)},
content_type="application/json",
)
diff --git a/products/conversations/backend/api/urls.py b/products/conversations/backend/api/urls.py
index 51d9becafade..b4a8147414f2 100644
--- a/products/conversations/backend/api/urls.py
+++ b/products/conversations/backend/api/urls.py
@@ -11,6 +11,7 @@ from .email_settings import (
EmailSetDefaultView,
EmailStatusView,
EmailVerifyDomainView,
+ EmailVerifyForwardingView,
)
from .external import ExternalTicketView
from .github_setup import (
@@ -63,6 +64,11 @@ urlpatterns = [
EmailConfirmForwardingView.as_view(),
name="email-confirm-forwarding",
),
+ re_path(
+ r"^v1/email/verify-forwarding/?$",
+ EmailVerifyForwardingView.as_view(),
+ name="email-verify-forwarding",
+ ),
re_path(r"^v1/email/disconnect/?$", EmailDisconnectView.as_view(), name="email-disconnect"),
re_path(r"^v1/email/set-default/?$", EmailSetDefaultView.as_view(), name="email-set-default"),
re_path(r"^v1/email/verify-domain/?$", EmailVerifyDomainView.as_view(), name="email-verify-domain"),
diff --git a/products/conversations/backend/services/email_channel_setup.py b/products/conversations/backend/services/email_channel_setup.py
index 6196322766d6..93c22d9e257b 100644
--- a/products/conversations/backend/services/email_channel_setup.py
+++ b/products/conversations/backend/services/email_channel_setup.py
@@ -1,13 +1,21 @@
import re
+import secrets
+from dataclasses import dataclass
+from datetime import timedelta
+from enum import StrEnum
from hashlib import sha256
from html import unescape
from urllib.parse import urlsplit
+from uuid import UUID
+from django.core import signing
+from django.db import transaction
from django.utils import timezone
from products.conversations.backend.models import (
EmailChannel,
EmailChannelConnectionStatus,
+ EmailChannelKind,
EmailChannelSetup,
EmailChannelSetupProvider,
)
@@ -24,6 +32,169 @@ _GOOGLE_FORWARDING_SUBJECT_RE = re.compile(
)
_HTTPS_URL_RE = re.compile(r"https://[^\s<>\"']+", re.IGNORECASE)
+CUSTOMER_EMAIL_SETUP_TTL = timedelta(hours=24)
+FORWARDING_CHALLENGE_HEADER = "X-PostHog-Forwarding-Challenge"
+FORWARDING_CHALLENGE_MARKER = "posthog-forwarding-challenge:"
+FORWARDING_CHALLENGE_MAX_AGE_SECONDS = int(CUSTOMER_EMAIL_SETUP_TTL.total_seconds())
+_FORWARDING_CHALLENGE_PURPOSE = "customer-email-forwarding"
+_FORWARDING_CHALLENGE_SALT = "products.conversations.customer-email-forwarding"
+
+
+@dataclass(frozen=True, kw_only=True)
+class ForwardingChallenge:
+ token: str
+ campaign_key: str
+
+
+@dataclass(frozen=True, kw_only=True)
+class _ForwardingChallengePayload:
+ team_id: int
+ channel_id: UUID
+ setup_id: UUID
+
+
+class ForwardingChallengeResult(StrEnum):
+ NOT_CHALLENGE = "not_challenge"
+ CONSUMED = "consumed"
+ ACTIVATED = "activated"
+
+
+def create_forwarding_challenge(*, team_id: int, channel_id: UUID, setup_id: UUID) -> ForwardingChallenge:
+ token = signing.dumps(
+ {
+ "purpose": _FORWARDING_CHALLENGE_PURPOSE,
+ "team_id": team_id,
+ "channel_id": str(channel_id),
+ "setup_id": str(setup_id),
+ "nonce": secrets.token_urlsafe(16),
+ },
+ salt=_FORWARDING_CHALLENGE_SALT,
+ compress=True,
+ )
+ token_hash = sha256(token.encode()).hexdigest()[:16]
+ return ForwardingChallenge(
+ token=token,
+ campaign_key=f"customer-email-forwarding:{setup_id}:{token_hash}",
+ )
+
+
+def _load_forwarding_challenge(token: str) -> tuple[_ForwardingChallengePayload | None, bool]:
+ expired = False
+ try:
+ raw_payload = signing.loads(
+ token,
+ salt=_FORWARDING_CHALLENGE_SALT,
+ max_age=FORWARDING_CHALLENGE_MAX_AGE_SECONDS,
+ )
+ except signing.SignatureExpired:
+ expired = True
+ try:
+ raw_payload = signing.loads(token, salt=_FORWARDING_CHALLENGE_SALT)
+ except signing.BadSignature:
+ return None, False
+ except signing.BadSignature:
+ return None, False
+
+ if not isinstance(raw_payload, dict):
+ return None, False
+ purpose = raw_payload.get("purpose")
+ team_id = raw_payload.get("team_id")
+ channel_id = raw_payload.get("channel_id")
+ setup_id = raw_payload.get("setup_id")
+ nonce = raw_payload.get("nonce")
+ if (
+ purpose != _FORWARDING_CHALLENGE_PURPOSE
+ or not isinstance(team_id, int)
+ or isinstance(team_id, bool)
+ or not isinstance(channel_id, str)
+ or not isinstance(setup_id, str)
+ or not isinstance(nonce, str)
+ or not nonce
+ ):
+ return None, False
+ try:
+ parsed_channel_id = UUID(channel_id)
+ parsed_setup_id = UUID(setup_id)
+ except ValueError:
+ return None, False
+ return (
+ _ForwardingChallengePayload(
+ team_id=team_id,
+ channel_id=parsed_channel_id,
+ setup_id=parsed_setup_id,
+ ),
+ expired,
+ )
+
+
+def process_forwarding_challenges(
+ *,
+ team_id: int,
+ channel: EmailChannel,
+ capture_address: str,
+ challenge_tokens: tuple[str, ...],
+) -> ForwardingChallengeResult:
+ saw_bound_challenge = False
+ expected_capture_prefix = f"team-{channel.inbound_token}@"
+
+ for token in challenge_tokens:
+ payload, expired = _load_forwarding_challenge(token)
+ if payload is None:
+ continue
+ if (
+ payload.team_id != team_id
+ or payload.channel_id != channel.id
+ or not capture_address.startswith(expected_capture_prefix)
+ ):
+ continue
+ saw_bound_challenge = True
+ if expired:
+ continue
+
+ with transaction.atomic():
+ locked_channel = (
+ EmailChannel.objects.select_for_update()
+ .filter(
+ id=channel.id,
+ team_id=team_id,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ )
+ .first()
+ )
+ if locked_channel is None:
+ return ForwardingChallengeResult.CONSUMED
+ if locked_channel.connection_status == EmailChannelConnectionStatus.ACTIVE:
+ return ForwardingChallengeResult.CONSUMED
+ if locked_channel.connection_status != EmailChannelConnectionStatus.PENDING_CONFIRMATION:
+ return ForwardingChallengeResult.CONSUMED
+
+ setup = (
+ EmailChannelSetup.objects.for_team(team_id)
+ .select_for_update()
+ .filter(
+ id=payload.setup_id,
+ channel_id=locked_channel.id,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ )
+ .first()
+ )
+ if setup is None:
+ continue
+
+ now = timezone.now()
+ if setup.expires_at <= now:
+ setup.delete()
+ locked_channel.connection_status = EmailChannelConnectionStatus.CONFIRMATION_EXPIRED
+ locked_channel.save(update_fields=["connection_status"])
+ return ForwardingChallengeResult.CONSUMED
+
+ setup.delete()
+ locked_channel.connection_status = EmailChannelConnectionStatus.ACTIVE
+ locked_channel.save(update_fields=["connection_status"])
+ return ForwardingChallengeResult.ACTIVATED
+
+ return ForwardingChallengeResult.CONSUMED if saw_bound_challenge else ForwardingChallengeResult.NOT_CHALLENGE
+
def _google_source_email(email: ParsedInboundEmail) -> str | None:
match = _GOOGLE_FORWARDING_SUBJECT_RE.fullmatch(email.subject.strip())
diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.py
index 348bca3ec6bc..293baea862bb 100644
--- a/products/conversations/backend/services/email_thread_ingestion.py
+++ b/products/conversations/backend/services/email_thread_ingestion.py
@@ -47,6 +47,7 @@ class ParsedInboundEmail:
dkim_signing_domains: tuple[str, ...]
capture_address: str
attachments: tuple[UploadedFile, ...]
+ forwarding_challenge_tokens: tuple[str, ...] = ()
@dataclass(frozen=True, kw_only=True)
diff --git a/products/conversations/backend/templates/email/customer_email_forwarding_verification.html b/products/conversations/backend/templates/email/customer_email_forwarding_verification.html
new file mode 100644
index 000000000000..9f6285b46395
--- /dev/null
+++ b/products/conversations/backend/templates/email/customer_email_forwarding_verification.html
@@ -0,0 +1,11 @@
+{% extends "email/base.html" %}
+{% block preheader %}PostHog is checking that Gmail forwards messages from this mailbox.{% endblock %}
+{% block heading %}Verify email forwarding{% endblock %}
+{% block section %}
+<p>PostHog sent this email to check that forwarding from this mailbox is working.</p>
+<p>You do not need to do anything. PostHog will connect this email when Gmail forwards the message.</p>
+<p>If you did not request this, you can ignore it.</p>
+<div class="mt muted">
+ <p>Verification reference: posthog-forwarding-challenge:{{ forwarding_challenge }}</p>
+</div>
+{% endblock %}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
index 61762ba34405..7672fd78f05b 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
@@ -20,8 +20,18 @@ import { customerEmailConfigLogic } from './customerEmailConfigLogic'
import type { CustomerEmailChannel } from './customerEmailConfigLogic'
function ConnectedEmailContent({ channel }: { channel: CustomerEmailChannel }): JSX.Element {
- const { channelsLoading, confirmingChannelId, disconnectingChannelId } = useValues(customerEmailConfigLogic)
- const { confirmForwarding, disconnectEmail, loadChannels } = useActions(customerEmailConfigLogic)
+ const {
+ channelsLoading,
+ disconnectingChannelId,
+ openingConfirmationChannelId,
+ verificationAwaitingChannelIds,
+ verificationTimedOutChannelIds,
+ verifyingChannelId,
+ } = useValues(customerEmailConfigLogic)
+ const { disconnectEmail, loadChannels, openGmailConfirmation, verifyForwarding } =
+ useActions(customerEmailConfigLogic)
+ const verificationAwaiting = verificationAwaitingChannelIds.includes(channel.id)
+ const verificationTimedOut = verificationTimedOutChannelIds.includes(channel.id)
return (
<div className="flex flex-col gap-3 p-3">
@@ -34,43 +44,90 @@ function ConnectedEmailContent({ channel }: { channel: CustomerEmailChannel }):
email domain.
</p>
))}
- {channel.connection_status === 'pending_confirmation' &&
- (channel.confirmation_available ? (
- <LemonBanner type="success">
+ {channel.connection_status === 'pending_confirmation' && (
+ <>
+ {channel.confirmation_available ? (
+ <LemonBanner type="success">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>
+ Gmail sent a forwarding confirmation. Open it, then enable forwarding and save your
+ changes in Gmail.
+ </span>
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconCheck />}
+ loading={openingConfirmationChannelId === channel.id}
+ disabledReason={
+ openingConfirmationChannelId && openingConfirmationChannelId !== channel.id
+ ? 'Another Gmail confirmation is opening'
+ : undefined
+ }
+ onClick={() => openGmailConfirmation(channel.id)}
+ >
+ Open Gmail confirmation
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ ) : (
+ <LemonBanner type="info">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>
+ Gmail may ask you to confirm the forwarding address. If it does, check again after
+ the confirmation email arrives.
+ </span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ loading={channelsLoading}
+ onClick={() => loadChannels(true)}
+ >
+ Check again
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ )}
+ <LemonBanner type={verificationTimedOut ? 'warning' : 'info'}>
<div className="flex flex-wrap items-center justify-between gap-2">
- <span>Gmail sent a forwarding confirmation. Open it to finish connecting this email.</span>
- <LemonButton
- type="primary"
- size="small"
- icon={<IconCheck />}
- loading={confirmingChannelId === channel.id}
- disabledReason={
- confirmingChannelId && confirmingChannelId !== channel.id
- ? 'Another email confirmation is opening'
- : undefined
- }
- onClick={() => confirmForwarding(channel.id)}
- >
- Verify forwarding
- </LemonButton>
+ <span>
+ {verificationAwaiting
+ ? 'Verification email sent. Waiting for Gmail to forward it to PostHog. PostHog checks every few seconds.'
+ : verificationTimedOut
+ ? "We haven't received the verification email. Check Gmail's spam folder and forwarding settings, then try again."
+ : 'After you enable forwarding and save your changes in Gmail, verify that messages reach PostHog.'}
+ </span>
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ loading={channelsLoading}
+ onClick={() => loadChannels(true)}
+ >
+ Check status
+ </LemonButton>
+ {!verificationAwaiting && (
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconCheck />}
+ loading={verifyingChannelId === channel.id}
+ disabledReason={
+ verifyingChannelId && verifyingChannelId !== channel.id
+ ? 'Another email is being verified'
+ : undefined
+ }
+ onClick={() => verifyForwarding(channel.id)}
+ >
+ Verify forwarding
+ </LemonButton>
+ )}
+ </div>
</div>
</LemonBanner>
- ) : (
- <LemonBanner type="info">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span>Waiting for Gmail to send the forwarding confirmation.</span>
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconRefresh />}
- loading={channelsLoading}
- onClick={loadChannels}
- >
- Check again
- </LemonButton>
- </div>
- </LemonBanner>
- ))}
+ </>
+ )}
{channel.connection_status === 'confirmation_expired' && (
<LemonBanner type="error">
This forwarding setup expired. Disconnect this email and add it again to restart setup.
@@ -181,7 +238,7 @@ export function CustomerEmailConfig(): JSX.Element {
}
if (channelsLoadFailed && channels.length === 0) {
return (
- <LemonBanner type="error" action={{ children: 'Try again', onClick: loadChannels }}>
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadChannels(true) }}>
Could not load your connected emails.
</LemonBanner>
)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
index 204774460d05..1c0a506b4536 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
@@ -39,6 +39,7 @@ describe('customerEmailConfigLogic', () => {
afterEach(() => {
logic.unmount()
+ jest.useRealTimers()
})
it('loads only customer communication channels', async () => {
@@ -51,7 +52,7 @@ describe('customerEmailConfigLogic', () => {
expect(logic.values.channelsLoading).toBe(false)
})
- it('opens an authenticated confirmation and activates the channel', async () => {
+ it('opens an authenticated confirmation without activating the channel', async () => {
const replace = jest.fn()
jest.spyOn(window, 'open').mockReturnValue({
opener: window,
@@ -68,7 +69,7 @@ describe('customerEmailConfigLogic', () => {
logic.mount()
await expectLogic(logic).toFinishAllListeners()
- logic.actions.confirmForwarding(channel.id)
+ logic.actions.openGmailConfirmation(channel.id)
await expectLogic(logic).toFinishAllListeners()
expect(createSpy).toHaveBeenCalledWith('api/conversations/v1/email/confirm-forwarding', {
@@ -76,13 +77,109 @@ describe('customerEmailConfigLogic', () => {
})
expect(window.open).toHaveBeenCalledWith('about:blank', '_blank')
expect(replace).toHaveBeenCalledWith('https://mail-settings.google.com/mail/vf-confirmation')
- expect(logic.values.channels[0]).toEqual({
- ...channel,
- connection_status: 'active',
- setup_expires_at: null,
- confirmation_available: false,
+ expect(logic.values.channels[0]).toEqual({ ...channel, confirmation_available: true })
+ expect(logic.values.openingConfirmationChannelId).toBeNull()
+ })
+
+ it('sends a forwarding challenge and refreshes until the channel is active', async () => {
+ jest.useFakeTimers()
+ getSpy
+ .mockResolvedValueOnce({ configs: [channel] })
+ .mockResolvedValueOnce({ configs: [channel] })
+ .mockResolvedValueOnce({
+ configs: [
+ {
+ ...channel,
+ connection_status: 'active',
+ setup_expires_at: null,
+ confirmation_available: false,
+ },
+ ],
+ })
+ createSpy.mockResolvedValue({ ok: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.verifyForwarding(channel.id)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledWith('api/conversations/v1/email/verify-forwarding', {
+ config_id: channel.id,
+ })
+ expect(logic.values.verifyingChannelId).toBeNull()
+ expect(logic.values.verificationAwaitingChannelIds).toEqual([channel.id])
+ expect(logic.values.channels[0].connection_status).toBe('pending_confirmation')
+ expect(getSpy).toHaveBeenCalledTimes(2)
+
+ await jest.advanceTimersByTimeAsync(3_000)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(getSpy).toHaveBeenLastCalledWith('api/conversations/v1/email/status?kind=customer_communication')
+ expect(getSpy).toHaveBeenCalledTimes(3)
+ expect(logic.values.channels[0].connection_status).toBe('active')
+ expect(logic.values.verificationAwaitingChannelIds).toEqual([])
+ })
+
+ it('does not overlap status refreshes', async () => {
+ let runPoll = (): void => {}
+ jest.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler): number => {
+ if (typeof handler === 'function') {
+ runPoll = () => handler()
+ }
+ return 1
})
- expect(logic.values.confirmingChannelId).toBeNull()
+ getSpy.mockResolvedValue({ configs: [channel] })
+ createSpy.mockResolvedValue({ ok: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.verifyForwarding(channel.id)
+ await expectLogic(logic).toFinishAllListeners()
+
+ const completedRequestCount = getSpy.mock.calls.length
+ let resolveRefresh!: (value: { configs: CustomerEmailChannel[] }) => void
+ getSpy.mockReturnValueOnce(
+ new Promise<{ configs: CustomerEmailChannel[] }>((resolve) => {
+ resolveRefresh = resolve
+ })
+ )
+ logic.actions.loadChannels(false)
+
+ expect(logic.values.channelsLoading).toBe(true)
+ runPoll()
+ expect(getSpy).toHaveBeenCalledTimes(completedRequestCount + 1)
+
+ resolveRefresh({ configs: [channel] })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.channelsLoading).toBe(false)
+ })
+
+ it('resets verification loading when sending the challenge fails', async () => {
+ getSpy.mockResolvedValue({ configs: [channel] })
+ createSpy.mockRejectedValue(new Error('queue unavailable'))
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.verifyForwarding(channel.id)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.verifyingChannelId).toBeNull()
+ expect(logic.values.verificationAwaitingChannelIds).toEqual([])
+ })
+
+ it('shows retry guidance when the forwarding challenge does not return', async () => {
+ jest.useFakeTimers()
+ getSpy.mockResolvedValue({ configs: [channel] })
+ createSpy.mockResolvedValue({ ok: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.verifyForwarding(channel.id)
+ await expectLogic(logic).toFinishAllListeners()
+ await jest.advanceTimersByTimeAsync(33_000)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.verificationAwaitingChannelIds).toEqual([])
+ expect(logic.values.verificationTimedOutChannelIds).toEqual([channel.id])
})
it('connects and disconnects the current user email', async () => {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
index 3e3da9041afa..281217aaf272 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
@@ -14,6 +14,13 @@ export type CustomerEmailChannel = Pick<
'id' | 'from_email' | 'forwarding_address' | 'connection_status' | 'setup_expires_at' | 'confirmation_available'
>
+const FORWARDING_VERIFICATION_POLL_INTERVAL_MS = 3_000
+const FORWARDING_VERIFICATION_POLL_ATTEMPTS = 10
+
+function forwardingVerificationPollKey(channelId: string): string {
+ return `forwardingVerificationPoll:${channelId}`
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customerEmailConfigLogicValues {
user: UserType | null // userLogic
@@ -21,24 +28,18 @@ export interface customerEmailConfigLogicValues {
channels: CustomerEmailChannel[]
channelsLoadFailed: boolean
channelsLoading: boolean
- confirmingChannelId: string | null
connecting: boolean
disconnectingChannelId: string | null
emailDraft: string
expandedChannelIds: string[]
+ openingConfirmationChannelId: string | null
+ verificationAwaitingChannelIds: string[]
+ verificationTimedOutChannelIds: string[]
+ verifyingChannelId: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customerEmailConfigLogicActions {
- confirmForwarding: (channelId: string) => {
- channelId: string
- }
- confirmForwardingFailure: () => {
- value: true
- }
- confirmForwardingSuccess: (channelId: string) => {
- channelId: string
- }
connectEmail: () => {
value: true
}
@@ -57,8 +58,8 @@ export interface customerEmailConfigLogicActions {
disconnectEmailSuccess: (channelId: string) => {
channelId: string
}
- loadChannels: () => {
- value: true
+ loadChannels: (showError: boolean) => {
+ showError: boolean
}
loadChannelsFailure: () => {
value: true
@@ -66,6 +67,15 @@ export interface customerEmailConfigLogicActions {
loadChannelsSuccess: (channels: CustomerEmailChannel[]) => {
channels: CustomerEmailChannel[]
}
+ openGmailConfirmation: (channelId: string) => {
+ channelId: string
+ }
+ openGmailConfirmationFailure: () => {
+ value: true
+ }
+ openGmailConfirmationSuccess: () => {
+ value: true
+ }
setAddEmailFormVisible: (visible: boolean) => {
visible: boolean
}
@@ -75,6 +85,18 @@ export interface customerEmailConfigLogicActions {
setExpandedChannelIds: (channelIds: string[]) => {
channelIds: string[]
}
+ verificationPollingTimedOut: (channelId: string) => {
+ channelId: string
+ }
+ verifyForwarding: (channelId: string) => {
+ channelId: string
+ }
+ verifyForwardingFailure: () => {
+ value: true
+ }
+ verifyForwardingSuccess: (channelId: string) => {
+ channelId: string
+ }
}
export type customerEmailConfigLogicType = MakeLogicType<
@@ -91,15 +113,19 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
setAddEmailFormVisible: (visible: boolean) => ({ visible }),
setEmailDraft: (email: string) => ({ email }),
setExpandedChannelIds: (channelIds: string[]) => ({ channelIds }),
- loadChannels: true,
+ loadChannels: (showError: boolean) => ({ showError }),
loadChannelsSuccess: (channels: CustomerEmailChannel[]) => ({ channels }),
loadChannelsFailure: true,
connectEmail: true,
connectEmailSuccess: (channel: CustomerEmailChannel) => ({ channel }),
connectEmailFailure: true,
- confirmForwarding: (channelId: string) => ({ channelId }),
- confirmForwardingSuccess: (channelId: string) => ({ channelId }),
- confirmForwardingFailure: true,
+ openGmailConfirmation: (channelId: string) => ({ channelId }),
+ openGmailConfirmationSuccess: true,
+ openGmailConfirmationFailure: true,
+ verifyForwarding: (channelId: string) => ({ channelId }),
+ verifyForwardingSuccess: (channelId: string) => ({ channelId }),
+ verifyForwardingFailure: true,
+ verificationPollingTimedOut: (channelId: string) => ({ channelId }),
disconnectEmail: (channelId: string) => ({ channelId }),
disconnectEmailSuccess: (channelId: string) => ({ channelId }),
disconnectEmailFailure: true,
@@ -132,17 +158,6 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
{
loadChannelsSuccess: (_, { channels }) => channels,
connectEmailSuccess: (state, { channel }) => [...state, channel],
- confirmForwardingSuccess: (state, { channelId }) =>
- state.map((channel) =>
- channel.id === channelId
- ? {
- ...channel,
- connection_status: 'active',
- setup_expires_at: null,
- confirmation_available: false,
- }
- : channel
- ),
disconnectEmailSuccess: (state, { channelId }) => state.filter((channel) => channel.id !== channelId),
},
],
@@ -170,12 +185,49 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
connectEmailFailure: () => false,
},
],
- confirmingChannelId: [
+ openingConfirmationChannelId: [
+ null as string | null,
+ {
+ openGmailConfirmation: (_, { channelId }) => channelId,
+ openGmailConfirmationSuccess: () => null,
+ openGmailConfirmationFailure: () => null,
+ },
+ ],
+ verifyingChannelId: [
null as string | null,
{
- confirmForwarding: (_, { channelId }) => channelId,
- confirmForwardingSuccess: () => null,
- confirmForwardingFailure: () => null,
+ verifyForwarding: (_, { channelId }) => channelId,
+ verifyForwardingSuccess: () => null,
+ verifyForwardingFailure: () => null,
+ },
+ ],
+ verificationAwaitingChannelIds: [
+ [] as string[],
+ {
+ verifyForwarding: (state, { channelId }) => state.filter((id) => id !== channelId),
+ verifyForwardingSuccess: (state, { channelId }) => [...new Set([...state, channelId])],
+ verificationPollingTimedOut: (state, { channelId }) => state.filter((id) => id !== channelId),
+ loadChannelsSuccess: (state, { channels }) =>
+ state.filter((id) =>
+ channels.some(
+ (channel) => channel.id === id && channel.connection_status === 'pending_confirmation'
+ )
+ ),
+ disconnectEmailSuccess: (state, { channelId }) => state.filter((id) => id !== channelId),
+ },
+ ],
+ verificationTimedOutChannelIds: [
+ [] as string[],
+ {
+ verifyForwarding: (state, { channelId }) => state.filter((id) => id !== channelId),
+ verificationPollingTimedOut: (state, { channelId }) => [...new Set([...state, channelId])],
+ loadChannelsSuccess: (state, { channels }) =>
+ state.filter((id) =>
+ channels.some(
+ (channel) => channel.id === id && channel.connection_status === 'pending_confirmation'
+ )
+ ),
+ disconnectEmailSuccess: (state, { channelId }) => state.filter((id) => id !== channelId),
},
],
disconnectingChannelId: [
@@ -187,8 +239,8 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
},
],
}),
- listeners(({ actions, values }) => ({
- loadChannels: async () => {
+ listeners(({ actions, cache, values }) => ({
+ loadChannels: async ({ showError }) => {
try {
// nosemgrep: prefer-codegen-api
const response = await api.get('api/conversations/v1/email/status?kind=customer_communication')
@@ -196,7 +248,16 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
} catch (error) {
posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.loadChannels' })
actions.loadChannelsFailure()
- lemonToast.error('Could not refresh your connected emails. Try again.')
+ if (showError) {
+ lemonToast.error('Could not refresh your connected emails. Try again.')
+ }
+ }
+ },
+ loadChannelsSuccess: ({ channels }) => {
+ for (const channel of channels) {
+ if (channel.connection_status !== 'pending_confirmation') {
+ cache.disposables.dispose(forwardingVerificationPollKey(channel.id))
+ }
}
},
connectEmail: async () => {
@@ -223,14 +284,14 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
lemonToast.error('Could not connect this email. Check the address and try again.')
}
},
- confirmForwarding: async ({ channelId }) => {
+ openGmailConfirmation: async ({ channelId }) => {
const confirmationWindow = window.open('about:blank', '_blank')
try {
// nosemgrep: prefer-codegen-api
const response = await api.create('api/conversations/v1/email/confirm-forwarding', {
config_id: channelId,
})
- actions.confirmForwardingSuccess(channelId)
+ actions.openGmailConfirmationSuccess()
if (confirmationWindow) {
confirmationWindow.opener = null
confirmationWindow.location.replace(response.confirmation_url)
@@ -240,15 +301,56 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
lemonToast.success('Gmail confirmation opened')
} catch (error) {
confirmationWindow?.close()
- posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.confirmForwarding' })
- actions.confirmForwardingFailure()
- lemonToast.error('Could not confirm forwarding. Check the setup and try again.')
+ posthog.captureException(error as Error, {
+ scope: 'customerEmailConfigLogic.openGmailConfirmation',
+ })
+ actions.openGmailConfirmationFailure()
+ lemonToast.error('Could not open the Gmail confirmation. Check the setup and try again.')
+ }
+ },
+ verifyForwarding: async ({ channelId }) => {
+ try {
+ // nosemgrep: prefer-codegen-api
+ await api.create('api/conversations/v1/email/verify-forwarding', {
+ config_id: channelId,
+ })
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ actions.verifyForwardingSuccess(channelId)
+ lemonToast.success('Verification email sent')
+
+ let pollAttempts = 0
+ cache.disposables.add(() => {
+ const intervalId = window.setInterval(() => {
+ if (values.channelsLoading) {
+ return
+ }
+ pollAttempts += 1
+ if (pollAttempts > FORWARDING_VERIFICATION_POLL_ATTEMPTS) {
+ cache.disposables.dispose(forwardingVerificationPollKey(channelId))
+ actions.verificationPollingTimedOut(channelId)
+ return
+ }
+ actions.loadChannels(false)
+ }, FORWARDING_VERIFICATION_POLL_INTERVAL_MS)
+ return () => window.clearInterval(intervalId)
+ }, forwardingVerificationPollKey(channelId))
+ actions.loadChannels(false)
+ } catch (error) {
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.verifyForwarding' })
+ actions.verifyForwardingFailure()
+ lemonToast.error('Could not send the verification email. Wait a moment and try again.')
}
},
disconnectEmail: async ({ channelId }) => {
try {
// nosemgrep: prefer-codegen-api
await api.create('api/conversations/v1/email/disconnect', { config_id: channelId })
+ cache.disposables.dispose(forwardingVerificationPollKey(channelId))
actions.disconnectEmailSuccess(channelId)
lemonToast.success('Email disconnected')
} catch (error) {
@@ -259,6 +361,6 @@ export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
},
})),
afterMount(({ actions }) => {
- actions.loadChannels()
+ actions.loadChannels(true)
}),
])