: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack): accept all attachment types and check files:read (#122519)
Vojta Bartošd722957fc063
diff --git a/products/slack_app/backend/temporal/activities/task_creation.py b/products/slack_app/backend/temporal/activities/task_creation.pyindex db8448121564..edcf7c709362 100644--- a/products/slack_app/backend/temporal/activities/task_creation.py+++ b/products/slack_app/backend/temporal/activities/task_creation.py@@ -27,6 +27,7 @@ from products.slack_app.backend.temporal.attachments import (SlackAttachmentBudget,attachment_display_name,build_slack_attachment_prompt_text,+ can_read_slack_files,get_slack_bot_token,merge_prepared_attachments,prepare_slack_file_artifacts,@@ -819,15 +820,22 @@ def create_posthog_code_task_for_repo_activity(task_run = created.latest_runif task_run:bot_token = get_slack_bot_token(slack, integration)+ can_read_files = can_read_slack_files(integration)event_files = parse_slack_file_refs(event.get("files"))# The thread's own attachments matter as much as the tagging message's: the# screenshot under discussion is usually the one the thread opened with, and the# request several replies down says "look at this" about it.attachment_budget = SlackAttachmentBudget()prepared_attachments = merge_prepared_attachments(- prepare_slack_file_artifacts(event_files, bot_token, budget=attachment_budget),+ prepare_slack_file_artifacts(+ event_files, bot_token, can_read_files=can_read_files, budget=attachment_budget+ ),prepare_slack_thread_file_artifacts(- thread_messages, bot_token, already_requested=event_files, budget=attachment_budget+ thread_messages,+ bot_token,+ can_read_files=can_read_files,+ already_requested=event_files,+ budget=attachment_budget,),)uploaded_attachments, attachment_skips = _upload_prepared_slack_attachments(@@ -1090,11 +1098,14 @@ def forward_posthog_code_followup_activity(# Taken before the thread digest and the speaker prefix join it, so it holds only this person's words.person_message = labeled_mentions_to_display_names(user_text) or Nonebot_token = get_slack_bot_token(slack, integration)+ can_read_files = can_read_slack_files(integration)event_files = parse_slack_file_refs(inputs.event.get("files"))# Shared with the thread fetch below, so the reply and the catch-up files draw on one# allowance instead of two.attachment_budget = SlackAttachmentBudget()- prepared_attachments = prepare_slack_file_artifacts(event_files, bot_token, budget=attachment_budget)+ prepared_attachments = prepare_slack_file_artifacts(+ event_files, bot_token, can_read_files=can_read_files, budget=attachment_budget+ )if not user_text and not prepared_attachments.has_files:return Trueif not user_text and not prepared_attachments.artifacts:@@ -1144,7 +1155,11 @@ def forward_posthog_code_followup_activity(prepared_attachments = merge_prepared_attachments(prepared_attachments,prepare_slack_thread_file_artifacts(- update.messages, bot_token, already_requested=event_files, budget=attachment_budget+ update.messages,+ bot_token,+ can_read_files=can_read_files,+ already_requested=event_files,+ budget=attachment_budget,),)@@ -1470,7 +1485,9 @@ def _resume_task_with_new_run(user_text = decode_slack_event_text(slack, integration, event_text)person_message = labeled_mentions_to_display_names(user_text) or Noneprepared_attachments = prepare_slack_file_artifacts(- parse_slack_file_refs(inputs.event.get("files")), get_slack_bot_token(slack, integration)+ parse_slack_file_refs(inputs.event.get("files")),+ get_slack_bot_token(slack, integration),+ can_read_files=can_read_slack_files(integration),)if not user_text and not prepared_attachments.has_files:return Truediff --git a/products/slack_app/backend/temporal/attachments.py b/products/slack_app/backend/temporal/attachments.pyindex 8e2cd3423a39..cf7ba7cf4b09 100644--- a/products/slack_app/backend/temporal/attachments.py+++ b/products/slack_app/backend/temporal/attachments.py@@ -5,11 +5,15 @@ from dataclasses import dataclassfrom typing import Anyfrom urllib.parse import urljoin, urlparse+from django.conf import settings+import structlogfrom posthog.egress.slack.transport import slack_request+from posthog.models.integration import Integrationfrom products.slack_app.backend.services.slack_messages import SlackFileRef, SlackThreadMessage+from products.slack_app.backend.services.slack_scopes import has_scopeslogger = structlog.get_logger(__name__)@@ -20,12 +24,11 @@ MAX_SLACK_ATTACHMENTS_PER_MESSAGE = 15# agent's workspace. The oldest survive the cap: the file being discussed is usually# the one the thread opened with.MAX_SLACK_ATTACHMENTS_PER_THREAD = 15-MAX_SLACK_ATTACHMENT_BYTES = 10 * 1024 * 1024SLACK_DOWNLOAD_TIMEOUT_SECONDS = 15MAX_SLACK_DOWNLOAD_REDIRECTS = 5# What one turn may spend fetching attachments, across the triggering message and the-# rest of the thread together. The per-file caps above bound a single download, but the+# rest of the thread together. The per-file caps bound a single download, but the# file counts multiply them: without these two budgets a turn could hold every payload# in memory at once, and could stay in the download loop past the activity's# `start_to_close` deadline, which fails the turn and repeats the whole batch on retry.@@ -38,69 +41,12 @@ _MAX_ATTACHMENT_NAME_CHARS = 120_ALLOWED_SLACK_FILE_HOST_SUFFIXES = ("slack.com", "slack-edge.com", "slack-files.com")-# Allowlist, not denylist: a wrongly blocked file produces a visible "skipped-# because…" note the user can act on, while a wrongly allowed file is silent.-# The realistic Slack-attachment set is small — images, PDFs, and plain-text-# data formats. Anything executable, scripted, or macro-capable stays out.-_ALLOWED_EXTENSIONS = frozenset(- {- ".bmp",- ".csv",- ".gif",- ".jpeg",- ".jpg",- ".json",- ".log",- ".markdown",- ".md",- ".pdf",- ".png",- ".tsv",- ".txt",- ".webp",- ".yaml",- ".yml",- }-)-_ALLOWED_MIME_TYPES = frozenset(- {- "application/json",- "application/pdf",- "application/x-yaml",- "application/yaml",- "image/bmp",- "image/gif",- "image/jpeg",- "image/png",- "image/webp",- "text/csv",- "text/markdown",- "text/plain",- "text/tab-separated-values",- "text/yaml",- }-)-_ALLOWED_SLACK_FILETYPES = frozenset(- {- "bmp",- "csv",- "gif",- "jpeg",- "jpg",- "json",- "markdown",- "pdf",- "png",- "text",- "tsv",- "webp",- "yaml",- }-)+# Slack applies no file type rule of its own. The task artifact store decides what a+# user may attach, so Slack, PostHog Desktop, and PostHog AI accept the same files.-_ATTACHMENT_TYPE_SKIP_REASON = (- "only image, PDF, and plain-text attachments (logs, markdown, CSV, JSON, YAML) are supported"-)+SLACK_FILE_READ_SCOPE = "files:read"+_HTML_MIME_TYPES = frozenset({"application/xhtml+xml", "text/html"})+_HTML_EXTENSIONS = frozenset({".htm", ".html", ".xhtml"})_SLOW_BATCH_SKIP_MESSAGE = ("Some Slack attachment(s) were skipped because they took too long to fetch. "@@ -111,16 +57,6 @@ _LARGE_BATCH_SKIP_MESSAGE = ("Post the one you want the agent to look at.")-_EXECUTABLE_MAGIC_PREFIXES = (- b"MZ",- b"\x7fELF",- b"\xcf\xfa\xed\xfe",- b"\xce\xfa\xed\xfe",- b"\xfe\xed\xfa\xcf",- b"\xfe\xed\xfa\xce",- b"\xca\xfe\xba\xbe",-)-class SlackAttachmentBudget:"""The bytes and the wall-clock time one turn may spend fetching Slack attachments.@@ -166,6 +102,10 @@ class PreparedSlackAttachments:return self.requested_count > 0+def can_read_slack_files(integration: Integration) -> bool:+ return has_scopes(integration, {SLACK_FILE_READ_SCOPE})++def get_slack_bot_token(slack: Any, integration: Any) -> str | None:token = getattr(integration, "access_token", None)if isinstance(token, str) and token:@@ -209,42 +149,25 @@ def _is_allowed_slack_file_url(url: str) -> bool:return any(hostname == suffix or hostname.endswith(f".{suffix}") for suffix in _ALLOWED_SLACK_FILE_HOST_SUFFIXES)-def _is_allowed_metadata(filename: str, content_type: str, slack_filetype: str) -> bool:- """Every signal present must be allowed, and at least one positive signal must exist.-- Fails closed on contradiction (a ``.png`` name with a script mimetype) and on- files with no recognizable signal. ``application/octet-stream`` is treated as- "no mimetype" — Slack falls back to it for perfectly safe uploads, so it neither- allows nor blocks on its own.- """+def _is_html_file(filename: str, content_type: str, slack_filetype: str) -> bool:extension = os.path.splitext(filename.lower())[1]- filetype = slack_filetype.lower()- extension_allowed = extension in _ALLOWED_EXTENSIONS- mime_allowed = content_type in _ALLOWED_MIME_TYPES- filetype_allowed = filetype in _ALLOWED_SLACK_FILETYPES- if extension and not extension_allowed:- return False- if content_type and content_type != "application/octet-stream" and not mime_allowed:- return False- if filetype and not filetype_allowed:- return False- return extension_allowed or mime_allowed or filetype_allowed---def _is_dangerous_payload(payload: bytes) -> bool:- stripped = payload.lstrip()- if stripped.startswith(b"#!"):- return True- return any(payload.startswith(prefix) for prefix in _EXECUTABLE_MAGIC_PREFIXES)+ return extension in _HTML_EXTENSIONS or content_type in _HTML_MIME_TYPES or slack_filetype.lower() == "html"def _source_url(file: SlackFileRef) -> str:return file.url_private_download or file.url_private-def _download_slack_file(url: str, bot_token: str, budget: SlackAttachmentBudget) -> bytes | None:+def _download_slack_file(+ url: str,+ bot_token: str,+ budget: SlackAttachmentBudget,+ *,+ max_file_bytes: int,+ expects_html: bool,+) -> bytes | None:next_url = url- max_bytes = min(MAX_SLACK_ATTACHMENT_BYTES, budget.remaining_bytes)+ max_bytes = min(max_file_bytes, budget.remaining_bytes)for _ in range(MAX_SLACK_DOWNLOAD_REDIRECTS + 1):if budget.is_expired():logger.warning("slack_attachment_download_deadline_reached")@@ -282,12 +205,12 @@ def _download_slack_file(url: str, bot_token: str, budget: SlackAttachmentBudgetlogger.warning("slack_attachment_download_failed_status", status_code=response.status_code)return None- # Slack answers HTTP 200 with an HTML login/interstitial page when the- # token lacks files:read or the file is access-restricted. HTML is never- # an allowed attachment type, so an HTML body is always the interstitial- # — forwarding it would silently hand the agent a login page as the file.+ # Slack answers HTTP 200 with its HTML login page when the bot cannot read a+ # file, for example a file with access restrictions. An HTML body for a file+ # that is not HTML is that page, and forwarding it would give the agent a+ # login page in place of the file.response_content_type = _normalize_content_type(response.headers.get("Content-Type"))- if response_content_type in ("text/html", "application/xhtml+xml"):+ if response_content_type in _HTML_MIME_TYPES and not expects_html:logger.warning("slack_attachment_download_html_interstitial", content_type=response_content_type)return None@@ -335,6 +258,7 @@ def prepare_slack_file_artifacts(files: list[SlackFileRef],bot_token: str | None,*,+ can_read_files: bool,budget: SlackAttachmentBudget | None = None,) -> PreparedSlackAttachments:"""Fetch the attachments on one Slack message, ready to upload to the agent's workspace."""@@ -345,6 +269,7 @@ def prepare_slack_file_artifacts(over_limit_message=(f"Additional Slack attachment(s) skipped: only {MAX_SLACK_ATTACHMENTS_PER_MESSAGE} files are supported per message."),+ can_read_files=can_read_files,budget=budget or SlackAttachmentBudget(),)@@ -353,6 +278,7 @@ def prepare_slack_thread_file_artifacts(thread_messages: list[SlackThreadMessage],bot_token: str | None,*,+ can_read_files: bool,already_requested: list[SlackFileRef] | None = None,budget: SlackAttachmentBudget | None = None,) -> PreparedSlackAttachments:@@ -388,6 +314,7 @@ def prepare_slack_thread_file_artifacts(f"Slack attachment(s) from earlier in the thread skipped: only {MAX_SLACK_ATTACHMENTS_PER_THREAD} ""thread files are supported."),+ can_read_files=can_read_files,budget=budget or SlackAttachmentBudget(),)@@ -407,8 +334,11 @@ def _prepare_files(*,max_files: int,over_limit_message: str,+ can_read_files: bool,budget: SlackAttachmentBudget,) -> PreparedSlackAttachments:+ from products.tasks.backend.facade import api as tasks_facade+if not files:return PreparedSlackAttachments(artifacts=[], skipped_messages=[], requested_count=0)@@ -419,6 +349,18 @@ def _prepare_files(skipped_messages=["Slack attachment(s) could not be read because the Slack bot token was unavailable."],requested_count=requested_count,)+ # Without files:read, Slack answers a download with HTTP 200 and its HTML login page.+ # That page would reach the agent as the file, so no download starts at all.+ if not can_read_files:+ return PreparedSlackAttachments(+ artifacts=[],+ skipped_messages=[+ f"PostHog needs the `{SLACK_FILE_READ_SCOPE}` permission to read Slack attachments. "+ f"Ask a project admin to reconnect Slack ({settings.SITE_URL}/settings/project-integrations), "+ "then post the files again."+ ],+ requested_count=requested_count,+ )artifacts: list[dict[str, Any]] = []skipped_messages: list[str] = []@@ -436,12 +378,11 @@ def _prepare_files(filename = attachment_display_name(file)content_type = _normalize_content_type(file.mimetype) or "application/octet-stream"- if not _is_allowed_metadata(filename, content_type, file.filetype):- skipped_messages.append(f"{filename} was skipped because {_ATTACHMENT_TYPE_SKIP_REASON}.")- continue-- if file.size is not None and file.size > MAX_SLACK_ATTACHMENT_BYTES:- skipped_messages.append(f"{filename} was skipped because it exceeds the 10 MB Slack attachment limit.")+ max_file_bytes = tasks_facade.get_user_attachment_max_size_bytes(filename, content_type)+ if file.size is not None and file.size > max_file_bytes:+ skipped_messages.append(+ f"{filename} was skipped because it is larger than the {max_file_bytes // (1024 * 1024)} MB attachment limit."+ )continue# Slack reports the size on nearly every upload, so stopping here reports the real# reason rather than starting a download the byte ceiling would abort part-way.@@ -458,7 +399,13 @@ def _prepare_files(continuetry:- payload = _download_slack_file(url, bot_token, budget)+ payload = _download_slack_file(+ url,+ bot_token,+ budget,+ max_file_bytes=max_file_bytes,+ expects_html=_is_html_file(filename, content_type, file.filetype),+ )except Exception:logger.exception("slack_attachment_download_exception", file_id=file.id)payload = None@@ -467,9 +414,6 @@ def _prepare_files(skipped_messages.append(f"{filename} was skipped because it could not be downloaded from Slack.")continuebudget.spend_bytes(len(payload))- if _is_dangerous_payload(payload):- skipped_messages.append(f"{filename} was skipped because its content looks like an executable or script.")- continueartifact: dict[str, Any] = {"name": filename,diff --git a/products/slack_app/backend/temporal/tests/test_attachments.py b/products/slack_app/backend/temporal/tests/test_attachments.pyindex 28e2de8a5272..1ed2bfafb2a6 100644--- a/products/slack_app/backend/temporal/tests/test_attachments.py+++ b/products/slack_app/backend/temporal/tests/test_attachments.py@@ -19,10 +19,6 @@ from products.slack_app.backend.temporal.attachments import (prepare_slack_thread_file_artifacts,)-_TYPE_SKIP_SUFFIX = (- "was skipped because only image, PDF, and plain-text attachments (logs, markdown, CSV, JSON, YAML) are supported."-)-def _slack_file(**overrides: Any) -> SlackFileRef:return replace(@@ -45,27 +41,32 @@ def _message_with(ts: str, *files: SlackFileRef) -> SlackThreadMessage:class TestSlackAttachments(SimpleTestCase):@parameterized.expand([- ("declared_mimetype", "text/plain", "text", "text/plain"),+ ("debug.log", "text/plain", "text", "text/plain"),# Slack falls back to octet-stream for safe uploads; it must stay neutral.- ("octet_stream_fallback", "application/octet-stream", "", "application/octet-stream"),+ ("debug.log", "application/octet-stream", "", "application/octet-stream"),+ ("page.html", "text/html", "html", "text/html"),+ ("standup.mp3", "audio/mpeg", "mp3", "audio/mpeg"),+ ("deploy.sh", "text/x-sh", "shell", "text/x-sh"),+ ("diagram.svg", "image/svg+xml", "svg", "image/svg+xml"),+ ("installer.exe", "application/x-msdownload", "", "application/x-msdownload"),])def test_prepares_safe_slack_file_as_user_attachment(- self, _name: str, mimetype: str, filetype: str, expected_content_type: str+ self, name: str, mimetype: str, filetype: str, expected_content_type: str) -> None:- file = _slack_file(mimetype=mimetype, filetype=filetype)+ file = _slack_file(name=name, mimetype=mimetype, filetype=filetype)with patch("products.slack_app.backend.temporal.attachments._download_slack_file", return_value=b"hello") as download:- prepared = prepare_slack_file_artifacts([file], "xoxb-token")- prepared_again = prepare_slack_file_artifacts([file], "xoxb-token")+ prepared = prepare_slack_file_artifacts([file], "xoxb-token", can_read_files=True)+ prepared_again = prepare_slack_file_artifacts([file], "xoxb-token", can_read_files=True)assert download.call_args.args[:2] == ("https://files.slack.com/files-pri/T123-F123/debug.log", "xoxb-token")assert prepared.requested_count == 1assert prepared.skipped_messages == []assert len(prepared.artifacts) == 1artifact = prepared.artifacts[0]- assert artifact["name"] == "debug.log"+ assert artifact["name"] == nameassert artifact["type"] == "user_attachment"assert artifact["source"] == "slack_user_attachment"assert artifact["content_type"] == expected_content_type@@ -76,60 +77,73 @@ class TestSlackAttachments(SimpleTestCase):@parameterized.expand([- ("installer.exe", "application/x-msdownload", ""),- ("deploy.sh", "text/plain", "shell"),- # Shebang-less macOS script: extension is the only dangerous signal.- ("run.command", "text/plain", ""),- ("report.docm", "application/vnd.ms-word.document.macroEnabled.12", ""),- ("page.html", "text/html", "html"),- ("diagram.svg", "image/svg+xml", ""),- # Contradiction: allowed extension, disallowed mimetype — fail closed.- ("notes.txt", "application/x-sh", ""),+ # Slack serves an HTTP 200 HTML login page when the bot can't read the file.+ ("login_page_for_a_log_file", "debug.log", "text/plain", "text", False),+ ("login_page_for_an_image", "chart.png", "image/png", "png", False),+ ("html_file", "page.html", "text/html", "html", True),])- def test_rejects_disallowed_attachment_metadata_without_downloading(- self, name: str, mimetype: str, filetype: str+ def test_html_response_is_forwarded_only_for_an_html_file(+ self, _case: str, name: str, mimetype: str, filetype: str, accepted: bool) -> None:+ body = b"<html>hello</html>"+ response = MagicMock()+ response.is_redirect = False+ response.status_code = 200+ response.headers = {"Content-Type": "text/html; charset=utf-8"}+ response.iter_content.return_value = [body]+ file = _slack_file(name=name, mimetype=mimetype, filetype=filetype)+ with patch("products.slack_app.backend.temporal.attachments.slack_request", return_value=response):+ prepared = prepare_slack_file_artifacts([file], "xoxb-token", can_read_files=True)++ if accepted:+ assert prepared.skipped_messages == []+ assert [artifact["content_bytes"] for artifact in prepared.artifacts] == [body]+ else:+ assert prepared.artifacts == []+ assert prepared.skipped_messages == [f"{name} was skipped because it could not be downloaded from Slack."]++ def test_skips_every_file_without_downloading_when_the_install_cannot_read_files(self) -> None:with patch("products.slack_app.backend.temporal.attachments._download_slack_file") as download:prepared = prepare_slack_file_artifacts(- [_slack_file(name=name, mimetype=mimetype, filetype=filetype)],- "xoxb-token",+ [_slack_file(), _slack_file(id="F456", name="chart.png")], "xoxb-token", can_read_files=False)download.assert_not_called()assert prepared.artifacts == []- assert prepared.skipped_messages == [f"{name} {_TYPE_SKIP_SUFFIX}"]+ assert prepared.requested_count == 2+ assert len(prepared.skipped_messages) == 1+ assert "`files:read`" in prepared.skipped_messages[0]+ assert "reconnect Slack" in prepared.skipped_messages[0]- def test_blocks_script_payload_after_download(self) -> None:- with patch(- "products.slack_app.backend.temporal.attachments._download_slack_file",- return_value=b"#!/bin/sh\necho unsafe\n",- ):- prepared = prepare_slack_file_artifacts([_slack_file(name="notes.txt")], "xoxb-token")+ @parameterized.expand(+ [+ ("standup.mp3", "audio/mpeg", 30 * 1024 * 1024 + 1, "30 MB"),+ ("spec.pdf", "application/pdf", 10 * 1024 * 1024 + 1, "10 MB"),+ ]+ )+ def test_skips_file_larger_than_the_task_attachment_limit_without_downloading(+ self, name: str, mimetype: str, size: int, limit: str+ ) -> None:+ with patch("products.slack_app.backend.temporal.attachments._download_slack_file") as download:+ prepared = prepare_slack_file_artifacts(+ [_slack_file(name=name, mimetype=mimetype, filetype="", size=size)],+ "xoxb-token",+ can_read_files=True,+ budget=SlackAttachmentBudget(max_total_bytes=100 * 1024 * 1024),+ )- assert prepared.artifacts == []+ download.assert_not_called()assert prepared.skipped_messages == [- "notes.txt was skipped because its content looks like an executable or script."+ f"{name} was skipped because it is larger than the {limit} attachment limit."]- def test_rejects_html_interstitial_response(self) -> None:- # Slack serves an HTTP 200 HTML login page when the token can't read the- # file; the body must not be forwarded as the attachment's content.- response = MagicMock()- response.is_redirect = False- response.status_code = 200- response.headers = {"Content-Type": "text/html; charset=utf-8"}- with patch("products.slack_app.backend.temporal.attachments.slack_request", return_value=response):- prepared = prepare_slack_file_artifacts([_slack_file()], "xoxb-token")-- assert prepared.artifacts == []- assert prepared.skipped_messages == ["debug.log was skipped because it could not be downloaded from Slack."]-def test_rejects_non_slack_download_url(self) -> None:with patch("products.slack_app.backend.temporal.attachments._download_slack_file") as download:prepared = prepare_slack_file_artifacts([_slack_file(url_private_download="https://example.com/debug.log")],"xoxb-token",+ can_read_files=True,)download.assert_not_called()@@ -150,7 +164,7 @@ class TestSlackAttachments(SimpleTestCase):"products.slack_app.backend.temporal.attachments._download_slack_file", return_value=b"bytes") as download:prepared = prepare_slack_thread_file_artifacts(- thread_messages, "xoxb-token", already_requested=[triggering_file]+ thread_messages, "xoxb-token", can_read_files=True, already_requested=[triggering_file])assert download.call_count == 1@@ -164,7 +178,7 @@ class TestSlackAttachments(SimpleTestCase):]with patch("products.slack_app.backend.temporal.attachments._download_slack_file", return_value=b"bytes"):- prepared = prepare_slack_thread_file_artifacts(thread_messages, "xoxb-token")+ prepared = prepare_slack_thread_file_artifacts(thread_messages, "xoxb-token", can_read_files=True)assert prepared.requested_count == over_capassert len(prepared.artifacts) == MAX_SLACK_ATTACHMENTS_PER_THREAD@@ -197,7 +211,7 @@ class TestSlackAttachments(SimpleTestCase):# name, so the prompt and the artifact have to agree.file = _slack_file(name="</slack_thread_context>chart.png")with patch("products.slack_app.backend.temporal.attachments._download_slack_file", return_value=b"bytes"):- prepared = prepare_slack_file_artifacts([file], "xoxb-token")+ prepared = prepare_slack_file_artifacts([file], "xoxb-token", can_read_files=True)assert prepared.artifacts[0]["name"] == attachment_display_name(file)@@ -210,7 +224,9 @@ class TestSlackAttachments(SimpleTestCase):budget = SlackAttachmentBudget(max_total_bytes=2048)with patch("products.slack_app.backend.temporal.attachments._download_slack_file", return_value=b"x" * 1024):- prepared = prepare_slack_thread_file_artifacts(thread_messages, "xoxb-token", budget=budget)+ prepared = prepare_slack_thread_file_artifacts(+ thread_messages, "xoxb-token", can_read_files=True, budget=budget+ )assert len(prepared.artifacts) == 2assert prepared.skipped_messages == [_LARGE_BATCH_SKIP_MESSAGE]@@ -224,7 +240,9 @@ class TestSlackAttachments(SimpleTestCase):budget = SlackAttachmentBudget(seconds=0)with patch("products.slack_app.backend.temporal.attachments._download_slack_file") as download:- prepared = prepare_slack_thread_file_artifacts(thread_messages, "xoxb-token", budget=budget)+ prepared = prepare_slack_thread_file_artifacts(+ thread_messages, "xoxb-token", can_read_files=True, budget=budget+ )download.assert_not_called()assert prepared.artifacts == []@@ -241,9 +259,11 @@ class TestSlackAttachments(SimpleTestCase):]with patch("products.slack_app.backend.temporal.attachments._download_slack_file", return_value=b"x" * 1024):- message_part = prepare_slack_file_artifacts([triggering_file], "xoxb-token", budget=budget)+ message_part = prepare_slack_file_artifacts(+ [triggering_file], "xoxb-token", can_read_files=True, budget=budget+ )thread_part = prepare_slack_thread_file_artifacts(- thread_messages, "xoxb-token", already_requested=[triggering_file], budget=budget+ thread_messages, "xoxb-token", can_read_files=True, already_requested=[triggering_file], budget=budget)assert len(message_part.artifacts) == 1@@ -254,11 +274,11 @@ class TestSlackAttachments(SimpleTestCase):prompt = build_slack_attachment_prompt_text(None,uploaded_artifacts=[{"name": "debug.log"}],- skipped_messages=[f"deploy.sh {_TYPE_SKIP_SUFFIX}"],+ skipped_messages=["deploy.sh was skipped because it could not be downloaded from Slack."],)assert prompt == ("Slack attachment(s) available to the agent as task files: debug.log.\n\n""Slack attachment(s) skipped:\n"- f"- deploy.sh {_TYPE_SKIP_SUFFIX}"+ "- deploy.sh was skipped because it could not be downloaded from Slack.")diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex 0a155be6b048..98b4491cd070 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -103,7 +103,9 @@ class TestSlackThreadTaskMapping(TestCase):self.org = Organization.objects.create(name="TestOrg")self.team = Team.objects.create(organization=self.org, name="TestTeam")self.user = User.objects.create(email="[email protected]")- self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T_SLACK", config={"scope": "files:read"}+ )self.task = self.Task.objects.create(team=self.team,title="Test task",@@ -199,7 +201,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):self.org = Organization.objects.create(name="TestOrg")self.team = Team.objects.create(organization=self.org, name="TestTeam")self.user = User.objects.create(email="[email protected]", distinct_id="user-1")- self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T_SLACK", config={"scope": "files:read"}+ )# The mock SlackIntegration doesn't stub `auth_test`, so `get_cached_bot_user_id`# would return None and the bot-mention fast-path strip wouldn't kick in. Force# it to return the literal "BOT" so `<@BOT>` in test inputs is stripped from@@ -860,7 +864,9 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):self.org = Organization.objects.create(name="TestOrg")self.team = Team.objects.create(organization=self.org, name="TestTeam")self.user = User.objects.create(email="[email protected]")- self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T_SLACK", config={"scope": "files:read"}+ )# See note in TestCreatePostHogCodeTaskForRepoActivity.setUp: force the# bot-id lookup so `<@BOT>` mentions in test inputs strip the way they# do in production.@@ -977,6 +983,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):self._create_mapping()mock_slack_instance = MagicMock()mock_slack_instance.client.token = "xoxb-test"+ mock_slack_instance.integration = self.integrationmock_slack_cls.return_value = mock_slack_instanceevent = {@@ -1632,13 +1639,15 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):if terminal:self.task_run.status = self.TaskRun.Status.COMPLETEDself.task_run.save()+ self.integration.config = {}+ self.integration.save()self._create_mapping()event = {"channel": "C123","ts": "1234.5679","user": "U_ALICE","text": "",- "files": [_make_slack_file(name="installer.exe", mimetype="application/x-msdownload", filetype="binary")],+ "files": [_make_slack_file(name="debug.log")],}inputs = PostHogCodeSlackMentionWorkflowInputs(event=event,@@ -1655,6 +1664,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):):mock_slack_instance = MagicMock()mock_slack_instance.client.token = "xoxb-test"+ mock_slack_instance.integration = self.integrationmock_slack_cls.return_value = mock_slack_instanceresult = forward_posthog_code_followup_activity(inputs, "C123", "1234.5678", "U_ALICE", "", "1234.5679")@@ -1666,7 +1676,8 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert self.TaskRun.objects.count() == 1notice = mock_slack_instance.client.chat_postMessage.call_args.kwargs["text"]assert "no attachment was accepted" in notice- assert "installer.exe" in notice+ assert "`files:read`" in notice+ assert "reconnect Slack" in notice@patch("products.tasks.backend.facade.api.signal_task_run_user_message", return_value=False)@patch("posthog.models.integration.SlackIntegration")@@ -1699,7 +1710,9 @@ class TestEnforcePostHogCodeBillingQuotaActivity(TestCase):self.org = Organization.objects.create(name="TestOrg")self.team = Team.objects.create(organization=self.org, name="TestTeam")self.user = User.objects.create(email="[email protected]")- self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T_SLACK", config={"scope": "files:read"}+ )@patch("posthog.models.integration.SlackIntegration")@patch("ee.billing.quota_limiting.is_team_limited", return_value=True)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex dfb8c7142375..f4356a87f8c6 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -308,6 +308,7 @@ __all__ = ["finalize_task_run_artifact_uploads","finalize_task_staged_artifacts","get_active_wizard_cloud_run",+ "get_user_attachment_max_size_bytes","get_latest_active_internal_task_run_for_organization","get_conversation_task_dtos","get_latest_pr_url_by_task",@@ -4402,6 +4403,15 @@ def _save_artifact_manifest(run: TaskRun, manifest: list[dict]) -> None:run.save(update_fields=["artifacts", "updated_at"])+def get_user_attachment_max_size_bytes(name: str, content_type: str) -> int:+ """The largest file a user may attach to a task run, the same on every surface that attaches one."""+ from products.tasks.backend.presentation.serializers import ( # noqa: PLC0415 — pure size helpers, kept off the api import path+ get_task_run_artifact_max_size_bytes,+ )++ return get_task_run_artifact_max_size_bytes(name, content_type, "user_attachment")++def upload_task_run_artifacts(run_id: str | UUID,task_id: str | UUID,