AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend): add the Microsoft Teams bot adapter (#14054)
Bentlyd9efc329d918
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 1ce9d97473..a4f9cac099 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -255,7 +255,7 @@ GOOGLE_MAPS_API_KEY=# Platform Bot LinkingPLATFORM_LINK_BASE_URL=http://localhost:3000/link-# CoPilot chat-platform bridge (Discord/Telegram/Slack)+# CoPilot chat-platform bridge (Discord/Telegram/Slack/Teams)# Uses FRONTEND_BASE_URL (above) for link confirmation pages.AUTOPILOT_BOT_DISCORD_TOKEN=# Slack adapter — set the signing secret + client id/secret to mount the Slack@@ -273,6 +273,18 @@ AUTOPILOT_BOT_SLACK_TOKEN=AUTOPILOT_BOT_TELEGRAM_TOKEN=AUTOPILOT_BOT_TELEGRAM_USERNAME=AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET=+# Teams adapter — set all three (Azure Bot app id, client secret, tenant id) to+# mount the Teams webhook route, and point the bot's messaging endpoint at+# <PLATFORM_BASE_URL>/api/copilot-webhooks/teams/messages. Tenant id is+# mandatory: new registrations are single-tenant only since 2025-07-31. In+# channels the bot only sees messages that @mention it — commands included,+# e.g. "@AutoGPT /setup".+MICROSOFT_CLIENT_ID=+MICROSOFT_CLIENT_SECRET=+MICROSOFT_TENANT_ID=+# Local only: accept unsigned activities so the M365 Agents Playground (which+# sends no JWT) works without a tenant or tunnel. Also requires APP_ENV=local.+AUTOPILOT_BOT_TEAMS_ALLOW_UNVERIFIED=false# Communication ServicesDISCORD_BOT_TOKEN=diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry.pyindex c76bba0a60..d38d648b62 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry.py@@ -11,6 +11,7 @@ from pydantic import BaseModel, ConfigDictfrom backend.copilot.bot.adapters.discord import config as discord_configfrom backend.copilot.bot.adapters.slack import config as slack_config+from backend.copilot.bot.adapters.teams import config as teams_configfrom backend.copilot.bot.adapters.telegram import config as telegram_configfrom backend.util.settings import Settings@@ -26,6 +27,7 @@ _SERVER_NOUNS = {"DISCORD": "server","SLACK": "workspace","TELEGRAM": "group",+ "TEAMS": "team",}_DEFAULT_SERVER_NOUN = "server"@@ -49,7 +51,12 @@ def enabled_platforms() -> list[PlatformMeta]:Platforms whose adapter isn't configured (missing credentials) areomitted entirely so the Bots page hides them."""- all_platforms = [_discord_meta(), _slack_meta(), _telegram_meta()]+ all_platforms = [+ _discord_meta(),+ _slack_meta(),+ _telegram_meta(),+ _teams_meta(),+ ]return [platform for platform in all_platforms if platform.enabled]@@ -117,6 +124,20 @@ def _telegram_meta() -> PlatformMeta:)+def _teams_meta() -> PlatformMeta:+ # Enabled on the same gate the webhook adapter mounts on. Teams has no+ # invite URL to build: installing means sideloading the app package (see+ # adapters/teams/manifest.json) or publishing it to the org's app catalog.+ return PlatformMeta(+ platform="TEAMS",+ display_name="Microsoft Teams",+ icon="teams.png",+ server_noun=_SERVER_NOUNS["TEAMS"],+ enabled=teams_config.is_configured(),+ add_bot_url=None,+ )++def _slack_install_url() -> str | None:base = Settings().config.platform_base_url.rstrip("/")if not base:diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.pyindex b815f1701c..92146757ce 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py@@ -2,11 +2,28 @@from unittest.mock import patch-from backend.api.features.platform_linking.registry import enabled_platforms+import pytest++from backend.api.features.platform_linking.registry import (+ enabled_platforms,+ server_noun_for,+)_REG = "backend.api.features.platform_linking.registry"[email protected](autouse=True)+def _teams_off():+ """Hide Teams unless a test opts in.++ Teams is the one platform whose gate isn't purely credential-based: the+ local Playground bypass enables it, so a developer running with+ APP_ENV=local would otherwise see it leak into every assertion here.+ """+ with patch(f"{_REG}.teams_config.is_configured", return_value=False):+ yield++def _slack_off():# Slack disabled unless a test opts in — enabled always requires the signing# secret, so clearing it hides Slack regardless of whatever token / OAuth@@ -175,3 +192,30 @@ def test_telegram_hidden_without_webhook_secret():patch(f"{_REG}.telegram_config.get_webhook_secret", return_value=""),):assert enabled_platforms() == []+++def test_teams_appears_without_add_bot_url_when_configured():+ # Teams is installed by sideloading an app package, so there is no invite+ # URL to build — the card renders without a button.+ with (+ _discord_off(),+ _slack_off(),+ _telegram_off(),+ patch(f"{_REG}.teams_config.is_configured", return_value=True),+ ):+ platforms = enabled_platforms()++ assert [p.platform for p in platforms] == ["TEAMS"]+ teams = platforms[0]+ assert teams.display_name == "Microsoft Teams"+ assert teams.icon == "teams.png"+ assert teams.add_bot_url is None+ # Teams calls a server a team, and the bot's own copy already says so+ # (adapters/teams/commands.py) — the API surface has to agree.+ assert teams.server_noun == "team"+ assert server_noun_for("TEAMS") == "team"+++def test_teams_hidden_when_not_configured():+ with _discord_off(), _slack_off(), _telegram_off():+ assert enabled_platforms() == []diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.mdindex dd4ab1c330..1a3ec60a1f 100644--- a/autogpt_platform/backend/backend/copilot/bot/README.md+++ b/autogpt_platform/backend/backend/copilot/bot/README.md@@ -1,6 +1,7 @@# CoPilot Bot-Multi-platform chat bot that bridges AutoGPT to Discord, Slack, and Telegram (Teams/WhatsApp next).+Multi-platform chat bot that bridges AutoGPT to Discord, Slack, Telegram, and+Microsoft Teams (WhatsApp next).## Running@@ -39,6 +40,7 @@ See `backend/.env.default` for the full list with documentation. Minimum setup:| `AUTOPILOT_BOT_DISCORD_TOKEN` | Discord bot token — enables the Discord (socket) adapter || `AUTOPILOT_BOT_SLACK_TOKEN` + `AUTOPILOT_BOT_SLACK_SIGNING_SECRET` | Slack bot token + signing secret — set **both** to mount the Slack (webhook / Events API) adapter on the main backend API || `AUTOPILOT_BOT_TELEGRAM_TOKEN` + `AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET` | Telegram BotFather token + webhook secret — set **both** to mount the Telegram (webhook / Bot API) adapter, then register the webhook once with `setWebhook` (see `.env.default`). Also disable group privacy mode via BotFather `/setprivacy` or the bot can't see @mentions in groups |+| `MICROSOFT_CLIENT_ID` + `MICROSOFT_CLIENT_SECRET` + `MICROSOFT_TENANT_ID` | Azure Bot registration — set **all three** to mount the Teams (webhook / Bot Connector) adapter, and point the bot's messaging endpoint at `/api/copilot-webhooks/teams/messages`. The tenant id is mandatory: new registrations are single-tenant only since 2025-07-31 || `FRONTEND_BASE_URL` | Frontend base URL for link confirmation pages (shared with the rest of the backend) || `REDIS_HOST` / `REDIS_PORT` | Session + thread subscription state + copilot stream subscription (inherited from the shared backend config) || `PLATFORMLINKINGMANAGER_HOST` | DNS name of the `PlatformLinkingManager` service pod (cluster-internal RPC) |@@ -72,14 +74,85 @@ bot/│ ├── signing.py # HMAC-SHA256 request signature verification│ ├── text.py # CommonMark → Slack mrkdwn│ └── app-manifest.yaml # Importable Slack app definition (scopes, events, commands)- └── telegram/ # WebhookAdapter — Telegram Bot API- ├── adapter.py # Inbound updates route, sends, chat-model mapping- ├── api_client.py # Thin httpx Bot API client (JSON + multipart + getFile)+ ├── telegram/ # WebhookAdapter — Telegram Bot API+ │ ├── adapter.py # Inbound updates route, sends, chat-model mapping+ │ ├── api_client.py # Thin httpx Bot API client (JSON + multipart + getFile)+ │ ├── commands.py # Bot commands (/setup, /help, /unlink)+ │ ├── config.py # BotFather token + webhook secret + platform limits+ │ └── text.py # CommonMark → Telegram HTML+ └── teams/ # WebhookAdapter — Bot Framework Connector+ ├── adapter.py # Inbound activities route, sends, conversation mapping+ ├── api_client.py # Bot Connector REST client (per-activity serviceUrl)+ ├── auth.py # Inbound JWT validation + outbound token minting├── commands.py # Bot commands (/setup, /help, /unlink)- ├── config.py # BotFather token + webhook secret + platform limits- └── text.py # CommonMark → Telegram HTML+ ├── config.py # App id + password + tenant id + platform limits+ └── text.py # CommonMark → Teams-flavoured markdown```+### Microsoft Teams notes++Teams differs from the other platforms in ways worth knowing before debugging:++- **Auth is a signed JWT, not an HMAC of the body.** The Connector's token+ authenticates the *sender*, not the payload, so a valid token could be+ replayed with any body. The `serviceUrl` claim binding in `auth.py` is what+ closes that — note the wire claim is lowercase `serviceurl`.+- **Replies go to the activity's `serviceUrl`**, not a fixed base URL, because+ Microsoft routes each tenant/region to its own Connector host. That makes it+ attacker-influenced input we attach a bearer token to, hence the host+ allowlist.+- **Single-tenant only.** Microsoft stopped issuing multi-tenant registrations+ after 2025-07-31, so `MICROSOFT_TENANT_ID` is mandatory.+- **No native slash commands.** In a channel the bot only receives messages+ that @mention it — commands included, e.g. `@AutoGPT /setup`. A bare+ `/setup` in a channel never reaches us.+- **Group chats are not supported.** A `groupChat` carries no team identity to+ bill against, so those activities are accepted and ignored (with a log line+ saying so). Only `personal` chats and `channel` messages are handled.+- **Delivery is at-most-once.** The route ACKs 200 and dispatches in a+ background task, and the activity id is claimed in Redis before processing.+ A dispatch failure or a replica recycle mid-turn therefore loses that turn,+ and the Connector's own redelivery is deduped away by the claim. This trades+ the Connector's retry for never double-answering a user; releasing the claim+ on failure is the change to make if the balance should tip the other way.+- **The learned `serviceUrl` map is per process.** The adapter rides the+ N-replica API, so another replica handling the same conversation falls back+ to the default public-cloud host. Fine while replies are reactive (the host+ comes off the inbound activity) and DMs use the default; a proactive channel+ send from a cold replica would 404 for a tenant Microsoft routes elsewhere,+ so persist the mapping in Redis before enabling that.+- **Mention matching is prefix-insensitive.** Teams spells a participant id+ `28:<app-id>` in some places and bare in others; `_bot_identities` accepts+ either, and also matches the activity's own `recipient.id`.++#### Local testing without a tenant++The [M365 Agents Playground](https://learn.microsoft.com/microsoftteams/platform/)+simulates Teams on `localhost:56150` with no tenant, tunnel, or app+registration — useful because sideloading a real app needs an M365 licence.+It sends **no** Bot Framework JWT, so set `APP_ENV=local` and+`AUTOPILOT_BOT_TEAMS_ALLOW_UNVERIFIED=true` to accept unsigned activities.+Both gates are required; neither works on a deployed environment.++When the backend runs in Docker, the Playground's loopback `serviceUrl` is+rewritten to `host.docker.internal` so replies can reach it on the host+(`auth.rewrite_loopback_for_container`) — also local-mode only.++#### App package++`adapters/teams/` holds the sideloadable app package: `manifest.json` plus+`color.png` (192×192) and `outline.png` (32×32, transparent, monochrome).+Replace both `<AZURE_BOT_APP_ID>` placeholders with the Azure Bot's app id,+then zip the three files **flat** (no containing folder):++```bash+cd backend/copilot/bot/adapters/teams+zip ../../../../../AutoGPT-teams.zip manifest.json color.png outline.png+```++Upload via Teams → Apps → Manage your apps → Upload an app. Sideloading needs+an M365 licence and the tenant's app-upload policy enabled.+**Connector taxonomy.** `PlatformAdapter` is the outbound contract the corehandler speaks through. Concrete adapters extend one of two subtypes by howinbound events arrive:diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/__init__.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.pynew file mode 100644index 0000000000..b5757c44b1--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py@@ -0,0 +1,780 @@+"""Microsoft Teams adapter — webhook-based, via the Azure Bot Connector.++Teams never talks to us directly: every inbound message arrives as a Bot+Connector "activity" POSTed to one endpoint, and every reply is a POST back to+the ``serviceUrl`` that activity carried. Authentication is therefore a bearer+JWT rather than a body HMAC (see ``auth.py``), which is why this adapter+verifies inbound requests itself instead of using the shared+``read_verified_webhook_body`` helper — that helper's verifier is synchronous+and Teams key validation needs async I/O. The ordering guarantee it exists to+provide (verify before parse) is preserved here explicitly.++Chat model mapping: a ``personal`` conversation is a DM (auto-converse); a+``channel`` conversation engages only when the bot is @mentioned, and replies+land in a Teams reply-chain rooted at that message. Group chats are not+handled in v1 — Teams gives them no team identity, which the core handler+requires for any non-DM turn.+"""++import asyncio+import base64+import json+import logging+from collections import OrderedDict+from collections.abc import Awaitable, Callable+from typing import Any, Optional++import httpx+from fastapi import FastAPI, Request, Response+from fastapi.responses import JSONResponse, PlainTextResponse++from backend.copilot.bot.adapters.base import (+ ChannelInfo,+ ChannelType,+ FileAttachment,+ MessageCallback,+ MessageContext,+ PostedRef,+ WebhookAdapter,+)+from backend.copilot.bot.adapters.shared import InboundFile, collect_attachments+from backend.copilot.bot.bot_backend import BotBackend+from backend.copilot.bot.config import MAX_INBOUND_ATTACHMENTS+from backend.copilot.bot.text import iter_chunks, resolve_mentions+from backend.data.redis_client import get_redis_async++from . import auth, commands, config+from .api_client import TeamsApiError, TeamsClient+from .text import mention_entities, mention_token, to_teams_markdown++logger = logging.getLogger(__name__)++MESSAGES_PATH = "/api/copilot-webhooks/teams/messages"++# Conversations we keep a learned serviceUrl for. Evicting one is cheap:+# the next reply falls back to the default host until it is relearned.+_MAX_REMEMBERED_SERVICE_URLS = 10_000++# Inbound rejections answer with fixed text: everything specific about why is+# logged instead, so an unauthenticated caller learns nothing from probing.+_REJECTED = "rejected"+_MALFORMED = "invalid activity payload"++# Teams routes every tenant in the public cloud through this host. Real traffic+# always carries its own ``serviceUrl``; this is only the seed for proactive+# sends that have no inbound activity to learn it from.+DEFAULT_SERVICE_URL = "https://smba.trafficmanager.net/teams/"++# Conversation ids are Teams' own opaque identifiers: channels/group threads are+# ``19:…@thread.tacv2`` (optionally with a ``;messageid=`` reply-chain suffix),+# 1:1 chats are ``a:…``. Channel *names* never take these shapes, which is what+# ``looks_like_channel_id`` relies on.+_CONVERSATION_ID_PREFIXES = ("19:", "a:")++# Attachment content types Teams uses for user-uploaded files.+_FILE_DOWNLOAD_CONTENT_TYPE = "application/vnd.microsoft.teams.file.download.info"+++class TeamsAdapter(WebhookAdapter):+ def __init__(self, api: BotBackend):+ self._api = api+ self._client = TeamsClient()+ self._validator = auth.ConnectorTokenValidator()+ self._on_message_callback: Optional[MessageCallback] = None+ # serviceUrl is per-tenant and can change, so it is deliberately NOT+ # baked into the conversation token the core handler round-trips (that+ # token is also a Redis key suffix — folding a mutable value into it+ # would silently orphan live sessions). Learned from inbound traffic+ # instead, with the public-cloud host as the fallback. Bounded: a+ # long-lived process would otherwise hold one entry per conversation+ # forever, and evicting only costs the default host on the next reply.+ self._service_urls: OrderedDict[str, str] = OrderedDict()+ # Strong-ref set so the GC doesn't drop fire-and-forget activity tasks.+ self._activity_tasks: set[asyncio.Task[None]] = set()++ @property+ def platform_name(self) -> str:+ return "teams"++ @property+ def max_message_length(self) -> int:+ return config.MAX_MESSAGE_LENGTH++ @property+ def chunk_flush_at(self) -> int:+ return config.CHUNK_FLUSH_AT++ @property+ def max_attachment_bytes(self) -> int:+ # Outbound cap: only a data-URI inline fits in one activity, so this+ # is the inline ceiling — larger artifacts take the link fallback.+ return config.INLINE_IMAGE_BYTES++ @property+ def max_thread_name_length(self) -> int:+ return config.MAX_THREAD_NAME_LENGTH++ @property+ def typing_refresh_interval(self) -> float:+ return config.TYPING_REFRESH_SECONDS++ def looks_like_channel_id(self, ref: str) -> bool:+ return ref.startswith(_CONVERSATION_ID_PREFIXES)++ def localize_markup(self, text: str) -> str:+ return to_teams_markdown(text)++ def on_message(self, callback: MessageCallback) -> None:+ self._on_message_callback = callback++ def register_routes(self, app: FastAPI) -> None:+ app.add_api_route(+ MESSAGES_PATH, self._handle_messages_request, methods=["POST"]+ )++ # -- Inbound --++ async def _handle_messages_request(self, request: Request) -> Response:+ """Authenticate, then ACK immediately and process off-request.++ The Connector retries deliveries it considers slow, so the real work+ must never happen inside the request; redeliveries that arrive anyway+ are dropped by the activity-id dedupe in ``_dispatch_activity``.+ """+ raw = await request.body()+ claims: dict[str, Any] = {}+ unverified = config.allow_unverified_requests()+ if unverified:+ logger.warning(+ "Accepting an unauthenticated Teams activity — Agents "+ "Playground mode (local dev only)"+ )+ else:+ try:+ claims = await self._validator.validate(+ request.headers.get("Authorization")+ )+ except auth.TeamsAuthError as e:+ # The reason stays in the log. The caller is unauthenticated+ # here, and the validator's message can carry text from the JWT+ # parser — the status code is all a legitimate sender needs.+ logger.warning(f"Rejected Teams activity: {e}")+ return PlainTextResponse(_REJECTED, status_code=e.status_code)++ try:+ activity = _parse_activity(raw)+ except ValueError:+ logger.warning("Rejected malformed Teams activity", exc_info=True)+ return PlainTextResponse(_MALFORMED, status_code=400)++ # The token authenticates the sender but does NOT sign the body, so it+ # must be bound to this payload before the serviceUrl inside it is+ # trusted as a reply destination.+ if not unverified:+ try:+ auth.verify_service_url(claims, activity.get("serviceUrl", ""))+ except auth.TeamsAuthError as e:+ logger.warning(f"Rejected Teams activity: {e}")+ return PlainTextResponse(_REJECTED, status_code=e.status_code)++ self._remember_service_url(activity)+ task = asyncio.create_task(self._dispatch_activity(activity))+ self._activity_tasks.add(task)+ task.add_done_callback(self._on_activity_task_done)+ return JSONResponse({}, status_code=200)++ async def _dispatch_activity(self, activity: dict[str, Any]) -> None:+ if await self._is_duplicate_activity(activity):+ return+ activity_type = activity.get("type")+ if activity_type in ("installationUpdate", "conversationUpdate"):+ self._track_team_membership(activity)+ return+ if activity_type != "message":+ return # reactions, invokes — not conversation input.+ # Configured id only — on an activity we sent, ``recipient`` is the+ # other party and must not count as "us".+ if _is_own_id((activity.get("from") or {}).get("id"), _configured_bot_ids()):+ return # Our own echo.++ command = commands.parse_command(_activity_text(activity))+ if command is not None:+ try:+ await commands.handle(self._api, self, activity, command)+ except Exception:+ logger.exception("Teams command handler failed")+ return++ if self._on_message_callback is None:+ return+ ctx = await self._build_context(activity)+ if ctx is None:+ return+ try:+ await self._on_message_callback(ctx, self)+ except Exception:+ logger.exception("Teams activity handler failed")++ async def _is_duplicate_activity(self, activity: dict[str, Any]) -> bool:+ """Drop redeliveries — first delivery of an activity id wins.++ The Connector retries deliveries it considers slow, and the inbound+ token does not sign the body, so a captured request can also be+ replayed wholesale for the token's lifetime. Both arrive as an+ already-seen activity id. Fails open: losing Redis briefly must not+ take the bot down with it.+ """+ activity_id = activity.get("id")+ if not activity_id:+ return False+ conversation_id = (activity.get("conversation") or {}).get("id") or ""+ key = f"copilot:bot:teams:activity:{conversation_id}:{activity_id}"+ try:+ redis = await get_redis_async()+ claimed = await redis.set(+ key, "1", nx=True, ex=config.ACTIVITY_DEDUPE_TTL_SECONDS+ )+ except Exception:+ logger.warning("Teams activity dedupe unavailable; processing anyway")+ return False+ if claimed:+ return False+ logger.info(f"Ignoring duplicate Teams activity {activity_id!r}")+ return True++ def _track_team_membership(self, activity: dict[str, Any]) -> None:+ """Keep the server roster in step with installs and removals.++ Without this the roster has no row for the team, so the admin+ analytics fall back to showing its raw id instead of its name.+ """+ team = (activity.get("channelData") or {}).get("team") or {}+ team_id = team.get("id")+ if not team_id:+ return # Personal install — no team to put on the roster.+ own = _bot_identities(activity)+ action = (activity.get("action") or "").lower()+ if action.startswith("remove") or _lists_bot(+ activity.get("membersRemoved"), own+ ):+ self._api.track_guild_left(self.platform_name, team_id)+ elif action.startswith("add") or _lists_bot(activity.get("membersAdded"), own):+ self._api.track_guild_joined(self.platform_name, team_id, team.get("name"))++ @property+ def client(self) -> TeamsClient:+ """The Connector client, for handlers that need their own reads."""+ return self._client++ def _on_activity_task_done(self, task: "asyncio.Task[None]") -> None:+ """Dispatch runs after the 200 ACK, so a failure has nowhere to surface.++ Without retrieving the exception here it is only ever reported as an+ unretrieved-task warning at collection time, detached from the activity+ that caused it.+ """+ self._activity_tasks.discard(task)+ if task.cancelled():+ return+ error = task.exception()+ if error is not None:+ logger.error("Teams activity dispatch failed", exc_info=error)++ def _remember_service_url(self, activity: dict[str, Any]) -> None:+ conversation_id = (activity.get("conversation") or {}).get("id")+ service_url = activity.get("serviceUrl")+ if conversation_id and service_url:+ # Cache the dialable form; the token binding was checked above+ # against the URL as it arrived. Also key by the channel base id,+ # so ids minted by ``create_thread`` (base + ";messageid=") and+ # sibling reply chains resolve to the learned regional host rather+ # than the geo-routed default.+ url = auth.rewrite_loopback_for_container(service_url)+ self._remember(conversation_id, url)+ base = _base_conversation_id(conversation_id)+ if base != conversation_id:+ self._remember(base, url)++ def _remember(self, conversation_id: str, url: str) -> None:+ self._service_urls[conversation_id] = url+ self._service_urls.move_to_end(conversation_id)+ while len(self._service_urls) > _MAX_REMEMBERED_SERVICE_URLS:+ self._service_urls.popitem(last=False)++ def _service_url_for(self, conversation_id: str) -> str:+ url = self._service_urls.get(conversation_id)+ if url:+ return url+ base = _base_conversation_id(conversation_id)+ return self._service_urls.get(base, DEFAULT_SERVICE_URL)++ # -- Outbound --++ async def send_message(+ self,+ channel_id: str,+ text: str,+ mentionable_users: tuple[tuple[str, str], ...] = (),+ ) -> None:+ await self._send_chunked(channel_id, text, mentionable_users)++ async def send_reply(+ self,+ channel_id: str,+ text: str,+ reply_to_message_id: str,+ mentionable_users: tuple[tuple[str, str], ...] = (),+ ) -> None:+ # Teams reply-chains are addressed by conversation id, not per-activity,+ # so a reply into an existing chain is an ordinary send.+ await self._send_chunked(channel_id, text, mentionable_users)++ async def send_ephemeral(self, channel_id: str, user_id: str, text: str) -> None:+ # Teams has no ephemeral message; deliver normally (Discord/Telegram+ # precedent) rather than silently dropping it.+ await self._send_chunked(channel_id, text, ())++ async def send_link(+ self, channel_id: str, text: str, link_label: str, link_url: str+ ) -> None:+ activity = {+ "type": "message",+ "text": self.localize_markup(text),+ "textFormat": "markdown",+ "attachments": [_link_card(link_label, link_url)],+ }+ await self._post(channel_id, activity)++ async def send_file(self, channel_id: str, text: str, file: FileAttachment) -> None:+ """Inline a small image; degrade anything else to a note.++ Teams' bot file API is a three-legged consent handshake (card -> user+ click -> upload session) that cannot complete inside a single awaited+ send, and it does not exist at all in channels. Data-URI inlining is+ the only single-shot delivery, and the whole activity is capped at+ ~28KB — ``max_attachment_bytes`` advertises that cap so callers route+ larger files to their link fallback instead of through here.+ """+ if (+ file.mime_type.startswith("image/")+ and len(file.content) <= config.INLINE_IMAGE_BYTES+ ):+ activity = {+ "type": "message",+ "text": self.localize_markup(text) if text else "",+ "textFormat": "markdown",+ "attachments": [+ {+ "contentType": file.mime_type,+ "contentUrl": _data_uri(file),+ "name": file.filename,+ }+ ],+ }+ try:+ await self._post(channel_id, activity)+ return+ except TeamsApiError:+ logger.warning(f"Teams rejected inline image {file.filename!r}")+ note = f"{text}\n\n_{file.filename} can't be attached in Teams._".strip()+ await self._send_chunked(channel_id, note, ())++ async def start_typing(self, channel_id: str) -> None:+ try:+ await self._post(channel_id, {"type": "typing"})+ except (TeamsApiError, httpx.HTTPError):+ # Runs in a keep-alive loop; never let it break the turn.+ logger.debug("Teams typing indicator failed", exc_info=True)++ async def create_thread(+ self, channel_id: str, message_id: str, name: str+ ) -> Optional[str]:+ """Root a reply-chain at ``message_id``.++ Teams threads are unnamed, so ``name`` is unused. Only a channel+ conversation can carry a chain, and one that already has a+ ``;messageid=`` suffix IS a chain — re-wrapping it would address a+ conversation that does not exist.+ """+ if not channel_id.startswith("19:") or ";messageid=" in channel_id:+ return None+ return f"{channel_id};messageid={message_id}"++ # -- Proactive output --++ async def list_text_channels(+ self, server_ids: tuple[str, ...]+ ) -> list[ChannelInfo]:+ # Enumerating channels needs a Graph permission the bot does not hold;+ # proactive posts target a conversation id directly.+ return []++ async def get_channel_server_id(self, channel_id: str) -> Optional[str]:+ # Without channel enumeration there is no channel -> team mapping to+ # authorize against, so raw-id posting stays unauthorized by design.+ return None++ async def post_channel_message(+ self, channel_id: str, text: str+ ) -> Optional[PostedRef]:+ first_id = await self._send_chunked(channel_id, text, ())+ return PostedRef(id=first_id) if first_id else None++ async def create_channel_thread(+ self, channel_id: str, name: str, text: str+ ) -> Optional[PostedRef]:+ # Teams threads carry no title; surface it as a heading instead, the+ # same degradation Telegram uses for its unnamed topics.+ body = f"**{name}**\n\n{text}" if name else text+ return await self.post_channel_message(channel_id, body)++ async def open_dm_channel(self, platform_user_id: str) -> Optional[str]:+ """Create (or fetch) the bot's 1:1 conversation with a user.++ Teams returns the existing conversation for a repeat call, so this is+ effectively idempotent. Only reachable for users who have the app+ installed personally.+ """+ payload = {+ # Participant form: Teams spells bot ids "28:<app-id>" on the wire.+ "bot": {"id": f"28:{config.get_app_id()}"},+ "members": [{"id": platform_user_id}],+ "channelData": {"tenant": {"id": config.get_tenant_id()}},+ "isGroup": False,+ }+ try:+ return await self._client.create_conversation(DEFAULT_SERVICE_URL, payload)+ except TeamsApiError:+ logger.warning(f"Cannot open Teams DM with user {platform_user_id}")+ return None++ # -- Send plumbing --++ async def _send_chunked(+ self,+ channel_id: str,+ text: str,+ mentionable_users: tuple[tuple[str, str], ...],+ ) -> Optional[str]:+ """Post ``text`` in message-sized chunks; return the first activity id.++ Chunks are awaited in sequence: Teams does not guarantee ordering for+ messages posted in quick succession.+ """+ first_id: Optional[str] = None+ for chunk in iter_chunks(self.localize_markup(text), config.CHUNK_FLUSH_AT):+ rendered, pinged = resolve_mentions(chunk, mentionable_users, mention_token)+ activity: dict[str, Any] = {+ "type": "message",+ "text": rendered,+ "textFormat": "markdown",+ }+ entities = mention_entities(pinged, mentionable_users)+ if entities:+ activity["entities"] = entities+ activity_id = await self._post(channel_id, activity)+ first_id = first_id or activity_id+ return first_id++ async def _post(self, channel_id: str, activity: dict[str, Any]) -> Optional[str]:+ return await self._client.send_activity(+ self._service_url_for(channel_id), channel_id, activity+ )++ async def _build_context(+ self, activity: dict[str, Any]+ ) -> Optional[MessageContext]:+ """Map a Teams message activity onto the platform-neutral context."""+ conversation = activity.get("conversation") or {}+ conversation_id = conversation.get("id")+ sender = activity.get("from") or {}+ if not conversation_id or not sender.get("id"):+ return None++ conversation_type = conversation.get("conversationType")+ if conversation_type == "personal":+ channel_type: ChannelType = "dm"+ server_id = None+ elif conversation_type == "channel":+ channel_type = _classify_channel_message(+ conversation_id, activity.get("id")+ )+ server_id = ((activity.get("channelData") or {}).get("team") or {}).get(+ "id"+ )+ if not server_id:+ logger.info(+ f"Ignoring Teams channel activity in {conversation_id!r}: "+ f"no team id in channelData"+ )+ return None+ else:+ # groupChat has no team identity for the core handler to bill+ # against, and a non-DM turn without one is dropped downstream.+ logger.info(+ f"Ignoring Teams {conversation_type!r} activity in "+ f"{conversation_id!r}: only personal chats and channels are "+ f"supported"+ )+ return None++ attachments, skipped = await collect_attachments(+ _inbound_files(activity, self._client),+ max_count=MAX_INBOUND_ATTACHMENTS,+ max_bytes=config.MAX_ATTACHMENT_BYTES,+ )++ return MessageContext(+ platform="teams",+ channel_type=channel_type,+ server_id=server_id,+ channel_id=conversation_id,+ message_id=activity.get("id", ""),+ user_id=sender["id"],+ username=sender.get("name") or "",+ text=_activity_text(activity),+ bot_mentioned=_mentions_bot(activity),+ attachments=attachments,+ skipped_attachments=skipped,+ mentionable_users=_mentionable_users(activity),+ )+++def _base_conversation_id(conversation_id: str) -> str:+ """``19:[email protected];messageid=17`` -> ``19:[email protected]``."""+ return conversation_id.split(";messageid=")[0]+++def _classify_channel_message(+ conversation_id: str, activity_id: str | None+) -> ChannelType:+ """Top-level channel post vs reply inside an existing chain.++ Real Teams suffixes every channel conversation id with the chain root's+ ``;messageid=`` — including a brand-new top-level post, whose root is the+ post itself. Suffix-presence alone would classify all production traffic+ as thread replies, so the root is compared to the activity's own id.+ Simulators (the Agents Playground) omit the suffix entirely.+ """+ _, sep, root = conversation_id.partition(";messageid=")+ if not sep:+ return "channel"+ return "channel" if root == (activity_id or "") else "thread"+++def _activity_text(activity: dict[str, Any]) -> str:+ """The message text with the bot's own @mention removed."""+ text = activity.get("text") or ""+ own = _bot_identities(activity)+ for entity in activity.get("entities") or []:+ if entity.get("type") != "mention":+ continue+ if not _is_own_id((entity.get("mentioned") or {}).get("id"), own):+ continue+ text = text.replace(entity.get("text") or "", "")+ return text.strip()+++def _mentions_bot(activity: dict[str, Any]) -> bool:+ own = _bot_identities(activity)+ return any(+ entity.get("type") == "mention"+ and _is_own_id((entity.get("mentioned") or {}).get("id"), own)+ for entity in activity.get("entities") or []+ )+++def _mentionable_users(+ activity: dict[str, Any],+) -> tuple[tuple[str, str], ...]:+ """Users the bot may ping back — those @mentioned in this message.++ Teams offers no cheap roster read, so the allowlist is exactly who the+ author already addressed, which is the conservative reading of the shared+ mention-safety contract.+ """+ users: list[tuple[str, str]] = []+ own = _bot_identities(activity)+ for entity in activity.get("entities") or []:+ if entity.get("type") != "mention":+ continue+ mentioned = entity.get("mentioned") or {}+ user_id, name = mentioned.get("id"), mentioned.get("name")+ if user_id and name and not _is_own_id(user_id, own):+ users.append((name, user_id))+ return tuple(users)+++def _inbound_files(activity: dict[str, Any], client: TeamsClient) -> list[InboundFile]:+ """Teams file attachments, normalized for ``collect_attachments``.++ Two shapes arrive: file *uploads* (personal chats only) carry a pre-signed+ ``downloadUrl``; *pasted* images carry an ``image/*`` contentType and a+ ``contentUrl`` that needs the bot's own Connector bearer to fetch. The+ full list is passed through — ``collect_attachments`` owns the count cap+ and its user-facing skip notes.+ """+ files: list[InboundFile] = []+ for attachment in activity.get("attachments") or []:+ content_type = attachment.get("contentType") or ""+ if content_type == _FILE_DOWNLOAD_CONTENT_TYPE:+ content = attachment.get("content") or {}+ download_url = content.get("downloadUrl")+ if not download_url:+ continue+ if not auth.is_fetchable_attachment_url(download_url):+ # Unsigned body: without this the URL is a server-side request+ # generator aimed at whatever the sender names.+ logger.warning("Skipping Teams attachment with an unfetchable URL")+ continue+ files.append(+ InboundFile(+ filename=attachment.get("name"),+ # Advisory only — the fetch below is what actually+ # bounds the download.+ size=_declared_size(content.get("fileSize")),+ mime_type=content.get("fileType"),+ fetch=_bounded_fetch(download_url),+ )+ )+ elif content_type.startswith("image/"):+ content_url = attachment.get("contentUrl")+ if not content_url:+ continue+ # This fetch carries the bot's Connector bearer, so it answers to+ # the same allowlist as every other token-bearing call rather than+ # the looser attachment check — the body naming it is unsigned.+ if not auth.is_allowed_service_url(content_url):+ logger.warning(+ "Refusing to send the Connector bearer to a non-Connector "+ "attachment host"+ )+ continue+ files.append(+ InboundFile(+ filename=attachment.get("name") or "pasted-image",+ size=0,+ mime_type=content_type,+ fetch=_bounded_fetch(content_url, headers=client.bearer_headers),+ )+ )+ return files+++def _declared_size(value: Any) -> int:+ """The sender's claimed size, which the unsigned body may spell anything.++ Only advisory: :func:`_bounded_fetch` enforces the real cap. Raising here+ would abort the turn, and the dedupe claim stops a redelivery recovering it.+ """+ try:+ return max(0, int(value or 0))+ except (TypeError, ValueError):+ return 0+++def _bounded_fetch(+ download_url: str,+ headers: Callable[[], Awaitable[dict[str, str]]] | None = None,+) -> Callable[[], Awaitable[bytes]]:+ """Download at most ``MAX_ATTACHMENT_BYTES``.++ The shared size gate cannot protect us here — Teams declares no size on a+ file attachment — so the bound is enforced while streaming instead.+ ``headers`` supplies auth for URLs that need the bot's bearer (pasted+ images); pre-signed upload URLs must be fetched bare.+ """++ async def fetch() -> bytes:+ # Checked here rather than at parse time: this is as close to the+ # connect as we can get without a custom transport, and the name may+ # not have resolved the same way when the activity arrived.+ await auth.ensure_attachment_host_is_external(download_url)+ request_headers = await headers() if headers else {}+ # follow_redirects stays off (httpx's default, pinned here because it+ # is load-bearing): a redirect would land us at an unchecked host.+ async with (+ httpx.AsyncClient(timeout=60.0, follow_redirects=False) as client,+ client.stream("GET", download_url, headers=request_headers) as response,+ ):+ response.raise_for_status()+ chunks: list[bytes] = []+ total = 0+ async for chunk in response.aiter_bytes():+ total += len(chunk)+ if total > config.MAX_ATTACHMENT_BYTES:+ raise ValueError("attachment exceeds the size limit")+ chunks.append(chunk)+ return b"".join(chunks)++ return fetch+++def _link_card(link_label: str, link_url: str) -> dict[str, Any]:+ """A minimal Adaptive Card carrying one link button.++ Pinned to schema 1.2 — the highest version every Teams client, including+ mobile, renders reliably.+ """+ return {+ "contentType": "application/vnd.microsoft.card.adaptive",+ "content": {+ "type": "AdaptiveCard",+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",+ "version": "1.2",+ "body": [],+ "actions": [+ {"type": "Action.OpenUrl", "title": link_label[:60], "url": link_url}+ ],+ },+ }+++def _data_uri(file: FileAttachment) -> str:+ encoded = base64.b64encode(file.content).decode("ascii")+ return f"data:{file.mime_type};base64,{encoded}"+++def _parse_activity(raw: bytes) -> dict[str, Any]:+ try:+ activity = json.loads(raw)+ except ValueError:+ raise ValueError("activity body is not valid JSON")+ if not isinstance(activity, dict):+ raise ValueError("activity body is not an object")+ return activity+++def _bot_identities(activity: dict[str, Any]) -> set[str]:+ """Every spelling of the bot's own id a mention entity may carry.++ Teams sometimes prefixes a participant id with its type (``28:`` for a+ bot) and sometimes doesn't, so match both. Getting this wrong is silent:+ a missed @mention means the bot never answers in a channel.+ """+ ids = _configured_bot_ids()+ recipient_id = (activity.get("recipient") or {}).get("id")+ if recipient_id:+ ids.add(_strip_participant_prefix(recipient_id))+ return ids+++def _configured_bot_ids() -> set[str]:+ """The bot's id from configuration alone, ignoring the activity."""+ app_id = config.get_app_id()+ return {_strip_participant_prefix(app_id)} if app_id else set()+++def _is_own_id(candidate: str | None, own: set[str]) -> bool:+ return bool(candidate) and _strip_participant_prefix(str(candidate)) in own+++def _lists_bot(members: list[dict[str, Any]] | None, own: set[str]) -> bool:+ """Whether a membersAdded/membersRemoved list names the bot itself."""+ return any(_is_own_id((m or {}).get("id"), own) for m in members or [])+++def _strip_participant_prefix(value: str) -> str:+ """``28:<app-id>`` -> ``<app-id>``; anything unprefixed is returned as-is."""+ prefix, sep, tail = value.partition(":")+ return (tail if sep and prefix.isdigit() else value).lower()diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.pynew file mode 100644index 0000000000..6ec28e7cba--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.py@@ -0,0 +1,1228 @@+"""Tests for the Teams adapter: inbound auth, activity mapping, and sends."""++import asyncio+import time+from unittest.mock import AsyncMock, MagicMock, patch++import jwt+import pytest+from cryptography.hazmat.primitives.asymmetric import rsa++from backend.copilot.bot.adapters.teams import auth, commands, config+from backend.copilot.bot.adapters.teams.adapter import (+ MESSAGES_PATH,+ TeamsAdapter,+ _inbound_files,+)+from backend.copilot.bot.adapters.teams.text import mention_entities, to_teams_markdown+from backend.util.settings import AppEnvironment++_APP_ID = "11111111-2222-3333-4444-555555555555"+_SERVICE_URL = "https://smba.trafficmanager.net/teams/"+_CONFIG_PATH = "backend.copilot.bot.adapters.teams.config"+++def app_id():+ with patch(f"{_CONFIG_PATH}.get_app_id", return_value=_APP_ID):+ yield _APP_ID++[email protected](autouse=True)+def dedupe_redis():+ """Fake the dedupe store: every activity claims its id first try."""+ redis = MagicMock()+ redis.set = AsyncMock(return_value=True)+ with patch(+ "backend.copilot.bot.adapters.teams.adapter.get_redis_async",+ AsyncMock(return_value=redis),+ ):+ yield redis++[email protected](scope="module")+def signing_key():+ """A throwaway RSA key standing in for Microsoft's signing key."""+ return rsa.generate_private_key(public_exponent=65537, key_size=2048)+++def _token(signing_key, **overrides) -> str:+ claims = {+ "iss": config.TOKEN_ISSUER,+ "aud": _APP_ID,+ "serviceurl": _SERVICE_URL,+ "exp": int(time.time()) + 600,+ "iat": int(time.time()),+ **overrides,+ }+ return jwt.encode(claims, signing_key, algorithm="RS256", headers={"kid": "test"})+++def _validator_with(signing_key) -> auth.ConnectorTokenValidator:+ """A validator pre-seeded with our test key, skipping the JWKS fetch."""+ validator = auth.ConnectorTokenValidator()+ jwk = jwt.algorithms.RSAAlgorithm.to_jwk(signing_key.public_key(), as_dict=True)+ jwk["kid"] = "test"+ validator._keys = {"test": jwk}+ validator._fetched_at = time.monotonic()+ return validator+++def _activity(**overrides) -> dict:+ return {+ "type": "message",+ "id": "activity-1",+ "serviceUrl": _SERVICE_URL,+ "text": "hello",+ "from": {"id": "29:user", "name": "Ada"},+ "conversation": {"id": "a:chat", "conversationType": "personal"},+ **overrides,+ }+++# ── Inbound authentication ─────────────────────────────────────────+++async def test_valid_token_is_accepted(app_id, signing_key):+ claims = await _validator_with(signing_key).validate(+ f"Bearer {_token(signing_key)}"+ )+ assert claims["aud"] == _APP_ID+++ "header", [None, "", "Basic abc", "Bearer", "Bearer ", "token abc"]+)+async def test_non_bearer_headers_are_rejected(app_id, signing_key, header):+ with pytest.raises(auth.TeamsAuthError):+ await _validator_with(signing_key).validate(header)+++async def test_algorithm_is_pinned_before_key_lookup(app_id, signing_key):+ # A token asking to be verified with HMAC must be refused outright — never+ # let the token choose its own algorithm family.+ forged = jwt.encode({"aud": _APP_ID}, "secret", algorithm="HS256")+ with pytest.raises(auth.TeamsAuthError, match="algorithm"):+ await _validator_with(signing_key).validate(f"Bearer {forged}")+++async def test_wrong_audience_is_rejected(app_id, signing_key):+ other = _token(signing_key, aud="00000000-0000-0000-0000-000000000000")+ with pytest.raises(auth.TeamsAuthError):+ await _validator_with(signing_key).validate(f"Bearer {other}")+++async def test_expired_token_is_rejected(app_id, signing_key):+ stale = _token(signing_key, exp=int(time.time()) - 3600)+ with pytest.raises(auth.TeamsAuthError):+ await _validator_with(signing_key).validate(f"Bearer {stale}")+++def test_service_url_claim_is_read_from_the_lowercase_key():+ # The wire claim is "serviceurl" even though the docs spell it serviceUrl.+ # Reading the camelCase spelling yields None, which would silently disable+ # this check entirely — hence a dedicated test.+ auth.verify_service_url({"serviceurl": _SERVICE_URL}, _SERVICE_URL)+ with pytest.raises(auth.TeamsAuthError):+ auth.verify_service_url({"serviceUrl": _SERVICE_URL}, _SERVICE_URL)+++def test_service_url_mismatch_is_rejected():+ with pytest.raises(auth.TeamsAuthError):+ auth.verify_service_url({"serviceurl": _SERVICE_URL}, "https://evil.example/")+++def test_service_url_trailing_slash_is_not_significant():+ auth.verify_service_url({"serviceurl": _SERVICE_URL.rstrip("/")}, _SERVICE_URL)+++ "url,allowed",+ [+ ("https://smba.trafficmanager.net/teams/", True),+ ("https://europe.botframework.com/", True),+ ("https://gov.botframework.azure.us/", True),+ ("https://evil.example.com/", False),+ # Suffix confusion: a lookalike host must not pass.+ ("https://smba.trafficmanager.net.evil.com/", False),+ # trafficmanager.net is customer-registerable — only the exact+ # Connector host is trusted, never the zone.+ ("https://evil-profile.trafficmanager.net/", False),+ # A bearer token never goes out in cleartext.+ ("http://smba.trafficmanager.net/teams/", False),+ ("", False),+ ("not-a-url", False),+ ],+)+def test_service_url_allowlist(url, allowed):+ assert auth.is_allowed_service_url(url) is allowed+++# ── Activity -> MessageContext ─────────────────────────────────────+++async def test_personal_chat_maps_to_dm(app_id):+ ctx = await TeamsAdapter(MagicMock())._build_context(_activity())+ assert ctx is not None+ assert ctx.channel_type == "dm"+ assert ctx.server_id is None+ assert ctx.channel_id == "a:chat"+++async def test_channel_message_carries_team_as_server_id(app_id):+ activity = _activity(+ conversation={"id": "19:[email protected]", "conversationType": "channel"},+ channelData={"team": {"id": "19:[email protected]", "name": "Eng"}},+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.channel_type == "channel"+ assert ctx.server_id == "19:[email protected]"+++async def test_reply_chain_maps_to_thread(app_id):+ activity = _activity(+ conversation={+ "id": "19:[email protected];messageid=1700",+ "conversationType": "channel",+ },+ channelData={"team": {"id": "19:[email protected]"}},+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.channel_type == "thread"+++async def test_top_level_post_with_own_messageid_maps_to_channel(app_id):+ # Real Teams suffixes even a brand-new top-level post with ;messageid= —+ # of the post itself. That must classify as a channel message, not a+ # thread reply, or the channel branch never runs in production.+ activity = _activity(+ id="1700",+ conversation={+ "id": "19:[email protected];messageid=1700",+ "conversationType": "channel",+ },+ channelData={"team": {"id": "19:[email protected]"}},+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.channel_type == "channel"+++def test_derived_thread_ids_reuse_the_learned_service_url(app_id):+ # create_thread mints "<base>;messageid=<n>" — replies there must go to+ # the regional host learned from inbound traffic, not the geo-routed+ # default, or an EMEA tenant served from a US deployment 404s.+ adapter = TeamsAdapter(MagicMock())+ adapter._remember_service_url(+ _activity(+ serviceUrl="https://emea.botframework.com/",+ conversation={"id": "19:[email protected];messageid=5"},+ )+ )+ assert (+ adapter._service_url_for("19:[email protected];messageid=999")+ == "https://emea.botframework.com/"+ )+ assert (+ adapter._service_url_for("19:[email protected]")+ == "https://emea.botframework.com/"+ )+ assert adapter._service_url_for("19:[email protected]") == (+ "https://smba.trafficmanager.net/teams/"+ )+++async def test_group_chat_is_skipped(app_id):+ # groupChat has no team identity, and the core handler drops any non-DM+ # turn without a server_id — so it is refused here rather than silently.+ activity = _activity(+ conversation={"id": "19:[email protected]", "conversationType": "groupChat"}+ )+ assert await TeamsAdapter(MagicMock())._build_context(activity) is None+++async def test_channel_without_team_is_skipped(app_id):+ activity = _activity(+ conversation={"id": "19:[email protected]", "conversationType": "channel"}+ )+ assert await TeamsAdapter(MagicMock())._build_context(activity) is None+++async def test_bot_mention_is_stripped_and_flagged(app_id):+ activity = _activity(+ text="<at>AutoGPT</at> summarise this",+ entities=[+ {+ "type": "mention",+ "text": "<at>AutoGPT</at>",+ "mentioned": {"id": _APP_ID, "name": "AutoGPT"},+ }+ ],+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.text == "summarise this"+ assert ctx.bot_mentioned is True++[email protected]("mentioned_id", [_APP_ID, f"28:{_APP_ID}"])+async def test_bot_mention_is_detected_in_either_spelling(app_id, mentioned_id):+ # Teams prefixes a participant id with its type, and the Bot Framework SDK+ # matches mentions against the prefixed ``recipient.id``. Reading only the+ # bare app id would mean the bot never sees an @mention — and channel turns+ # only run when mentioned, so it would be silent in every channel.+ activity = _activity(+ text="<at>AutoGPT</at> summarise this",+ recipient={"id": f"28:{_APP_ID}", "name": "AutoGPT"},+ entities=[+ {+ "type": "mention",+ "text": "<at>AutoGPT</at>",+ "mentioned": {"id": mentioned_id, "name": "AutoGPT"},+ }+ ],+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.bot_mentioned is True+ assert ctx.text == "summarise this"+++async def test_bot_mention_is_detected_from_recipient_when_app_id_is_unset():+ # Playground mode configures no app id; the activity's own recipient is+ # then the only thing identifying us.+ activity = _activity(+ text="<at>AutoGPT</at> hi",+ recipient={"id": "28:playground-bot", "name": "AutoGPT"},+ entities=[+ {+ "type": "mention",+ "text": "<at>AutoGPT</at>",+ "mentioned": {"id": "28:playground-bot", "name": "AutoGPT"},+ }+ ],+ )+ with patch(f"{_CONFIG_PATH}.get_app_id", return_value=""):+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.bot_mentioned is True+++async def test_a_users_mention_is_not_mistaken_for_the_bot(app_id):+ activity = _activity(+ text="<at>Bob</at> hi",+ recipient={"id": f"28:{_APP_ID}", "name": "AutoGPT"},+ entities=[+ {+ "type": "mention",+ "text": "<at>Bob</at>",+ "mentioned": {"id": "29:bob", "name": "Bob"},+ }+ ],+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.bot_mentioned is False+ assert ctx.mentionable_users == (("Bob", "29:bob"),)+++async def test_mentionable_users_exclude_the_bot(app_id):+ activity = _activity(+ entities=[+ {+ "type": "mention",+ "text": "<at>AutoGPT</at>",+ "mentioned": {"id": _APP_ID, "name": "AutoGPT"},+ },+ {+ "type": "mention",+ "text": "<at>Grace</at>",+ "mentioned": {"id": "29:grace", "name": "Grace"},+ },+ ],+ )+ ctx = await TeamsAdapter(MagicMock())._build_context(activity)+ assert ctx is not None+ assert ctx.mentionable_users == (("Grace", "29:grace"),)+++# ── Threading ──────────────────────────────────────────────────────+++ "conversation_id,expected",+ [+ ("19:[email protected]", "19:[email protected];messageid=1700"),+ # Already a reply-chain: re-wrapping would address a conversation that+ # does not exist.+ ("19:[email protected];messageid=1", None),+ # Personal chats have no threads.+ ("a:chat", None),+ ],+)+async def test_create_thread_rules(app_id, conversation_id, expected):+ adapter = TeamsAdapter(MagicMock())+ assert await adapter.create_thread(conversation_id, "1700", "Title") == expected+++# ── Sending ────────────────────────────────────────────────────────+++async def test_send_message_posts_markdown_activity(app_id):+ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(return_value="activity-9")+ await adapter.send_message("a:chat", "# Title\n\nbody")+ activity = adapter._client.send_activity.await_args.args[2]+ assert activity["type"] == "message"+ assert activity["textFormat"] == "markdown"+ # Headings do not render in Teams; they are downgraded to bold.+ assert "**Title**" in activity["text"]+ assert "entities" not in activity+++async def test_send_message_attaches_entities_only_for_allowlisted_mentions(app_id):+ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(return_value="activity-9")+ await adapter.send_message(+ "a:chat", "@Grace and @Mallory", mentionable_users=(("Grace", "29:grace"),)+ )+ activity = adapter._client.send_activity.await_args.args[2]+ assert activity["entities"] == [+ {+ "type": "mention",+ "text": "<at>Grace</at>",+ "mentioned": {"id": "29:grace", "name": "Grace"},+ }+ ]+ # The un-allowlisted name stays plain text and cannot ping.+ assert "<at>Mallory</at>" not in activity["text"]+++async def test_send_link_uses_an_adaptive_card_button(app_id):+ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(return_value="activity-9")+ await adapter.send_link("a:chat", "Link up", "Connect", "https://example.com/link")+ card = adapter._client.send_activity.await_args.args[2]["attachments"][0]+ assert card["contentType"] == "application/vnd.microsoft.card.adaptive"+ # Pinned to 1.2 — the highest version every Teams client renders.+ assert card["content"]["version"] == "1.2"+ assert card["content"]["actions"][0]["url"] == "https://example.com/link"+++async def test_non_image_file_degrades_to_a_note(app_id):+ from backend.copilot.bot.adapters.base import FileAttachment++ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(return_value="activity-9")+ await adapter.send_file(+ "a:chat",+ "here you go",+ FileAttachment(+ filename="report.pdf", mime_type="application/pdf", content=b"%PDF"+ ),+ )+ text = adapter._client.send_activity.await_args.args[2]["text"]+ assert "report.pdf" in text+ assert "attachments" not in adapter._client.send_activity.await_args.args[2]+++async def test_image_file_is_inlined(app_id):+ from backend.copilot.bot.adapters.base import FileAttachment++ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(return_value="activity-9")+ await adapter.send_file(+ "a:chat",+ "chart",+ FileAttachment(filename="c.png", mime_type="image/png", content=b"\x89PNG"),+ )+ attachment = adapter._client.send_activity.await_args.args[2]["attachments"][0]+ assert attachment["contentUrl"].startswith("data:image/png;base64,")+++async def test_oversized_image_degrades_to_a_note(app_id):+ # A Teams activity is capped at ~28KB total; an image too big to inline+ # must fall back to text, never a doomed multi-hundred-KB activity.+ from backend.copilot.bot.adapters.base import FileAttachment++ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(return_value="activity-9")+ await adapter.send_file(+ "a:chat",+ "chart",+ FileAttachment(+ filename="big.png",+ mime_type="image/png",+ content=b"\x89" * (config.INLINE_IMAGE_BYTES + 1),+ ),+ )+ posted = adapter._client.send_activity.await_args.args[2]+ assert "attachments" not in posted+ assert "can't be attached" in posted["text"]+++async def test_rejected_inline_image_degrades_to_a_note(app_id):+ from backend.copilot.bot.adapters.base import FileAttachment+ from backend.copilot.bot.adapters.teams.api_client import TeamsApiError++ adapter = TeamsAdapter(MagicMock())+ adapter._client.send_activity = AsyncMock(+ side_effect=[TeamsApiError("413"), "activity-9"]+ )+ await adapter.send_file(+ "a:chat",+ "chart",+ FileAttachment(filename="c.png", mime_type="image/png", content=b"\x89PNG"),+ )+ posted = adapter._client.send_activity.await_args.args[2]+ assert "attachments" not in posted+ assert "can't be attached" in posted["text"]+++async def test_open_dm_channel_uses_the_participant_bot_id(app_id):+ adapter = TeamsAdapter(MagicMock())+ adapter._client.create_conversation = AsyncMock(return_value="a:new")+ with patch(f"{_CONFIG_PATH}.get_tenant_id", return_value="tenant-1"):+ assert await adapter.open_dm_channel("29:user") == "a:new"+ payload = adapter._client.create_conversation.await_args.args[1]+ assert payload["bot"]["id"] == f"28:{_APP_ID}"+ assert payload["members"] == [{"id": "29:user"}]+++# ── Markup localization ────────────────────────────────────────────+++def test_headings_become_bold():+ assert to_teams_markdown("## Results") == "**Results**"+++def test_tables_are_fenced_to_keep_alignment():+ out = to_teams_markdown("| a | b |\n|---|---|\n| 1 | 2 |")+ assert out.startswith("```")+ assert out.rstrip().endswith("```")+++def test_code_blocks_are_left_alone():+ src = "```python\n# comment\n| not | a table |\n```"+ assert to_teams_markdown(src) == src+++def test_mention_entities_ignore_unknown_ids():+ assert mention_entities(["29:nobody"], (("Grace", "29:grace"),)) == []+++# ── Commands ───────────────────────────────────────────────────────+++ "text,expected",+ [+ ("/setup", "setup"),+ ("/help extra words", "help"),+ ("/UNLINK", "unlink"),+ ("/unknown", None),+ ("no command here", None),+ ("", None),+ ],+)+def test_parse_command(text, expected):+ assert commands.parse_command(text) == expected+++async def test_setup_outside_a_team_explains_where_to_go(app_id):+ adapter = MagicMock()+ adapter.send_message = AsyncMock()+ adapter.send_link = AsyncMock()+ await commands.handle(MagicMock(), adapter, _activity(), "setup")+ message = adapter.send_message.await_args.args[1]+ assert "channel" in message.lower()+ adapter.send_link.assert_not_awaited()+++async def test_setup_in_a_team_links_the_team(app_id):+ from backend.copilot.bot.command_core import CommandReply++ adapter = MagicMock()+ adapter.send_message = AsyncMock()+ adapter.send_link = AsyncMock()+ activity = _activity(+ text="/setup",+ conversation={"id": "19:[email protected]", "conversationType": "channel"},+ channelData={"team": {"id": "19:[email protected]", "name": "Eng"}},+ )+ reply = CommandReply(+ text="Set up", button_label="Link Team", button_url="https://link.example/t"+ )+ with patch(+ "backend.copilot.bot.adapters.teams.commands.setup_reply",+ AsyncMock(return_value=reply),+ ) as setup:+ await commands.handle(MagicMock(), adapter, activity, "setup")+ kwargs = setup.await_args.kwargs+ assert kwargs["platform_server_id"] == "19:[email protected]"+ assert kwargs["server_name"] == "Eng"+ assert kwargs["server_noun"] == "team"+ adapter.send_link.assert_awaited_once_with(+ "19:[email protected]", "Set up", "Link Team", "https://link.example/t"+ )+++async def test_setup_asks_the_connector_for_a_missing_team_name():+ from backend.copilot.bot.command_core import CommandReply++ # Teams stamps the team name onto install activities but not onto the+ # message carrying /setup, so without the lookup the link is stored+ # nameless and settings can only show the raw thread id.+ adapter = MagicMock()+ adapter.send_message = AsyncMock()+ adapter.send_link = AsyncMock()+ adapter.client.get_team_details = AsyncMock(return_value={"name": "Engineering"})+ activity = _activity(+ text="/setup",+ conversation={"id": "19:[email protected]", "conversationType": "channel"},+ channelData={"team": {"id": "19:[email protected]"}},+ )+ with patch(+ "backend.copilot.bot.adapters.teams.commands.setup_reply",+ AsyncMock(return_value=CommandReply(text="Set up")),+ ) as setup:+ await commands.handle(MagicMock(), adapter, activity, "setup")++ adapter.client.get_team_details.assert_awaited_once_with(+ activity["serviceUrl"], "19:[email protected]"+ )+ assert setup.await_args.kwargs["server_name"] == "Engineering"+++async def test_setup_does_not_call_the_connector_when_the_name_is_present():+ from backend.copilot.bot.command_core import CommandReply++ adapter = MagicMock()+ adapter.send_message = AsyncMock()+ adapter.send_link = AsyncMock()+ adapter.client.get_team_details = AsyncMock()+ activity = _activity(+ text="/setup",+ conversation={"id": "19:[email protected]", "conversationType": "channel"},+ channelData={"team": {"id": "19:[email protected]", "name": "Eng"}},+ )+ with patch(+ "backend.copilot.bot.adapters.teams.commands.setup_reply",+ AsyncMock(return_value=CommandReply(text="Set up")),+ ) as setup:+ await commands.handle(MagicMock(), adapter, activity, "setup")++ adapter.client.get_team_details.assert_not_awaited()+ assert setup.await_args.kwargs["server_name"] == "Eng"+++async def test_setup_survives_a_failed_team_lookup():+ from backend.copilot.bot.command_core import CommandReply++ # A nameless link still works; the settings page falls back to the id.+ adapter = MagicMock()+ adapter.send_message = AsyncMock()+ adapter.send_link = AsyncMock()+ adapter.client.get_team_details = AsyncMock(side_effect=RuntimeError("connector"))+ activity = _activity(+ text="/setup",+ conversation={"id": "19:[email protected]", "conversationType": "channel"},+ channelData={"team": {"id": "19:[email protected]"}},+ )+ with patch(+ "backend.copilot.bot.adapters.teams.commands.setup_reply",+ AsyncMock(return_value=CommandReply(text="Set up")),+ ) as setup:+ await commands.handle(MagicMock(), adapter, activity, "setup")++ assert setup.await_args.kwargs["server_name"] == ""+++# ── Factory gating ─────────────────────────────────────────────────+++def test_adapter_is_not_built_without_credentials():+ from backend.copilot.bot.webhook_routes import build_webhook_adapters++ with (+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False),+ patch(f"{_CONFIG_PATH}.get_app_id", return_value=""),+ patch(f"{_CONFIG_PATH}.get_app_password", return_value=""),+ patch(f"{_CONFIG_PATH}.get_tenant_id", return_value=""),+ patch(+ "backend.copilot.bot.adapters.slack.config.get_signing_secret",+ return_value="",+ ),+ patch(+ "backend.copilot.bot.adapters.telegram.config.get_bot_token",+ return_value="",+ ),+ ):+ assert build_webhook_adapters(MagicMock()) == []+++def _settings_with(app_env, flag):+ settings = MagicMock()+ settings.config.app_env = app_env+ settings.config.autopilot_bot_teams_allow_unverified = flag+ return settings+++ "app_env,flag,expected",+ [+ (AppEnvironment.LOCAL, True, True),+ # The flag alone must never be enough on a deployed environment.+ (AppEnvironment.DEVELOPMENT, True, False),+ (AppEnvironment.PRODUCTION, True, False),+ # Nor is being local enough without the explicit opt-in.+ (AppEnvironment.LOCAL, False, False),+ ],+)+def test_playground_bypass_is_double_gated(app_env, flag, expected):+ with patch(f"{_CONFIG_PATH}.Settings", return_value=_settings_with(app_env, flag)):+ assert config.allow_unverified_requests() is expected+++def test_loopback_service_url_only_allowed_in_playground_mode():+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=True):+ assert auth.is_allowed_service_url("http://localhost:56150/") is True+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ assert auth.is_allowed_service_url("http://localhost:56150/") is False+++_AUTH_PATH = "backend.copilot.bot.adapters.teams.auth"++_TEAM = {"id": "19:[email protected]", "name": "Eng"}+++def _membership_activity(**overrides) -> dict:+ return {+ "type": "installationUpdate",+ "recipient": {"id": f"28:{_APP_ID}", "name": "AutoGPT"},+ "conversation": {"id": "19:[email protected]"},+ "channelData": {"team": _TEAM},+ **overrides,+ }+++async def test_install_puts_the_team_on_the_roster(app_id):+ # Without this the roster has no row, so admin analytics show the raw+ # team id instead of its name.+ api = MagicMock()+ adapter = TeamsAdapter(api)+ await adapter._dispatch_activity(_membership_activity(action="add"))+ api.track_guild_joined.assert_called_once_with("teams", _TEAM["id"], "Eng")+ api.track_guild_left.assert_not_called()+++async def test_uninstall_marks_the_team_left(app_id):+ api = MagicMock()+ adapter = TeamsAdapter(api)+ await adapter._dispatch_activity(_membership_activity(action="remove"))+ api.track_guild_left.assert_called_once_with("teams", _TEAM["id"])+ api.track_guild_joined.assert_not_called()+++async def test_bot_added_via_conversation_update_is_tracked(app_id):+ api = MagicMock()+ adapter = TeamsAdapter(api)+ await adapter._dispatch_activity(+ _membership_activity(+ type="conversationUpdate",+ membersAdded=[{"id": f"28:{_APP_ID}"}],+ )+ )+ api.track_guild_joined.assert_called_once_with("teams", _TEAM["id"], "Eng")+++async def test_other_people_joining_does_not_touch_the_roster(app_id):+ # membersAdded fires for every new team member; only the bot's own+ # add/remove should move the roster.+ api = MagicMock()+ adapter = TeamsAdapter(api)+ await adapter._dispatch_activity(+ _membership_activity(type="conversationUpdate", membersAdded=[{"id": "29:bob"}])+ )+ api.track_guild_joined.assert_not_called()+ api.track_guild_left.assert_not_called()+++async def test_personal_install_is_not_put_on_the_roster(app_id):+ api = MagicMock()+ adapter = TeamsAdapter(api)+ await adapter._dispatch_activity(_membership_activity(action="add", channelData={}))+ api.track_guild_joined.assert_not_called()+ api.track_guild_left.assert_not_called()+++ "url,expected",+ [+ ("http://localhost:56150/", "http://host.docker.internal:56150/"),+ ("http://127.0.0.1:56150/", "http://host.docker.internal:56150/"),+ # No port to preserve.+ ("http://localhost/", "http://host.docker.internal/"),+ # Paths and queries must survive the host swap.+ (+ "http://localhost:56150/v3/x?a=1",+ "http://host.docker.internal:56150/v3/x?a=1",+ ),+ # A real Connector host is never touched.+ (+ "https://smba.trafficmanager.net/teams/",+ "https://smba.trafficmanager.net/teams/",+ ),+ ],+)+def test_loopback_is_rewritten_to_the_container_host(url, expected):+ with (+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=True),+ patch(f"{_AUTH_PATH}._in_container", return_value=True),+ ):+ assert auth.rewrite_loopback_for_container(url) == expected+++ "unverified,in_container",+ [(False, True), (True, False), (False, False)],+)+def test_loopback_rewrite_needs_both_playground_mode_and_a_container(+ unverified, in_container+):+ url = "http://localhost:56150/"+ with (+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=unverified),+ patch(f"{_AUTH_PATH}._in_container", return_value=in_container),+ ):+ assert auth.rewrite_loopback_for_container(url) == url+++def test_container_host_alias_is_dialable_only_in_playground_mode():+ url = "http://host.docker.internal:56150/"+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=True):+ assert auth.is_allowed_service_url(url) is True+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ assert auth.is_allowed_service_url(url) is False+++def test_rejection_bodies_do_not_echo_the_reason(app_id):+ """The caller is unauthenticated, so the body says nothing specific.++ The validator wraps the JWT parser's own exception text, which would+ otherwise be handed straight back to whoever is probing the endpoint.+ """+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ app = FastAPI()+ adapter = TeamsAdapter(MagicMock())+ adapter.register_routes(app)+ client = TestClient(app)++ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ with patch.object(+ adapter._validator,+ "validate",+ AsyncMock(+ side_effect=auth.TeamsAuthError(+ "malformed token: Invalid header string: codec can't decode 0x9e"+ )+ ),+ ):+ rejected = client.post(MESSAGES_PATH, json=_activity())+ malformed = client.post(+ MESSAGES_PATH,+ content=b"not json",+ headers={"Content-Type": "application/json"},+ )++ assert rejected.status_code == 401+ assert "codec" not in rejected.text+ assert "malformed token" not in rejected.text+ # A parse failure must not hand back the payload or the parser's message.+ assert malformed.status_code in (400, 401)+ assert "not json" not in malformed.text+++async def _drain(adapter: TeamsAdapter) -> None:+ """Await the adapter's fire-and-forget dispatch tasks.++ ``_handle_messages_request`` answers 200 and dispatches in a background+ task, so asserting on the handler's side effects immediately is a race.+ Polling from the test thread does not fix it: without a context manager+ the TestClient builds a portal per request and tears it down when the call+ returns, taking the loop that would run the dispatch with it.+ """+ while adapter._activity_tasks:+ await asyncio.gather(*tuple(adapter._activity_tasks))+++def test_unauthenticated_request_is_rejected_when_not_in_playground_mode(app_id):+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ app = FastAPI()+ adapter = TeamsAdapter(MagicMock())+ adapter.register_routes(app)+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ response = TestClient(app).post(MESSAGES_PATH, json=_activity())+ assert response.status_code == 401+++def test_route_accepts_a_properly_signed_activity(app_id, signing_key):+ """End-to-end through the real HTTP route: signed token -> dispatch."""+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ app = FastAPI()+ adapter = TeamsAdapter(MagicMock())+ adapter._validator = _validator_with(signing_key)+ seen = []+ adapter.on_message(lambda ctx, _adapter: _record(seen, ctx))+ adapter.register_routes(app)++ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ # One portal for both the request and the drain, so the dispatch has+ # a live loop to run on.+ with TestClient(app) as client:+ response = client.post(+ MESSAGES_PATH,+ json=_activity(),+ headers={"Authorization": f"Bearer {_token(signing_key)}"},+ )+ client.portal.call(_drain, adapter)+ assert response.status_code == 200+ assert [ctx.text for ctx in seen] == ["hello"]+++async def test_route_rejects_a_body_whose_service_url_was_swapped(app_id, signing_key):+ """A captured token replayed with a redirected serviceUrl must not pass."""+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ app = FastAPI()+ adapter = TeamsAdapter(MagicMock())+ adapter._validator = _validator_with(signing_key)+ adapter.register_routes(app)++ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ response = TestClient(app).post(+ MESSAGES_PATH,+ json=_activity(serviceUrl="https://attacker.example/"),+ headers={"Authorization": f"Bearer {_token(signing_key)}"},+ )+ assert response.status_code == 401+++async def _record(seen: list, ctx) -> None:+ seen.append(ctx)+++# ── Activity dedupe ────────────────────────────────────────────────+++async def test_redelivered_activity_is_dispatched_once(app_id, dedupe_redis):+ # The Connector retries slow deliveries, and a captured request can be+ # replayed for the token's lifetime — both arrive as a repeated id.+ dedupe_redis.set = AsyncMock(side_effect=[True, None])+ adapter = TeamsAdapter(MagicMock())+ seen = []+ adapter.on_message(lambda ctx, _a: _record(seen, ctx))+ await adapter._dispatch_activity(_activity(text="original"))+ await adapter._dispatch_activity(_activity(text="redelivery"))+ # The FIRST delivery survives — dropping it and keeping the retry would+ # also pass a bare count assertion.+ assert [ctx.text for ctx in seen] == ["original"]+++async def test_activity_without_id_is_still_processed(app_id, dedupe_redis):+ adapter = TeamsAdapter(MagicMock())+ seen = []+ adapter.on_message(lambda ctx, _a: _record(seen, ctx))+ await adapter._dispatch_activity(_activity(id=""))+ assert len(seen) == 1+ dedupe_redis.set.assert_not_called()+++async def test_dedupe_fails_open_when_redis_is_down(app_id, dedupe_redis):+ dedupe_redis.set = AsyncMock(side_effect=ConnectionError("redis down"))+ adapter = TeamsAdapter(MagicMock())+ seen = []+ adapter.on_message(lambda ctx, _a: _record(seen, ctx))+ await adapter._dispatch_activity(_activity())+ assert len(seen) == 1+++# ── Inbound attachments ────────────────────────────────────────────+++def _file_attachment(name: str, **content) -> dict:+ return {+ "contentType": "application/vnd.microsoft.teams.file.download.info",+ "name": name,+ "content": {"downloadUrl": f"https://files.example/{name}", **content},+ }+++def test_inbound_files_are_not_capped_before_the_shared_bookkeeping(app_id):+ # Teams puts a non-file text/html attachment in the same array; it must+ # not consume cap slots, and the cap itself belongs to+ # collect_attachments, which owns the "too many files" note.+ activity = _activity(+ attachments=[{"contentType": "text/html", "content": "<div>hi</div>"}]+ + [_file_attachment(f"f{i}.txt") for i in range(10)]+ )+ files = _inbound_files(activity, MagicMock())+ assert [f.filename for f in files] == [f"f{i}.txt" for i in range(10)]+++def test_pasted_image_is_ingested(app_id):+ activity = _activity(+ attachments=[+ {+ "contentType": "image/png",+ "contentUrl": "https://smba.trafficmanager.net/amer/attachment/1",+ }+ ]+ )+ files = _inbound_files(activity, MagicMock())+ assert len(files) == 1+ assert files[0].mime_type == "image/png"+ assert files[0].filename == "pasted-image"+++def test_pasted_image_on_a_foreign_host_never_sees_the_bearer(app_id):+ """The activity body is unsigned, so contentUrl is attacker-choosable.++ Fetching it with the bot's Connector bearer would hand that token to+ whatever host the sender names, within the token's whole validity window.+ """+ activity = _activity(+ attachments=[+ {+ "contentType": "image/png",+ "contentUrl": "https://attacker.example/collect",+ }+ ]+ )+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ assert _inbound_files(activity, MagicMock()) == []+++def test_pasted_image_host_must_be_a_connector_host_not_merely_public(app_id):+ # A public HTTPS host passes the looser attachment check; the bearer path+ # has to be stricter than that.+ activity = _activity(+ attachments=[+ {"contentType": "image/png", "contentUrl": "https://example.com/x.png"}+ ]+ )+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ assert _inbound_files(activity, MagicMock()) == []+ assert auth.is_fetchable_attachment_url("https://example.com/x.png") is True+++ "url",+ [+ "http://files.example.com/doc.txt", # cleartext+ "https://169.254.169.254/latest/meta-data/", # cloud metadata+ "https://127.0.0.1/secret",+ "https://10.0.0.5/internal",+ "https://[::1]/secret",+ "file:///etc/passwd",+ ],+)+def test_file_download_urls_that_point_inward_are_skipped(app_id, url):+ activity = _activity(+ attachments=[+ {+ "contentType": ("application/vnd.microsoft.teams.file.download.info"),+ "name": "doc.txt",+ "content": {"downloadUrl": url, "fileType": "txt"},+ }+ ]+ )+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ assert _inbound_files(activity, MagicMock()) == []+++ "host",+ [+ "127.1", # shorthand: ipaddress rejects it, getaddrinfo resolves it+ "2130706433", # integer form of 127.0.0.1+ "0177.0.0.1", # octal form of 127.0.0.1+ "localhost", # a name, not a literal+ ],+)+async def test_attachment_hosts_that_resolve_inward_are_refused(app_id, host):+ """The URL text cannot say where a name points — only resolving can."""+ with (+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False),+ pytest.raises(ValueError),+ ):+ await auth.ensure_attachment_host_is_external(f"https://{host}/x")+++async def test_an_unresolvable_attachment_host_is_refused(app_id):+ with (+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False),+ pytest.raises(ValueError),+ ):+ await auth.ensure_attachment_host_is_external("https://no-such-host.invalid/x")+++async def test_the_playground_may_still_serve_attachments_from_loopback(app_id):+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=True):+ await auth.ensure_attachment_host_is_external("http://localhost:56150/x")+++async def test_the_attachment_fetch_stops_at_the_size_cap(app_id):+ """The only DoS bound on downloads — Teams declares no size for a file."""+ from backend.copilot.bot.adapters.teams.adapter import _bounded_fetch++ oversized = config.MAX_ATTACHMENT_BYTES + 1++ async def chunks():+ yield b"x" * oversized++ response = MagicMock()+ response.raise_for_status = MagicMock()+ response.aiter_bytes = chunks+ stream = MagicMock()+ stream.__aenter__ = AsyncMock(return_value=response)+ stream.__aexit__ = AsyncMock(return_value=False)+ client = MagicMock()+ client.stream = MagicMock(return_value=stream)+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=False)++ fetch = _bounded_fetch("https://files.example/big.bin")+ with (+ patch(+ "backend.copilot.bot.adapters.teams.auth."+ "ensure_attachment_host_is_external",+ new=AsyncMock(),+ ),+ patch(+ "backend.copilot.bot.adapters.teams.adapter.httpx.AsyncClient",+ return_value=client,+ ),+ pytest.raises(ValueError, match="size limit"),+ ):+ await fetch()+++async def test_the_attachment_fetch_never_follows_redirects(app_id):+ # A redirect would land the fetch on a host the SSRF check never saw.+ from backend.copilot.bot.adapters.teams.adapter import _bounded_fetch++ async def chunks():+ yield b"ok"++ response = MagicMock()+ response.raise_for_status = MagicMock()+ response.aiter_bytes = chunks+ stream = MagicMock()+ stream.__aenter__ = AsyncMock(return_value=response)+ stream.__aexit__ = AsyncMock(return_value=False)+ client = MagicMock()+ client.stream = MagicMock(return_value=stream)+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=False)+ made = MagicMock(return_value=client)++ fetch = _bounded_fetch("https://files.example/ok.txt")+ with (+ patch(+ "backend.copilot.bot.adapters.teams.auth."+ "ensure_attachment_host_is_external",+ new=AsyncMock(),+ ),+ patch("backend.copilot.bot.adapters.teams.adapter.httpx.AsyncClient", made),+ ):+ assert await fetch() == b"ok"++ assert made.call_args.kwargs["follow_redirects"] is False+++def test_a_normal_sharepoint_download_still_works(app_id):+ activity = _activity(attachments=[_file_attachment("notes.txt")])+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False):+ files = _inbound_files(activity, MagicMock())+ assert [f.filename for f in files] == ["notes.txt"]+++def test_file_attachment_without_download_url_is_skipped(app_id):+ activity = _activity(+ attachments=[+ {+ "contentType": "application/vnd.microsoft.teams.file.download.info",+ "name": "ghost.txt",+ "content": {},+ }+ ]+ )+ assert _inbound_files(activity, MagicMock()) == []+++def test_tenant_id_is_required_to_enable_the_adapter():+ # A single-tenant registration mints tokens against its own tenant+ # authority, so app id + password alone must NOT enable the adapter.+ # The bypass is pinned off so a developer's own Playground settings can't+ # decide the result.+ with (+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False),+ patch(f"{_CONFIG_PATH}.get_app_id", return_value=_APP_ID),+ patch(f"{_CONFIG_PATH}.get_app_password", return_value="secret"),+ patch(f"{_CONFIG_PATH}.get_tenant_id", return_value=""),+ ):+ assert config.is_configured() is Falsediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.pynew file mode 100644index 0000000000..a464deb908--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.py@@ -0,0 +1,158 @@+"""Thin async client for the Bot Connector REST API.++Every outbound call is addressed relative to the ``serviceUrl`` carried on the+inbound activity rather than a fixed base URL, because Microsoft routes each+tenant/region to its own Connector host. That makes ``serviceUrl``+attacker-influenced input which we then attach a bearer token to, so every+request funnels through :func:`auth.is_allowed_service_url` first.+"""++import asyncio+import logging+import time+from typing import Any++import httpx++from . import auth, config++logger = logging.getLogger(__name__)++_HTTP_TIMEOUT_SECONDS = 30.0++# Refresh this far ahead of expiry so an in-flight request never races the+# token going stale.+_TOKEN_REFRESH_MARGIN_SECONDS = 300+++class TeamsApiError(Exception):+ """A Bot Connector call failed."""+++class TeamsClient:+ """Authenticated Bot Connector client. Safe to share across requests."""++ def __init__(self) -> None:+ self._token: str = ""+ self._token_expires_at = 0.0+ self._token_lock = asyncio.Lock()+ # One pooled client for the adapter's lifetime, matching the Telegram+ # adapter — avoids a TCP+TLS handshake per Connector call.+ self._http = httpx.AsyncClient(timeout=_HTTP_TIMEOUT_SECONDS)++ async def send_activity(+ self, service_url: str, conversation_id: str, activity: dict[str, Any]+ ) -> str | None:+ """Append an activity to a conversation; returns its new activity id."""+ return await self._post_activity(+ service_url,+ f"v3/conversations/{conversation_id}/activities",+ activity,+ )++ async def create_conversation(+ self, service_url: str, payload: dict[str, Any]+ ) -> str | None:+ """Create a conversation (e.g. a 1:1 chat); returns its id.++ Used for proactive delivery, where there is no inbound activity to+ reply to.+ """+ body = await self._request("POST", service_url, "v3/conversations", payload)+ return (body or {}).get("id")++ async def aclose(self) -> None:+ """Release the pooled connections."""+ await self._http.aclose()++ async def get_team_details(+ self, service_url: str, team_id: str+ ) -> dict[str, Any] | None:+ """The team's name and metadata.++ Teams only stamps ``channelData.team.name`` onto install and+ conversation-update activities, not onto ordinary messages — so a+ command handler that needs the name has to ask for it.+ """+ return await self._request("GET", service_url, f"v3/teams/{team_id}")++ async def _post_activity(+ self, service_url: str, path: str, activity: dict[str, Any]+ ) -> str | None:+ body = await self._request("POST", service_url, path, activity)+ return (body or {}).get("id")++ async def _request(+ self,+ method: str,+ service_url: str,+ path: str,+ payload: dict[str, Any] | None = None,+ ) -> dict[str, Any] | None:+ if not auth.is_allowed_service_url(service_url):+ raise TeamsApiError(+ f"refusing to call untrusted serviceUrl {service_url!r}"+ )+ url = f"{service_url.rstrip('/')}/{path}"+ headers = await self.bearer_headers()+ response = await self._http.request(method, url, json=payload, headers=headers)+ if response.status_code >= 400:+ raise TeamsApiError(+ f"{method} {path} failed ({response.status_code}): {response.text[:300]}"+ )+ if not response.content:+ return None+ try:+ return response.json()+ except ValueError:+ return None++ async def bearer_headers(self) -> dict[str, str]:+ """Connector auth headers — empty in Playground mode.++ The Agents Playground neither issues nor checks tokens, and there are+ no credentials to mint one from in that mode.+ """+ if config.allow_unverified_requests():+ return {}+ return {"Authorization": f"Bearer {await self._access_token()}"}++ async def _access_token(self) -> str:+ if self._token and time.monotonic() < self._token_expires_at:+ return self._token+ async with self._token_lock:+ if self._token and time.monotonic() < self._token_expires_at:+ return self._token+ self._token, lifetime = await self._mint_access_token()+ self._token_expires_at = time.monotonic() + max(+ lifetime - _TOKEN_REFRESH_MARGIN_SECONDS, 60+ )+ return self._token++ async def _mint_access_token(self) -> tuple[str, float]:+ """Client-credentials grant against the bot's own tenant authority.++ Single-tenant registrations (the only kind Microsoft issues now) must+ use ``login.microsoftonline.com/{tenant}``; the tenant-less+ ``botframework.com`` authority is the multi-tenant form and 401s here.+ """+ url = f"https://login.microsoftonline.com/{config.get_tenant_id()}/oauth2/v2.0/token"+ response = await self._http.post(+ url,+ data={+ "grant_type": "client_credentials",+ "client_id": config.get_app_id(),+ "client_secret": config.get_app_password(),+ "scope": config.CONNECTOR_SCOPE,+ },+ )+ if response.status_code >= 400:+ raise TeamsApiError(+ f"could not mint Connector token ({response.status_code}): "+ f"{response.text[:300]}"+ )+ body = response.json()+ token = body.get("access_token")+ if not token:+ raise TeamsApiError("token response carried no access_token")+ return token, float(body.get("expires_in", 3600))diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.pynew file mode 100644index 0000000000..1a28ffa372--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.py@@ -0,0 +1,168 @@+"""Tests for the Bot Connector client: token minting and the outbound gate."""++import time+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.bot.adapters.teams import config+from backend.copilot.bot.adapters.teams.api_client import (+ _TOKEN_REFRESH_MARGIN_SECONDS,+ TeamsApiError,+ TeamsClient,+)++_CONFIG_PATH = "backend.copilot.bot.adapters.teams.config"+_ALLOWED = "https://smba.trafficmanager.net/emea/"+++def _token_response(status_code=200, **body):+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = {"access_token": "tok", "expires_in": 3600, **body}+ response.text = "boom"+ return response+++def _creds():+ return (+ patch(f"{_CONFIG_PATH}.get_app_id", return_value="app-id"),+ patch(f"{_CONFIG_PATH}.get_app_password", return_value="secret"),+ patch(f"{_CONFIG_PATH}.get_tenant_id", return_value="tenant-id"),+ patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=False),+ )+++async def test_token_is_minted_against_the_bots_own_tenant():+ """The tenant-less botframework.com authority is the multi-tenant form.++ Microsoft only issues single-tenant registrations now, and using the wrong+ authority 401s every outbound call — the PR's most-cited failure mode.+ """+ client = TeamsClient()+ client._http = MagicMock()+ client._http.post = AsyncMock(return_value=_token_response())+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ token = await client._access_token()++ assert token == "tok"+ url = client._http.post.await_args.args[0]+ assert url == ("https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token")+ body = client._http.post.await_args.kwargs["data"]+ assert body["grant_type"] == "client_credentials"+ assert body["client_id"] == "app-id"+ assert body["client_secret"] == "secret"+ assert body["scope"] == config.CONNECTOR_SCOPE+++async def test_token_expiry_keeps_a_refresh_margin():+ client = TeamsClient()+ client._http = MagicMock()+ client._http.post = AsyncMock(return_value=_token_response(expires_in=3600))+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ before = time.monotonic()+ await client._access_token()++ # Expire early so a call never rides a token that dies mid-flight.+ assert client._token_expires_at <= before + 3600 - _TOKEN_REFRESH_MARGIN_SECONDS + 1+++async def test_a_short_lived_token_never_expires_in_the_past():+ # A lifetime under the margin would otherwise compute a already-expired+ # deadline and remint on every single call.+ client = TeamsClient()+ client._http = MagicMock()+ client._http.post = AsyncMock(return_value=_token_response(expires_in=60))+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ await client._access_token()++ assert client._token_expires_at > time.monotonic()+++async def test_a_cached_token_is_not_reminted():+ client = TeamsClient()+ client._http = MagicMock()+ client._http.post = AsyncMock(return_value=_token_response())+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ await client._access_token()+ await client._access_token()++ assert client._http.post.await_count == 1+++async def test_a_token_response_without_a_token_is_an_error():+ client = TeamsClient()+ client._http = MagicMock()+ client._http.post = AsyncMock(return_value=_token_response(access_token=""))+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified, pytest.raises(TeamsApiError):+ await client._access_token()+++async def test_a_rejected_grant_is_an_error():+ client = TeamsClient()+ client._http = MagicMock()+ client._http.post = AsyncMock(return_value=_token_response(status_code=401))+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified, pytest.raises(TeamsApiError):+ await client._access_token()+++async def test_an_untrusted_service_url_is_refused_before_any_request():+ """The allowlist is the outbound gate, so nothing may be dialed first.++ serviceUrl arrives on the activity body, which the Connector token does+ not sign — sending the bearer anywhere it names would hand out the token.+ """+ client = TeamsClient()+ client._http = MagicMock()+ client._http.request = AsyncMock()+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified, pytest.raises(TeamsApiError):+ await client.send_activity(+ "https://attacker.example/", "19:conv", {"type": "message"}+ )++ client._http.request.assert_not_awaited()+++async def test_an_allowed_service_url_is_dialed_with_the_bearer():+ client = TeamsClient()+ response = MagicMock()+ response.status_code = 200+ response.content = b"{}"+ response.json.return_value = {}+ client._http = MagicMock()+ client._http.request = AsyncMock(return_value=response)+ client._token = "tok"+ client._token_expires_at = time.monotonic() + 600+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ await client.send_activity(_ALLOWED, "19:conv", {"type": "message"})++ method, url = client._http.request.await_args.args+ assert method == "POST"+ assert url == f"{_ALLOWED.rstrip('/')}/v3/conversations/19:conv/activities"+ headers = client._http.request.await_args.kwargs["headers"]+ assert headers["Authorization"] == "Bearer tok"+++async def test_the_playground_sends_no_bearer():+ # Nothing issues or checks tokens in that mode, and there are no+ # credentials to mint one from.+ client = TeamsClient()+ with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=True):+ assert await client.bearer_headers() == {}diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/auth.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/auth.pynew file mode 100644index 0000000000..81ce30f88c--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/auth.py@@ -0,0 +1,352 @@+"""Inbound Bot Connector authentication and outbound token minting.++Teams differs from every other adapter we run: Slack and Telegram authenticate+a webhook by HMAC-ing the raw body against a shared secret, so one cheap+synchronous comparison proves both *who sent it* and *that the bytes are+untampered*. The Bot Connector instead sends a bearer JWT signed by Microsoft,+which authenticates **the sender only — it does not sign the payload**.++Two consequences drive the shape of this module:++1. Validation needs network I/O (fetching and rotating Microsoft's signing+ keys), so it cannot be expressed through the shared synchronous+ ``read_verified_webhook_body`` verifier. The adapter still reads the raw+ body first and refuses to parse it until the token checks out, preserving+ the same verify-before-parse ordering.+2. Because the token does not cover the body, a valid token may be replayed+ with *any* payload for its ~1h lifetime. Three layers narrow that gap: the+ ``serviceUrl`` claim binding below, the outbound host allowlist, and the+ adapter's per-activity-id dedupe.+"""++import asyncio+import ipaddress+import logging+import os+import socket+import time+from typing import Any+from urllib.parse import urlparse, urlunparse++import httpx+import jwt++from . import config++logger = logging.getLogger(__name__)++_LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1")++# Docker Desktop's DNS alias for the host's loopback interface.+_CONTAINER_HOST_ALIAS = "host.docker.internal"++# Microsoft rotates Connector signing keys; the discovery document is cheap and+# highly cacheable, so refresh daily rather than per request.+_KEY_CACHE_TTL_SECONDS = 24 * 60 * 60++# An unknown ``kid`` may mean a legitimate rotation — or an attacker spraying+# random values to force outbound fetches. Refresh at most this often so a+# spray can't turn every replica into a load generator against Microsoft.+_UNKNOWN_KID_REFRESH_INTERVAL_SECONDS = 300++# Microsoft's documented clock-skew allowance for Connector tokens.+_CLOCK_SKEW_SECONDS = 300++_HTTP_TIMEOUT_SECONDS = 10.0+++class TeamsAuthError(Exception):+ """An inbound request failed Bot Connector authentication.++ ``status_code`` distinguishes a failed identity check (401) from a caller+ whose identity is proven but who is not endorsed for this channel (403),+ which Microsoft specifies as the correct response to an endorsement+ mismatch.+ """++ def __init__(self, message: str, *, status_code: int = 401):+ super().__init__(message)+ self.status_code = status_code+++class ConnectorTokenValidator:+ """Validates inbound JWTs issued by the Bot Connector.++ Holds the signing-key cache. One instance per adapter; safe to share+ across concurrent requests.+ """++ def __init__(self) -> None:+ self._keys: dict[str, dict[str, Any]] = {}+ self._fetched_at = 0.0+ # -inf, not 0.0: monotonic() is process uptime, so a zero start would+ # throttle the first forced refresh for the process's first 5 minutes.+ self._last_forced_refresh = float("-inf")+ self._lock = asyncio.Lock()++ async def validate(self, authorization: str | None) -> dict[str, Any]:+ """Return the token's claims, or raise :class:`TeamsAuthError`.++ This proves only that the Bot Connector sent the request. The caller+ MUST additionally bind the token to the request body via+ :func:`verify_service_url` — the token does not sign the payload.+ """+ token = _bearer_token(authorization)++ # Pin the algorithm from the UNVERIFIED header before touching key+ # material: never let a token nominate its own algorithm family, which+ # is how "alg: none" and HMAC-with-public-key forgeries work.+ try:+ header = jwt.get_unverified_header(token)+ except jwt.InvalidTokenError as e:+ raise TeamsAuthError(f"malformed token: {e}")+ if header.get("alg") != "RS256":+ raise TeamsAuthError(f"unexpected signing algorithm {header.get('alg')!r}")++ kid = header.get("kid")+ if not kid:+ raise TeamsAuthError("token header carries no key id")++ raw_key = await self._key_for(str(kid))++ try:+ claims = jwt.decode(+ token,+ key=jwt.PyJWK(raw_key).key,+ algorithms=["RS256"],+ audience=config.get_app_id(),+ issuer=config.TOKEN_ISSUER,+ leeway=_CLOCK_SKEW_SECONDS,+ )+ except jwt.InvalidTokenError as e:+ raise TeamsAuthError(f"token rejected: {e}")++ _check_endorsements(raw_key)+ return claims++ async def _key_for(self, kid: str) -> dict[str, Any]:+ await self._ensure_keys()+ key = self._keys.get(kid)+ if key is not None:+ return key+ # Unknown kid: possibly a rotation we haven't picked up yet. One+ # throttled refresh, then give up rather than fetching per request.+ if time.monotonic() - self._last_forced_refresh >= (+ _UNKNOWN_KID_REFRESH_INTERVAL_SECONDS+ ):+ await self._ensure_keys(force=True)+ key = self._keys.get(kid)+ if key is None:+ raise TeamsAuthError(f"no signing key matches key id {kid!r}")+ return key++ async def _ensure_keys(self, *, force: bool = False) -> None:+ fresh = time.monotonic() - self._fetched_at < _KEY_CACHE_TTL_SECONDS+ if self._keys and fresh and not force:+ return+ async with self._lock:+ # Re-check under the lock so concurrent requests share one fetch.+ fresh = time.monotonic() - self._fetched_at < _KEY_CACHE_TTL_SECONDS+ if self._keys and fresh and not force:+ return+ if force:+ self._last_forced_refresh = time.monotonic()+ keys = await _fetch_signing_keys()+ if not keys:+ raise TeamsAuthError("no Bot Connector signing keys available")+ self._keys = keys+ self._fetched_at = time.monotonic()+++async def _fetch_signing_keys() -> dict[str, dict[str, Any]]:+ """Resolve the discovery document, then its JWKS, keyed by ``kid``.++ Raw JWK dicts are kept (rather than parsed key objects) because Microsoft+ attaches a non-standard ``endorsements`` list to each key that the JWK+ parsers drop.+ """+ async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT_SECONDS) as client:+ try:+ metadata = (await client.get(config.OPENID_METADATA_URL)).raise_for_status()+ jwks_uri = metadata.json()["jwks_uri"]+ jwks = (await client.get(jwks_uri)).raise_for_status().json()+ except (httpx.HTTPError, KeyError, ValueError) as e:+ raise TeamsAuthError(f"could not load Bot Connector signing keys: {e}")+ return {k["kid"]: k for k in jwks.get("keys", []) if k.get("kid")}+++def _check_endorsements(raw_key: dict[str, Any]) -> None:+ """Log — but do not yet enforce — the channel endorsement on the key.++ Microsoft documents rejecting an un-endorsed key with 403. Enforcing that+ on day one is a live-fire risk: if the key that actually signs ``msteams``+ traffic turns out not to carry the endorsement, hard enforcement would+ reject *all* inbound traffic. Observe real tokens first, then enforce.+ """+ endorsements = raw_key.get("endorsements")+ if endorsements and "msteams" not in endorsements:+ logger.warning(+ f"Connector key {raw_key.get('kid')} is not endorsed for msteams "+ f"(endorsements={endorsements}); allowing while endorsement "+ f"enforcement is in observation mode"+ )+++def verify_service_url(claims: dict[str, Any], activity_service_url: str) -> None:+ """Bind an authenticated token to the body it arrived with.++ The Connector puts the ``serviceUrl`` it will accept replies for inside the+ token. Comparing it against the activity's own ``serviceUrl`` is what stops+ a captured token being replayed with a body pointing our replies (and the+ bearer token attached to them) at an attacker's host.++ NOTE the claim key is lowercase ``serviceurl`` on the wire even though the+ docs spell it ``serviceUrl``; reading the camelCase spelling yields+ ``None`` and silently disables this check entirely.+ """+ claimed = claims.get("serviceurl")+ if not claimed:+ raise TeamsAuthError("token carries no serviceurl claim")+ if claimed.rstrip("/") != (activity_service_url or "").rstrip("/"):+ raise TeamsAuthError("activity serviceUrl does not match the token")+++def is_allowed_service_url(service_url: str) -> bool:+ """Whether we will attach our outbound bearer token to this URL.++ Defence in depth behind :func:`verify_service_url`: even a correctly+ signed token only ever directs us at Connector hosts, over HTTPS.+ """+ try:+ parsed = urlparse(service_url)+ host = (parsed.hostname or "").lower()+ except ValueError:+ return False+ if not host:+ return False+ # The Agents Playground runs on the developer's own machine, so its+ # serviceUrl is loopback (plain http) — or the container's alias for it+ # once :func:`rewrite_loopback_for_container` has redirected it. Only+ # reachable in the double-gated local mode, where no token is attached to+ # the request anyway.+ if host in _LOOPBACK_HOSTS or host == _CONTAINER_HOST_ALIAS:+ return config.allow_unverified_requests()+ if parsed.scheme != "https":+ return False # Never send a bearer token in cleartext.+ return host in config.ALLOWED_SERVICE_URL_HOSTS or any(+ host == suffix.lstrip(".") or host.endswith(suffix)+ for suffix in config.ALLOWED_SERVICE_URL_SUFFIXES+ )+++def is_fetchable_attachment_url(url: str) -> bool:+ """Whether we will issue a server-side GET for this attachment.++ Attachment URLs ride in the activity body, which the Connector token does+ not sign — the same reason ``serviceUrl`` is bound to the token. A fetch+ with no allowlist is a request generator pointed at our own network, so+ require HTTPS and refuse addresses inside our own network.++ This is the cheap pre-filter only: it reads the URL, and the URL cannot+ tell us where a name points. :func:`ensure_attachment_host_is_external`+ is the actual boundary, applied at fetch time.+ """+ try:+ parsed = urlparse(url)+ except ValueError:+ return False+ host = (parsed.hostname or "").lower()+ if not host:+ return False+ if host in _LOOPBACK_HOSTS or host == _CONTAINER_HOST_ALIAS:+ # Playground attachments are served off the developer's own machine.+ return config.allow_unverified_requests()+ if parsed.scheme != "https":+ return False+ return not _is_internal_host(host)+++async def ensure_attachment_host_is_external(url: str) -> None:+ """Raise unless every address ``url``'s host resolves to is off our network.++ The text check cannot catch the interesting cases: ``127.1`` and+ ``2130706433`` are not valid literals to :mod:`ipaddress` but+ ``getaddrinfo`` resolves both to loopback, and a plain DNS name can point+ anywhere at all.++ Resolution still races the connect that follows it, so a name that flips+ between the two would slip through; closing that needs peer-address+ validation inside the transport. What this removes is every bypass that+ costs an attacker nothing.+ """+ parsed = urlparse(url)+ host = (parsed.hostname or "").lower()+ if not host:+ raise ValueError("attachment URL has no host")+ if (host in _LOOPBACK_HOSTS or host == _CONTAINER_HOST_ALIAS) and (+ config.allow_unverified_requests()+ ):+ return # Playground attachments are served from the developer's machine.+ try:+ infos = await asyncio.get_running_loop().getaddrinfo(+ host, parsed.port or 443, proto=socket.IPPROTO_TCP+ )+ except socket.gaierror as exc:+ raise ValueError(f"attachment host {host!r} does not resolve") from exc+ addresses = {info[4][0] for info in infos}+ if not addresses or any(_is_internal_host(address) for address in addresses):+ raise ValueError(f"attachment host {host!r} resolves inside our network")+++def _is_internal_host(host: str) -> bool:+ """True for a literal address inside a range we must never dial.++ Only literals are decided here: a name that *resolves* into one of these+ ranges still gets through, which is why the bearer-bearing path uses the+ stricter Connector allowlist instead of this check.+ """+ try:+ address = ipaddress.ip_address(host.strip("[]"))+ except ValueError:+ return False+ return (+ address.is_private+ or address.is_loopback+ or address.is_link_local+ or address.is_reserved+ or address.is_multicast+ or address.is_unspecified+ )+++def rewrite_loopback_for_container(service_url: str) -> str:+ """Point a loopback ``serviceUrl`` at the container's host instead.++ The Playground advertises itself as ``localhost``, which from inside Docker+ resolves to the container, so replies never reach it. Gated on local mode+ plus being in a container, and must run *after*+ :func:`verify_service_url`, which compares the URL as it arrived.+ """+ if not config.allow_unverified_requests() or not _in_container():+ return service_url+ parsed = urlparse(service_url)+ if (parsed.hostname or "").lower() not in _LOOPBACK_HOSTS:+ return service_url+ netloc = _CONTAINER_HOST_ALIAS+ if parsed.port:+ netloc = f"{netloc}:{parsed.port}"+ return urlunparse(parsed._replace(netloc=netloc))+++def _in_container() -> bool:+ """Whether this process is running inside a Docker container."""+ return os.path.exists("/.dockerenv")+++def _bearer_token(authorization: str | None) -> str:+ if not authorization:+ raise TeamsAuthError("missing Authorization header")+ scheme, _, token = authorization.partition(" ")+ if scheme.lower() != "bearer" or not token.strip():+ raise TeamsAuthError("Authorization header is not a bearer token")+ return token.strip()diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/color.png b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/color.pngnew file mode 100644index 0000000000..1d57355199Binary files /dev/null and b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/color.png differdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/commands.pynew file mode 100644index 0000000000..25125623d2--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/commands.py@@ -0,0 +1,132 @@+"""Teams bot commands — /setup, /help, /unlink.++Policy comes from the shared ``command_core``; this module owns only Teams'+transport. Teams has no first-class slash-command surface for bots: commands+arrive as ordinary message text (optionally after an @mention of the bot,+which the adapter has already stripped), and replies render as a normal+message with an Adaptive Card button.+"""++import logging+from typing import TYPE_CHECKING, Any, Optional++from backend.copilot.bot.bot_backend import BotBackend+from backend.copilot.bot.command_core import CommandReply, setup_reply, unlink_reply++if TYPE_CHECKING:+ from .adapter import TeamsAdapter++logger = logging.getLogger(__name__)++_HELP_TEXT = (+ "**AutoGPT for Teams**\n"+ "- Add me to a team, then @mention me to run a command: a bare /setup\n"+ " in a channel never reaches me, but `@AutoGPT /setup` links the team.\n"+ "- @mention me in a channel to chat; I'll reply in a thread.\n"+ "- Message me directly to chat with your personal AutoGPT account.\n"+ "- Run /unlink to manage your linked account and teams."+)++_KNOWN_COMMANDS = {"setup", "help", "unlink"}+++def parse_command(text: str) -> Optional[str]:+ """Return the command name when ``text`` is one of ours, else None.++ The adapter strips the bot's @mention before this runs, so a channel+ message reads as a bare ``/setup`` exactly like a DM does.+ """+ stripped = text.strip()+ if not stripped.startswith("/"):+ return None+ command = stripped.split()[0][1:].casefold()+ return command if command in _KNOWN_COMMANDS else None+++async def handle(+ api: BotBackend,+ adapter: "TeamsAdapter",+ activity: dict[str, Any],+ command: str,+) -> None:+ """Run ``command`` and render its reply into the conversation."""+ conversation = activity.get("conversation") or {}+ conversation_id = conversation.get("id") or ""+ if not conversation_id:+ return++ if command == "help":+ reply = CommandReply(text=_HELP_TEXT)+ elif command == "unlink":+ reply = unlink_reply()+ else:+ reply = await _setup(api, adapter, activity, conversation_id)++ if reply.button_label and reply.button_url:+ await adapter.send_link(+ conversation_id, reply.text, reply.button_label, reply.button_url+ )+ else:+ await adapter.send_message(conversation_id, reply.text)+++async def _setup(+ api: BotBackend,+ adapter: "TeamsAdapter",+ activity: dict[str, Any],+ conversation_id: str,+) -> CommandReply:+ """Link the team this command came from.++ Teams' unit of installation is the team, so /setup in a channel links the+ team. In a personal chat there is no team to link — the DM link is made+ from the Bots settings page instead.+ """+ channel_data = activity.get("channelData") or {}+ team = channel_data.get("team") or {}+ team_id = team.get("id")+ if not team_id:+ return CommandReply(+ text=(+ "Run /setup from a channel in the team you want to link. "+ "To chat with me privately, link your account from the Bots "+ "page in AutoGPT settings."+ )+ )++ sender = activity.get("from") or {}+ return await setup_reply(+ api,+ platform="teams",+ server_noun="team",+ platform_server_id=team_id,+ platform_user_id=sender.get("id") or "",+ platform_username=sender.get("name") or "",+ server_name=await _team_name(adapter, activity, team),+ channel_id=conversation_id,+ )+++async def _team_name(+ adapter: "TeamsAdapter", activity: dict[str, Any], team: dict[str, Any]+) -> str:+ """The team's display name, asking the Connector when the activity omits it.++ Teams stamps ``channelData.team.name`` onto install and conversation-update+ activities but not onto the message that carries /setup, so relying on the+ activity alone stores an empty name and the settings page can only show the+ raw thread id.+ """+ name = team.get("name") or ""+ if name:+ return name+ service_url = activity.get("serviceUrl") or ""+ team_id = team.get("id") or ""+ if not service_url or not team_id:+ return ""+ try:+ details = await adapter.client.get_team_details(service_url, team_id)+ except Exception:+ logger.warning("Could not resolve the Teams team name", exc_info=True)+ return ""+ return (details or {}).get("name") or ""diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/config.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/config.pynew file mode 100644index 0000000000..0e89f3a5df--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/config.py@@ -0,0 +1,145 @@+"""Microsoft Teams-specific configuration.++One bot registration serves every tenant conversation. Unlike Slack there is+no per-workspace install token: Teams routes everything through the Bot+Connector, and the bot authenticates itself with an Entra app credential.++Three secrets are required, not two. This adapter mints its outbound token+with a client-credentials grant against a *tenant* authority —+``https://login.microsoftonline.com/{TENANT_ID}/...`` — so the tenant ID is+part of the credential rather than an optional extra, and omitting it is the+single most common cause of 401s from the Connector.++That requirement is about the Azure **Bot** resource, which since 2025-07-31+must be created as Single Tenant or with a user-assigned managed identity.+The Entra **app registration** behind it has its own, separate audience+setting: this adapter does not require that to be single-tenant, so do not+narrow an existing registration on account of this note — doing so would cut+off any other integration that relies on it serving external tenants.++Registration checklist (once per environment — dev and prod need separate+registrations because a bot has exactly ONE messaging endpoint):+- Create the bot (either an Azure Bot resource, or ``teams app create`` from+ the Teams Developer CLI for a Teams-managed registration that needs no+ Azure subscription).+- Point its messaging endpoint at+ ``<PLATFORM_BASE_URL>/api/copilot-webhooks/teams/messages``.+- Enable the Microsoft Teams channel.+- Sideload the app package (see ``manifest.json``) into the tenant; the+ tenant must have custom app upload enabled.+"""++from backend.util.settings import AppEnvironment, Settings+++def get_app_id() -> str:+ """The bot's Entra application (client) ID.++ Doubles as the expected ``aud`` claim on inbound Connector tokens and as+ ``bots[0].botId`` in the Teams app manifest — the manifest and this value+ must agree or Teams silently routes nothing.+ """+ return Settings().secrets.microsoft_client_id+++def get_app_password() -> str:+ """The Entra client secret used to mint outbound Connector tokens."""+ return Settings().secrets.microsoft_client_secret+++def get_tenant_id() -> str:+ """The tenant the single-tenant bot registration belongs to."""+ return Settings().secrets.microsoft_tenant_id+++def is_configured() -> bool:+ """Whether the adapter should be mounted.++ All three credentials, or the local Playground bypass — which needs no+ credentials because nothing is authenticated in that mode.++ The adapter factory (``build_webhook_adapters``) calls this directly; the+ copilot tool's availability gate mirrors the credential check WITHOUT the+ bypass, because outbound posting must mint a real Connector token — see+ ``chat_platform._any_chat_platform_configured``.+ """+ if allow_unverified_requests():+ return True+ return bool(get_app_id() and get_app_password() and get_tenant_id())+++def allow_unverified_requests() -> bool:+ """Local-dev escape hatch for the Microsoft 365 Agents Playground.++ The Playground simulates Teams without a tenant, tunnel or registration,+ but it sends activities with **no Bot Connector token** — so accepting its+ traffic means accepting unauthenticated requests on a public route.++ Guarded twice on purpose: the opt-in flag alone is not enough, the process+ must also be running as ``app_env=local``. A deployed environment is+ ``dev``/``prod``, so the bypass cannot activate there even if the flag is+ set by mistake.+ """+ settings = Settings()+ return (+ settings.config.app_env == AppEnvironment.LOCAL+ and settings.config.autopilot_bot_teams_allow_unverified+ )+++# Teams imposes no documented per-message character limit; the real ceiling is+# a ~100KB UTF-16 payload for the whole activity. Our contract is+# character-based, so this is a deliberate choice well inside that budget:+# 8000 chars is 16KB of UTF-16 text, leaving ample room for activity JSON+# overhead, and keeps single messages readable in the Teams client.+MAX_MESSAGE_LENGTH = 8000++# Flush streamed replies a little under the cap so the boundary splitter can+# reach a natural break without overshooting.+CHUNK_FLUSH_AT = 7000++# Inbound-only ceiling: how much of a user-uploaded file we will download and+# ingest into the workspace.+MAX_ATTACHMENT_BYTES = 4 * 1024 * 1024++# Outbound ceiling. A bot message activity is capped at ~28KB TOTAL, and the+# only single-shot file delivery is a base64 data URI inside that activity+# (~1.37x inflation + JSON overhead), so only genuinely small images can be+# inlined. Anything larger must go out as a link.+INLINE_IMAGE_BYTES = 16 * 1024++# Teams threads have no titles. The shared thread-naming logic still clamps+# candidate names against this, so any sane value satisfies the contract.+MAX_THREAD_NAME_LENGTH = 128++# A Teams typing indicator expires after ~3s; refresh just inside that.+TYPING_REFRESH_SECONDS = 2.0++# First delivery wins, per activity id. Covers Connector redeliveries and —+# because the inbound token does not sign the body — replays of a captured+# request, which stay valid for the token's ~1h lifetime plus clock skew.+ACTIVITY_DEDUPE_TTL_SECONDS = 75 * 60++# Inbound activities are signed by the Bot Connector, whose keys are published+# here. Discovery document -> jwks_uri -> signing keys.+OPENID_METADATA_URL = (+ "https://login.botframework.com/v1/.well-known/openidconfiguration"+)++# Every inbound Connector token must carry exactly this issuer.+TOKEN_ISSUER = "https://api.botframework.com"++# Outbound tokens are minted for this audience/scope.+CONNECTOR_SCOPE = "https://api.botframework.com/.default"++# ``serviceUrl`` arrives inside the (authenticated) activity and is where we+# send replies — i.e. it is attacker-influenced data that we then attach a+# bearer token to. Only HTTPS to these Connector hosts is ever dialled. Kept+# deliberately narrow: broad zones like ``.trafficmanager.net`` are+# customer-registerable (any Azure account can mint <name>.trafficmanager.net),+# which would defeat the point of the allowlist.+ALLOWED_SERVICE_URL_HOSTS = ("smba.trafficmanager.net",)+ALLOWED_SERVICE_URL_SUFFIXES = (+ ".botframework.com",+ ".botframework.azure.us",+)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/manifest.json b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/manifest.jsonnew file mode 100644index 0000000000..3b4a932f9e--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/manifest.json@@ -0,0 +1,81 @@+{+ "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.17/MicrosoftTeams.schema.json",+ "manifestVersion": "1.17",+ "version": "1.0.0",+ "id": "<AZURE_BOT_APP_ID>",+ "developer": {+ "name": "AutoGPT",+ "websiteUrl": "https://agpt.co",+ "privacyUrl": "https://agpt.co/legal/platform-privacy-policy",+ "termsOfUseUrl": "https://agpt.co/legal/platform-terms-of-use"+ },+ "icons": {+ "color": "color.png",+ "outline": "outline.png"+ },+ "name": {+ "short": "AutoGPT",+ "full": "AutoGPT"+ },+ "description": {+ "short": "Your AutoGPT agent in Microsoft Teams",+ "full": "AutoGPT brings your AutoGPT account into Microsoft Teams. @mention AutoGPT in a channel or chat with it directly to give it work. Mention it with /setup in a channel to link the team to your AutoGPT account, or chat with it directly to link your own personal account. Usage is billed to the linked AutoGPT account, and you can unlink at any time from Settings -> Bots."+ },+ "accentColor": "#1A1A1A",+ "bots": [+ {+ "botId": "<AZURE_BOT_APP_ID>",+ "scopes": [+ "personal",+ "team"+ ],+ "isNotificationOnly": false,+ "supportsFiles": true,+ "commandLists": [+ {+ "scopes": [+ "personal"+ ],+ "commands": [+ {+ "title": "/setup",+ "description": "How to link your AutoGPT account"+ },+ {+ "title": "/help",+ "description": "How to use AutoGPT in Teams"+ },+ {+ "title": "/unlink",+ "description": "Manage your linked AutoGPT account"+ }+ ]+ },+ {+ "scopes": [+ "team"+ ],+ "commands": [+ {+ "title": "/setup",+ "description": "Link this team to an AutoGPT account"+ },+ {+ "title": "/help",+ "description": "How to use AutoGPT in Teams"+ },+ {+ "title": "/unlink",+ "description": "Manage linked teams from your settings"+ }+ ]+ }+ ]+ }+ ],+ "permissions": [+ "identity",+ "messageTeamMembers"+ ],+ "validDomains": []+}diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/outline.png b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/outline.pngnew file mode 100644index 0000000000..60d48d2820Binary files /dev/null and b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/outline.png differdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/text.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/text.pynew file mode 100644index 0000000000..ac3f56fc13--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/text.py@@ -0,0 +1,114 @@+"""Convert the bot's canonical CommonMark output into what Teams renders.++Teams supports a noticeably smaller markdown subset than Discord or Telegram:+headings, tables and horizontal rules are simply **not rendered at all** and+leak through as literal ``#``/``|`` characters. LLM output uses all three+constantly, so they are downgraded here rather than shipped raw.++Bold, italic, inline code, fenced code and links render fine and pass through+untouched.+"""++import re+from typing import Any++_FENCE_RE = re.compile(r"```.*?```", re.DOTALL)+_HEADING_RE = re.compile(r"^[ \t]{0,3}#{1,6}[ \t]+(.+?)[ \t]*#*$", re.MULTILINE)+_RULE_RE = re.compile(r"^[ \t]{0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$", re.MULTILINE)+_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")+_TABLE_ROW_RE = re.compile(r"^[ \t]*\|.*\|[ \t]*$")++# Placeholder for stashed code so downgrades never rewrite code content.+_STASH = "\x00{}\x00"+++def to_teams_markdown(text: str) -> str:+ """Downgrade canonical CommonMark to Teams' rendered subset."""+ # NUL is the stash delimiter below, so input carrying one could otherwise+ # steer a restore into the wrong position.+ text = text.replace("\x00", "")+ stashed: list[str] = []++ def _stash(match: re.Match[str]) -> str:+ stashed.append(match.group(0))+ return _STASH.format(len(stashed) - 1)++ text = _FENCE_RE.sub(_stash, text)++ # Headings render as literal '#' in Teams — bold is the closest thing that+ # survives on every client.+ text = _HEADING_RE.sub(lambda m: f"**{m.group(1).strip()}**", text)+ # Horizontal rules render as literal dashes.+ text = _RULE_RE.sub("", text)+ # Inline images are not rendered in message text; keep them reachable.+ text = _IMAGE_RE.sub(lambda m: f"[{m.group(1) or 'image'}]({m.group(2)})", text)+ text = _fence_tables(text)++ for index, original in enumerate(stashed):+ text = text.replace(_STASH.format(index), original)+ return text+++def _fence_tables(text: str) -> str:+ """Wrap markdown tables in a code fence so they keep their alignment.++ Teams renders no table markup at all, so an unfenced table collapses into+ an unreadable run of pipes. Monospace preserves the columns.+ """+ lines = text.split("\n")+ out: list[str] = []+ block: list[str] = []++ def flush() -> None:+ if not block:+ return+ # A single piped line is more likely prose than a table.+ if len(block) > 1:+ out.extend(["```", *block, "```"])+ else:+ out.extend(block)+ block.clear()++ for line in lines:+ if _TABLE_ROW_RE.match(line):+ block.append(line)+ continue+ flush()+ out.append(line)+ flush()+ return "\n".join(out)+++def mention_token(display_name: str, _user_id: str) -> str:+ """Teams mention markup, for ``resolve_mentions``' ``render_token``.++ The tag alone does nothing — a mention only pings when a matching entity+ accompanies the activity (see :func:`mention_entities`). That is why LLM+ output containing a literal ``<at>…</at>`` cannot forge a ping.+ """+ return f"<at>{display_name}</at>"+++def mention_entities(+ pinged_user_ids: list[str],+ mentionable_users: tuple[tuple[str, str], ...],+) -> list[dict[str, Any]]:+ """Build the ``entities`` array that makes rendered mentions actually ping.++ Only ids that ``resolve_mentions`` allowlisted are included, so the entity+ array inherits the shared mention-safety policy rather than restating it.+ """+ names_by_id = {user_id: name for name, user_id in mentionable_users}+ entities: list[dict[str, Any]] = []+ for user_id in pinged_user_ids:+ name = names_by_id.get(user_id)+ if not name:+ continue+ entities.append(+ {+ "type": "mention",+ "text": mention_token(name, user_id),+ "mentioned": {"id": user_id, "name": name},+ }+ )+ return entitiesdiff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.pyindex 65eaf3e3e3..3ebd4f9f9f 100644--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py@@ -14,6 +14,8 @@ from fastapi import FastAPIfrom .adapters.base import WebhookAdapterfrom .adapters.slack import config as slack_configfrom .adapters.slack.adapter import SlackAdapter+from .adapters.teams import config as teams_config+from .adapters.teams.adapter import TeamsAdapterfrom .adapters.telegram import config as telegram_configfrom .adapters.telegram.adapter import TelegramAdapterfrom .bot_backend import BotBackend@@ -64,4 +66,10 @@ def build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:if telegram_config.get_bot_token() and telegram_config.get_webhook_secret():adapters.append(TelegramAdapter(api))logger.info("Telegram adapter enabled")+ # Teams: the tenant id is part of the credential, not optional — a+ # single-tenant registration mints its outbound token against its own+ # tenant authority.+ if teams_config.is_configured():+ adapters.append(TeamsAdapter(api))+ logger.info("Teams adapter enabled")return adaptersdiff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.pyindex 62b47e5218..f443de8cfb 100644--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py@@ -9,6 +9,7 @@ from .webhook_routes import build_webhook_adapters, register_webhook_adapters_SLACK_CFG = "backend.copilot.bot.webhook_routes.slack_config"_TELEGRAM_CFG = "backend.copilot.bot.webhook_routes.telegram_config"+_TEAMS_CFG = "backend.copilot.bot.webhook_routes.teams_config"def test_build_webhook_adapters_empty_without_creds():@@ -16,6 +17,7 @@ def test_build_webhook_adapters_empty_without_creds():patch(f"{_SLACK_CFG}.get_bot_token", return_value=""),patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value=""),+ patch(f"{_TEAMS_CFG}.is_configured", return_value=False),):assert build_webhook_adapters(MagicMock()) == []@@ -26,6 +28,7 @@ def test_build_webhook_adapters_includes_slack_when_configured():patch(f"{_SLACK_CFG}.get_bot_token", return_value="xoxb-x"),patch(f"{_SLACK_CFG}.get_signing_secret", return_value="secret"),patch("backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"),+ patch(f"{_TEAMS_CFG}.is_configured", return_value=False),):adapters = build_webhook_adapters(MagicMock())assert len(adapters) == 1@@ -38,6 +41,7 @@ def test_build_webhook_adapters_includes_telegram_when_configured():patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value="123:abc"),patch(f"{_TELEGRAM_CFG}.get_webhook_secret", return_value="s3cret"),+ patch(f"{_TEAMS_CFG}.is_configured", return_value=False),):adapters = build_webhook_adapters(MagicMock())assert len(adapters) == 1@@ -50,10 +54,23 @@ def test_telegram_needs_both_token_and_webhook_secret():patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value="123:abc"),patch(f"{_TELEGRAM_CFG}.get_webhook_secret", return_value=""),+ patch(f"{_TEAMS_CFG}.is_configured", return_value=False),):assert build_webhook_adapters(MagicMock()) == []+def test_build_webhook_adapters_includes_teams_when_configured():+ with (+ patch(f"{_SLACK_CFG}.get_bot_token", return_value=""),+ patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),+ patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value=""),+ patch(f"{_TEAMS_CFG}.is_configured", return_value=True),+ ):+ adapters = build_webhook_adapters(MagicMock())+ assert len(adapters) == 1+ assert adapters[0].platform_name == "teams"++def test_register_webhook_adapters_wires_each_adapter():app = FastAPI()adapter = MagicMock(spec=WebhookAdapter)diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform.pyindex 2abe5d587e..89784a32a6 100644--- a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform.py@@ -1,8 +1,9 @@"""Tools for the copilot to post to a linked chat platform on the user's behalf.-``post_to_chat_platform`` lets AutoPilot send a standalone message or open a new-thread in a channel of a chat platform (Discord, Slack, or Telegram) the user-has linked. The headline use case is *scheduled* output: "every Monday post an+``post_to_chat_platform`` lets AutoPilot send a standalone message or open a+new thread in a channel of a chat platform (Discord, Slack, Telegram, or+Microsoft Teams) the user has linked. The headline use case is *scheduled*+output: "every Monday post anupdate in #standup" — AutoPilot schedules a follow-up turn (via``schedule_followup``) whose message instructs it to post, and at fire time itcalls this tool.@@ -41,7 +42,7 @@ logger = logging.getLogger(__name__)# Chat platforms with a wired bridge adapter. Add a value here (and its bot# token check in ``_any_chat_platform_configured``) when a new adapter ships —# the tool surface stays the same.-SUPPORTED_PLATFORMS: tuple[str, ...] = ("discord", "slack", "telegram")+SUPPORTED_PLATFORMS: tuple[str, ...] = ("discord", "slack", "telegram", "teams")# Telegram's Bot API can't enumerate a bot's chats, so name→ID resolution is# impossible there — posts must target a linked group's numeric chat ID.@@ -50,6 +51,14 @@ _TELEGRAM_TARGETING_HINT = ("group that's linked to this account.")+# Teams offers no channel enumeration either (needs a Graph permission the bot+# doesn't hold), and without it there is no channel→team mapping to authorize+# a raw conversation id against — so channel posting is DM-only for now.+_TEAMS_TARGETING_HINT = (+ "Teams channels can't be targeted for proactive posts yet — "+ "the bot can only deliver to users who linked their personal chat."+)+# Maps the bridge's stable DeliveryResult error codes to user-facing text the# model can relay or act on. Anything unmapped falls back to the raw code._ERROR_MESSAGES: dict[str, str] = {@@ -116,8 +125,18 @@ def _any_chat_platform_configured() -> bool:secrets.autopilot_bot_telegram_tokenand secrets.autopilot_bot_telegram_webhook_secret)+ # Stricter than teams_config.is_configured(): the Playground bypass mounts+ # the inbound route without credentials, but posting needs a real token.+ teams_configured = bool(+ secrets.microsoft_client_id+ and secrets.microsoft_client_secret+ and secrets.microsoft_tenant_id+ )return bool(- secrets.autopilot_bot_discord_token or slack_configured or telegram_configured+ secrets.autopilot_bot_discord_token+ or slack_configured+ or telegram_configured+ or teams_configured)@@ -132,9 +151,24 @@ def _error_message(code: str | None, platform_name: str = "") -> str:# The generic messages steer toward list_chat_platform_channels,# which can't help on Telegram — replace them entirely.return f"That chat could not be resolved. {_TELEGRAM_TARGETING_HINT}"+ if platform_name == "teams" and code in (+ "channel_not_found",+ "ambiguous_channel",+ "not_authorized",+ ):+ return f"That channel could not be posted to. {_TEAMS_TARGETING_HINT}"return message+def _default_target(platform_name: str) -> str:+ """Teams only delivers to a linked personal chat, so that is its default.++ Leaving the generic "channel" default in place would send every Teams call+ that omits ``target`` on a doomed round-trip to the bridge.+ """+ return "dm" if platform_name == "teams" else "channel"++def _platform_param() -> dict[str, Any]:return {"type": "string",@@ -161,12 +195,13 @@ class PostToChatPlatformTool(BaseTool):@propertydef description(self) -> str:return (- "Post to a linked chat platform (Discord, Slack, or Telegram). "- "target='dm' sends to the user's own DMs with the bot. "- "mode='thread' opens a thread (needs thread_name; "+ "Post to a linked chat platform (Discord, Slack, Telegram or "+ "Microsoft Teams). target='dm' sends to the user's own DMs with "+ "the bot. mode='thread' opens a thread (needs thread_name; ""channels only). 'channel' is a name (#standup) or numeric ID — "- "on Telegram, a linked group's numeric chat ID. Pair with "- "schedule_followup for recurring posts; call "+ "on Telegram, a linked group's numeric chat ID. Teams supports "+ "target='dm' only; its channels cannot be posted to yet. Pair "+ "with schedule_followup for recurring posts; call ""list_chat_platform_channels if a Discord/Slack channel won't ""resolve.")@@ -228,13 +263,19 @@ class PostToChatPlatformTool(BaseTool):error="unsupported_platform",session_id=session_id,)- target: str = kwargs.get("target") or "channel"+ target: str = kwargs.get("target") or _default_target(platform_name)if target not in ("channel", "dm"):return ErrorResponse(message="`target` must be 'channel' or 'dm'.",error="invalid_target",session_id=session_id,)+ if platform_name == "teams" and target != "dm":+ return ErrorResponse(+ message=_TEAMS_TARGETING_HINT,+ error="unsupported_target",+ session_id=session_id,+ )channel: str | None = kwargs.get("channel")content: str | None = kwargs.get("content")mode: str = kwargs.get("mode") or "message"@@ -296,7 +337,7 @@ class PostToChatPlatformTool(BaseTool):error="unsupported_platform",session_id=session_id,)- target: str = kwargs.get("target") or "channel"+ target: str = kwargs.get("target") or _default_target(platform_name)channel: str = kwargs.get("channel") or ""content: str = kwargs["content"]mode: str = kwargs.get("mode") or "message"@@ -357,8 +398,9 @@ class ListChatPlatformChannelsTool(BaseTool):"List server channels the bot can post to on Discord or Slack — ""use to resolve a channel name to an ID before ""post_to_chat_platform. Telegram can't list channels (use a "- "linked group's numeric chat ID). The user's own DMs never "- "appear here — use target='dm' instead."+ "linked group's numeric chat ID) and neither can Teams (post to "+ "target='dm'). The user's own DMs never appear here — use "+ "target='dm' instead.")@property@@ -416,6 +458,8 @@ class ListChatPlatformChannelsTool(BaseTool):)elif platform_name == "telegram":message = _TELEGRAM_TARGETING_HINT+ elif platform_name == "teams":+ message = _TEAMS_TARGETING_HINTelse:message = (f"No postable {platform_name} channels found. Link a server via "diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.pyindex 4c0f81f897..c29e020f55 100644--- a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py@@ -212,6 +212,54 @@ async def test_post_dm_happy_path_needs_no_channel(session):bridge.send_message_to_channel.assert_not_awaited()+async def test_teams_post_defaults_to_the_users_dm(session):+ # Teams cannot be targeted by channel, so omitting `target` must not send+ # the call down the channel path just to have the bridge reject it.+ bridge = _bridge()+ bridge.send_dm_to_user.return_value = DeliveryResult(+ ok=True, kind="dm", channel_id="19:dm", ref_id="m1"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, platform="teams", content="morning brief"+ )+ assert isinstance(result, ChatPlatformPostedResponse)+ bridge.send_dm_to_user.assert_awaited_once()+ bridge.send_message_to_channel.assert_not_awaited()+++async def test_teams_rejects_an_explicit_channel_target(session):+ bridge = _bridge()+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER,+ session=session,+ platform="teams",+ target="channel",+ channel="General",+ content="hi",+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "unsupported_target"+ bridge.send_message_to_channel.assert_not_awaited()+++async def test_other_platforms_still_default_to_channel(session):+ bridge = _bridge()+ bridge.send_message_to_channel.return_value = DeliveryResult(+ ok=True, kind="message", channel_id="c1", ref_id="m1"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="#standup", content="hi"+ )+ assert isinstance(result, ChatPlatformPostedResponse)+ bridge.send_message_to_channel.assert_awaited_once()++@pytest.mark.asyncioasync def test_post_dm_without_link_maps_error(session):bridge = _bridge()@@ -362,6 +410,9 @@ def _secrets(**overrides) -> MagicMock:secrets.autopilot_bot_slack_client_secret = ""secrets.autopilot_bot_telegram_token = ""secrets.autopilot_bot_telegram_webhook_secret = ""+ secrets.microsoft_client_id = ""+ secrets.microsoft_client_secret = ""+ secrets.microsoft_tenant_id = ""for key, value in overrides.items():setattr(secrets, key, value)return secrets@@ -398,6 +449,24 @@ def _secrets(**overrides) -> MagicMock:},True,),+ # Teams needs all three; posting has to mint a real Connector token,+ # so a partial registration must not enable the tool.+ ({"microsoft_client_id": "app"}, False),+ (+ {+ "microsoft_client_id": "app",+ "microsoft_client_secret": "pw",+ },+ False,+ ),+ (+ {+ "microsoft_client_id": "app",+ "microsoft_client_secret": "pw",+ "microsoft_tenant_id": "tenant",+ },+ True,+ ),],)def test_configured_gate_mirrors_adapter_gates(overrides, expected):diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex c261fc4e34..e17a858dcb 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -631,6 +631,15 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):description="What environment to behave as: local or cloud",)+ autopilot_bot_teams_allow_unverified: bool = Field(+ default=False,+ description="Local dev only: accept Teams activities that carry no Bot "+ "Connector token, so the Microsoft 365 Agents Playground can drive the "+ "bot without a Teams tenant. Ignored unless app_env is 'local' — it "+ "disables inbound authentication and must never take effect on a "+ "deployed environment.",+ )+execution_event_bus_name: str = Field(default="execution_event",description="Name of the event bus",@@ -895,6 +904,23 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):description="The bot's public @username (without the @) — used to ""build the t.me add-to-group link on the Bots settings page.",)+ microsoft_client_id: str = Field(+ default="",+ description="Entra application (client) ID, shared by Microsoft "+ "integrations. Set together with the client secret and tenant ID to "+ "mount the Teams bot adapter on the main API.",+ )+ microsoft_client_secret: str = Field(+ default="",+ description="Entra client secret for the shared Microsoft app, used "+ "by the Teams bot to mint outbound Bot Connector tokens.",+ )+ microsoft_tenant_id: str = Field(+ default="",+ description="Tenant the Entra app belongs to. Required for the Teams "+ "bot: single-tenant bots mint tokens against their own tenant "+ "authority, and new registrations can no longer be multi-tenant.",+ )smtp_server: str = Field(default="", description="SMTP server IP")smtp_port: str = Field(default="", description="SMTP server port")diff --git a/autogpt_platform/backend/poetry.lock b/autogpt_platform/backend/poetry.lockindex c324886a6c..7b72366f4f 100644--- a/autogpt_platform/backend/poetry.lock+++ b/autogpt_platform/backend/poetry.lock@@ -8659,4 +8659,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt[metadata]lock-version = "2.1"python-versions = ">=3.10,<3.14"-content-hash = "6dec3b5359b806ce23abc81506d4d2e6f8e7e47fa1637672996fecb7953ec113"+content-hash = "e8bab234faec1b6b792df40152f60681295cdfaa7aed30344a4b94b4df7775c9"diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.tomlindex 1acf9c57a3..469a061782 100644--- a/autogpt_platform/backend/pyproject.toml+++ b/autogpt_platform/backend/pyproject.toml@@ -60,6 +60,7 @@ prometheus-client = "^0.24.1"prometheus-fastapi-instrumentator = "^7.0.0"psutil = "^7.0.0"psycopg2-binary = "^2.9.10"+pyjwt = "^2.13.0"pydantic = { extras = ["email"], version = "^2.12.5" }pydantic-settings = "^2.12.0"pywebpush = "^2.3"diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.tsindex b95ac062fc..95d4af0142 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.ts@@ -11,6 +11,7 @@ export const PLATFORM_OPTIONS = [{ value: "DISCORD", label: "Discord" },{ value: "SLACK", label: "Slack" },{ value: "TELEGRAM", label: "Telegram" },+ { value: "TEAMS", label: "Microsoft Teams" },];export function formatNumber(value: number | null | undefined): string {