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(user_interviews): harden send_invites with throttle and recipient cap (#61279)

Paul D'Ambra30d35476dc3b
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 8959d2663d60..f21c492c1c60 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -923,6 +923,28 @@ class SubscriptionTestDeliveryThrottle(PersonalApiKeyOrUserRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
+class UserInterviewInviteThrottle(PersonalApiKeyOrUserRateThrottle):
+ # Cap how often a team can fire the user-interview send_invites action.
+ #
+ # The content (subject + intro) and the recipient list are both
+ # user-controlled, so without a limit a member could use the action as a
+ # PostHog-branded spam relay by rotating the topic's interviewee_emails and
+ # re-sending. Idempotency only stops re-sending to the *same*
+ # SharingConfiguration, not sending to fresh addresses.
+ #
+ # Keyed per team (not per personal API key, not per topic) so neither
+ # rotating topics nor minting extra API keys bypasses the limit. Extends
+ # PersonalApiKeyOrUserRateThrottle so every authenticated caller is covered
+ # (PATs, OAuth bearer tokens, and session-cookie UI users alike).
+ scope = "user_interview_invite"
+ rate = "10/minute"
+
+ def get_cache_key(self, request, view):
+ team_id = self.safely_get_team_id_from_view(view)
+ if team_id:
+ return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
+
+
class _OrganizationInviteRateThrottleBase(PersonalApiKeyOrUserRateThrottle):
# Cap how many organization invites a single organization can create in a
# given window. A malicious member can otherwise use the invite flow to
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.py
index e277035546d6..4b835a04880f 100644
--- a/products/user_interviews/backend/presentation/views.py
+++ b/products/user_interviews/backend/presentation/views.py
@@ -42,6 +42,7 @@ from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team import Team
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
+from posthog.rate_limit import UserInterviewInviteThrottle
from posthog.security.spreadsheet_safety import sanitize_formula_injection
from posthog.utils import absolute_uri
@@ -820,7 +821,10 @@ class InterviewInviteResultSerializer(serializers.Serializer):
reason = serializers.CharField(
required=False,
allow_blank=True,
- help_text="Why the email was skipped (e.g., `not_an_email`, `already_sent`). Empty when sent=true.",
+ help_text=(
+ "Why the email was skipped (e.g., `not_an_email`, `duplicate_recipient`, `already_sent`). "
+ "Empty when sent=true."
+ ),
)
@@ -873,6 +877,9 @@ def _disable_shares_for_identifiers(*, topic: UserInterviewTopic, identifiers: l
).update(enabled=False)
+MAX_INVITE_RECIPIENTS_PER_SEND = 500
+
+
class SendInvitesRequestSerializer(serializers.Serializer):
subject = serializers.CharField(
required=False,
@@ -1025,7 +1032,7 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"token rotation produce a fresh send."
),
)
- @action(detail=True, methods=["post"], url_path="send_invites")
+ @action(detail=True, methods=["post"], url_path="send_invites", throttle_classes=[UserInterviewInviteThrottle])
def send_invites(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
if not is_email_available():
return response.Response(
@@ -1037,8 +1044,15 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
params.is_valid(raise_exception=True)
topic = self.get_object()
- links = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)
- if not links:
+ # Enforce the cap on targeted identifiers BEFORE materializing share links, so an oversized
+ # topic is rejected without first minting an IntervieweeContext + SharingConfiguration for
+ # every target. dict.fromkeys dedups while preserving order, matching _materialize_links_for_topic.
+ targeted_identifiers = list(
+ dict.fromkeys(
+ raw for raw in [*(topic.interviewee_emails or []), *(topic.interviewee_distinct_ids or [])] if raw
+ )
+ )
+ if not targeted_identifiers:
return response.Response(
{
"error": (
@@ -1048,6 +1062,18 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
},
status=status.HTTP_400_BAD_REQUEST,
)
+ if len(targeted_identifiers) > MAX_INVITE_RECIPIENTS_PER_SEND:
+ return response.Response(
+ {
+ "error": (
+ f"Topic targets {len(targeted_identifiers)} interviewees, more than the per-send limit of "
+ f"{MAX_INVITE_RECIPIENTS_PER_SEND}. Split the targeting across multiple topics."
+ )
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ links = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)
subject_override = params.validated_data.get("subject") or ""
reply_to = params.validated_data.get("reply_to")
@@ -1056,6 +1082,7 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
send_async = params.validated_data["send_async"]
results: list[dict[str, Any]] = []
+ seen_emails: set[str] = set()
for link in links:
base = {
"interviewee_identifier": link["identifier"],
@@ -1066,6 +1093,14 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
results.append({**base, "sent": False, "reason": "not_an_email"})
continue
+ # Collapse display-name aliases that resolve to the same mailbox (e.g.
+ # "A1 <x@host>" and "A2 <x@host>") so one mailbox can't be invited repeatedly.
+ email_key = link["email"].strip().lower()
+ if email_key in seen_emails:
+ results.append({**base, "sent": False, "reason": "duplicate_recipient"})
+ continue
+ seen_emails.add(email_key)
+
built = build_invite_email_context(
topic=topic,
user_name=link["user_name"],
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index 78370451cfa5..150e8ef1921a 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -1131,6 +1131,54 @@ class TestSendInterviewInvites(_FeatureFlagEnabledMixin):
assert "evil.com" not in kwargs["subject"]
assert kwargs["template_context"]["invite_message"] == ""
+ def test_send_invites_rejects_over_recipient_cap(self):
+ topic = self._create_topic(
+ interviewee_emails=["[email protected]", "[email protected]"], interviewee_distinct_ids=[]
+ )
+
+ with (
+ patch("products.user_interviews.backend.presentation.views.MAX_INVITE_RECIPIENTS_PER_SEND", 1),
+ patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
+ ):
+ response = self.client.post(self._url(str(topic.id)), data={}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "per-send limit" in response.json()["error"]
+
+ def test_send_invites_collapses_aliases_to_one_mailbox(self):
+ topic = self._create_topic(
+ interviewee_emails=["A1 <[email protected]>", "A2 <[email protected]>", "[email protected]"],
+ interviewee_distinct_ids=[],
+ )
+
+ with (
+ patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,
+ patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),
+ ):
+ response = self.client.post(self._url(str(topic.id)), data={"send_async": False}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ results = response.json()
+ sent = [r for r in results if r["sent"]]
+ duplicates = [r for r in results if r.get("reason") == "duplicate_recipient"]
+ assert len(sent) == 1
+ assert len(duplicates) == 2
+ assert mock_message_cls.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("url", "chat about http://evil.com"),
+ ("brackets", "chat <b>now</b>"),
+ ("newline", "line one\nline two"),
+ ]
+ )
+ def test_send_invites_rejects_unsafe_subject_override(self, _name: str, subject: str):
+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
+ with patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True):
+ response = self.client.post(self._url(str(topic.id)), data={"subject": subject}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert response.json()["attr"] == "subject"
+
class TestInviteFieldValidation(_FeatureFlagEnabledMixin):
def _url(self) -> str:
diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.ts
index 23b010a71874..4e93586c82c0 100644
--- a/products/user_interviews/frontend/generated/api.schemas.ts
+++ b/products/user_interviews/frontend/generated/api.schemas.ts
@@ -178,7 +178,7 @@ export interface InterviewInviteResultApi {
interview_url: string
/** True if an email was queued for delivery. False when the recipient was skipped — see `reason`. */
sent: boolean
- /** Why the email was skipped (e.g., `not_an_email`, `already_sent`). Empty when sent=true. */
+ /** Why the email was skipped (e.g., `not_an_email`, `duplicate_recipient`, `already_sent`). Empty when sent=true. */
reason?: string
}
diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yaml
index 861a87a9ea6b..bc5a5921424a 100644
--- a/products/user_interviews/mcp/tools.yaml
+++ b/products/user_interviews/mcp/tools.yaml
@@ -272,7 +272,10 @@ tools:
on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a
button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in
the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per
- share via the messaging system's idempotency record, and a token rotation produces a fresh send key.
+ share via the messaging system's idempotency record, and a token rotation produces a fresh send key. Email
+ delivery is intentionally capped at 500 recipients per send (and rate-limited per team). For larger
+ audiences, don't loop this — use user-interview-topics-generate-links (or the links CSV export) to get one
+ public link per interviewee and mail-merge them through your own email tooling instead.
include_params:
- subject
- reply_to
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a983d41da9c4..fe8ae7551cba 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5866,7 +5866,7 @@
"feature_flag": "user-interviews"
},
"user-interview-topics-send-invites": {
- "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key.",
+ "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key. Email delivery is intentionally capped at 500 recipients per send (and rate-limited per team). For larger audiences, don't loop this — use user-interview-topics-generate-links (or the links CSV export) to get one public link per interviewee and mail-merge them through your own email tooling instead.",
"category": "User interview topics",
"feature": "user_interviews",
"summary": "Email interview invites to every targeted interviewee",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 1ec0f8074d95..2d4ebb2a720d 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6235,7 +6235,7 @@
"feature_flag": "user-interviews"
},
"user-interview-topics-send-invites": {
- "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key.",
+ "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key. Email delivery is intentionally capped at 500 recipients per send (and rate-limited per team). For larger audiences, don't loop this — use user-interview-topics-generate-links (or the links CSV export) to get one public link per interviewee and mail-merge them through your own email tooling instead.",
"category": "User interview topics",
"feature": "user_interviews",
"summary": "Email interview invites to every targeted interviewee",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9682034a8073..6ec96229ab5a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21233,7 +21233,7 @@ export namespace Schemas {
interview_url: string;
/** True if an email was queued for delivery. False when the recipient was skipped — see `reason`. */
sent: boolean;
- /** Why the email was skipped (e.g., `not_an_email`, `already_sent`). Empty when sent=true. */
+ /** Why the email was skipped (e.g., `not_an_email`, `duplicate_recipient`, `already_sent`). Empty when sent=true. */
reason?: string;
}