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): sync Teams image attachments into support tickets (#65769)

Alex V1cb4b68db5dd
diff --git a/products/conversations/backend/api/tests/test_teams_image_sync.py b/products/conversations/backend/api/tests/test_teams_image_sync.py
new file mode 100644
index 000000000000..2d6f46c7d513
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_teams_image_sync.py
@@ -0,0 +1,233 @@
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from products.conversations.backend.teams_attachments import (
+ _download_image,
+ extract_teams_bot_attachments,
+ extract_teams_graph_images,
+)
+
+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"
+)
+
+
+class TestTeamsImageIngest(SimpleTestCase):
+ @patch("products.conversations.backend.teams_attachments.save_file_to_uploaded_media")
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_bot_attachments_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
+
+ attachments = [
+ {
+ "contentType": "image/png",
+ "contentUrl": "https://smba.trafficmanager.net/images/abc",
+ "name": "screenshot.png",
+ }
+ ]
+ images = extract_teams_bot_attachments(attachments, fake_team, "bot-token")
+
+ assert len(images) == 1
+ assert images[0]["url"] == "https://app.posthog.com/uploaded_media/abc"
+ assert images[0]["name"] == "screenshot.png"
+ mock_download.assert_called_once_with("https://smba.trafficmanager.net/images/abc", "bot-token")
+ 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:
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ attachments = [
+ {
+ "contentType": "application/vnd.microsoft.card.adaptive",
+ "content": {"type": "AdaptiveCard"},
+ }
+ ]
+ images = extract_teams_bot_attachments(attachments, fake_team, "bot-token")
+
+ 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_skips_invalid_image(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
+ mock_download.return_value = b"not-an-image"
+
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ attachments = [
+ {
+ "contentType": "image/png",
+ "contentUrl": "https://smba.trafficmanager.net/images/abc",
+ "name": "bad.png",
+ }
+ ]
+ images = extract_teams_bot_attachments(attachments, fake_team, "bot-token")
+
+ assert images == []
+ mock_save.assert_not_called()
+
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_bot_attachments_skips_failed_download(self, mock_download: MagicMock) -> None:
+ mock_download.return_value = None
+
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ attachments = [
+ {
+ "contentType": "image/jpeg",
+ "contentUrl": "https://smba.trafficmanager.net/images/abc",
+ "name": "test.jpg",
+ }
+ ]
+ images = extract_teams_bot_attachments(attachments, fake_team, "bot-token")
+
+ assert images == []
+
+ @patch("products.conversations.backend.teams_attachments.save_file_to_uploaded_media")
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_graph_images_from_hosted_contents(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/xyz"
+
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ hosted_url = "https://graph.microsoft.com/v1.0/teams/t1/channels/c1/messages/m1/hostedContents/hc1/$value"
+ msg = {
+ "id": "m1",
+ "body": {
+ "contentType": "html",
+ "content": f'<p>Check this</p><img src="{hosted_url}" />',
+ },
+ "hostedContents": [
+ {"id": "hc1", "contentType": "image/png"},
+ ],
+ }
+ images = extract_teams_graph_images(msg, fake_team, "t1", "c1", "graph-token")
+
+ assert len(images) == 1
+ assert images[0]["url"] == "https://app.posthog.com/uploaded_media/xyz"
+ mock_download.assert_called_once_with(hosted_url, "graph-token")
+
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_graph_images_no_img_tags(self, mock_download: MagicMock) -> None:
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ msg = {
+ "id": "m1",
+ "body": {"contentType": "html", "content": "<p>Just text</p>"},
+ }
+ images = extract_teams_graph_images(msg, fake_team, "t1", "c1", "graph-token")
+
+ assert images == []
+ mock_download.assert_not_called()
+
+ def test_extract_bot_attachments_empty_list(self) -> None:
+ fake_team = MagicMock()
+ fake_team.id = 1
+ assert extract_teams_bot_attachments([], fake_team, "bot-token") == []
+ assert extract_teams_bot_attachments(None, fake_team, "bot-token") == []
+
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_bot_attachments_rejects_untrusted_host(self, mock_download: MagicMock) -> None:
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ attachments = [
+ {
+ "contentType": "image/png",
+ "contentUrl": "https://evil.example.com/steal",
+ "name": "x.png",
+ }
+ ]
+ assert extract_teams_bot_attachments(attachments, fake_team, "bot-token") == []
+ mock_download.assert_not_called()
+
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_graph_images_rejects_wrong_team_channel(self, mock_download: MagicMock) -> None:
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ # URL points to a different team/channel than the one we're processing
+ evil_url = (
+ "https://graph.microsoft.com/v1.0/teams/OTHER_TEAM/channels/OTHER_CH/messages/m1/hostedContents/hc1/$value"
+ )
+ msg = {
+ "id": "m1",
+ "body": {
+ "contentType": "html",
+ "content": f'<img src="{evil_url}" />',
+ },
+ }
+ images = extract_teams_graph_images(msg, fake_team, "t1", "c1", "graph-token")
+
+ assert images == []
+ mock_download.assert_not_called()
+
+ @patch("products.conversations.backend.teams_attachments._download_image")
+ def test_extract_graph_images_rejects_wrong_message_id(self, mock_download: MagicMock) -> None:
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ # URL references a different message than the one we're processing
+ evil_url = "https://graph.microsoft.com/v1.0/teams/t1/channels/c1/messages/OTHER_MSG/hostedContents/hc1/$value"
+ msg = {
+ "id": "m1",
+ "body": {
+ "contentType": "html",
+ "content": f'<img src="{evil_url}" />',
+ },
+ }
+ images = extract_teams_graph_images(msg, fake_team, "t1", "c1", "graph-token")
+
+ 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_graph_images_accepts_reply_path(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/reply"
+
+ fake_team = MagicMock()
+ fake_team.id = 1
+
+ reply_url = "https://graph.microsoft.com/v1.0/teams/t1/channels/c1/messages/root123/replies/r1/hostedContents/hc1/$value"
+ msg = {
+ "id": "r1",
+ "body": {
+ "contentType": "html",
+ "content": f'<img src="{reply_url}" />',
+ },
+ "hostedContents": [{"id": "hc1", "contentType": "image/jpeg"}],
+ }
+ images = extract_teams_graph_images(msg, fake_team, "t1", "c1", "graph-token")
+
+ assert len(images) == 1
+ mock_download.assert_called_once_with(reply_url, "graph-token")
+
+ @patch("products.conversations.backend.teams_attachments.requests.get")
+ def test_download_image_blocks_redirects(self, mock_get: MagicMock) -> None:
+ resp = MagicMock()
+ resp.is_redirect = True
+ resp.is_permanent_redirect = False
+ resp.status_code = 302
+ mock_get.return_value = resp
+
+ assert _download_image("https://graph.microsoft.com/v1.0/x/$value", "graph-token") is None
+ mock_get.assert_called_once()
+ # token must not leak across the redirect hop
+ assert mock_get.call_args.kwargs["allow_redirects"] is False
diff --git a/products/conversations/backend/services/attachments.py b/products/conversations/backend/services/attachments.py
index 0e0acd08df2a..2b8e09303183 100644
--- a/products/conversations/backend/services/attachments.py
+++ b/products/conversations/backend/services/attachments.py
@@ -1,6 +1,7 @@
"""Shared attachment helpers for conversations channels (email, Slack, etc.)."""
from io import BytesIO
+from typing import Any
from django.conf import settings
@@ -77,3 +78,26 @@ def save_file_to_uploaded_media(
bytes_size=len(content),
)
return uploaded_media.get_absolute_url()
+
+
+def build_content_with_images(
+ cleaned_text: str, rich_content: dict[str, Any] | None, images: list[dict[str, Any]]
+) -> tuple[str, dict[str, Any] | None]:
+ """Merge extracted image metadata into plain-text content and rich_content doc."""
+ content = cleaned_text
+ if not images:
+ 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
+ if not isinstance(rich_content, dict):
+ rich_content = {"type": "doc", "content": []}
+ rich_nodes = rich_content.setdefault("content", [])
+ for img in images:
+ rich_nodes.append(
+ {
+ "type": "image",
+ "attrs": {"src": img["url"], "alt": img.get("name", "image")},
+ }
+ )
+ return content, rich_content
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index f461996bb3da..ab18d9942427 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -37,7 +37,7 @@ from .cache import (
from .formatting import extract_slack_user_ids, slack_to_content_and_rich_content
from .models import Ticket
from .models.constants import Channel, ChannelDetail, Status
-from .services.attachments import is_valid_image, save_file_to_uploaded_media
+from .services.attachments import build_content_with_images, is_valid_image, save_file_to_uploaded_media
from .support_slack import (
SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES,
SUPPORT_SLACK_MAX_IMAGE_BYTES,
@@ -61,28 +61,6 @@ def _get_team_id(team: Team) -> int:
return team_id
-def _build_content_with_images(
- cleaned_text: str, rich_content: dict[str, Any] | None, images: list[dict[str, Any]]
-) -> tuple[str, dict[str, Any] | None]:
- content = cleaned_text
- if not images:
- 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
- if not isinstance(rich_content, dict):
- rich_content = {"type": "doc", "content": []}
- rich_nodes = rich_content.setdefault("content", [])
- for img in images:
- rich_nodes.append(
- {
- "type": "image",
- "attrs": {"src": img["url"], "alt": img.get("name", "image")},
- }
- )
- return content, rich_content
-
-
class _NoRedirectHandler(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
@@ -428,7 +406,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)
Comment.objects.create(
team=team,
@@ -468,7 +446,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)
# Serialize concurrent ticket creation for the same Slack thread via Redis lock.
# Without this, two reaction_added events from different users race through the
@@ -851,7 +829,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)
comments_to_create.append(
Comment(
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index c7685b92573a..13c90d1cec32 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -79,6 +79,7 @@ from products.conversations.backend.teams import (
post_help_card,
post_teams_channel_message_via_graph,
)
+from products.conversations.backend.teams_attachments import extract_teams_graph_images
from products.conversations.backend.teams_formatting import rich_content_to_teams_html
from .support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, SUPPORT_SLACK_MAX_IMAGE_BYTES
@@ -997,12 +998,14 @@ def _sync_one_ticket_thread_replies(
if activity is None:
continue
+ reply_images = extract_teams_graph_images(reply, team, teams_team_id, channel_id, token)
try:
result = create_or_update_teams_ticket(
team=team,
activity=activity,
tenant_id=tenant_id,
is_thread_reply=True,
+ images=reply_images,
)
except Exception:
logger.exception(
@@ -1264,6 +1267,7 @@ def _poll_one_shared_channel(
conversation_id = (activity.get("conversation") or {}).get("id")
if conversation_id:
surfaced_conversation_ids.add(conversation_id)
+ images = extract_teams_graph_images(msg, team, teams_team_id, channel_id, token)
try:
create_or_update_teams_ticket(
team=team,
@@ -1274,6 +1278,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,
)
except Exception:
logger.exception(
diff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.py
index 8417aaf07729..3289788ff9de 100644
--- a/products/conversations/backend/teams.py
+++ b/products/conversations/backend/teams.py
@@ -27,6 +27,7 @@ from posthog.models.user import User
from .cache import get_cached_teams_user, set_cached_teams_user
from .models import Ticket
from .models.constants import Channel, ChannelDetail, Status
+from .services.attachments import build_content_with_images
from .support_teams import (
get_bot_framework_token,
get_bot_from_id,
@@ -36,6 +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_formatting import teams_html_to_content_and_rich_content
logger = structlog.get_logger(__name__)
@@ -528,6 +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,
) -> Ticket | None:
"""
Core function: create a new ticket or add a message to an existing one from a Teams Activity.
@@ -569,7 +572,12 @@ 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)
- if not cleaned_text:
+ # 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)
+
+ if not cleaned_text and not resolved_images:
logger.warning("teams_ticket_ingest_empty", team_id=team_id, activity_id=activity_id)
return None
@@ -624,6 +632,7 @@ def create_or_update_teams_ticket(
"teams_author_name": user_info["name"],
"teams_author_email": user_info.get("email"),
"teams_graph_message_id": activity_id,
+ "teams_images": resolved_images if resolved_images else None,
},
)
mark_teams_graph_message_seen(team_id, channel_id, activity_id)
@@ -695,6 +704,7 @@ def create_or_update_teams_ticket(
"teams_author_name": user_info["name"],
"teams_author_email": user_info.get("email"),
"teams_graph_message_id": activity_id,
+ "teams_images": resolved_images if resolved_images else None,
},
)
@@ -747,6 +757,18 @@ 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."""
+ attachments = activity.get("attachments")
+ if not attachments:
+ return []
+ try:
+ bot_token = get_bot_framework_token()
+ except ValueError:
+ return []
+ return extract_teams_bot_attachments(attachments, team, bot_token)
+
+
def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:
"""
Handle a Teams message activity for the dedicated support channel.
@@ -781,11 +803,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)
create_or_update_teams_ticket(
team=team,
activity=activity,
tenant_id=tenant_id,
is_thread_reply=True,
+ images=images,
)
return
@@ -793,12 +817,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)
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,
)
@@ -839,12 +865,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)
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,
)
@@ -870,7 +898,8 @@ def graph_message_to_activity(msg: dict, channel_id: str, service_url: str) -> d
body = msg.get("body") or {}
content = body.get("content") or ""
- if not content.strip():
+ has_hosted_images = bool(msg.get("hostedContents"))
+ if not content.strip() and not has_hosted_images:
return None
# System/bot/app posts (incl. our own confirmation cards) carry from.application
@@ -935,7 +964,8 @@ def graph_reply_to_activity(
body = msg.get("body") or {}
content = body.get("content") or ""
- if not content.strip():
+ has_hosted_images = bool(msg.get("hostedContents"))
+ if not content.strip() and not has_hosted_images:
logger.debug(
"teams_reply_skipped",
reason="empty_content",
diff --git a/products/conversations/backend/teams_attachments.py b/products/conversations/backend/teams_attachments.py
new file mode 100644
index 000000000000..6e0544cae5c0
--- /dev/null
+++ b/products/conversations/backend/teams_attachments.py
@@ -0,0 +1,259 @@
+"""Download and re-host Microsoft Teams image attachments into UploadedMedia.
+
+Two entry points mirror the two inbound transports:
+- ``extract_teams_bot_attachments`` — bot-framework webhook ``activity.attachments``
+- ``extract_teams_graph_images`` — Graph chatMessage ``hostedContents``
+"""
+
+import re
+from typing import Any
+from urllib.parse import urlparse
+
+import requests
+import structlog
+
+from posthog.models.team.team import Team
+
+from .services.attachments import is_valid_image, save_file_to_uploaded_media
+from .support_teams import is_trusted_teams_service_url
+
+logger = structlog.get_logger(__name__)
+
+TEAMS_MAX_IMAGE_BYTES = 20 * 1024 * 1024 # 20 MiB
+TEAMS_DOWNLOAD_TIMEOUT_SECONDS = 15
+
+GRAPH_API_BASE = "https://graph.microsoft.com/v1.0"
+GRAPH_HOST = "graph.microsoft.com"
+
+_RE_HOSTED_CONTENT_SRC = re.compile(
+ r'<img[^>]+src="(https://graph\.microsoft\.com/[^"]*hostedContents/[^"]*)"',
+ re.IGNORECASE,
+)
+
+
+def _is_graph_url(url: str) -> bool:
+ """Return True iff `url` is HTTPS and hosted on graph.microsoft.com."""
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return False
+ if parsed.scheme != "https" or not parsed.hostname:
+ return False
+ host = parsed.hostname.lower()
+ return host == GRAPH_HOST or host.endswith(f".{GRAPH_HOST}")
+
+
+def _download_image(url: str, token: str) -> bytes | None:
+ """Fetch image bytes from an auth-gated URL. Returns None on any failure.
+
+ Redirects are disabled: the bearer token is privileged and the source URL
+ originates from unsigned payload fields, so we never follow a hop to a host
+ we didn't validate up front (mirrors the Slack downloader's redirect guard).
+ """
+ try:
+ resp = requests.get(
+ url,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=TEAMS_DOWNLOAD_TIMEOUT_SECONDS,
+ stream=True,
+ allow_redirects=False,
+ )
+ except requests.RequestException:
+ logger.warning("teams_image_download_error", url=url[:200])
+ return None
+
+ if resp.is_redirect or resp.is_permanent_redirect:
+ logger.warning("teams_image_download_redirect_blocked", url=url[:200], status=resp.status_code)
+ return None
+
+ if resp.status_code != 200:
+ logger.warning("teams_image_download_non_200", url=url[:200], status=resp.status_code)
+ return None
+
+ content_length = resp.headers.get("Content-Length")
+ if content_length:
+ try:
+ if int(content_length) > TEAMS_MAX_IMAGE_BYTES:
+ logger.warning("teams_image_too_large_header", url=url[:200], content_length=content_length)
+ return None
+ except ValueError:
+ pass
+
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in resp.iter_content(chunk_size=64 * 1024):
+ total += len(chunk)
+ if total > TEAMS_MAX_IMAGE_BYTES:
+ logger.warning("teams_image_too_large_body", url=url[:200], bytes_read=total)
+ return None
+ chunks.append(chunk)
+
+ 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):
+ 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)
+ if not stored_url:
+ return None
+
+ return {"url": stored_url, "name": name, "mimetype": mimetype}
+
+
+def extract_teams_bot_attachments(
+ attachments: list[dict[str, Any]] | None,
+ team: Team,
+ bot_token: str,
+) -> list[dict[str, Any]]:
+ """Extract image attachments from a bot-framework activity and re-host them."""
+ if not attachments:
+ return []
+
+ images: list[dict[str, Any]] = []
+ for att in attachments:
+ content_type = att.get("contentType") or ""
+ if not content_type.startswith("image/"):
+ continue
+
+ content_url = att.get("contentUrl") or ""
+ if not content_url:
+ continue
+
+ # contentUrl is unsigned payload data; only send the bot token to hosts
+ # we trust (Bot Framework / Teams service endpoints).
+ if not is_trusted_teams_service_url(content_url):
+ logger.warning("teams_bot_attachment_untrusted_host", url=content_url[:200])
+ continue
+
+ image_bytes = _download_image(content_url, bot_token)
+ if not image_bytes:
+ continue
+
+ name = att.get("name") or "image"
+ result = _save_image(team, image_bytes, name, content_type)
+ if result:
+ images.append(result)
+
+ return images
+
+
+def extract_teams_graph_images(
+ msg: dict[str, Any],
+ team: Team,
+ teams_team_id: str,
+ channel_id: str,
+ token: str,
+) -> list[dict[str, Any]]:
+ """Extract hostedContents images from a Graph chatMessage and re-host them.
+
+ Graph inline images appear as ``<img src="...hostedContents/{id}/$value">``
+ in ``body.content``. The src URL requires a Graph token to fetch.
+
+ The URL path is validated against the expected teams_team_id, channel_id,
+ and message id to prevent a confused-deputy attack where crafted HTML
+ could make us fetch arbitrary hostedContents the Graph token can read.
+ """
+ body = msg.get("body") or {}
+ html_content = body.get("content") or ""
+
+ src_urls = _RE_HOSTED_CONTENT_SRC.findall(html_content)
+ if not src_urls:
+ return []
+
+ msg_id = msg.get("id") or ""
+
+ hosted_contents = msg.get("hostedContents") or []
+ hosted_map: dict[str, dict[str, Any]] = {}
+ for hc in hosted_contents:
+ hc_id = hc.get("id")
+ if hc_id:
+ hosted_map[hc_id] = hc
+
+ images: list[dict[str, Any]] = []
+ for idx, src_url in enumerate(src_urls):
+ if not _is_graph_url(src_url):
+ logger.warning("teams_graph_image_untrusted_host", url=src_url[:200])
+ continue
+
+ if not _is_expected_hosted_content_path(src_url, teams_team_id, channel_id, msg_id):
+ logger.warning("teams_graph_image_path_mismatch", url=src_url[:200], msg_id=msg_id)
+ continue
+
+ image_bytes = _download_image(src_url, token)
+ if not image_bytes:
+ continue
+
+ name = f"image_{idx + 1}"
+ mimetype = "image/png"
+ hc_id = _extract_hosted_content_id(src_url)
+ if hc_id and hc_id in hosted_map:
+ hc = hosted_map[hc_id]
+ mimetype = hc.get("contentType") or mimetype
+
+ result = _save_image(team, image_bytes, name, mimetype)
+ if result:
+ images.append(result)
+
+ return images
+
+
+_RE_GRAPH_HOSTED_PATH = re.compile(
+ r"^/(?:v1\.0|beta)/teams/(?P<tid>[^/]+)/channels/(?P<cid>[^/]+)"
+ r"/messages/(?P<mid>[^/]+)"
+ r"(?:/replies/(?P<rid>[^/]+))?"
+ r"/hostedcontents/[^/]+/\$value$",
+ re.IGNORECASE,
+)
+
+
+def _is_expected_hosted_content_path(url: str, teams_team_id: str, channel_id: str, msg_id: str) -> bool:
+ """Validate that a hostedContents URL belongs to the expected team/channel/message.
+
+ Parses the path positionally against the exact Graph API structure:
+ /v1.0/teams/{tid}/channels/{cid}/messages/{mid}/hostedContents/{hcid}/$value
+ /v1.0/teams/{tid}/channels/{cid}/messages/{root}/replies/{rid}/hostedContents/{hcid}/$value
+ """
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return False
+
+ m = _RE_GRAPH_HOSTED_PATH.match(parsed.path)
+ if not m:
+ return False
+
+ if m.group("tid").lower() != teams_team_id.lower():
+ return False
+ if m.group("cid").lower() != channel_id.lower():
+ return False
+
+ # For a top-level message, msg_id must match the messages segment.
+ # For a reply, msg_id must match the replies segment.
+ mid_lower = msg_id.lower()
+ rid = m.group("rid")
+ if rid:
+ if rid.lower() != mid_lower:
+ return False
+ else:
+ if m.group("mid").lower() != mid_lower:
+ return False
+
+ return True
+
+
+def _extract_hosted_content_id(url: str) -> str | None:
+ """Pull the hostedContent id from a Graph hostedContents URL."""
+ marker = "hostedcontents/"
+ url_lower = url.lower()
+ idx = url_lower.find(marker)
+ if idx == -1:
+ return None
+ rest = url[idx + len(marker) :]
+ end = rest.find("/")
+ if end == -1:
+ return rest or None
+ return rest[:end] or None