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(conversations): request slack file scopes so attachments sync (#74184)

Alex V2174446c8a5b
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 4bc7251fd46a..ad144be92c1c 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -767,6 +767,8 @@ export interface ConversationsSettings {
slack_notify_on_leave?: boolean
slack_alert_channel_id?: string | null
slack_nudge_enabled?: boolean
+ /** Bot scopes Slack granted at install. Absent for installs authorized before we recorded them. */
+ slack_scopes?: string[] | null
email_enabled?: boolean
teams_enabled?: boolean
teams_team_id?: string | null
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 0104eb633c0c..ca73034ac5b9 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1232,6 +1232,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
"slack_bot_token",
"slack_team_id",
"slack_enabled",
+ "slack_scopes",
"email_enabled",
"teams_enabled",
"teams_tenant_id",
diff --git a/products/conversations/backend/api/slack_oauth.py b/products/conversations/backend/api/slack_oauth.py
index 66f4fc259cc1..ba4a03c71549 100644
--- a/products/conversations/backend/api/slack_oauth.py
+++ b/products/conversations/backend/api/slack_oauth.py
@@ -25,19 +25,24 @@ from products.conversations.backend.support_slack import clear_supporthog_slack_
STATE_SALT = "conversations.supporthog.slack.oauth"
STATE_MAX_AGE_SECONDS = 10 * 60
-SUPPORTHOG_SLACK_SCOPE = ",".join(
- [
- "channels:history",
- "channels:read",
- "chat:write",
- "chat:write.customize",
- "groups:history",
- "groups:read",
- "reactions:read",
- "users:read",
- "users:read.email",
- ]
-)
+SUPPORTHOG_SLACK_SCOPES = [
+ "channels:history",
+ "channels:read",
+ "chat:write",
+ "chat:write.customize",
+ # files:read to download inbound attachments, files:write to upload our replies' images.
+ # Slack only grants scopes at install time, so installs authorized before these were
+ # requested keep working without attachment sync until an admin reconnects. See
+ # SUPPORT_SLACK_FILE_SCOPES for how the settings page detects those installs.
+ "files:read",
+ "files:write",
+ "groups:history",
+ "groups:read",
+ "reactions:read",
+ "users:read",
+ "users:read.email",
+]
+SUPPORTHOG_SLACK_SCOPE = ",".join(SUPPORTHOG_SLACK_SCOPES)
def _append_query(url: str, params: dict[str, str]) -> str:
@@ -184,6 +189,7 @@ def support_slack_oauth_callback(request: HttpRequest) -> HttpResponse:
bot_token = payload.get("access_token")
slack_team_id = payload.get("team", {}).get("id")
+ granted_scopes = [scope.strip() for scope in str(payload.get("scope") or "").split(",") if scope.strip()]
user_id = state_data.get("user_id")
team_id = state_data.get("team_id")
if not isinstance(bot_token, str) or not bot_token:
@@ -221,6 +227,7 @@ def support_slack_oauth_callback(request: HttpRequest) -> HttpResponse:
is_impersonated_session=is_impersonated(request),
bot_token=bot_token,
slack_team_id=slack_team_id,
+ granted_scopes=granted_scopes,
)
except IntegrityError:
return _error_response(next_path, "slack_workspace_already_connected", 409)
diff --git a/products/conversations/backend/api/tests/test_slack_endpoints.py b/products/conversations/backend/api/tests/test_slack_endpoints.py
index c59a4108b25c..2e4a4654dabe 100644
--- a/products/conversations/backend/api/tests/test_slack_endpoints.py
+++ b/products/conversations/backend/api/tests/test_slack_endpoints.py
@@ -1,6 +1,6 @@
import json
from typing import Any
-from urllib.parse import urlencode
+from urllib.parse import parse_qs, urlencode, urlparse
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import MagicMock, patch
@@ -380,6 +380,11 @@ class TestSlackChannelPermissions(BaseTest):
response = self.client.get("/api/conversations/v1/slack/authorize")
assert response.status_code == 200
+ requested_scopes = parse_qs(urlparse(response.json()["url"]).query)["scope"][0].split(",")
+ # Attachment sync in both directions silently degrades without these
+ assert "files:read" in requested_scopes
+ assert "files:write" in requested_scopes
+
@patch(
"products.conversations.backend.api.slack_oauth.clear_supporthog_slack_token",
)
diff --git a/products/conversations/backend/api/tests/test_slack_image_sync.py b/products/conversations/backend/api/tests/test_slack_image_sync.py
index 0eef356617ad..3aeb34b880fe 100644
--- a/products/conversations/backend/api/tests/test_slack_image_sync.py
+++ b/products/conversations/backend/api/tests/test_slack_image_sync.py
@@ -15,6 +15,21 @@ VALID_PNG_BYTES = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde"
b"\x00\x00\x00\x0cIDATx\x9cc```\x00\x00\x00\x04\x00\x01\xf6\x178U\x00\x00\x00\x00IEND\xaeB`\x82"
)
+GRANTED_FILE_SCOPES = ["chat:write", "files:read", "files:write"]
+
+
+def fake_slack_team(slack_scopes: list[str] | None = GRANTED_FILE_SCOPES) -> MagicMock:
+ """A team whose install granted the file scopes. None means an install predating scope records."""
+ team = MagicMock()
+ team.id = 1
+ team.conversations_settings = {"slack_scopes": slack_scopes} if slack_scopes is not None else {}
+ return team
+
+
+def fake_slack_client() -> MagicMock:
+ client = MagicMock()
+ client.token = "xoxb-token"
+ return client
class TestSlackImageIngest(SimpleTestCase):
@@ -24,16 +39,46 @@ class TestSlackImageIngest(SimpleTestCase):
assert image_bytes is None
mock_build_opener.assert_not_called()
+ @parameterized.expand(
+ [
+ ("sign_in_page_for_a_pdf", "text/html; charset=utf-8", "application/pdf", None),
+ ("sign_in_page_for_an_image", "text/html", "image/png", None),
+ ("genuine_html_attachment", "text/html", "text/html", b"<html>report</html>"),
+ ("matching_content_type", "application/pdf", "application/pdf", b"%PDF-1.4 fake content"),
+ ]
+ )
+ @patch("products.conversations.backend.slack.build_opener")
+ def test_download_rejects_slack_sign_in_page(
+ self,
+ _label: str,
+ content_type: str,
+ expected_mimetype: str,
+ expected_bytes: bytes | None,
+ mock_build_opener: MagicMock,
+ ) -> None:
+ body = expected_bytes or b"<html>Sign in to Slack</html>"
+ fake_response = MagicMock()
+ fake_response.getcode.return_value = 200
+ fake_response.headers = {"Content-Type": content_type}
+ fake_response.read.return_value = body
+ mock_build_opener.return_value.open.return_value.__enter__.return_value = fake_response
+
+ payload = _download_slack_image_bytes(
+ "https://files.slack.com/files-pri/T/F/report.pdf",
+ "xoxb-token",
+ expected_mimetype=expected_mimetype,
+ )
+
+ assert payload == expected_bytes
+
@patch("products.conversations.backend.slack.save_file_to_uploaded_media")
@patch("products.conversations.backend.slack._download_slack_image_bytes")
def test_extract_slack_files_copies_to_uploaded_media(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
mock_download.return_value = VALID_PNG_BYTES
mock_save.return_value = "https://app.posthog.com/uploaded_media/abc"
- fake_team = MagicMock()
- fake_team.id = 1
- fake_client = MagicMock()
- fake_client.token = "xoxb-token"
+ fake_team = fake_slack_team()
+ fake_client = fake_slack_client()
files = [
{
@@ -50,16 +95,28 @@ class TestSlackImageIngest(SimpleTestCase):
mock_download.assert_called_once()
mock_save.assert_called_once()
+ @parameterized.expand(
+ [
+ ("with_permalink", "https://acme.slack.com/files/U1/F123/test.jpg", True),
+ ("with_untrusted_permalink", "https://phish.example.com/files/U1/F123/test.jpg", False),
+ ("without_permalink", None, False),
+ ]
+ )
@patch("products.conversations.backend.slack.save_file_to_uploaded_media")
@patch("products.conversations.backend.slack._download_slack_image_bytes")
- def test_extract_slack_files_skips_failed_downloads(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
+ def test_extract_slack_files_falls_back_to_slack_link_when_download_fails(
+ self,
+ _label: str,
+ permalink: str | None,
+ expects_link: bool,
+ mock_download: MagicMock,
+ mock_save: MagicMock,
+ ) -> None:
mock_download.return_value = None
- fake_team = MagicMock()
- fake_team.id = 1
- fake_client = MagicMock()
- fake_client.token = "xoxb-token"
+ fake_team = fake_slack_team()
+ fake_client = fake_slack_client()
- files = [
+ files: list[dict] = [
{
"id": "F123",
"mimetype": "image/jpeg",
@@ -67,10 +124,55 @@ class TestSlackImageIngest(SimpleTestCase):
"url_private_download": "https://files.slack.com/files-pri/T/F/test.jpg",
}
]
- images = extract_slack_files(files, fake_team, fake_client)
+ if permalink:
+ files[0]["permalink"] = permalink
+ attachments = extract_slack_files(files, fake_team, fake_client)
+ images, file_attachments = split_slack_attachments(attachments)
+ mock_save.assert_not_called()
+ # Nothing is re-hosted, so nothing can be inlined
assert images == []
+ if expects_link:
+ # Rendered as a link instead of vanishing from the ticket
+ assert file_attachments == [
+ {"url": permalink, "name": "test.jpg", "mimetype": "image/jpeg", "unavailable": True}
+ ]
+ else:
+ assert file_attachments == []
+
+ @parameterized.expand(
+ [
+ ("install_predating_scope_records", None),
+ ("install_without_files_read", ["chat:write", "files:write"]),
+ ]
+ )
+ @patch("products.conversations.backend.slack.save_file_to_uploaded_media")
+ @patch("products.conversations.backend.slack._download_slack_image_bytes")
+ def test_extract_slack_files_does_not_download_without_files_read(
+ self,
+ _label: str,
+ slack_scopes: list[str] | None,
+ mock_download: MagicMock,
+ mock_save: MagicMock,
+ ) -> None:
+ # A text/html attachment is the case content-type checks can't screen: Slack's sign-in page
+ # and the real file are both HTML, so an under-scoped install must not fetch at all.
+ permalink = "https://acme.slack.com/files/U1/F123/report.html"
+ files = [
+ {
+ "id": "F123",
+ "mimetype": "text/html",
+ "name": "report.html",
+ "url_private_download": "https://files.slack.com/files-pri/T/F/report.html",
+ "permalink": permalink,
+ }
+ ]
+
+ attachments = extract_slack_files(files, fake_slack_team(slack_scopes), fake_slack_client())
+
+ mock_download.assert_not_called()
mock_save.assert_not_called()
+ assert attachments == [{"url": permalink, "name": "report.html", "mimetype": "text/html", "unavailable": True}]
@patch("products.conversations.backend.slack.save_file_to_uploaded_media")
@patch("products.conversations.backend.slack._download_slack_image_bytes")
@@ -78,10 +180,8 @@ class TestSlackImageIngest(SimpleTestCase):
self, mock_download: MagicMock, mock_save: MagicMock
) -> None:
mock_download.return_value = b"not-an-image"
- fake_team = MagicMock()
- fake_team.id = 1
- fake_client = MagicMock()
- fake_client.token = "xoxb-token"
+ fake_team = fake_slack_team()
+ fake_client = fake_slack_client()
files = [
{
@@ -102,10 +202,8 @@ class TestSlackImageIngest(SimpleTestCase):
mock_download.return_value = b"%PDF-1.4 fake content"
mock_save.return_value = "https://app.posthog.com/uploaded_media/pdf"
- fake_team = MagicMock()
- fake_team.id = 1
- fake_client = MagicMock()
- fake_client.token = "xoxb-token"
+ fake_team = fake_slack_team()
+ fake_client = fake_slack_client()
files = [
{
@@ -133,10 +231,8 @@ class TestSlackImageIngest(SimpleTestCase):
mock_download.return_value = b"%PDF-1.4 fake content"
mock_save.return_value = "https://app.posthog.com/uploaded_media/pdf"
- fake_team = MagicMock()
- fake_team.id = 1
- fake_client = MagicMock()
- fake_client.token = "xoxb-token"
+ fake_team = fake_slack_team()
+ fake_client = fake_slack_client()
files = [
{
diff --git a/products/conversations/backend/api/tests/test_slack_token_storage.py b/products/conversations/backend/api/tests/test_slack_token_storage.py
index 559107342233..e26457f6b3e2 100644
--- a/products/conversations/backend/api/tests/test_slack_token_storage.py
+++ b/products/conversations/backend/api/tests/test_slack_token_storage.py
@@ -34,12 +34,15 @@ class TestSlackTokenStorage(BaseTest):
is_impersonated_session=False,
bot_token="xoxb-test-token",
slack_team_id="T_SETTINGS",
+ granted_scopes=["chat:write", "files:read"],
)
self.team.refresh_from_db()
settings = self.team.conversations_settings or {}
assert settings["slack_enabled"] is True
assert "slack_team_id" not in settings
+ # Recorded so the settings page can tell which installs predate the files: scopes
+ assert settings["slack_scopes"] == ["chat:write", "files:read"]
config = TeamConversationsSlackConfig.objects.get(team=self.team)
assert config.slack_team_id == "T_SETTINGS"
diff --git a/products/conversations/backend/services/attachments.py b/products/conversations/backend/services/attachments.py
index a1bb04ea2cf7..4f7e5a93281b 100644
--- a/products/conversations/backend/services/attachments.py
+++ b/products/conversations/backend/services/attachments.py
@@ -103,6 +103,12 @@ def save_file_to_uploaded_media(
return uploaded_media.get_absolute_url()
+def attachment_link_label(attachment: dict[str, Any]) -> str:
+ """Link text for a file attachment. Flags the ones that still live in Slack."""
+ name = attachment.get("name") or "attachment"
+ return f"{name} (open in Slack)" if attachment.get("unavailable") else name
+
+
def build_content_with_images(
cleaned_text: str,
rich_content: dict[str, Any] | None,
@@ -122,7 +128,7 @@ def build_content_with_images(
if images:
parts.append("\n".join(f"![{img['name']}]({img['url']})" for img in images))
if files:
- parts.append("\n".join(f"[{f['name']}]({f['url']})" for f in files))
+ parts.append("\n".join(f"[{attachment_link_label(f)}]({f['url']})" for f in files))
content = "\n\n".join(parts)
if not isinstance(rich_content, dict):
@@ -151,7 +157,7 @@ def build_content_with_images(
"content": [
{
"type": "text",
- "text": f.get("name", "attachment"),
+ "text": attachment_link_label(f),
"marks": [{"type": "link", "attrs": {"href": f["url"]}}],
}
],
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index e8f2ac716d7c..a2fcc9b429e3 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -53,7 +53,12 @@ from .services.attachments import (
sanitize_attachment_filename,
save_file_to_uploaded_media,
)
-from .support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, get_support_slack_bot_token
+from .support_slack import (
+ SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES,
+ SUPPORT_SLACK_FILE_READ_SCOPE,
+ get_support_slack_bot_token,
+ supporthog_missing_file_scopes,
+)
logger = structlog.get_logger(__name__)
SLACK_DOWNLOAD_TIMEOUT_SECONDS = 10
@@ -260,7 +265,7 @@ def _is_allowed_slack_file_url(url: str) -> bool:
return any(hostname == suffix or hostname.endswith(f".{suffix}") for suffix in SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES)
-def _download_slack_image_bytes(url: str, bot_token: str) -> bytes | None:
+def _download_slack_image_bytes(url: str, bot_token: str, expected_mimetype: str = "") -> bytes | None:
if not _is_allowed_slack_file_url(url):
logger.warning("🖼️ slack_file_download_invalid_host", url=url)
return None
@@ -289,6 +294,20 @@ def _download_slack_image_bytes(url: str, bot_token: str) -> bytes | None:
logger.warning("🖼️ slack_file_download_non_200", url=next_url, status=status)
return None
+ # A rejected file request (a revoked or downgraded token) lands on a Slack sign-in page
+ # served as a 200. Storing that as the customer's attachment is worse than having none,
+ # and only images get byte validation. Callers skip the request entirely when the
+ # install is known to lack files:read, which is the case this can't catch on its own:
+ # a sign-in page and a genuine text/html attachment look the same here.
+ content_type = (response.headers.get("Content-Type") or "").split(";")[0].strip().lower()
+ if content_type == "text/html" and expected_mimetype.lower() != "text/html":
+ logger.warning(
+ "🖼️ slack_file_download_unexpected_html",
+ url=next_url,
+ expected_mimetype=expected_mimetype,
+ )
+ return None
+
content_length_header = response.headers.get("Content-Length")
if content_length_header:
try:
@@ -321,13 +340,86 @@ def _download_slack_image_bytes(url: str, bot_token: str) -> bytes | None:
return None
+def _is_inline_image(attachment: dict) -> bool:
+ return (attachment.get("mimetype") or "").startswith("image/") and not attachment.get("unavailable")
+
+
def split_slack_attachments(attachments: list[dict]) -> tuple[list[dict], list[dict]]:
- """Partition extracted attachments into (images, non-image files) by mimetype."""
- images = [a for a in attachments if (a.get("mimetype") or "").startswith("image/")]
- files = [a for a in attachments if not (a.get("mimetype") or "").startswith("image/")]
+ """Partition extracted attachments into (images, non-image files) by mimetype.
+
+ Attachments we couldn't re-host go to the file bucket whatever their mimetype:
+ they point at Slack, so they can only be rendered as a link, not inlined.
+ """
+ images = [a for a in attachments if _is_inline_image(a)]
+ files = [a for a in attachments if not _is_inline_image(a)]
return images, files
+def _rehost_slack_file(f: dict, team: Team, bot_token: str | None) -> dict | None:
+ """Copy one Slack file into UploadedMedia, or None when it can't be read or stored."""
+ mimetype = f.get("mimetype", "")
+ is_image = mimetype.startswith("image/")
+ file_id = f.get("id")
+
+ source_url = f.get("url_private_download") or f.get("url_private")
+ if not source_url or not bot_token:
+ logger.warning(
+ "🖼️ slack_file_missing_download_info",
+ file_id=file_id,
+ has_source_url=bool(source_url),
+ has_bot_token=bool(bot_token),
+ )
+ return None
+
+ try:
+ file_bytes = _download_slack_image_bytes(source_url, bot_token, expected_mimetype=mimetype)
+ except Exception as e:
+ logger.warning("🖼️ slack_file_download_failed", file_id=file_id, error=str(e))
+ return None
+
+ if not file_bytes:
+ logger.warning("🖼️ slack_file_download_rejected", file_id=file_id, source_url=source_url)
+ return None
+
+ # Only images get byte-level validation; other types are stored as-is and
+ # served as opaque downloads by the media endpoint.
+ if is_image and not is_valid_image(file_bytes):
+ logger.warning("🖼️ slack_file_invalid_image_content", file_id=file_id)
+ return None
+
+ safe_name = sanitize_attachment_filename(f.get("name"))
+ stored_url = save_file_to_uploaded_media(team, safe_name, mimetype, file_bytes, validate_images=False)
+ if not stored_url:
+ logger.warning("🖼️ slack_file_copy_save_failed", file_id=file_id)
+ return None
+
+ attachment = {
+ "url": stored_url,
+ "name": safe_name,
+ "mimetype": mimetype,
+ }
+ if is_image:
+ attachment["thumb"] = f.get("thumb_360") or f.get("thumb_160")
+ return attachment
+
+
+def _slack_hosted_fallback(f: dict) -> dict | None:
+ """A link back to the file in Slack, for when re-hosting failed.
+
+ Without this the attachment vanishes from the ticket with no trace, which reads as
+ "the customer sent nothing". Most often this is an install missing files:read.
+ """
+ permalink = f.get("permalink")
+ if not isinstance(permalink, str) or not _is_allowed_slack_file_url(permalink):
+ return None
+ return {
+ "url": permalink,
+ "name": sanitize_attachment_filename(f.get("name")),
+ "mimetype": f.get("mimetype", ""),
+ "unavailable": True,
+ }
+
+
def extract_slack_files(files: list[dict] | None, team: Team, client: WebClient | None = None) -> list[dict]:
"""
Extract attachments from Slack and re-host them in UploadedMedia.
@@ -340,53 +432,29 @@ def extract_slack_files(files: list[dict] | None, team: Team, client: WebClient
team_id = _get_team_id(team)
bot_token = getattr(client, "token", None) if client else None
+ # Slack answers an unauthorized download with a 200 sign-in page, which is indistinguishable
+ # from a genuine text/html attachment. So don't ask: we've requested files:read for as long as
+ # we've recorded granted scopes, meaning an install with none recorded definitively lacks it.
+ missing_file_scopes = supporthog_missing_file_scopes(team)
+ can_read_files = SUPPORT_SLACK_FILE_READ_SCOPE not in missing_file_scopes
logger.info("🖼️ slack_file_extract_started", team_id=team_id, total_files=len(files), has_bot_token=bool(bot_token))
attachments: list[dict] = []
+ unavailable_count = 0
for f in files[:MAX_ATTACHMENTS_PER_MESSAGE]:
- mimetype = f.get("mimetype", "")
- is_image = mimetype.startswith("image/")
-
- file_id = f.get("id")
- source_url = f.get("url_private_download") or f.get("url_private")
- if not source_url or not bot_token:
- logger.warning(
- "🖼️ slack_file_missing_download_info",
- file_id=file_id,
- has_source_url=bool(source_url),
- has_bot_token=bool(bot_token),
- )
- continue
-
- try:
- file_bytes = _download_slack_image_bytes(source_url, bot_token)
- except Exception as e:
- logger.warning("🖼️ slack_file_download_failed", file_id=file_id, error=str(e))
- continue
-
- if not file_bytes:
- logger.warning("🖼️ slack_file_download_rejected", file_id=file_id, source_url=source_url)
- continue
-
- # Only images get byte-level validation; other types are stored as-is and
- # served as opaque downloads by the media endpoint.
- if is_image and not is_valid_image(file_bytes):
- logger.warning("🖼️ slack_file_invalid_image_content", file_id=file_id)
- continue
-
- safe_name = sanitize_attachment_filename(f.get("name"))
- stored_url = save_file_to_uploaded_media(team, safe_name, mimetype, file_bytes, validate_images=False)
- if stored_url:
- attachment = {
- "url": stored_url,
- "name": safe_name,
- "mimetype": mimetype,
- }
- if is_image:
- attachment["thumb"] = f.get("thumb_360") or f.get("thumb_160")
+ attachment = _rehost_slack_file(f, team, bot_token) if can_read_files else None
+ if attachment is None:
+ attachment = _slack_hosted_fallback(f)
+ unavailable_count += 1
+ if attachment:
attachments.append(attachment)
- else:
- logger.warning("🖼️ slack_file_copy_save_failed", file_id=file_id)
logger.info("🖼️ slack_file_extract_finished", team_id=team_id, attachment_count=len(attachments))
+ if unavailable_count:
+ logger.warning(
+ "🖼️ slack_file_extract_incomplete",
+ team_id=team_id,
+ unavailable_count=unavailable_count,
+ missing_file_scopes=missing_file_scopes,
+ )
return attachments
diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.py
index 11fde2f50a37..c7fded776294 100644
--- a/products/conversations/backend/support_slack.py
+++ b/products/conversations/backend/support_slack.py
@@ -22,6 +22,12 @@ if TYPE_CHECKING:
SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES = ("slack.com", "slack-edge.com", "slack-files.com")
+# Attachment sync in both directions depends on these. Older installs were authorized without
+# them, so the settings page asks those teams to reconnect.
+SUPPORT_SLACK_FILE_READ_SCOPE = "files:read"
+SUPPORT_SLACK_FILE_WRITE_SCOPE = "files:write"
+SUPPORT_SLACK_FILE_SCOPES = frozenset({SUPPORT_SLACK_FILE_READ_SCOPE, SUPPORT_SLACK_FILE_WRITE_SCOPE})
+
def get_support_slack_settings() -> dict:
return get_instance_settings(
@@ -31,6 +37,17 @@ def get_support_slack_settings() -> dict:
)
+def supporthog_missing_file_scopes(team: "Team") -> list[str]:
+ """File scopes this install hasn't granted, for logging why attachments failed.
+
+ Installs authorized before we recorded scopes report both as missing, which is what
+ they are: neither was requested at the time.
+ """
+ settings = team.conversations_settings
+ granted = settings.get("slack_scopes") if isinstance(settings, dict) else None
+ return sorted(SUPPORT_SLACK_FILE_SCOPES.difference(granted or []))
+
+
def get_support_slack_bot_token(team: "Team") -> str:
config = get_or_create_team_extension(team, TeamConversationsSlackConfig)
return str(config.slack_bot_token or "")
@@ -89,6 +106,7 @@ def save_supporthog_slack_token(
is_impersonated_session: bool,
bot_token: str,
slack_team_id: str,
+ granted_scopes: list[str] | None = None,
) -> None:
config = get_or_create_team_extension(team, TeamConversationsSlackConfig)
old_token = config.slack_bot_token
@@ -96,6 +114,10 @@ def save_supporthog_slack_token(
settings = team.conversations_settings or {}
settings["slack_enabled"] = True
+ if granted_scopes is not None:
+ # Left untouched when the caller doesn't know them, so we never replace a real
+ # install's scopes with an empty list and prompt a pointless reconnect.
+ settings["slack_scopes"] = sorted(set(granted_scopes))
team.conversations_settings = settings
with transaction.atomic():
@@ -149,6 +171,7 @@ def clear_supporthog_slack_token(
settings["slack_enabled"] = False
settings.pop("slack_bot_display_name", None)
settings.pop("slack_bot_icon_url", None)
+ settings.pop("slack_scopes", None)
team.conversations_settings = settings
with transaction.atomic():
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index 653c0e89c7eb..fcb4bf96c0e5 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -99,7 +99,7 @@ from products.conversations.backend.teams import (
from products.conversations.backend.teams_attachments import extract_teams_graph_images
from products.conversations.backend.teams_formatting import build_teams_reply_html
-from .support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES
+from .support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, supporthog_missing_file_scopes
logger = structlog.get_logger(__name__)
SUPPORTHOG_EVENT_IDEMPOTENCY_TTL_SECONDS = 6 * 60
@@ -499,6 +499,7 @@ def post_reply_to_slack(
ticket_id=ticket_id,
channel=slack_channel_id,
fallback_count=len(unique_urls),
+ missing_file_scopes=supporthog_missing_file_scopes(team),
)
logger.info(
diff --git a/products/conversations/frontend/scenes/settings/SlackSection.tsx b/products/conversations/frontend/scenes/settings/SlackSection.tsx
index c31354ba1b54..25c1f58660ac 100644
--- a/products/conversations/frontend/scenes/settings/SlackSection.tsx
+++ b/products/conversations/frontend/scenes/settings/SlackSection.tsx
@@ -1,6 +1,15 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonCard, LemonCheckbox, LemonDivider, LemonInput, LemonTag, Link } from '@posthog/lemon-ui'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCard,
+ LemonCheckbox,
+ LemonDivider,
+ LemonInput,
+ LemonTag,
+ Link,
+} from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
@@ -49,6 +58,7 @@ function SlackChannelSection(): JSX.Element {
slackNotifyOnLeave,
slackAlertChannelId,
slackNudgeEnabled,
+ slackNeedsReconnect,
currentTeamLoading,
} = useValues(supportSettingsLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -92,6 +102,20 @@ function SlackChannelSection(): JSX.Element {
Add SupportHog to Slack
</LemonButton>
)}
+ {slackNeedsReconnect && (
+ <LemonBanner
+ type="warning"
+ className="mt-2"
+ action={{
+ children: 'Reconnect',
+ disabledReason: adminRestrictionReason,
+ onClick: () => connectSlack(window.location.pathname),
+ }}
+ >
+ Files sent in Slack won't appear on tickets, and images you send from PostHog arrive as links
+ instead of attachments. Reconnect SupportHog to give it access to files.
+ </LemonBanner>
+ )}
</div>
{slackConnected && (
<>
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
index d9041b6fa488..ab1dd4d54a73 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
@@ -98,6 +98,24 @@ describe('supportSettingsLogic', () => {
})
})
+ describe('slackNeedsReconnect selector', () => {
+ it.each([
+ ['slack not connected', { slack_enabled: false }, false],
+ ['install predates scope tracking', { slack_enabled: true }, true],
+ ['install missing files:write', { slack_enabled: true, slack_scopes: ['chat:write', 'files:read'] }, true],
+ [
+ 'install has both file scopes',
+ { slack_enabled: true, slack_scopes: ['chat:write', 'files:read', 'files:write'] },
+ false,
+ ],
+ ])('%s', async (_label, settings, expected) => {
+ initKeaTests(true, { conversations_settings: settings } as unknown as TeamType)
+ logic = supportSettingsLogic()
+ logic.mount()
+ await expectLogic(logic).toMatchValues({ slackNeedsReconnect: expected })
+ })
+ })
+
describe('aiSuggestionsEnabled selector', () => {
it.each([
['conversations_settings is undefined', undefined, false],
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
index 6f89e3bc5edd..dce2287c455b 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
@@ -15,6 +15,9 @@ import { TicketChannel } from '../../types'
const BASE_AI_CHANNELS: TicketChannel[] = ['widget', 'email', 'slack']
+/** Kept in sync with SUPPORT_SLACK_FILE_SCOPES in products/conversations/backend/support_slack.py. */
+const SLACK_FILE_SCOPES = ['files:read', 'files:write']
+
export function aiAllChannelsForFeatureFlags(featureFlags: Record<string, boolean | string>): TicketChannel[] {
const channels: TicketChannel[] = [...BASE_AI_CHANNELS]
if (featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_TEAMS_ENABLED]) {
@@ -91,6 +94,7 @@ export interface supportSettingsLogicValues {
slackChannelsLoading: boolean
slackConnected: boolean
slackEnabled: boolean
+ slackNeedsReconnect: boolean
slackNotifyOnJoin: boolean
slackNotifyOnLeave: boolean
slackNudgeEnabled: boolean
@@ -515,6 +519,7 @@ export interface supportSettingsLogicMeta {
slackChannelIds: (currentTeam: TeamPublicType | TeamType | null) => string[]
slackTicketEmoji: (currentTeam: TeamPublicType | TeamType | null) => string
slackConnected: (currentTeam: TeamPublicType | TeamType | null) => boolean
+ slackNeedsReconnect: (currentTeam: TeamPublicType | TeamType | null) => boolean
slackBotIconUrl: (currentTeam: TeamPublicType | TeamType | null) => string | null
slackBotDisplayName: (currentTeam: TeamPublicType | TeamType | null) => string | null
slackNotifyOnJoin: (currentTeam: TeamPublicType | TeamType | null) => boolean
@@ -998,6 +1003,17 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
(currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType): boolean =>
!!currentTeam?.conversations_settings?.slack_enabled,
],
+ slackNeedsReconnect: [
+ (s) => [s.currentTeam],
+ (currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType): boolean => {
+ const cs = currentTeam?.conversations_settings
+ if (!cs?.slack_enabled) {
+ return false
+ }
+ const scopes = cs.slack_scopes ?? []
+ return SLACK_FILE_SCOPES.some((scope) => !scopes.includes(scope))
+ },
+ ],
slackBotIconUrl: [
(s) => [s.currentTeam],
(currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType): string | null =>
diff --git a/products/conversations/skills/setting-up-support-slack-locally/SKILL.md b/products/conversations/skills/setting-up-support-slack-locally/SKILL.md
index 8b56501c9b21..b2979941e54a 100644
--- a/products/conversations/skills/setting-up-support-slack-locally/SKILL.md
+++ b/products/conversations/skills/setting-up-support-slack-locally/SKILL.md
@@ -68,10 +68,11 @@ At [api.slack.com/apps](https://api.slack.com/apps), create an app in a throwawa
1. **App Home** → enable a **bot user** (give it a display name). Without this, install fails with "requesting
permission to install a bot ... but it's not currently configured with a bot".
-2. **OAuth & Permissions → Bot Token Scopes** — the flow requests these (from `SUPPORTHOG_SLACK_SCOPE` in
+2. **OAuth & Permissions → Bot Token Scopes** — the flow requests these (from `SUPPORTHOG_SLACK_SCOPES` in
`products/conversations/backend/api/slack_oauth.py`): `channels:history`, `channels:read`, `chat:write`,
- `chat:write.customize`, `groups:history`, `groups:read`, `reactions:read`, `users:read`,
- `users:read.email`.
+ `chat:write.customize`, `files:read`, `files:write`, `groups:history`, `groups:read`, `reactions:read`,
+ `users:read`, `users:read.email`. Attachments need the two `files:` scopes in both directions, so a
+ workspace installed without them shows a "reconnect" banner in support settings.
3. **OAuth & Permissions → Redirect URLs** — add `http://localhost:8010/api/conversations/v1/slack/callback`
and Save. If Slack refuses a plain-http localhost URL, use the tunnel URL for the callback too and log in
once on the tunnel origin (see [references/troubleshooting.md](references/troubleshooting.md)).