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): keep non-image attachments on slack and teams (#70997)

Alex V1dacbb5cd9ba
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index a8539e7a8663..c2caddff21c9 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -20,7 +20,10 @@ from posthog.models.user import User
from products.conversations.backend.mailgun import validate_webhook_signature
from products.conversations.backend.models import Channel, EmailChannel, EmailMessageMapping, Status
from products.conversations.backend.models.ticket import Ticket
-from products.conversations.backend.services.attachments import save_file_to_uploaded_media
+from products.conversations.backend.services.attachments import (
+ sanitize_attachment_filename,
+ save_file_to_uploaded_media,
+)
from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region
logger = structlog.get_logger(__name__)
@@ -31,17 +34,6 @@ _BASIC_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
MAX_EMAIL_BODY_LENGTH = 50_000
MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 # 10 MB per file
MAX_ATTACHMENTS = 20
-MAX_FILENAME_LENGTH = 255
-_FILENAME_STRIP_RE = re.compile(r"[^\w\s\-.,()]+")
-
-
-def _sanitize_filename(name: str) -> str:
- """Strip potentially dangerous characters from an email attachment filename."""
- name = name.strip().replace("/", "_").replace("\\", "_")
- name = _FILENAME_STRIP_RE.sub("", name)
- if len(name) > MAX_FILENAME_LENGTH:
- name = name[:MAX_FILENAME_LENGTH]
- return name or "attachment"
def _extract_inbound_token(recipient: str) -> str | None:
@@ -100,7 +92,7 @@ def _extract_attachments(request: HttpRequest, team: Team) -> list[dict[str, Any
continue
file_bytes = uploaded_file.read()
- safe_name = _sanitize_filename(uploaded_file.name or "attachment")
+ safe_name = sanitize_attachment_filename(uploaded_file.name)
url = save_file_to_uploaded_media(team, safe_name, uploaded_file.content_type or "", file_bytes)
if url:
attachments.append(
diff --git a/products/conversations/backend/api/tests/test_attachments_service.py b/products/conversations/backend/api/tests/test_attachments_service.py
new file mode 100644
index 000000000000..1f1ba3e16056
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_attachments_service.py
@@ -0,0 +1,54 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.conversations.backend.services.attachments import build_content_with_images, sanitize_attachment_filename
+
+
+class TestAttachmentsService(SimpleTestCase):
+ def test_build_content_renders_files_as_links(self) -> None:
+ files = [{"url": "https://app.posthog.com/uploaded_media/a", "name": "invoice.pdf"}]
+ content, rich_content = build_content_with_images("hello", None, [], files)
+
+ assert "[invoice.pdf](https://app.posthog.com/uploaded_media/a)" in content
+ assert rich_content is not None
+ link_nodes = [
+ n
+ for n in rich_content["content"]
+ if n["type"] == "paragraph"
+ and any(m["type"] == "link" for c in n.get("content", []) for m in c.get("marks", []))
+ ]
+ assert len(link_nodes) == 1
+
+ def test_build_content_renders_images_and_files_together(self) -> None:
+ images = [{"url": "https://app.posthog.com/uploaded_media/img", "name": "shot.png"}]
+ files = [{"url": "https://app.posthog.com/uploaded_media/doc", "name": "doc.pdf"}]
+ content, rich_content = build_content_with_images("", None, images, files)
+
+ assert "![shot.png](https://app.posthog.com/uploaded_media/img)" in content
+ assert "[doc.pdf](https://app.posthog.com/uploaded_media/doc)" in content
+ assert rich_content is not None
+ node_types = [n["type"] for n in rich_content["content"]]
+ assert "image" in node_types
+ assert "paragraph" in node_types
+
+ def test_build_content_no_attachments_returns_unchanged(self) -> None:
+ content, rich_content = build_content_with_images("just text", None, [], [])
+ assert content == "just text"
+ assert rich_content is None
+
+ @parameterized.expand(
+ [
+ ("markdown_link", "evil](https://phish.example.com).pdf", ["[", "]"]),
+ ("markdown_image", "![x](y).png", ["[", "]", "!"]),
+ ("path_traversal", "../../etc/passwd", ["/"]),
+ ]
+ )
+ def test_sanitize_strips_dangerous_chars(self, _label: str, raw: str, forbidden: list[str]) -> None:
+ cleaned = sanitize_attachment_filename(raw)
+ for ch in forbidden:
+ assert ch not in cleaned
+
+ def test_sanitize_empty_falls_back(self) -> None:
+ assert sanitize_attachment_filename(None) == "attachment"
+ assert sanitize_attachment_filename(" ") == "attachment"
diff --git a/products/conversations/backend/api/tests/test_reaction_backfill.py b/products/conversations/backend/api/tests/test_reaction_backfill.py
index 0244a13bc2b2..fd46036fcd67 100644
--- a/products/conversations/backend/api/tests/test_reaction_backfill.py
+++ b/products/conversations/backend/api/tests/test_reaction_backfill.py
@@ -271,6 +271,7 @@ class TestBackfillThreadReplies(BaseTest):
"slack_author_email": "[email protected]",
"slack_author_avatar": "http://av",
"slack_images": None,
+ "slack_files": None,
}
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 1d84d82486c8..0eef356617ad 100644
--- a/products/conversations/backend/api/tests/test_slack_image_sync.py
+++ b/products/conversations/backend/api/tests/test_slack_image_sync.py
@@ -4,7 +4,11 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.conversations.backend.slack import _download_slack_image_bytes, extract_slack_files
+from products.conversations.backend.slack import (
+ _download_slack_image_bytes,
+ extract_slack_files,
+ split_slack_attachments,
+)
from products.conversations.backend.tasks import _read_image_bytes_for_slack_upload, post_reply_to_slack
VALID_PNG_BYTES = (
@@ -92,6 +96,62 @@ class TestSlackImageIngest(SimpleTestCase):
assert images == []
mock_save.assert_not_called()
+ @patch("products.conversations.backend.slack.save_file_to_uploaded_media")
+ @patch("products.conversations.backend.slack._download_slack_image_bytes")
+ def test_extract_slack_files_keeps_non_image_file(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
+ 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"
+
+ files = [
+ {
+ "id": "F123",
+ "mimetype": "application/pdf",
+ "name": "invoice.pdf",
+ "url_private_download": "https://files.slack.com/files-pri/T/F/invoice.pdf",
+ }
+ ]
+ attachments = extract_slack_files(files, fake_team, fake_client)
+ images, file_attachments = split_slack_attachments(attachments)
+
+ assert images == []
+ assert len(file_attachments) == 1
+ assert file_attachments[0]["mimetype"] == "application/pdf"
+ assert file_attachments[0]["name"] == "invoice.pdf"
+ # Non-image bytes are stored without image validation
+ assert mock_save.call_args.kwargs["validate_images"] is 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_sanitizes_markdown_in_name(
+ self, mock_download: MagicMock, mock_save: MagicMock
+ ) -> None:
+ 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"
+
+ files = [
+ {
+ "id": "F123",
+ "mimetype": "application/pdf",
+ "name": "evil](https://phish.example.com).pdf",
+ "url_private_download": "https://files.slack.com/files-pri/T/F/evil.pdf",
+ }
+ ]
+ attachments = extract_slack_files(files, fake_team, fake_client)
+
+ # Markdown link syntax stripped so the name can't inject a link
+ assert "[" not in attachments[0]["name"]
+ assert "]" not in attachments[0]["name"]
+
class TestSlackImageOutbound(SimpleTestCase):
def test_outbound_reader_rejects_non_uploaded_media_urls(self) -> None:
diff --git a/products/conversations/backend/api/tests/test_teams_image_sync.py b/products/conversations/backend/api/tests/test_teams_image_sync.py
index 2d6f46c7d513..6cf44d99209f 100644
--- a/products/conversations/backend/api/tests/test_teams_image_sync.py
+++ b/products/conversations/backend/api/tests/test_teams_image_sync.py
@@ -42,7 +42,7 @@ class TestTeamsImageIngest(SimpleTestCase):
mock_save.assert_called_once()
@patch("products.conversations.backend.teams_attachments._download_image")
- def test_extract_bot_attachments_skips_non_image(self, mock_download: MagicMock) -> None:
+ def test_extract_bot_attachments_skips_adaptive_card(self, mock_download: MagicMock) -> None:
fake_team = MagicMock()
fake_team.id = 1
@@ -57,6 +57,30 @@ class TestTeamsImageIngest(SimpleTestCase):
assert images == []
mock_download.assert_not_called()
+ @patch("products.conversations.backend.teams_attachments.save_file_to_uploaded_media")
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_bot_attachments_keeps_non_image_file(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
+ 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
+
+ attachments = [
+ {
+ "contentType": "application/pdf",
+ "contentUrl": "https://smba.trafficmanager.net/files/invoice.pdf",
+ "name": "invoice.pdf",
+ }
+ ]
+ results = extract_teams_bot_attachments(attachments, fake_team, "bot-token")
+
+ assert len(results) == 1
+ assert results[0]["mimetype"] == "application/pdf"
+ assert results[0]["name"] == "invoice.pdf"
+ # Non-image bytes are stored without image validation
+ assert mock_save.call_args.kwargs["validate_images"] is False
+
@patch("products.conversations.backend.teams_attachments.save_file_to_uploaded_media")
@patch("products.conversations.backend.teams_attachments._download_image")
def test_extract_bot_attachments_skips_invalid_image(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
diff --git a/products/conversations/backend/services/attachments.py b/products/conversations/backend/services/attachments.py
index 71c9d98dfd97..fc17b107586d 100644
--- a/products/conversations/backend/services/attachments.py
+++ b/products/conversations/backend/services/attachments.py
@@ -1,5 +1,6 @@
"""Shared attachment helpers for conversations channels (email, Slack, etc.)."""
+import re
from io import BytesIO
from typing import Any
@@ -14,6 +15,26 @@ from posthog.models.uploaded_media import UploadedMedia, save_content_to_object_
logger = structlog.get_logger(__name__)
CONVERSATIONS_MAX_IMAGE_BYTES = 20 * 1024 * 1024 # 20 MiB
+MAX_ATTACHMENTS_PER_MESSAGE = 20
+
+MAX_FILENAME_LENGTH = 255
+# Keep word chars, whitespace and a small punctuation set. Notably drops "[", "]"
+# and "!" so an attacker-controlled filename can't inject markdown link/image
+# syntax when we render it as `[name](url)` / `![name](url)`.
+_FILENAME_STRIP_RE = re.compile(r"[^\w\s\-.,()]+")
+
+
+def sanitize_attachment_filename(name: str | None) -> str:
+ """Strip potentially dangerous characters from an inbound attachment filename.
+
+ Names arrive from untrusted sources (email, Slack, Teams) and flow into
+ markdown/rich content, object storage, and Content-Disposition headers.
+ """
+ name = (name or "").strip().replace("/", "_").replace("\\", "_")
+ name = _FILENAME_STRIP_RE.sub("", name)
+ if len(name) > MAX_FILENAME_LENGTH:
+ name = name[:MAX_FILENAME_LENGTH]
+ return name or "attachment"
def is_valid_image(content: bytes) -> bool:
@@ -83,15 +104,27 @@ def save_file_to_uploaded_media(
def build_content_with_images(
- cleaned_text: str, rich_content: dict[str, Any] | None, images: list[dict[str, Any]]
+ cleaned_text: str,
+ rich_content: dict[str, Any] | None,
+ images: list[dict[str, Any]],
+ files: list[dict[str, Any]] | None = None,
) -> tuple[str, dict[str, Any] | None]:
- """Merge extracted image metadata into plain-text content and rich_content doc."""
+ """Merge extracted attachment metadata into plain-text content and rich_content doc.
+
+ Images render as inline image nodes; non-image files render as download links.
+ """
+ files = files or []
content = cleaned_text
- if not images:
+ if not images and not files:
return content, rich_content
- image_markdown = "\n".join(f"![{img['name']}]({img['url']})" for img in images)
- content = f"{cleaned_text}\n\n{image_markdown}" if cleaned_text else image_markdown
+ parts = [cleaned_text] if cleaned_text else []
+ 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))
+ content = "\n\n".join(parts)
+
if not isinstance(rich_content, dict):
rich_content = {"type": "doc", "content": []}
rich_nodes = rich_content.setdefault("content", [])
@@ -102,4 +135,17 @@ def build_content_with_images(
"attrs": {"src": img["url"], "alt": img.get("name", "image")},
}
)
+ for f in files:
+ rich_nodes.append(
+ {
+ "type": "paragraph",
+ "content": [
+ {
+ "type": "text",
+ "text": f.get("name", "attachment"),
+ "marks": [{"type": "link", "attrs": {"href": f["url"]}}],
+ }
+ ],
+ }
+ )
return content, rich_content
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index 56542cbf5b06..592a12923a9a 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -47,8 +47,10 @@ from .models import Ticket
from .models.constants import Channel, ChannelDetail, Status
from .services.attachments import (
CONVERSATIONS_MAX_IMAGE_BYTES,
+ MAX_ATTACHMENTS_PER_MESSAGE,
build_content_with_images,
is_valid_image,
+ sanitize_attachment_filename,
save_file_to_uploaded_media,
)
from .support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, get_support_slack_bot_token
@@ -319,9 +321,19 @@ def _download_slack_image_bytes(url: str, bot_token: str) -> bytes | None:
return None
+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/")]
+ return images, files
+
+
def extract_slack_files(files: list[dict] | None, team: Team, client: WebClient | None = None) -> list[dict]:
"""
- Extract image attachments from Slack and re-host them in UploadedMedia.
+ Extract attachments from Slack and re-host them in UploadedMedia.
+
+ Returns a combined list of images and non-image files (PDFs, docs, etc.),
+ each tagged with its ``mimetype``. Callers split with ``split_slack_attachments``.
"""
if not files:
return []
@@ -329,12 +341,10 @@ 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
logger.info("🖼️ slack_file_extract_started", team_id=team_id, total_files=len(files), has_bot_token=bool(bot_token))
- images = []
- for f in files:
+ attachments: list[dict] = []
+ for f in files[:MAX_ATTACHMENTS_PER_MESSAGE]:
mimetype = f.get("mimetype", "")
- if not mimetype.startswith("image/"):
- logger.debug("🖼️ slack_file_extract_skipped_non_image", file_id=f.get("id"), mimetype=mimetype)
- continue
+ is_image = mimetype.startswith("image/")
file_id = f.get("id")
source_url = f.get("url_private_download") or f.get("url_private")
@@ -348,35 +358,36 @@ def extract_slack_files(files: list[dict] | None, team: Team, client: WebClient
continue
try:
- image_bytes = _download_slack_image_bytes(source_url, bot_token)
+ 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 image_bytes:
+ if not file_bytes:
logger.warning("🖼️ slack_file_download_rejected", file_id=file_id, source_url=source_url)
continue
- if not is_valid_image(image_bytes):
+ # 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
- stored_url = save_file_to_uploaded_media(
- team, f.get("name", "image"), mimetype, image_bytes, validate_images=False
- )
+ 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:
- images.append(
- {
- "url": stored_url,
- "name": f.get("name", "image"),
- "mimetype": mimetype,
- "thumb": f.get("thumb_360") or f.get("thumb_160"),
- }
- )
+ attachment = {
+ "url": stored_url,
+ "name": safe_name,
+ "mimetype": mimetype,
+ }
+ if is_image:
+ attachment["thumb"] = f.get("thumb_360") or f.get("thumb_160")
+ 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, image_count=len(images))
- return images
+ logger.info("🖼️ slack_file_extract_finished", team_id=team_id, attachment_count=len(attachments))
+ return attachments
def create_or_update_slack_ticket(
@@ -416,8 +427,8 @@ def create_or_update_slack_ticket(
files_count=len(files or []),
)
- # Extract images from Slack files, making them publicly accessible
- images = extract_slack_files(files, team, client)
+ # Extract attachments from Slack files, making them publicly accessible
+ images, file_attachments = split_slack_attachments(extract_slack_files(files, team, client))
# Resolve Slack user info for this message author
user_info = resolve_slack_user(client, slack_user_id)
@@ -457,8 +468,8 @@ def create_or_update_slack_ticket(
if slack_team_id and not ticket.slack_team_id:
Ticket.objects.filter(id=ticket.id, team=team).update(slack_team_id=slack_team_id)
- # Allow messages with only images (no text)
- if not cleaned_text and not images:
+ # Allow messages with only attachments (no text)
+ if not cleaned_text and not images and not file_attachments:
logger.warning(
"🧵 slack_support_ticket_ingest_empty_after_processing",
team_id=team_id,
@@ -468,7 +479,7 @@ def create_or_update_slack_ticket(
)
return ticket
- content, rich_content = build_content_with_images(cleaned_text, rich_content, images)
+ content, rich_content = build_content_with_images(cleaned_text, rich_content, images, file_attachments)
Comment.objects.create(
team=team,
@@ -486,6 +497,7 @@ def create_or_update_slack_ticket(
"slack_author_email": user_info.get("email"),
"slack_author_avatar": user_info.get("avatar"),
"slack_images": images if images else None,
+ "slack_files": file_attachments if file_attachments else None,
},
)
@@ -497,8 +509,8 @@ def create_or_update_slack_ticket(
return ticket
# New ticket from top-level message
- # Allow messages with only images (no text)
- if not cleaned_text and not images:
+ # Allow messages with only attachments (no text)
+ if not cleaned_text and not images and not file_attachments:
logger.warning(
"🧵 slack_support_ticket_ingest_empty_after_processing",
team_id=team_id,
@@ -508,7 +520,7 @@ def create_or_update_slack_ticket(
)
return None
- content, rich_content = build_content_with_images(cleaned_text, rich_content, images)
+ content, rich_content = build_content_with_images(cleaned_text, rich_content, images, file_attachments)
# Serialize concurrent ticket creation for the same Slack thread via Redis lock.
# Without this, two reaction_added events from different users race through the
@@ -567,6 +579,7 @@ def create_or_update_slack_ticket(
"slack_author_email": user_info.get("email"),
"slack_author_avatar": user_info.get("avatar"),
"slack_images": images if images else None,
+ "slack_files": file_attachments if file_attachments else None,
},
)
@@ -1263,7 +1276,7 @@ def _backfill_thread_replies(
if not reply_text.strip() and not reply_files:
continue
- images = extract_slack_files(reply_files, team, client)
+ images, file_attachments = split_slack_attachments(extract_slack_files(reply_files, team, client))
if reply_user not in user_cache:
user_cache[reply_user] = resolve_slack_user(client, reply_user)
@@ -1286,7 +1299,7 @@ def _backfill_thread_replies(
cleaned_text, rich_content = slack_to_content_and_rich_content(
reply_text, reply_blocks, user_names=reply_user_names
)
- if not cleaned_text and not images:
+ if not cleaned_text and not images and not file_attachments:
continue
if is_team_member:
@@ -1294,7 +1307,7 @@ def _backfill_thread_replies(
else:
customer_message_count += 1
- content, rich_content = build_content_with_images(cleaned_text, rich_content, images)
+ content, rich_content = build_content_with_images(cleaned_text, rich_content, images, file_attachments)
comments_to_create.append(
Comment(
@@ -1313,6 +1326,7 @@ def _backfill_thread_replies(
"slack_author_email": user_info.get("email"),
"slack_author_avatar": user_info.get("avatar"),
"slack_images": images if images else None,
+ "slack_files": file_attachments if file_attachments else None,
},
)
)
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index ec6b09993609..affa6a6b5b74 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -1176,7 +1176,7 @@ def _sync_one_ticket_thread_replies(
activity=activity,
tenant_id=tenant_id,
is_thread_reply=True,
- images=reply_images,
+ attachments=reply_images,
)
except Exception:
logger.exception(
@@ -1449,7 +1449,7 @@ def _poll_one_shared_channel(
# Shared channel: confirm via Graph (bot connector can't post here),
# reusing the token we already hold for the delta read.
graph_post_context={"teams_team_id": teams_team_id, "token": token},
- images=images,
+ attachments=images,
)
except Exception:
logger.exception(
diff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.py
index 046b819f551e..930a7c44867a 100644
--- a/products/conversations/backend/teams.py
+++ b/products/conversations/backend/teams.py
@@ -37,7 +37,7 @@ from .support_teams import (
is_trusted_teams_service_url,
mark_teams_graph_message_seen,
)
-from .teams_attachments import extract_teams_bot_attachments
+from .teams_attachments import extract_teams_bot_attachments, split_teams_attachments
from .teams_formatting import teams_html_to_content_and_rich_content
logger = structlog.get_logger(__name__)
@@ -530,7 +530,7 @@ def create_or_update_teams_ticket(
is_thread_reply: bool = False,
channel_detail: ChannelDetail | None = None,
graph_post_context: dict | None = None,
- images: list[dict[str, Any]] | None = None,
+ attachments: list[dict[str, Any]] | None = None,
) -> Ticket | None:
"""
Core function: create a new ticket or add a message to an existing one from a Teams Activity.
@@ -572,12 +572,14 @@ def create_or_update_teams_ticket(
# Convert Teams HTML to content and rich_content
cleaned_text, rich_content = teams_html_to_content_and_rich_content(text_html)
- # Merge extracted images into content + rich_content
- resolved_images = images or []
- if resolved_images:
- cleaned_text, rich_content = build_content_with_images(cleaned_text, rich_content, resolved_images)
+ # Merge extracted attachments into content + rich_content
+ resolved_images, resolved_files = split_teams_attachments(attachments or [])
+ if resolved_images or resolved_files:
+ cleaned_text, rich_content = build_content_with_images(
+ cleaned_text, rich_content, resolved_images, resolved_files
+ )
- if not cleaned_text and not resolved_images:
+ if not cleaned_text and not resolved_images and not resolved_files:
logger.warning("teams_ticket_ingest_empty", team_id=team_id, activity_id=activity_id)
return None
@@ -633,6 +635,7 @@ def create_or_update_teams_ticket(
"teams_author_email": user_info.get("email"),
"teams_graph_message_id": activity_id,
"teams_images": resolved_images if resolved_images else None,
+ "teams_files": resolved_files if resolved_files else None,
},
)
mark_teams_graph_message_seen(team_id, channel_id, activity_id)
@@ -707,6 +710,7 @@ def create_or_update_teams_ticket(
"teams_author_email": user_info.get("email"),
"teams_graph_message_id": activity_id,
"teams_images": resolved_images if resolved_images else None,
+ "teams_files": resolved_files if resolved_files else None,
},
)
@@ -759,8 +763,8 @@ def _configured_support_channel_ids(settings: dict) -> set[str]:
return ids
-def _extract_bot_images(activity: dict, team: Team) -> list[dict[str, Any]]:
- """Best-effort extraction of image attachments from a bot-framework activity."""
+def _extract_bot_attachments(activity: dict, team: Team) -> list[dict[str, Any]]:
+ """Best-effort extraction of attachments from a bot-framework activity."""
attachments = activity.get("attachments")
if not attachments:
return []
@@ -805,13 +809,13 @@ def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:
if channel_id not in configured_channels:
return
- images = _extract_bot_images(activity, team)
+ attachments = _extract_bot_attachments(activity, team)
create_or_update_teams_ticket(
team=team,
activity=activity,
tenant_id=tenant_id,
is_thread_reply=True,
- images=images,
+ attachments=attachments,
)
return
@@ -819,14 +823,14 @@ def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:
return
# Top-level message -> create new ticket
- images = _extract_bot_images(activity, team)
+ attachments = _extract_bot_attachments(activity, team)
create_or_update_teams_ticket(
team=team,
activity=activity,
tenant_id=tenant_id,
is_thread_reply=False,
channel_detail=ChannelDetail.TEAMS_CHANNEL_MESSAGE,
- images=images,
+ attachments=attachments,
)
@@ -867,14 +871,14 @@ def handle_teams_mention(activity: dict, team: Team, tenant_id: str) -> None:
teams_conversation_id__in=candidate_conversation_ids,
).exists()
- images = _extract_bot_images(activity, team)
+ attachments = _extract_bot_attachments(activity, team)
create_or_update_teams_ticket(
team=team,
activity=activity,
tenant_id=tenant_id,
is_thread_reply=existing,
channel_detail=ChannelDetail.TEAMS_BOT_MENTION,
- images=images,
+ attachments=attachments,
)
diff --git a/products/conversations/backend/teams_attachments.py b/products/conversations/backend/teams_attachments.py
index 6736d2b514a8..69a808ffa54e 100644
--- a/products/conversations/backend/teams_attachments.py
+++ b/products/conversations/backend/teams_attachments.py
@@ -14,7 +14,13 @@ import structlog
from posthog.models.team.team import Team
-from .services.attachments import CONVERSATIONS_MAX_IMAGE_BYTES, is_valid_image, save_file_to_uploaded_media
+from .services.attachments import (
+ CONVERSATIONS_MAX_IMAGE_BYTES,
+ MAX_ATTACHMENTS_PER_MESSAGE,
+ is_valid_image,
+ sanitize_attachment_filename,
+ save_file_to_uploaded_media,
+)
from .support_teams import is_trusted_teams_service_url
logger = structlog.get_logger(__name__)
@@ -90,17 +96,22 @@ def _download_image(url: str, token: str) -> bytes | None:
return b"".join(chunks)
-def _save_image(team: Team, image_bytes: bytes, name: str, mimetype: str) -> dict[str, Any] | None:
- """Validate and persist image bytes, returning the image dict or None."""
- if not is_valid_image(image_bytes):
+def _save_attachment(team: Team, file_bytes: bytes, name: str, mimetype: str) -> dict[str, Any] | None:
+ """Validate and persist attachment bytes, returning the attachment dict or None.
+
+ Only ``image/*`` content is byte-validated; other types are stored as-is and
+ served as opaque downloads by the media endpoint.
+ """
+ if mimetype.startswith("image/") and not is_valid_image(file_bytes):
logger.warning("teams_image_invalid_content", name=name)
return None
- stored_url = save_file_to_uploaded_media(team, name, mimetype, image_bytes, validate_images=False)
+ safe_name = sanitize_attachment_filename(name)
+ stored_url = save_file_to_uploaded_media(team, safe_name, mimetype, file_bytes, validate_images=False)
if not stored_url:
return None
- return {"url": stored_url, "name": name, "mimetype": mimetype}
+ return {"url": stored_url, "name": safe_name, "mimetype": mimetype}
def extract_teams_bot_attachments(
@@ -108,14 +119,20 @@ def extract_teams_bot_attachments(
team: Team,
bot_token: str,
) -> list[dict[str, Any]]:
- """Extract image attachments from a bot-framework activity and re-host them."""
+ """Extract attachments from a bot-framework activity and re-host them.
+
+ Returns a combined list of images and non-image files, each tagged with its
+ ``mimetype``. Callers split with ``split_teams_attachments``.
+ """
if not attachments:
return []
- images: list[dict[str, Any]] = []
- for att in attachments:
+ results: list[dict[str, Any]] = []
+ for att in attachments[:MAX_ATTACHMENTS_PER_MESSAGE]:
content_type = att.get("contentType") or ""
- if not content_type.startswith("image/"):
+ # Skip cards and other non-file attachments (adaptive cards, etc.) which
+ # have a card content type and no downloadable contentUrl.
+ if not content_type or content_type.startswith("application/vnd.microsoft.card"):
continue
content_url = att.get("contentUrl") or ""
@@ -128,16 +145,23 @@ def extract_teams_bot_attachments(
logger.warning("teams_bot_attachment_untrusted_host", url=content_url[:200])
continue
- image_bytes = _download_image(content_url, bot_token)
- if not image_bytes:
+ file_bytes = _download_image(content_url, bot_token)
+ if not file_bytes:
continue
- name = att.get("name") or "image"
- result = _save_image(team, image_bytes, name, content_type)
+ name = att.get("name") or "attachment"
+ result = _save_attachment(team, file_bytes, name, content_type)
if result:
- images.append(result)
+ results.append(result)
- return images
+ return results
+
+
+def split_teams_attachments(attachments: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """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/")]
+ return images, files
def extract_teams_graph_images(
@@ -193,7 +217,7 @@ def extract_teams_graph_images(
hc = hosted_map[hc_id]
mimetype = hc.get("contentType") or mimetype
- result = _save_image(team, image_bytes, name, mimetype)
+ result = _save_attachment(team, image_bytes, name, mimetype)
if result:
images.append(result)