Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(comments): tighten send to slack checks for ticket discussions (#126384)

Chris Shine095a49a87c87
diff --git a/frontend/src/lib/components/Comments/Comment.tsx b/frontend/src/lib/components/Comments/Comment.tsx
index b28f8d98b013..b5bfe22fdfd7 100644
--- a/frontend/src/lib/components/Comments/Comment.tsx
+++ b/frontend/src/lib/components/Comments/Comment.tsx
@@ -187,7 +187,7 @@ const CommentEditingForm = ({ comment }: { comment: CommentType }): JSX.Element
}
const CommentTopRow = ({ comment }: { comment: CommentType }): JSX.Element => {
- const { disabledReasonFor } = useValues(commentsLogic)
+ const { disabledReasonFor, sendToSlackDisabledReasonFor } = useValues(commentsLogic)
const { deleteComment, setEditingComment, sendEmojiReaction, setReplyingComment } = useActions(commentsLogic)
const { featureFlags } = useValues(featureFlagLogic)
const { openModal } = useActions(sendCommentToSlackLogic)
@@ -261,6 +261,7 @@ const CommentTopRow = ({ comment }: { comment: CommentType }): JSX.Element => {
icon: <IconSlack />,
label: 'Send to Slack',
onClick: () => openModal(comment),
+ disabledReason: sendToSlackDisabledReasonFor(comment),
},
]
: []),
diff --git a/frontend/src/lib/components/Comments/commentsLogic.ts b/frontend/src/lib/components/Comments/commentsLogic.ts
index fdb8c905837d..385fbcdc3720 100644
--- a/frontend/src/lib/components/Comments/commentsLogic.ts
+++ b/frontend/src/lib/components/Comments/commentsLogic.ts
@@ -15,7 +15,7 @@ import { userLogic } from 'scenes/userLogic'
import { sidePanelDiscussionLogic } from '~/layout/navigation-3000/sidepanel/panels/discussion/sidePanelDiscussionLogic'
import { membersLogic } from '~/models/membersLogic'
-import { CommentType } from '~/types'
+import { ActivityScope, CommentType } from '~/types'
import type { OrganizationMemberType, UserType } from '~/types'
import { commentsSendToSlackCreate } from 'products/platform_features/frontend/generated/api'
@@ -92,6 +92,7 @@ export interface commentsLogicValues {
replyingCommentId: string | null
richContentEditor: RichContentEditorType | null
selectedCommentId: string | null
+ sendToSlackDisabledReasonFor: (comment: CommentType) => string | null
sortedComments: CommentType[]
threadExpansion: Record<string, boolean>
}
@@ -370,6 +371,9 @@ export interface commentsLogicMeta {
) => JSONContent | null
isMyComment: (user: UserType | null) => (comment: CommentType) => boolean
disabledReasonFor: (user: UserType | null) => (comment: CommentType) => string | null
+ sendToSlackDisabledReasonFor: (
+ isMyComment: (comment: CommentType) => boolean
+ ) => (comment: CommentType) => string | null
}
}
@@ -1003,6 +1007,16 @@ export const commentsLogic = kea<commentsLogicType>([
comment.created_by?.uuid === user?.uuid ? null : 'You can only delete your own comments'
},
],
+
+ sendToSlackDisabledReasonFor: [
+ (s) => [s.isMyComment],
+ (isMyComment: (comment: CommentType) => boolean) => {
+ return (comment: CommentType): string | null =>
+ comment.scope === ActivityScope.TICKET && !isMyComment(comment)
+ ? 'Only the person who started this discussion can send it to Slack'
+ : null
+ },
+ ],
}),
subscriptions(({ actions, values }) => ({
diff --git a/posthog/api/comments.py b/posthog/api/comments.py
index 30db638eb85c..1097d819d4f6 100644
--- a/posthog/api/comments.py
+++ b/posthog/api/comments.py
@@ -19,6 +19,7 @@ from rest_framework.response import Response
from slack_sdk.errors import SlackApiError
from posthog.api.forbid_destroy_model import ForbidDestroyModel
+from posthog.api.integration import take_slack_channels_info_budget
from posthog.api.pagination import StableCursorPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
@@ -51,6 +52,7 @@ from posthog.models.comment.utils import (
from posthog.models.integration import SlackIntegration
from posthog.oauth_provenance import get_oauth_access_token, is_sandbox_oauth_request
from posthog.permissions import is_scout_sandbox_request
+from posthog.slack.channels import is_shared_channel
from posthog.tasks.comment_slack_sync import backfill_comment_slack_thread
from posthog.tasks.email import send_discussions_mentioned
@@ -766,6 +768,16 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
pagination_class = CommentPagination
scope_object = "comment"
scope_object_read_actions = ["list", "retrieve", "thread", "count"]
+ # A custom action missing here resolves to no required scope, and a scoped token is then refused
+ # even with comment:write.
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "patch",
+ "destroy",
+ "send_to_slack",
+ ]
def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
"""Ticket-scoped comments require ticket API scope access instead of comment access.
@@ -1212,14 +1224,19 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
serializer = CommentSerializer(comment, context=self.get_serializer_context())
return Response(serializer.data)
- def _resolve_slack_channel_name(self, integration: IntegrationRecord, channel_id: str, user: User) -> str:
+ def _resolve_slack_channel_name(
+ self, integration: IntegrationRecord, channel_id: str, user: User, *, workspace_only: bool
+ ) -> str:
"""Resolve the target channel server-side — the caller-supplied id is never paired with a
caller-supplied label. Private channels are restricted to the workspace connector (matching
the channel picker, which hides them from everyone else) and their names are never persisted,
- since the stored name is shown to every reader of the discussion.
+ since the stored name is shown to every reader of the discussion. With `workspace_only`, a
+ channel shared with another Slack workspace is refused too: ticket discussions are internal
+ notes about a customer, and that customer can be a member of a shared channel.
"""
client = SlackIntegration(integration).client
client.timeout = 10 # keep a slow Slack workspace from pinning the request worker
+ take_slack_channels_info_budget(integration.id)
try:
channel = client.conversations_info(channel=channel_id)["channel"]
except SlackApiError as e:
@@ -1229,6 +1246,11 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
# guard and let any member mirror a discussion into someone's DMs with the bot.
if channel.get("is_im") or channel.get("is_mpim"):
raise exceptions.ValidationError("Discussions can only be sent to Slack channels, not direct messages")
+ if workspace_only and is_shared_channel(channel):
+ raise exceptions.ValidationError(
+ "Ticket discussions can't be sent to a Slack channel shared with another workspace. "
+ "Pick a channel only your workspace can access."
+ )
if channel.get("is_private"):
if integration.created_by_id != user.id:
raise exceptions.PermissionDenied(
@@ -1237,6 +1259,27 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
return ""
return channel.get("name") or ""
+ @staticmethod
+ def _existing_mirror_response(slack_thread: CommentSlackThread, channel_id: str) -> Response | None:
+ """Answer a send for a discussion that already has a mirror row, without calling Slack.
+
+ A posted mirror is idempotent: the same channel returns the mapping with no re-post, and
+ another channel is a 400 that names the existing one. A reservation with no posted root is
+ a send still in flight (409) until STALE_SLACK_RESERVATION_GRACE passes. After that it is a
+ crashed send, and None tells the caller to adopt it. send_to_slack calls this before the
+ channel lookup too, so a re-send spends no Slack call and no lookup budget.
+ """
+ if slack_thread.slack_thread_ts:
+ if slack_thread.slack_channel_id != channel_id:
+ raise exceptions.ValidationError(
+ "This discussion is already mirrored to Slack channel "
+ f"{slack_thread.slack_channel_id} — a discussion can only sync to one thread"
+ )
+ return Response(CommentSlackThreadSerializer(slack_thread).data)
+ if timezone.now() - slack_thread.created_at < STALE_SLACK_RESERVATION_GRACE:
+ raise Conflict("This discussion is already being sent to Slack — try again shortly")
+ return None
+
@extend_schema(
request=SendCommentToSlackSerializer,
responses=CommentSlackThreadSerializer,
@@ -1245,14 +1288,17 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
"replies) as a new Slack thread; later replies on either side sync across. A discussion "
"mirrors to exactly one Slack thread: re-calling with the same channel returns the "
"existing mirror; a different channel is a 400 naming the existing one. 409 while a "
- "concurrent send is in flight. 404 when the feature is not enabled for the team."
+ "concurrent send is in flight. 404 when the feature is not enabled for the team. "
+ "Only the person who started a ticket discussion can send it (403), and it cannot go to "
+ "a channel shared with another Slack workspace (400). "
+ "429 when the Slack integration has made too many channel lookups in the last minute."
),
)
@action(methods=["POST"], detail=True)
def send_to_slack(self, request: Request, *args: Any, **kwargs: Any) -> Response:
team = self.team
if not self._slack_mirror_flag_enabled():
- raise exceptions.NotFound()
+ raise exceptions.NotFound("Sending discussions to Slack isn't available for your account yet.")
comment = self.get_object()
if comment.source_comment_id is not None:
@@ -1262,6 +1308,14 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
if comment.scope in OBSERVATION_COMMENT_SCOPES:
# A Slack channel has no observation access check, in either direction.
raise exceptions.ValidationError("Replay Vision observation notes cannot be sent to Slack")
+ is_ticket_discussion = comment.scope in TICKET_COMMENT_SCOPES
+ if is_ticket_discussion:
+ if is_scout_sandbox_request(request):
+ raise exceptions.PermissionDenied("Scouts can't send ticket discussions to Slack.")
+ if comment.created_by_id != request.user.pk:
+ raise exceptions.PermissionDenied(
+ "Only the person who started this discussion can send it to Slack. Ask them to send it."
+ )
params = SendCommentToSlackSerializer(data=request.data)
params.is_valid(raise_exception=True)
@@ -1273,7 +1327,13 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
except IntegrationNotFound:
raise exceptions.ValidationError("Slack integration not found")
- channel_name = self._resolve_slack_channel_name(integration, channel_id, cast(User, request.user))
+ existing = CommentSlackThread.objects.for_team(team.id).filter(source_comment=comment).first()
+ if existing is not None and (response := self._existing_mirror_response(existing, channel_id)):
+ return response
+
+ channel_name = self._resolve_slack_channel_name(
+ integration, channel_id, cast(User, request.user), workspace_only=is_ticket_discussion
+ )
# Reserve the mapping before posting: a discussion mirrors to exactly one Slack thread (1:1),
# and the source_comment OneToOne makes this get_or_create race-safe — a double-click can't
@@ -1292,17 +1352,8 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
},
)
if not created:
- if slack_thread.slack_thread_ts:
- if slack_thread.slack_channel_id != channel_id:
- raise exceptions.ValidationError(
- "This discussion is already mirrored to Slack channel "
- f"{slack_thread.slack_channel_id} — a discussion can only sync to one thread"
- )
- # Idempotent: already mirrored to this channel — return the mapping, no re-post.
- return Response(CommentSlackThreadSerializer(slack_thread).data)
- if timezone.now() - slack_thread.created_at < STALE_SLACK_RESERVATION_GRACE:
- # Another request holds the reservation and its root post is still in flight.
- raise Conflict("This discussion is already being sent to Slack — try again shortly")
+ if response := self._existing_mirror_response(slack_thread, channel_id):
+ return response
# A reservation this old with no root message is a crashed send that would otherwise
# block the discussion forever. Adopt it and retry the post; resetting created_at
# re-bounds the reply backfill to this attempt.
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 9722ae246c84..251eef084756 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -721,6 +721,15 @@ SLACK_CHANNELS_CACHE_SECONDS = 60 * 60
# quota. A re-check spends one per channel it warned about, well inside the cap.
SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE = 30
+
+def take_slack_channels_info_budget(integration_id: int) -> None:
+ _take_slack_lookup_budget(
+ f"slack/{integration_id}/channels_info_budget",
+ SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE,
+ "Too many Slack channel lookups. Try again in a minute.",
+ )
+
+
# Server-side floor between forced member-list refreshes, matching the picker's visible cooldown.
SLACK_USERS_MIN_REFRESH_SECONDS = 30
@@ -2036,11 +2045,7 @@ class IntegrationViewSet(
return Response({"channels": [channel], "next": None, "previous": None})
# Past the cached list every lookup reaches Slack, and a forced one skips the list
# altogether, so the same per-minute budget the member lookup uses applies here.
- _take_slack_lookup_budget(
- f"slack/{instance.id}/channels_info_budget",
- SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE,
- "Too many Slack channel lookups. Try again in a minute.",
- )
+ take_slack_channels_info_budget(instance.id)
try:
channel = slack.get_channel_by_id(channel_id, should_include_private_channels, authed_user)
except SlackApiError as e:
diff --git a/posthog/api/test/test_comment_slack_sync.py b/posthog/api/test/test_comment_slack_sync.py
index adebd002ef01..57b2e9ec7132 100644
--- a/posthog/api/test/test_comment_slack_sync.py
+++ b/posthog/api/test/test_comment_slack_sync.py
@@ -16,6 +16,8 @@ from posthog.api.comments import _slack_thread_url
from posthog.helpers.slack_thread_mirror import _discussion_card_blocks
from posthog.models.comment import Comment, CommentSlackThread
from posthog.models.integration import Integration
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
from posthog.tasks.comment_slack_sync import (
BACKFILL_BATCH_SIZE,
BACKFILL_RESCHEDULE_COUNTDOWN_SECONDS,
@@ -25,6 +27,8 @@ from posthog.tasks.comment_slack_sync import (
)
from products.canvas.backend.facade import testing as canvas_testing
+from products.conversations.backend.models import Ticket
+from products.conversations.backend.models.constants import Channel, Status
class TestDiscussionCardBlocks(SimpleTestCase):
@@ -65,6 +69,15 @@ class TestSendCommentToSlack(APIBaseTest):
"content": "hello",
"created_by": self.user,
}
+ if kwargs.get("scope") == "Ticket":
+ ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.WIDGET,
+ widget_session_id="slack-send-session",
+ distinct_id="slack-send-user",
+ status=Status.OPEN,
+ )
+ defaults["item_id"] = str(ticket.id)
defaults.update(kwargs)
return Comment.objects.create(**defaults)
@@ -95,30 +108,45 @@ class TestSendCommentToSlack(APIBaseTest):
"channel": {"id": "C1", "name": name, "is_private": is_private, **flags}
}
- @parameterized.expand([("dm", {"is_im": True}), ("group_dm", {"is_mpim": True, "is_private": True})])
+ @parameterized.expand(
+ [
+ # is_im conversations don't report is_private, so without an explicit guard a member
+ # could mirror a discussion into someone's DMs with the bot.
+ ("dm", "Insight", {"is_im": True}, "direct message"),
+ ("group_dm", "Insight", {"is_mpim": True, "is_private": True}, "direct message"),
+ ("ticket_to_shared_channel", "Ticket", {"is_ext_shared": True}, "shared with another workspace"),
+ ]
+ )
@patch("posthog.api.comments.backfill_comment_slack_thread.delay")
@patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
@patch("posthog.api.comments.SlackIntegration")
- def test_cannot_send_to_a_direct_message(self, _name, flags, mock_slack, _flag, _backfill):
- # is_im conversations don't report is_private, so without an explicit guard a member
- # could mirror a discussion into someone's DMs with the bot.
+ def test_rejects_disallowed_channel_kinds(self, _name, scope, flags, expected_detail, mock_slack, _flag, _backfill):
self._mock_channel_info(mock_slack, **flags)
- comment = self._comment()
+ comment = self._comment(scope=scope)
- res = self._send(comment.id, channel_id="D1")
+ res = self._send(comment.id)
assert res.status_code == status.HTTP_400_BAD_REQUEST
- assert "direct message" in str(res.json())
+ assert expected_detail in str(res.json())
assert not CommentSlackThread.objects.for_team(self.team.id).exists()
mock_slack.return_value.client.chat_postMessage.assert_not_called()
+ @parameterized.expand(
+ [
+ ("insight", "Insight", {}),
+ ("insight_to_shared_channel", "Insight", {"is_ext_shared": True}),
+ ("ticket", "Ticket", {}),
+ ]
+ )
@patch("posthog.api.comments.backfill_comment_slack_thread.delay")
@patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
@patch("posthog.api.comments.SlackIntegration")
- def test_creates_mirror_posts_root_and_enqueues_backfill(self, mock_slack, _flag, mock_backfill):
+ def test_creates_mirror_posts_root_and_enqueues_backfill(
+ self, _name, scope, flags, mock_slack, _flag, mock_backfill
+ ):
mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.1"}
- self._mock_channel_info(mock_slack)
- comment = self._comment()
+ self._mock_channel_info(mock_slack, **flags)
+ comment = self._comment(scope=scope)
# A client-supplied channel_name must have no effect — the name is resolved from Slack.
res = self._send(comment.id, extra={"channel_name": "#spoofed"})
@@ -134,6 +162,25 @@ class TestSendCommentToSlack(APIBaseTest):
assert mock_slack.return_value.client.chat_postMessage.call_count == 1
mock_backfill.assert_called_once_with(comment_slack_thread_id=str(mirror.id))
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_a_token_with_comment_write_can_send_a_discussion(self, mock_slack, _flag, _backfill):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.1"}
+ self._mock_channel_info(mock_slack)
+ comment = self._comment()
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="agent", user=self.user, secure_value=hash_key_value(value), scopes=["comment:write"]
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {value}")
+
+ res = self._send(comment.id)
+
+ assert res.status_code == status.HTTP_200_OK, res.json()
+
+ @patch("posthog.api.integration.SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE", 1)
@patch("posthog.api.comments.backfill_comment_slack_thread.delay")
@patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
@patch("posthog.api.comments.SlackIntegration")
@@ -171,8 +218,10 @@ class TestSendCommentToSlack(APIBaseTest):
res = self._send(comment.id)
assert res.status_code == status.HTTP_404_NOT_FOUND
+ assert "Sending discussions to Slack" in res.json()["detail"]
assert not CommentSlackThread.objects.for_team(self.team.id).exists()
+ @patch("posthog.api.integration.SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE", 1)
@patch("posthog.api.comments.backfill_comment_slack_thread.delay")
@patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
@patch("posthog.api.comments.SlackIntegration")
@@ -190,6 +239,7 @@ class TestSendCommentToSlack(APIBaseTest):
assert mock_slack.return_value.client.chat_postMessage.call_count == 1
assert CommentSlackThread.objects.for_team(self.team.id).get().slack_channel_id == "C1"
+ @patch("posthog.api.integration.SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE", 0)
@patch("posthog.api.comments.backfill_comment_slack_thread.delay")
@patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
@patch("posthog.api.comments.SlackIntegration")
@@ -267,19 +317,23 @@ class TestSendCommentToSlack(APIBaseTest):
assert not CommentSlackThread.objects.for_team(self.team.id).exists()
mock_slack.return_value.client.chat_postMessage.assert_not_called()
+ @patch("posthog.api.integration.SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE", 1)
@patch("posthog.api.comments.backfill_comment_slack_thread.delay")
@patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
@patch("posthog.api.comments.SlackIntegration")
- def test_channel_lookup_failure_is_a_400(self, mock_slack, _flag, _backfill):
+ def test_channel_lookup_failure_is_a_400_and_spends_the_lookup_budget(self, mock_slack, _flag, _backfill):
mock_slack.return_value.client.conversations_info.side_effect = SlackApiError(
"boom", {"error": "channel_not_found"}
)
comment = self._comment()
res = self._send(comment.id)
+ retry = self._send(comment.id, channel_id="C2")
assert res.status_code == status.HTTP_400_BAD_REQUEST
assert "channel_not_found" in str(res.json())
+ assert retry.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert mock_slack.return_value.client.conversations_info.call_count == 1
assert not CommentSlackThread.objects.for_team(self.team.id).exists()
mock_slack.return_value.client.chat_postMessage.assert_not_called()
@@ -295,6 +349,27 @@ class TestSendCommentToSlack(APIBaseTest):
assert res.status_code == status.HTTP_400_BAD_REQUEST
assert not CommentSlackThread.objects.for_team(self.team.id).exists()
+ @parameterized.expand(
+ [
+ ("ticket", "Ticket", status.HTTP_403_FORBIDDEN),
+ ("insight", "Insight", status.HTTP_200_OK),
+ ]
+ )
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_only_the_author_can_send_a_ticket_discussion(
+ self, _name, scope, expected_status, mock_slack, _flag, _backfill
+ ):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.1"}
+ self._mock_channel_info(mock_slack)
+ teammate = self._create_user("[email protected]")
+
+ res = self._send(self._comment(scope=scope, created_by=teammate).id)
+
+ assert res.status_code == expected_status, res.json()
+ assert CommentSlackThread.objects.for_team(self.team.id).exists() is (expected_status == status.HTTP_200_OK)
+
class TestCommentReplySlackSignal(APIBaseTest):
def setUp(self):
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index ce264f09353e..dc962b9dede6 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -2789,24 +2789,30 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):
if expected_status == status.HTTP_200_OK:
assert self.ticket.status == Status.RESOLVED
- @parameterized.expand([("create", "post"), ("update", "patch")])
- def test_scout_cannot_write_generic_ticket_comments(self, _name: str, method: str) -> None:
+ @parameterized.expand(
+ [
+ ("create", "post", "conversations_ticket", ""),
+ ("update", "patch", "conversations_ticket", "{id}/"),
+ ("send_to_slack", "post", "Ticket", "{id}/send_to_slack/"),
+ ]
+ )
+ @patch("posthog.api.comments.CommentViewSet._slack_mirror_flag_enabled", return_value=True)
+ def test_scout_cannot_write_generic_ticket_comments(
+ self, _name: str, method: str, scope: str, path: str, _flag: object
+ ) -> None:
note = Comment.objects.create(
team=self.team,
created_by=self.user,
- scope="conversations_ticket",
+ scope=scope,
item_id=str(self.ticket.id),
content="Original note",
item_context={"author_type": "support", "is_private": True},
)
self._auth_with_scopes(["ticket:write", "signal_scout_internal:write"])
- url = f"/api/projects/{self.team.id}/comments/"
- if method == "patch":
- url += f"{note.id}/"
response = getattr(self.client, method)(
- url,
+ f"/api/projects/{self.team.id}/comments/{path.format(id=note.id)}",
{
- "scope": "conversations_ticket",
+ "scope": scope,
"item_id": str(self.ticket.id),
"content": "Changed note",
"item_context": {"author_type": "customer"},
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 7c3bf2a49cb5..edcc8c223ffd 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -1205,7 +1205,7 @@ export const getCommentsSendToSlackCreateUrl = (projectId: string, id: string) =
}
/**
- * Mirror this discussion thread to a Slack channel. Posts the comment (and its existing replies) as a new Slack thread; later replies on either side sync across. A discussion mirrors to exactly one Slack thread: re-calling with the same channel returns the existing mirror; a different channel is a 400 naming the existing one. 409 while a concurrent send is in flight. 404 when the feature is not enabled for the team.
+ * Mirror this discussion thread to a Slack channel. Posts the comment (and its existing replies) as a new Slack thread; later replies on either side sync across. A discussion mirrors to exactly one Slack thread: re-calling with the same channel returns the existing mirror; a different channel is a 400 naming the existing one. 409 while a concurrent send is in flight. 404 when the feature is not enabled for the team. Only the person who started a ticket discussion can send it (403), and it cannot go to a channel shared with another Slack workspace (400). 429 when the Slack integration has made too many channel lookups in the last minute.
*/
export const commentsSendToSlackCreate = async (
projectId: string,
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index 19e50b2ef960..a4bbe54dacea 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -559,7 +559,7 @@ export const CommentsPartialUpdateBody = /* @__PURE__ */ zod.object({
})
/**
- * Mirror this discussion thread to a Slack channel. Posts the comment (and its existing replies) as a new Slack thread; later replies on either side sync across. A discussion mirrors to exactly one Slack thread: re-calling with the same channel returns the existing mirror; a different channel is a 400 naming the existing one. 409 while a concurrent send is in flight. 404 when the feature is not enabled for the team.
+ * Mirror this discussion thread to a Slack channel. Posts the comment (and its existing replies) as a new Slack thread; later replies on either side sync across. A discussion mirrors to exactly one Slack thread: re-calling with the same channel returns the existing mirror; a different channel is a 400 naming the existing one. 409 while a concurrent send is in flight. 404 when the feature is not enabled for the team. Only the person who started a ticket discussion can send it (403), and it cannot go to a channel shared with another Slack workspace (400). 429 when the Slack integration has made too many channel lookups in the last minute.
*/
export const commentsSendToSlackCreateBodyChannelIdMax = 255