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(conversations): show the Slack ticket link to org members only (#101658)

Alex V9c019c73baf9
diff --git a/products/conversations/backend/api/tests/test_slack_message_routing.py b/products/conversations/backend/api/tests/test_slack_message_routing.py
index 92b7954f9c08..88557efa0a8b 100644
--- a/products/conversations/backend/api/tests/test_slack_message_routing.py
+++ b/products/conversations/backend/api/tests/test_slack_message_routing.py
@@ -12,6 +12,7 @@ from parameterized import parameterized
from slack_sdk.errors import SlackApiError
from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.team import Team
from products.conversations.backend.cache import is_nudge_suppressed
from products.conversations.backend.models import TeamConversationsSlackConfig, Ticket
@@ -19,6 +20,7 @@ from products.conversations.backend.models.constants import Channel, ChannelDeta
from products.conversations.backend.slack import (
TICKET_CONFIRM_ACTION_DISMISS,
TICKET_CONFIRM_ACTION_OPEN,
+ TICKET_VIEW_ACTION,
SlackConfirmationNeedsRetry,
create_ticket_from_confirmation,
handle_member_joined_channel,
@@ -26,6 +28,8 @@ from products.conversations.backend.slack import (
handle_support_mention,
handle_support_message,
handle_support_reaction,
+ ticket_created_blocks,
+ ticket_deep_link,
)
from products.conversations.backend.tasks.slack import process_supporthog_interactivity
from products.customer_analytics.backend.facade import api as customer_analytics
@@ -38,6 +42,17 @@ MESSAGE_SENT_AT = datetime(2023, 11, 14, 22, 13, 20, 100, tzinfo=UTC)
USE_TEAMMATE_EMAIL = "use-the-org-members-own-email"
+def _create_slack_ticket(team: Team) -> Ticket:
+ return Ticket.objects.create_with_number(
+ team=team,
+ channel_source=Channel.SLACK,
+ widget_session_id="",
+ distinct_id="",
+ slack_channel_id="C_CONFIG",
+ slack_thread_ts=MESSAGE_TS,
+ )
+
+
class TestSlackMessageRouting(BaseTest):
def setUp(self):
super().setUp()
@@ -1147,6 +1162,9 @@ class TestSupporthogInteractivity(BaseTest):
capture_patcher = patch(f"{TASKS_MODULE}.capture_nudge_event")
self.mock_capture_event = capture_patcher.start()
self.addCleanup(capture_patcher.stop)
+ support_capture_patcher = patch(f"{TASKS_MODULE}.capture_support_event")
+ self.mock_capture_support_event = support_capture_patcher.start()
+ self.addCleanup(support_capture_patcher.stop)
def _payload(self, action_id: str, value: dict) -> dict:
return {
@@ -1355,3 +1373,97 @@ class TestSupporthogInteractivity(BaseTest):
_team, event_name, event_props = self.mock_capture_event.call_args.args
assert event_name == "support nudge open ticket clicked"
assert event_props["ticket_created"] is False
+
+ def _view_payload(self, ticket_number: object, *, thread_ts: str = MESSAGE_TS) -> dict:
+ payload = self._payload(TICKET_VIEW_ACTION, {"ticket_number": ticket_number})
+ payload["message"]["thread_ts"] = thread_ts
+ return payload
+
+ def _link_click_properties(self) -> dict:
+ _team, event_name, event_props = self.mock_capture_support_event.call_args.args
+ assert event_name == "support slack ticket link clicked"
+ return event_props
+
+ @patch(f"{TASKS_MODULE}.resolve_slack_user")
+ @patch(f"{TASKS_MODULE}.get_slack_client")
+ def test_view_sends_the_link_to_an_org_member_only_they_can_see(self, mock_get_client, mock_resolve_user):
+ ticket = _create_slack_ticket(self.team)
+ mock_resolve_user.return_value = {"name": "Teammate", "email": self.user.email, "team_id": "T123"}
+
+ process_supporthog_interactivity(self._view_payload(ticket.ticket_number), "T123")
+
+ client = mock_get_client.return_value
+ client.chat_postEphemeral.assert_called_once()
+ kwargs = client.chat_postEphemeral.call_args.kwargs
+ assert kwargs["user"] == "U_CLICKER"
+ assert kwargs["thread_ts"] == MESSAGE_TS
+ assert ticket_deep_link(ticket, self.team) in kwargs["text"]
+ client.chat_postMessage.assert_not_called()
+ client.chat_update.assert_not_called()
+ assert self._link_click_properties()["is_org_member"] is True
+
+ @patch(f"{TASKS_MODULE}.resolve_slack_user")
+ @patch(f"{TASKS_MODULE}.get_slack_client")
+ def test_view_withholds_the_link_from_a_non_member(self, mock_get_client, mock_resolve_user):
+ ticket = _create_slack_ticket(self.team)
+ mock_resolve_user.return_value = {"name": "Customer", "email": "[email protected]", "team_id": "T123"}
+
+ process_supporthog_interactivity(self._view_payload(ticket.ticket_number), "T123")
+
+ text = mock_get_client.return_value.chat_postEphemeral.call_args.kwargs["text"]
+ assert ticket_deep_link(ticket, self.team) not in text
+ assert "reply in this thread" in text.lower()
+ assert self._link_click_properties()["is_org_member"] is False
+
+ @patch(f"{TASKS_MODULE}.resolve_slack_user")
+ @patch(f"{TASKS_MODULE}.get_slack_client")
+ def test_view_withholds_the_link_from_an_external_workspace(self, mock_get_client, mock_resolve_user):
+ # A Slack Connect participant's profile email is set by their own workspace, so an
+ # email that matches a teammate is not proof of membership on its own.
+ ticket = _create_slack_ticket(self.team)
+ mock_resolve_user.return_value = {"name": "Outsider", "email": self.user.email, "team_id": "T_OTHER"}
+
+ process_supporthog_interactivity(self._view_payload(ticket.ticket_number), "T123")
+
+ text = mock_get_client.return_value.chat_postEphemeral.call_args.kwargs["text"]
+ assert ticket_deep_link(ticket, self.team) not in text
+ assert self._link_click_properties()["is_org_member"] is False
+
+ @parameterized.expand([("unknown_number", 4242), ("malformed_value", None)])
+ @patch(f"{TASKS_MODULE}.resolve_slack_user")
+ @patch(f"{TASKS_MODULE}.get_slack_client")
+ def test_view_reports_a_ticket_it_cannot_resolve(self, _name, ticket_number, mock_get_client, mock_resolve_user):
+ mock_resolve_user.return_value = {"name": "Teammate", "email": self.user.email, "team_id": "T123"}
+
+ process_supporthog_interactivity(self._view_payload(ticket_number), "T123")
+
+ text = mock_get_client.return_value.chat_postEphemeral.call_args.kwargs["text"]
+ assert "isn't available" in text
+ assert "http" not in text
+ properties = self._link_click_properties()
+ assert properties["ticket_found"] is False
+ assert properties["is_org_member"] is False
+
+
+class TestTicketConfirmationBlocks(BaseTest):
+ def test_confirmation_carries_a_view_button_and_no_url(self):
+ ticket = _create_slack_ticket(self.team)
+
+ blocks = ticket_created_blocks(ticket, self.team)
+
+ assert ticket_deep_link(ticket, self.team) not in json.dumps(blocks)
+ actions = [block for block in blocks if block["type"] == "actions"]
+ assert len(actions) == 1
+ button = actions[0]["elements"][0]
+ assert button["action_id"] == TICKET_VIEW_ACTION
+ assert json.loads(button["value"]) == {"ticket_number": ticket.ticket_number}
+
+ def test_deep_link_addresses_the_ticket_by_number(self):
+ ticket = _create_slack_ticket(self.team)
+
+ assert ticket_deep_link(ticket, self.team).endswith(
+ f"/project/{self.team.id}/support/tickets/{ticket.ticket_number}"
+ )
+
+ def test_no_button_without_a_ticket(self):
+ assert [block["type"] for block in ticket_created_blocks(None, self.team)] == ["section"]
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index 818d1adfb510..e00bbeaf93db 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -127,6 +127,10 @@ def get_safe_ticket_emoji(settings_dict: dict) -> str:
TICKET_CONFIRM_ACTION_OPEN = "supporthog_open_ticket_confirm"
TICKET_CONFIRM_ACTION_DISMISS = "supporthog_open_ticket_dismiss"
+# "View ticket" button on a ticket confirmation. The URL stays out of the message because
+# Slack has no message that only part of a channel can see (see _post_ticket_link).
+TICKET_VIEW_ACTION = "supporthog_view_ticket"
+
def _get_team_id(team: Team) -> int:
team_id = getattr(team, "id", None)
@@ -140,6 +144,36 @@ def ticket_created_text(ticket: "Ticket | None") -> str:
return f":ticket: Ticket #{ticket.ticket_number} created" if ticket else ":ticket: Ticket created"
+def ticket_deep_link(ticket: "Ticket", team: Team) -> str:
+ """App URL for a ticket. The detail scene is addressed by ticket number, not by UUID."""
+ return f"{settings.SITE_URL}/project/{_get_team_id(team)}/support/tickets/{ticket.ticket_number}"
+
+
+def ticket_created_blocks(ticket: "Ticket | None", team: Team) -> list[dict]:
+ """Blocks for the ticket confirmation, carrying a "View ticket" button when there is a ticket.
+
+ The button holds the ticket number rather than the link, so the channel never shows the URL.
+ Without a ticket there is nothing to view, so the section stands alone.
+ """
+ blocks: list[dict] = [{"type": "section", "text": {"type": "mrkdwn", "text": ticket_created_text(ticket)}}]
+ if ticket is None:
+ return blocks
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "action_id": TICKET_VIEW_ACTION,
+ "text": {"type": "plain_text", "text": "View ticket", "emoji": True},
+ "value": json.dumps({"ticket_number": ticket.ticket_number}),
+ }
+ ],
+ }
+ )
+ return blocks
+
+
class _NoRedirectHandler(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
@@ -598,15 +632,7 @@ def create_or_update_slack_ticket(
"channel": slack_channel_id,
"thread_ts": thread_ts,
"text": f"Ticket #{ticket.ticket_number} created.",
- "blocks": [
- {
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": ticket_created_text(ticket),
- },
- },
- ],
+ "blocks": ticket_created_blocks(ticket, team),
}
bot_display_name = support_settings.get("slack_bot_display_name")
bot_icon_url = support_settings.get("slack_bot_icon_url")
@@ -855,10 +881,10 @@ def nudge_event_properties(
}
-def capture_nudge_event(team: Team, event: str, properties: dict[str, Any]) -> None:
- """Internal product analytics for the nudge funnel, attributed to the team like
- report_team_action — but through a scoped client, since both call sites run in
- Celery tasks where the global client's flush can be lost."""
+def capture_support_event(team: Team, event: str, properties: dict[str, Any]) -> None:
+ """Internal product analytics attributed to the team like report_team_action — but through
+ a scoped client, since every call site runs in a Celery task where the global client's
+ flush can be lost."""
with ph_scoped_capture() as capture:
capture(
distinct_id=str(team.uuid),
@@ -868,6 +894,11 @@ def capture_nudge_event(team: Team, event: str, properties: dict[str, Any]) -> N
)
+def capture_nudge_event(team: Team, event: str, properties: dict[str, Any]) -> None:
+ """Internal product analytics for the nudge funnel."""
+ capture_support_event(team, event, properties)
+
+
def _is_nudge_classifier_flag_enabled(team: Team) -> bool:
# Same shape as the AI-suggestions master flag (temporal/coordinator.py): targeted by
# project group, and release conditions can match on the project's `uuid`, so it must be
diff --git a/products/conversations/backend/tasks/slack.py b/products/conversations/backend/tasks/slack.py
index 74d392fcc1b2..f5d457f9ef63 100644
--- a/products/conversations/backend/tasks/slack.py
+++ b/products/conversations/backend/tasks/slack.py
@@ -15,7 +15,11 @@ from celery.exceptions import MaxRetriesExceededError
from slack_sdk.errors import SlackApiError
from posthog.comment.formatting import extract_images_from_rich_content, rich_content_to_slack_payload
-from posthog.helpers.slack_identity import resolve_slack_avatar_by_email
+from posthog.helpers.slack_identity import (
+ resolve_posthog_user_for_slack,
+ resolve_slack_avatar_by_email,
+ resolve_slack_user,
+)
from posthog.models.team import Team
from posthog.models.uploaded_media import UploadedMedia
from posthog.scoping_audit import skip_team_scope_audit
@@ -49,10 +53,12 @@ from products.conversations.backend.services.inbound_events import (
from products.conversations.backend.slack import (
TICKET_CONFIRM_ACTION_DISMISS,
TICKET_CONFIRM_ACTION_OPEN,
+ TICKET_VIEW_ACTION,
NudgeClassifierVerdict,
NudgeFunnelVerdict,
SlackConfirmationNeedsRetry,
capture_nudge_event,
+ capture_support_event,
create_ticket_from_confirmation,
get_bot_user_id,
get_safe_ticket_emoji,
@@ -63,7 +69,9 @@ from products.conversations.backend.slack import (
handle_support_message,
handle_support_reaction,
nudge_event_properties,
+ ticket_created_blocks,
ticket_created_text,
+ ticket_deep_link,
)
from ..support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, supporthog_missing_file_scopes
@@ -261,8 +269,13 @@ def _slack_api_error_code(exc: Exception) -> str | None:
return error if isinstance(error, str) else None
-def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: str) -> PromptUpdateResult:
- """Replace the "open a ticket?" prompt in place with a new status line (buttons removed).
+def _update_supporthog_prompt(
+ team: Team, channel: str, message_ts: str, text: str, *, blocks: list[dict] | None = None
+) -> PromptUpdateResult:
+ """Replace the "open a ticket?" prompt in place with a new status line.
+
+ The prompt's own buttons go away unless the caller passes replacement ``blocks`` — a
+ resolved prompt carries the confirmation's "View ticket" button, nothing else.
Never raises. Callers retry only a ``transient`` result. A missing or deleted prompt
cannot recover, so those must not sit in the inbound retry queue.
@@ -274,7 +287,7 @@ def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: s
channel=channel,
ts=message_ts,
text=text,
- blocks=[{"type": "section", "text": {"type": "mrkdwn", "text": text}}],
+ blocks=blocks or [{"type": "section", "text": {"type": "mrkdwn", "text": text}}],
)
return "updated"
except Exception as exc:
@@ -307,6 +320,65 @@ def _post_dismiss_acknowledgment(team: Team, channel: str, user: str, thread_ts:
logger.warning("supporthog_interactivity_dismiss_ack_failed", exc_info=True)
+def _post_ticket_link(
+ team: Team,
+ *,
+ slack_team_id: str,
+ channel: str,
+ thread_ts: str,
+ clicker: str,
+ ticket_number: int | str | None,
+) -> None:
+ """Answer a "View ticket" click with an ephemeral link, so only the clicker sees the URL.
+
+ The button rides on a public confirmation, so anyone in the channel can click it. Two checks
+ gate the link: the clicker belongs to the workspace the app is installed in, and their Slack
+ profile email matches a member of the team's organization. The workspace check is what makes
+ the email check worth anything — an external (Slack Connect) participant's profile email is
+ set by their own workspace, so it can claim a teammate's address.
+
+ Best-effort: a failure leaves the click unanswered rather than retrying.
+ """
+ if not channel or not clicker:
+ return
+ try:
+ number = int(ticket_number) if ticket_number is not None else 0
+ except (TypeError, ValueError):
+ number = 0
+ try:
+ client = get_slack_client(team)
+ ticket = Ticket.objects.filter(team=team, ticket_number=number).first() if number > 0 else None
+ is_org_member = False
+ if ticket is None:
+ logger.warning("supporthog_ticket_link_unknown_ticket", team_id=team.pk, ticket_number=number)
+ text = "That ticket isn't available any more."
+ else:
+ slack_user = resolve_slack_user(client, clicker, workspace=slack_team_id)
+ in_workspace = bool(slack_team_id) and slack_user.get("team_id") == slack_team_id
+ is_org_member = in_workspace and resolve_posthog_user_for_slack(slack_user.get("email"), team) is not None
+ if is_org_member:
+ link = ticket_deep_link(ticket, team)
+ text = f"<{link}|Ticket #{ticket.ticket_number}>. Only you can see this message."
+ else:
+ text = (
+ f"Ticket #{ticket.ticket_number} opens in PostHog, which only the support team can reach. "
+ "Reply in this thread and they'll see it."
+ )
+ client.chat_postEphemeral(channel=channel, user=clicker, thread_ts=thread_ts or None, text=text)
+ capture_support_event(
+ team,
+ "support slack ticket link clicked",
+ {
+ "slack_team_id": slack_team_id,
+ "slack_channel_id": channel,
+ "ticket_found": ticket is not None,
+ "is_org_member": is_org_member,
+ },
+ )
+ except Exception:
+ logger.warning("supporthog_ticket_link_failed", exc_info=True)
+
+
def _raise_if_retry_allowed(allow_retry: bool) -> None:
if allow_retry:
raise TransientInboundError
@@ -347,6 +419,18 @@ def _handle_supporthog_interactivity(
value = json.loads(action.get("value") or "{}")
except (json.JSONDecodeError, TypeError):
value = {}
+
+ if action_id == TICKET_VIEW_ACTION:
+ _post_ticket_link(
+ team,
+ slack_team_id=slack_team_id,
+ channel=prompt_channel,
+ thread_ts=(payload.get("message") or {}).get("thread_ts") or "",
+ clicker=clicker,
+ ticket_number=value.get("ticket_number"),
+ )
+ return True
+
source_channel = value.get("channel", "")
source_message_ts = value.get("message_ts", "")
# Echoed back from the prompt's button value, normalized at the trust boundary: the
@@ -407,7 +491,13 @@ def _handle_supporthog_interactivity(
else:
emoji = get_safe_ticket_emoji(support_settings)
text = f":warning: Couldn't open a ticket — react with :{emoji}: or @mention us to try again."
- final_update = _update_supporthog_prompt(team, prompt_channel, prompt_ts, text)
+ final_update = _update_supporthog_prompt(
+ team,
+ prompt_channel,
+ prompt_ts,
+ text,
+ blocks=ticket_created_blocks(ticket, team) if ticket else None,
+ )
prompt_can_be_updated = bool(prompt_channel and prompt_ts)
if final_update == "transient" and prompt_can_be_updated:
# The progress placeholder must never be the prompt's last word. Retry a