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/copilot-bot): multi-workspace Slack install via OAuth (#13514)
Bentlyda1fbe00f963
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 534bbc373a..4b13d27336 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -227,9 +227,14 @@ PLATFORM_LINK_BASE_URL=http://localhost:3000/link# CoPilot chat-platform bridge (Discord/Telegram/Slack)# Uses FRONTEND_BASE_URL (above) for link confirmation pages.AUTOPILOT_BOT_DISCORD_TOKEN=-# Slack adapter — set BOTH to mount the Slack webhook routes on the main API.-AUTOPILOT_BOT_SLACK_TOKEN=+# Slack adapter — set the signing secret + client id/secret to mount the Slack+# webhook routes and the multi-workspace "Add to Slack" install flow. The static+# token is an optional fallback for the app's own (dev) workspace; installs from+# other workspaces obtain their own per-team token via OAuth.+AUTOPILOT_BOT_SLACK_CLIENT_ID=+AUTOPILOT_BOT_SLACK_CLIENT_SECRET=AUTOPILOT_BOT_SLACK_SIGNING_SECRET=+AUTOPILOT_BOT_SLACK_TOKEN=# 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 351b8a00d3..7bea0dc182 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,12 @@ 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.util.settings import Settings++# Backend route that starts the Slack "Add to Slack" OAuth install (kept in sync+# with slack.oauth.INSTALL_PATH; hardcoded here to avoid importing the heavier+# oauth module — which pulls in the Slack SDK + Prisma — into this metadata file).+_SLACK_INSTALL_PATH = "/api/copilot-webhooks/slack/install"class PlatformMeta(BaseModel):@@ -47,20 +53,31 @@ def _discord_meta() -> PlatformMeta:def _slack_meta() -> PlatformMeta:- # Slack has no Discord-style one-click invite for a self-hosted app — it's- # installed per-workspace via the app manifest, then linked with /setup — so- # there's no add_bot_url. Enabled once both the token and signing secret are- # set (the same gate the webhook adapter mounts on).- enabled = bool(slack_config.get_bot_token() and slack_config.get_signing_secret())+ # Enabled once the signing secret plus credentials are set — the same gate+ # the webhook adapter mounts on. "Add to Slack" needs the OAuth app creds+ # (multi-workspace install); with only a static token there's no install URL+ # (single-workspace mode), so the button is hidden.+ oauth_ready = bool(+ slack_config.get_client_id() and slack_config.get_client_secret()+ )+ has_credentials = oauth_ready or bool(slack_config.get_bot_token())+ enabled = bool(slack_config.get_signing_secret() and has_credentials)return PlatformMeta(platform="SLACK",display_name="Slack",icon="slack.png",enabled=enabled,- add_bot_url=None,+ add_bot_url=_slack_install_url() if (enabled and oauth_ready) else None,)+def _slack_install_url() -> str | None:+ base = Settings().config.platform_base_url.rstrip("/")+ if not base:+ return None+ return f"{base}{_SLACK_INSTALL_PATH}"++def _discord_invite_url() -> str | None:client_id = discord_config.get_client_id()if not client_id: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 f1e52a0ec3..4f7c56cae6 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@@ -8,9 +8,18 @@ _REG = "backend.api.features.platform_linking.registry"def _slack_off():- # Slack disabled unless a test opts in — keeps the Discord assertions from- # depending on whatever Slack creds happen to be in the environment.- return patch(f"{_REG}.slack_config.get_bot_token", return_value="")+ # Slack disabled unless a test opts in — enabled always requires the signing+ # secret, so clearing it hides Slack regardless of whatever token / OAuth+ # creds happen to be in the environment.+ return patch(f"{_REG}.slack_config.get_signing_secret", return_value="")+++def _slack_oauth_off():+ # Force single-workspace mode: no "Add to Slack" URL even when Slack is on.+ return (+ patch(f"{_REG}.slack_config.get_client_id", return_value=""),+ patch(f"{_REG}.slack_config.get_client_secret", return_value=""),+ )def _discord_off():@@ -51,11 +60,16 @@ def test_discord_appears_without_invite_url_when_client_id_missing():assert platforms[0].add_bot_url is None-def test_slack_appears_when_token_and_signing_secret_set():+def test_slack_appears_in_single_workspace_mode_without_install_url():+ # Static token + signing secret only (no OAuth app creds) → Slack is enabled+ # but there's no multi-workspace "Add to Slack" button.+ oauth_id_off, oauth_secret_off = _slack_oauth_off()with (_discord_off(),patch(f"{_REG}.slack_config.get_bot_token", return_value="xoxb-x"),patch(f"{_REG}.slack_config.get_signing_secret", return_value="secret"),+ oauth_id_off,+ oauth_secret_off,):platforms = enabled_platforms()@@ -64,10 +78,30 @@ def test_slack_appears_when_token_and_signing_secret_set():assert slack.enabled is Trueassert slack.display_name == "Slack"assert slack.icon == "slack.png"- # Slack has no one-click invite for a self-hosted app.assert slack.add_bot_url is None+def test_slack_add_to_slack_url_when_oauth_configured():+ with (+ _discord_off(),+ patch(f"{_REG}.slack_config.get_bot_token", return_value=""),+ patch(f"{_REG}.slack_config.get_signing_secret", return_value="secret"),+ patch(f"{_REG}.slack_config.get_client_id", return_value="cid"),+ patch(f"{_REG}.slack_config.get_client_secret", return_value="csecret"),+ patch(f"{_REG}.Settings") as settings,+ ):+ settings.return_value.config.platform_base_url = "https://backend.example"+ platforms = enabled_platforms()++ assert [p.platform for p in platforms] == ["SLACK"]+ slack = platforms[0]+ assert slack.enabled is True+ assert (+ slack.add_bot_url+ == "https://backend.example/api/copilot-webhooks/slack/install"+ )++def test_slack_hidden_when_signing_secret_missing():with (_discord_off(),@@ -78,11 +112,14 @@ def test_slack_hidden_when_signing_secret_missing():def test_both_platforms_when_both_configured():+ oauth_id_off, oauth_secret_off = _slack_oauth_off()with (patch(f"{_REG}.discord_config.get_bot_token", return_value="token"),patch(f"{_REG}.discord_config.get_client_id", return_value=""),patch(f"{_REG}.slack_config.get_bot_token", return_value="xoxb-x"),patch(f"{_REG}.slack_config.get_signing_secret", return_value="secret"),+ oauth_id_off,+ oauth_secret_off,):platforms = enabled_platforms()diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.pyindex c6ed48ae18..01742538d0 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py@@ -1,15 +1,23 @@-"""Slack adapter — webhook-based (Events API).+"""Slack adapter — webhook-based (Events API), multi-workspace.-Mounts inbound Events API + slash-command routes on the main backend API. All+Mounts inbound Events API + slash-command + OAuth-install routes on the main+backend API. Each installed workspace has its own bot token (obtained via the+"Add to Slack" OAuth flow, stored encrypted per team); every outbound call+resolves the right token from the workspace (team) the message came from. Allplatform-agnostic logic (attachment policy, mention allowlist, chunk splitting,history budgeting) comes from the shared layer; only Slack API calls and Slack'sevent/ID grammar live here.++The opaque ``channel_id`` the handler passes back into ``send_*`` therefore+carries the team: it is ``team|channel|thread_ts`` so a send can pick the+workspace's client without any extra lookup."""import asyncioimport jsonimport loggingimport re+import timefrom typing import Any, Optionalimport httpx@@ -30,8 +38,14 @@ from backend.copilot.bot.adapters.shared import InboundFile, collect_attachmentsfrom backend.copilot.bot.bot_backend import BotBackendfrom backend.copilot.bot.config import MAX_INBOUND_ATTACHMENTSfrom backend.copilot.bot.text import iter_chunks, resolve_mentions+from backend.data.bot_installs import (+ get_bot_install,+ is_install_revoked,+ revoke_bot_install,+)+from backend.platform_linking.models import Platform-from . import commands, config, signing+from . import commands, config, oauth, signingfrom .text import to_mrkdwnlogger = logging.getLogger(__name__)@@ -39,6 +53,9 @@ logger = logging.getLogger(__name__)EVENTS_PATH = "/api/copilot-webhooks/slack/events"COMMANDS_PATH = "/api/copilot-webhooks/slack/commands"+# Slack lifecycle events that end a workspace's install — revoke its token.+_UNINSTALL_EVENTS = {"app_uninstalled", "tokens_revoked"}+# Matches both `<@U123>` and `<@U123|displayname>` mention forms._USER_MENTION_RE = re.compile(r"<@(U[A-Z0-9]+)(?:\|[^>]+)?>")@@ -47,15 +64,23 @@ _USER_MENTION_RE = re.compile(r"<@(U[A-Z0-9]+)(?:\|[^>]+)?>")# resolver to tell an ID from a name._CHANNEL_ID_RE = re.compile(r"^[CGD][A-Z0-9]{7,}$")+# Cached per-workspace clients expire so a token replaced by a re-install (scope+# change / rotation) stops being used within this window on EVERY replica — the+# OAuth callback only evicts the replica that handled it.+_CLIENT_CACHE_TTL_SECONDS = 15 * 60+class SlackAdapter(WebhookAdapter):def __init__(self, api: BotBackend):self._api = api- self._client = AsyncWebClient(token=config.get_bot_token())self._on_message_callback: Optional[MessageCallback] = None- self._bot_user_id: Optional[str] = None- self._team_id: Optional[str] = None- self._user_name_cache: dict[str, str] = {}+ # Per-workspace caches, keyed by team_id. A workspace's client + bot user+ # id are resolved once from its stored install token and reused.+ self._clients: dict[str, AsyncWebClient] = {}+ self._client_cached_at: dict[str, float] = {}+ self._bot_user_ids: dict[str, str] = {}+ # User display names are workspace-scoped: keyed by (team_id, user_id).+ self._user_name_cache: dict[tuple[str, str], str] = {}# Strong-ref set so the GC doesn't drop fire-and-forget event tasks.self._event_tasks: set[asyncio.Task[None]] = set()@@ -95,6 +120,55 @@ class SlackAdapter(WebhookAdapter):def register_routes(self, app: FastAPI) -> None:app.add_api_route(EVENTS_PATH, self._handle_event_request, methods=["POST"])app.add_api_route(COMMANDS_PATH, self._handle_command_request, methods=["POST"])+ # Multi-workspace "Add to Slack" install + OAuth callback (no-op unless+ # the app's client id/secret are configured). A (re)install replaces the+ # workspace's token, so it must drop this replica's cached client.+ oauth.register_routes(app, on_installed=self._evict)++ # -- Per-workspace client resolution --++ async def _client_for(self, team_id: str) -> Optional[AsyncWebClient]:+ """Return a cached Slack client for ``team_id``, building it from the+ workspace's stored install token (or the static back-compat token).++ An empty ``team_id`` (e.g. a raw channel ref in a proactive post that+ carries no workspace) can't be looked up, so it falls straight through to+ the static single-workspace token. Returns ``None`` only when there is no+ usable token at all — the caller then can't respond, which is the correct+ outcome for an uninstalled workspace."""+ client = self._clients.get(team_id)+ if client is not None:+ cached_at = self._client_cached_at.get(team_id)+ if (+ cached_at is None+ or time.monotonic() - cached_at < _CLIENT_CACHE_TTL_SECONDS+ ):+ return client+ self._evict(team_id)+ install = await get_bot_install(Platform.SLACK, team_id) if team_id else None+ if install is None:+ # A workspace that explicitly uninstalled / revoked us gets NOTHING —+ # the static token belongs to the app's own workspace and must never+ # be used on a revoked one's behalf. Fallback is only for+ # never-installed refs (single-workspace mode, raw proactive refs).+ if team_id and await is_install_revoked(Platform.SLACK, team_id):+ return None+ token = config.get_bot_token()+ else:+ token = install.bot_token+ if not token:+ return None+ if install and install.bot_user_id:+ self._bot_user_ids[team_id] = install.bot_user_id+ client = AsyncWebClient(token=token)+ self._clients[team_id] = client+ self._client_cached_at[team_id] = time.monotonic()+ return client++ def _evict(self, team_id: str) -> None:+ self._clients.pop(team_id, None)+ self._client_cached_at.pop(team_id, None)+ self._bot_user_ids.pop(team_id, None)# -- Inbound --@@ -109,7 +183,7 @@ class SlackAdapter(WebhookAdapter):event = payload.get("event") or {}# The workspace (team) ID lives at the top level of the Events API# payload — it isn't reliably inside the event object — so thread it- # through for server_id resolution.+ # through for token + server_id resolution.team_id = payload.get("team_id")# Fire-and-forget so we ACK within Slack's 3s window.task = asyncio.create_task(self._dispatch_event(event, team_id))@@ -132,6 +206,13 @@ class SlackAdapter(WebhookAdapter):async def _dispatch_event(self, event: dict[str, Any], team_id: Optional[str] = None) -> None:+ # Workspace removed the app / revoked its token → drop its stored install+ # and cached client so we stop trying to use a dead token.+ if event.get("type") in _UNINSTALL_EVENTS:+ if team_id:+ self._evict(team_id)+ await revoke_bot_install(Platform.SLACK, team_id)+ returnif self._on_message_callback is None:return# Skip bot messages (including our own) to avoid reply loops.@@ -173,47 +254,48 @@ class SlackAdapter(WebhookAdapter):ts = event.get("ts")user = event.get("user")text = event.get("text") or ""- if not channel or not ts or not user:+ # team is required to resolve the workspace's token for the reply.+ team = event.get("team") or team_id+ if not channel or not ts or not user or not team:return Nonethread_ts = event.get("thread_ts")channel_type: ChannelType- target_channel_id: strif is_dm:channel_type = "dm"- target_channel_id = channelelif thread_ts:channel_type = "thread"- target_channel_id = _encode_target(channel, thread_ts)else:channel_type = "channel"- target_channel_id = channel+ target_channel_id = _encode_target(team, channel, thread_ts)- attachments, skipped = await self._extract_attachments(event)+ attachments, skipped = await self._extract_attachments(team, event)return MessageContext(platform="slack",channel_type=channel_type,# DMs bill to the user (no server); channel/thread need the workspace.- server_id=None if is_dm else (event.get("team") or team_id),+ server_id=None if is_dm else team,channel_id=target_channel_id,message_id=ts,user_id=user,- username=await self._user_display_name(user),- text=await self._strip_mentions(text),+ username=await self._user_display_name(team, user),+ text=await self._strip_mentions(team, text),bot_mentioned=bot_mentioned,- mentionable_users=await self._collect_mentionable_users(text),+ mentionable_users=await self._collect_mentionable_users(team, text),attachments=attachments,skipped_attachments=skipped,)- async def _extract_attachments(self, event: dict[str, Any]) -> tuple[tuple, tuple]:+ async def _extract_attachments(+ self, team_id: str, event: dict[str, Any]+ ) -> tuple[tuple, tuple]:files = event.get("files") or []inbound = [InboundFile(filename=f.get("name"),size=int(f.get("size") or 0),mime_type=f.get("mimetype"),- fetch=lambda f=f: self._download_slack_file(f),+ fetch=lambda f=f: self._download_slack_file(team_id, f),)for f in files]@@ -223,17 +305,22 @@ class SlackAdapter(WebhookAdapter):max_bytes=self.max_attachment_bytes,)- async def _download_slack_file(self, file_obj: dict[str, Any]) -> bytes:- # Slack file URLs are private — download needs the bot token as a- # bearer credential (files:read scope), unlike Discord's public CDN.+ async def _download_slack_file(+ self, team_id: str, file_obj: dict[str, Any]+ ) -> bytes:+ # Slack file URLs are private — download needs the workspace's bot token+ # as a bearer credential (files:read scope), unlike Discord's public CDN.url = file_obj.get("url_private_download") or file_obj.get("url_private") or ""+ token = await self._token_for(team_id)async with httpx.AsyncClient(timeout=30.0) as client:- resp = await client.get(- url, headers={"Authorization": f"Bearer {config.get_bot_token()}"}- )+ resp = await client.get(url, headers={"Authorization": f"Bearer {token}"})resp.raise_for_status()return resp.content+ async def _token_for(self, team_id: str) -> str:+ client = await self._client_for(team_id)+ return client.token or "" if client else ""+# -- Outbound --def _render(self, text: str, mentionable_users: tuple[tuple[str, str], ...]) -> str:@@ -251,8 +338,11 @@ class SlackAdapter(WebhookAdapter):text: str,mentionable_users: tuple[tuple[str, str], ...] = (),) -> None:- channel, thread_ts = _decode_target(channel_id)- await self._client.chat_postMessage(+ team, channel, thread_ts = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:+ return+ await client.chat_postMessage(channel=channel,text=self._render(text, mentionable_users),thread_ts=thread_ts,@@ -265,8 +355,11 @@ class SlackAdapter(WebhookAdapter):reply_to_message_id: str,mentionable_users: tuple[tuple[str, str], ...] = (),) -> None:- channel, thread_ts = _decode_target(channel_id)- await self._client.chat_postMessage(+ team, channel, thread_ts = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:+ return+ await client.chat_postMessage(channel=channel,text=self._render(text, mentionable_users),thread_ts=thread_ts or reply_to_message_id,@@ -275,9 +368,12 @@ class SlackAdapter(WebhookAdapter):async def send_link(self, channel_id: str, text: str, link_label: str, link_url: str) -> None:- channel, thread_ts = _decode_target(channel_id)+ team, channel, thread_ts = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:+ returnrendered = self.localize_markup(text)- await self._client.chat_postMessage(+ await client.chat_postMessage(channel=channel,text=rendered,thread_ts=thread_ts,@@ -285,8 +381,11 @@ class SlackAdapter(WebhookAdapter):)async def send_file(self, channel_id: str, text: str, file: FileAttachment) -> None:- channel, thread_ts = _decode_target(channel_id)- await self._client.files_upload_v2(+ team, channel, thread_ts = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:+ return+ await client.files_upload_v2(channel=channel,thread_ts=thread_ts,content=file.content,@@ -295,8 +394,11 @@ class SlackAdapter(WebhookAdapter):)async def send_ephemeral(self, channel_id: str, user_id: str, text: str) -> None:- channel, _ = _decode_target(channel_id)- await self._client.chat_postEphemeral(channel=channel, user=user_id, text=text)+ team, channel, _ = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:+ return+ await client.chat_postEphemeral(channel=channel, user=user_id, text=text)async def start_typing(self, channel_id: str) -> None:pass # Slack bot apps don't expose a typing indicator API.@@ -307,9 +409,10 @@ class SlackAdapter(WebhookAdapter):async def create_thread(self, channel_id: str, message_id: str, name: str) -> Optional[str]:- # Slack threads are implicit — pack (channel, parent_ts) into a single- # target_id the handler passes back to the outbound send_* calls.- return _encode_target(channel_id, message_id)+ # Slack threads are implicit — re-pack (team, channel, parent_ts) into a+ # single target_id the handler passes back to the outbound send_* calls.+ team, channel, _ = _decode_target(channel_id)+ return _encode_target(team, channel, message_id)async def rename_thread(self, thread_id: str, name: str) -> bool:return False # Slack threads have no name.@@ -319,116 +422,141 @@ class SlackAdapter(WebhookAdapter):async def list_text_channels(self, server_ids: tuple[str, ...]) -> list[ChannelInfo]:- team_id = await self._team_id_cached()- if not team_id or team_id not in server_ids:- return []channels: list[ChannelInfo] = []- cursor: Optional[str] = None- while True:- resp = await self._client.conversations_list(- types="public_channel",- exclude_archived=True,- limit=200,- cursor=cursor,- )- for c in resp.get("channels") or []:- # Only channels the bot is in can be posted to without a join.- if c.get("is_member"):- channels.append(- ChannelInfo(- id=c["id"], name=c.get("name", ""), server_id=team_id+ for team_id in server_ids:+ client = await self._client_for(team_id)+ if client is None:+ continue+ cursor: Optional[str] = None+ while True:+ resp = await client.conversations_list(+ types="public_channel",+ exclude_archived=True,+ limit=200,+ cursor=cursor,+ )+ for c in resp.get("channels") or []:+ # Only channels the bot is in can be posted to without a join.+ if c.get("is_member"):+ channels.append(+ ChannelInfo(+ id=_encode_target(team_id, c["id"]),+ name=c.get("name", ""),+ server_id=team_id,+ ))- )- cursor = (resp.get("response_metadata") or {}).get("next_cursor")- if not cursor:- break+ cursor = (resp.get("response_metadata") or {}).get("next_cursor")+ if not cursor:+ breakreturn channelsasync def get_channel_server_id(self, channel_id: str) -> Optional[str]:- team_id = await self._team_id_cached()- if not team_id:+ team, channel, _ = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:return Nonetry:- await self._client.conversations_info(channel=channel_id)+ await client.conversations_info(channel=channel)+ except Exception:+ return None+ if team:+ return team+ # Static single-workspace fallback: the ref carried no team, so resolve+ # the bot's own workspace from auth_test.+ try:+ resp = await client.auth_test()+ return resp.get("team_id") or Noneexcept Exception:return None- return team_idasync def post_channel_message(self, channel_id: str, text: str) -> Optional[PostedRef]:- channel, thread_ts = _decode_target(channel_id)- first_ts = await self._post_chunked(channel, text, thread_ts=thread_ts)+ team, channel, thread_ts = _decode_target(channel_id)+ first_ts = await self._post_chunked(team, channel, text, thread_ts=thread_ts)if first_ts is None:return None- return PostedRef(id=first_ts, url=await self._permalink(channel, first_ts))+ return PostedRef(+ id=first_ts, url=await self._permalink(team, channel, first_ts)+ )async def create_channel_thread(self, channel_id: str, name: str, text: str) -> Optional[PostedRef]:# Slack threads are implicit + unnamed: post text as the root message;# the returned ref threads subsequent sends off it.- channel, _ = _decode_target(channel_id)- root_ts = await self._post_chunked(channel, text)+ team, channel, _ = _decode_target(channel_id)+ root_ts = await self._post_chunked(team, channel, text)if root_ts is None:return Nonereturn PostedRef(- id=_encode_target(channel, root_ts),- url=await self._permalink(channel, root_ts),+ id=_encode_target(team, channel, root_ts),+ url=await self._permalink(team, channel, root_ts),)async def _post_chunked(- self, channel: str, text: str, thread_ts: Optional[str] = None+ self, team_id: str, channel: str, text: str, thread_ts: Optional[str] = None) -> Optional[str]:"""Post ``text`` chunked under the message cap; return the first ts.Later chunks thread off the first so a long post stays one conversation."""+ client = await self._client_for(team_id)+ if client is None:+ return Nonefirst_ts = thread_tsfor chunk in iter_chunks(self.localize_markup(text), config.CHUNK_FLUSH_AT):- resp = await self._client.chat_postMessage(+ resp = await client.chat_postMessage(channel=channel, text=chunk, thread_ts=first_ts)if first_ts is None:first_ts = resp.get("ts")return first_ts- async def _permalink(self, channel: str, ts: str) -> Optional[str]:+ async def _permalink(self, team_id: str, channel: str, ts: str) -> Optional[str]:+ client = await self._client_for(team_id)+ if client is None:+ return Nonetry:- resp = await self._client.chat_getPermalink(channel=channel, message_ts=ts)+ resp = await client.chat_getPermalink(channel=channel, message_ts=ts)return resp.get("permalink")except Exception:return None# -- Helpers --- async def _user_display_name(self, user_id: str) -> str:- if user_id in self._user_name_cache:- return self._user_name_cache[user_id]- try:- resp = await self._client.users_info(user=user_id)- user = resp.get("user") or {}- profile = user.get("profile") or {}- name = (- profile.get("display_name")- or user.get("real_name")- or user.get("name")- or user_id- )- except Exception:- logger.warning("Failed to fetch Slack user %s", user_id, exc_info=True)- name = user_id- self._user_name_cache[user_id] = name- return name-- async def _strip_mentions(self, text: str) -> str:+ async def _user_display_name(self, team_id: str, user_id: str) -> str:+ cache_key = (team_id, user_id)+ if cache_key in self._user_name_cache:+ return self._user_name_cache[cache_key]+ client = await self._client_for(team_id)+ if client is not None:+ try:+ resp = await client.users_info(user=user_id)+ user = resp.get("user") or {}+ profile = user.get("profile") or {}+ name = (+ profile.get("display_name")+ or user.get("real_name")+ or user.get("name")+ or user_id+ )+ # Only cache a real resolution — a transient API failure must not+ # poison the cache with the raw id (mirrors _bot_user_id_for).+ self._user_name_cache[cache_key] = name+ return name+ except Exception:+ logger.warning("Failed to fetch Slack user %s", user_id, exc_info=True)+ return user_id++ async def _strip_mentions(self, team_id: str, text: str) -> str:"""Drop the bot's own mention; rewrite others as `@displayname`."""- bot_id = await self._bot_user_id_cached()+ bot_id = await self._bot_user_id_for(team_id)names: dict[str, str] = {}for match in _USER_MENTION_RE.finditer(text):uid = match.group(1)if uid not in names:- names[uid] = await self._user_display_name(uid)+ names[uid] = await self._user_display_name(team_id, uid)def _replace(match: re.Match[str]) -> str:uid = match.group(1)@@ -439,44 +567,41 @@ class SlackAdapter(WebhookAdapter):return _USER_MENTION_RE.sub(_replace, text).strip()async def _collect_mentionable_users(- self, text: str+ self, team_id: str, text: str) -> tuple[tuple[str, str], ...]:- bot_id = await self._bot_user_id_cached()+ bot_id = await self._bot_user_id_for(team_id)pairs: list[tuple[str, str]] = []for match in _USER_MENTION_RE.finditer(text):uid = match.group(1)if bot_id and uid == bot_id:continue- pair = (await self._user_display_name(uid), uid)+ pair = (await self._user_display_name(team_id, uid), uid)if pair not in pairs:pairs.append(pair)return tuple(pairs)- async def _ensure_identity(self) -> None:- """Resolve the bot's own user_id + team_id from auth_test, once.-- Only a truthy result is cached — on a transient failure *or* a falsy- response the fields stay ``None`` so the next event retries. Otherwise a- single blip would permanently break self-mention stripping and channel/- team lookups.- """- if self._bot_user_id and self._team_id:- return+ async def _bot_user_id_for(self, team_id: str) -> str:+ """The bot's own user id in ``team_id`` — needed to strip its self-mention.++ Prefer the id captured at install time; fall back to auth_test on the+ workspace's client. Only a truthy result is cached, so a transient blip+ doesn't permanently break self-mention stripping."""+ if team_id in self._bot_user_ids:+ return self._bot_user_ids[team_id]+ client = await self._client_for(team_id)+ if team_id in self._bot_user_ids: # populated by _client_for from install+ return self._bot_user_ids[team_id]+ if client is None:+ return ""try:- resp = await self._client.auth_test()+ resp = await client.auth_test()except Exception:logger.warning("Failed to fetch Slack identity (auth_test)", exc_info=True)- return- self._bot_user_id = self._bot_user_id or resp.get("user_id") or None- self._team_id = self._team_id or resp.get("team_id") or None-- async def _bot_user_id_cached(self) -> str:- await self._ensure_identity()- return self._bot_user_id or ""-- async def _team_id_cached(self) -> str:- await self._ensure_identity()- return self._team_id or ""+ return ""+ uid = resp.get("user_id") or ""+ if uid:+ self._bot_user_ids[team_id] = uid+ return uiddef _verify_signature(request: Request, body: bytes) -> bool:@@ -487,15 +612,22 @@ def _verify_signature(request: Request, body: bytes) -> bool:)-def _encode_target(channel_id: str, thread_ts: str) -> str:- return f"{channel_id}|{thread_ts}"+def _encode_target(+ team_id: str, channel_id: str, thread_ts: Optional[str] = None+) -> str:+ return f"{team_id}|{channel_id}|{thread_ts or ''}"-def _decode_target(target_id: str) -> tuple[str, Optional[str]]:- if "|" in target_id:- channel, thread_ts = target_id.split("|", 1)- return channel, thread_ts- return target_id, None+def _decode_target(target_id: str) -> tuple[str, str, Optional[str]]:+ parts = target_id.split("|")+ if len(parts) == 3:+ team, channel, thread_ts = parts+ return team, channel, (thread_ts or None)+ if len(parts) == 2:+ # Back-compat with the single-workspace 'channel|thread_ts' form.+ channel, thread_ts = parts+ return "", channel, (thread_ts or None)+ return "", target_id, Nonedef _link_blocks(text: str, link_label: str, link_url: str) -> list[dict[str, Any]]:diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.pyindex 7ffc310e1d..53a97c1e01 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py@@ -1,4 +1,4 @@-"""Tests for the Slack webhook adapter."""+"""Tests for the Slack webhook adapter (multi-workspace)."""import jsonfrom unittest.mock import AsyncMock, MagicMock, patch@@ -6,17 +6,16 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.copilot.bot.adapters.base import FileAttachment+from backend.data.bot_installs import BotInstallCredentialsfrom .adapter import SlackAdapter, _decode_target, _encode_target_SIGN = "backend.copilot.bot.adapters.slack.adapter.signing.verify"-def adapter() -> SlackAdapter:- with patch("backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"):- a = SlackAdapter(MagicMock())+def _mock_client() -> MagicMock:client = MagicMock()+ client.token = "xoxb-test"client.chat_postMessage = AsyncMock(return_value={"ts": "111.222"})client.chat_postEphemeral = AsyncMock()client.chat_getPermalink = AsyncMock(return_value={"permalink": "https://x/p"})@@ -26,7 +25,17 @@ def adapter() -> SlackAdapter:return_value={"user": {"profile": {"display_name": "Bently"}}})client.auth_test = AsyncMock(return_value={"user_id": "UBOT", "team_id": "T1"})- a._client = client+ return client+++def adapter() -> SlackAdapter:+ a = SlackAdapter(MagicMock())+ client = _mock_client()+ # Seed the per-workspace client cache so the real _client_for resolves to the+ # mock without a DB lookup — covers every team the behaviour tests use.+ for team in ("T1", "T99", ""):+ a._clients[team] = clientreturn a@@ -74,6 +83,8 @@ class TestInboundRouting:assert ctx.channel_type == "channel"assert ctx.bot_mentioned is Trueassert ctx.text == "hi there" # bot mention stripped+ # The opaque channel_id carries the workspace so sends pick its token.+ assert ctx.channel_id == "T1|C1|"@pytest.mark.asyncioasync def test_thread_reply_is_not_bot_mentioned(self, adapter):@@ -92,12 +103,13 @@ class TestInboundRouting:"thread_ts": "1.0","user": "U1","text": "follow up",+ "team": "T1",})ctx = captured["ctx"]assert ctx.channel_type == "thread"assert ctx.bot_mentioned is False- assert ctx.channel_id == "C1|1.0"+ assert ctx.channel_id == "T1|C1|1.0"@pytest.mark.asyncioasync def test_channel_uses_top_level_team_id_for_server(self, adapter):@@ -120,6 +132,7 @@ class TestInboundRouting:"T99",)assert captured["ctx"].server_id == "T99"+ assert captured["ctx"].channel_id == "T99|C1|"@pytest.mark.asyncioasync def test_dm_has_no_server_id(self, adapter):@@ -142,6 +155,22 @@ class TestInboundRouting:)assert captured["ctx"].channel_type == "dm"assert captured["ctx"].server_id is None+ # Even DMs carry the team in the target so the reply picks the token.+ assert captured["ctx"].channel_id == "T99|D1|"++ @pytest.mark.asyncio+ async def test_event_without_team_is_dropped(self, adapter):+ # No workspace → no token to reply with → ignore rather than guess.+ called = []++ async def cb(ctx, ad):+ called.append(ctx)++ adapter.on_message(cb)+ await adapter._dispatch_event(+ {"type": "app_mention", "channel": "C1", "ts": "1", "user": "U1"}+ )+ assert called == []@pytest.mark.asyncioasync def test_bot_messages_are_skipped(self, adapter):@@ -151,8 +180,18 @@ class TestInboundRouting:called.append(ctx)adapter.on_message(cb)+ # Carries a valid team so the only thing standing between this event+ # and the callback is the bot filter itself (not the missing-team guard).await adapter._dispatch_event(- {"type": "app_mention", "bot_id": "B9", "channel": "C1", "ts": "1"}+ {+ "type": "app_mention",+ "bot_id": "B9",+ "channel": "C1",+ "ts": "1",+ "user": "U1",+ "text": "hi",+ "team": "T1",+ })assert called == []@@ -173,6 +212,7 @@ class TestInboundRouting:"ts": "1","user": "U1","text": "look",+ "team": "T1","files": [{"name": "a.txt", "size": 8, "mimetype": "text/plain"}],})@@ -183,28 +223,46 @@ class TestInboundRouting:assert ctx.attachments[0].content == b"filedata"+class TestUninstall:+ @pytest.mark.asyncio+ async def test_uninstall_event_revokes_and_evicts(self, adapter):+ adapter._clients["T5"] = MagicMock()+ adapter._bot_user_ids["T5"] = "UBOT"+ with patch(+ "backend.copilot.bot.adapters.slack.adapter.revoke_bot_install",+ new=AsyncMock(),+ ) as revoke:+ await adapter._dispatch_event({"type": "app_uninstalled"}, "T5")+ revoke.assert_awaited_once()+ assert "T5" not in adapter._clients+ assert "T5" not in adapter._bot_user_ids++class TestOutbound:@pytest.mark.asyncioasync def test_send_message_renders_mrkdwn_and_mentions_and_threads(self, adapter):- await adapter.send_message("C1|1.2", "**hi** @Bently", (("Bently", "U9"),))- call = adapter._client.chat_postMessage.await_args.kwargs+ await adapter.send_message("T1|C1|1.2", "**hi** @Bently", (("Bently", "U9"),))+ call = adapter._clients["T1"].chat_postMessage.await_args.kwargsassert call["channel"] == "C1"assert call["thread_ts"] == "1.2"assert call["text"] == "*hi* <@U9>"@pytest.mark.asyncioasync def test_non_allowlisted_mention_is_not_pinged(self, adapter):- await adapter.send_message("C1", "hi @Ghost", ())- assert adapter._client.chat_postMessage.await_args.kwargs["text"] == "hi @Ghost"+ await adapter.send_message("T1|C1|", "hi @Ghost", ())+ assert (+ adapter._clients["T1"].chat_postMessage.await_args.kwargs["text"]+ == "hi @Ghost"+ )@pytest.mark.asyncioasync def test_send_file_uploads_into_thread(self, adapter):await adapter.send_file(- "C1|1.2",+ "T1|C1|1.2","here you go",FileAttachment(filename="r.txt", mime_type="text/plain", content=b"x"),)- call = adapter._client.files_upload_v2.await_args.kwargs+ call = adapter._clients["T1"].files_upload_v2.await_args.kwargsassert call["channel"] == "C1"assert call["thread_ts"] == "1.2"assert call["filename"] == "r.txt"@@ -212,18 +270,18 @@ class TestOutbound:@pytest.mark.asyncioasync def test_post_channel_message_returns_ref_with_permalink(self, adapter):- ref = await adapter.post_channel_message("C1", "hello")+ ref = await adapter.post_channel_message("T1|C1|", "hello")assert ref is not Noneassert ref.id == "111.222"assert ref.url == "https://x/p"@pytest.mark.asyncioasync def test_create_thread_encodes_target(self, adapter):- assert await adapter.create_thread("C1", "9.9", "name") == "C1|9.9"+ assert await adapter.create_thread("T1|C1|", "9.9", "name") == "T1|C1|9.9"@pytest.mark.asyncioasync def test_rename_thread_is_noop(self, adapter):- assert await adapter.rename_thread("C1|9.9", "x") is False+ assert await adapter.rename_thread("T1|C1|9.9", "x") is Falseclass TestChannelIdGrammar:@@ -236,32 +294,144 @@ class TestChannelIdGrammar:assert not adapter.looks_like_channel_id("announcements")+class TestPerWorkspaceClient:+ @pytest.mark.asyncio+ async def test_client_for_builds_from_stored_install_and_caches(self):+ a = SlackAdapter(MagicMock())+ install = BotInstallCredentials(+ team_id="T1", bot_token="xoxb-abc", bot_user_id="UBOT"+ )+ with (+ patch(+ "backend.copilot.bot.adapters.slack.adapter.get_bot_install",+ new=AsyncMock(return_value=install),+ ) as lookup,+ patch(+ "backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"+ ) as web_client,+ ):+ first = await a._client_for("T1")+ second = await a._client_for("T1")+ web_client.assert_called_once_with(token="xoxb-abc")+ assert first is second # cached — a single DB lookup + client build+ lookup.assert_awaited_once()+ assert a._bot_user_ids["T1"] == "UBOT"++ @pytest.mark.asyncio+ async def test_client_for_returns_none_when_uninstalled(self):+ a = SlackAdapter(MagicMock())+ with (+ patch(+ "backend.copilot.bot.adapters.slack.adapter.get_bot_install",+ new=AsyncMock(return_value=None),+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.is_install_revoked",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.config.get_bot_token",+ return_value="",+ ),+ ):+ assert await a._client_for("T1") is None++ @pytest.mark.asyncio+ async def test_client_for_rebuilds_after_ttl_so_reinstalled_tokens_apply(self):+ # A re-install replaces the workspace token in the DB; the TTL bounds+ # how long any replica keeps using a client built from the old token.+ from .adapter import _CLIENT_CACHE_TTL_SECONDS++ a = SlackAdapter(MagicMock())+ stale = MagicMock()+ a._clients["T1"] = stale+ a._client_cached_at["T1"] = -_CLIENT_CACHE_TTL_SECONDS # long expired+ install = BotInstallCredentials(team_id="T1", bot_token="xoxb-new")+ with (+ patch(+ "backend.copilot.bot.adapters.slack.adapter.get_bot_install",+ new=AsyncMock(return_value=install),+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"+ ) as web_client,+ ):+ fresh = await a._client_for("T1")+ assert fresh is not stale+ web_client.assert_called_once_with(token="xoxb-new")++ @pytest.mark.asyncio+ async def test_client_for_revoked_workspace_never_falls_back_to_static(self):+ # An uninstalled workspace must get None — the static token belongs to+ # the app's own workspace, not a workspace that revoked us.+ a = SlackAdapter(MagicMock())+ with (+ patch(+ "backend.copilot.bot.adapters.slack.adapter.get_bot_install",+ new=AsyncMock(return_value=None),+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.is_install_revoked",+ new=AsyncMock(return_value=True),+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.config.get_bot_token",+ return_value="xoxb-static",+ ),+ ):+ assert await a._client_for("TREVOKED") is None++ @pytest.mark.asyncio+ async def test_client_for_empty_team_falls_back_to_static_token(self):+ # A raw channel ref (no team) must resolve via the static token rather+ # than returning None — otherwise proactive posts fail (channel_not_found).+ a = SlackAdapter(MagicMock())+ lookup = AsyncMock(return_value=None)+ with (+ patch(+ "backend.copilot.bot.adapters.slack.adapter.get_bot_install",+ new=lookup,+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.config.get_bot_token",+ return_value="xoxb-static",+ ),+ patch(+ "backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"+ ) as web_client,+ ):+ client = await a._client_for("")+ assert client is not None+ web_client.assert_called_once_with(token="xoxb-static")+ lookup.assert_not_awaited() # no DB lookup for an empty team++class TestIdentityCaching:@pytest.mark.asyncioasync def test_auth_failure_is_not_cached_and_retries(self, adapter):- adapter._client.auth_test = AsyncMock(- side_effect=[RuntimeError("blip"), {"user_id": "UBOT", "team_id": "T1"}]+ adapter._clients["T1"].auth_test = AsyncMock(+ side_effect=[RuntimeError("blip"), {"user_id": "UBOT"}])# First call fails → not cached as "".- assert await adapter._bot_user_id_cached() == ""- assert adapter._bot_user_id is None- # Next call recovers.- assert await adapter._bot_user_id_cached() == "UBOT"- assert adapter._team_id == "T1"+ assert await adapter._bot_user_id_for("T1") == ""+ assert "T1" not in adapter._bot_user_ids+ # Next call recovers and caches.+ assert await adapter._bot_user_id_for("T1") == "UBOT"+ assert adapter._bot_user_ids["T1"] == "UBOT"@pytest.mark.asyncioasync def test_empty_auth_response_is_not_cached_and_retries(self, adapter):- adapter._client.auth_test = AsyncMock(- side_effect=[- {"user_id": "", "team_id": ""},- {"user_id": "UBOT", "team_id": "T1"},- ]+ adapter._clients["T1"].auth_test = AsyncMock(+ side_effect=[{"user_id": ""}, {"user_id": "UBOT"}])- assert await adapter._bot_user_id_cached() == ""- assert adapter._bot_user_id is None # falsy response not cached- assert await adapter._bot_user_id_cached() == "UBOT"+ assert await adapter._bot_user_id_for("T1") == ""+ assert "T1" not in adapter._bot_user_ids # falsy response not cached+ assert await adapter._bot_user_id_for("T1") == "UBOT"def test_target_encode_decode_roundtrip():- assert _decode_target(_encode_target("C1", "1.2")) == ("C1", "1.2")- assert _decode_target("D1") == ("D1", None)+ assert _decode_target(_encode_target("T1", "C1", "1.2")) == ("T1", "C1", "1.2")+ assert _decode_target(_encode_target("T1", "D1")) == ("T1", "D1", None)+ # Back-compat: the old single-workspace two-part form decodes with no team.+ assert _decode_target("C1|1.2") == ("", "C1", "1.2")+ assert _decode_target("D1") == ("", "D1", None)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yamlindex 42ca11fda5..cef451b36a 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml@@ -37,6 +37,10 @@ features:should_escape: falseoauth_config:+ # Where Slack sends the auth code after a workspace clicks "Add to Slack".+ # Required to activate public distribution (multi-workspace installs).+ redirect_urls:+ - <BASE_URL>/api/copilot-webhooks/slack/oauth/callbackscopes:bot:- app_mentions:read # @AutoPilot in any channel the app is in@@ -60,6 +64,8 @@ settings:- app_mention # @bot in any channel the app is in- message.im # DMs to the bot- message.channels # replies in channel threads the bot is part of+ - app_uninstalled # workspace removed the app → revoke its stored token+ - tokens_revoked # workspace revoked the bot token → revoke our copyorg_deploy_enabled: falsesocket_mode_enabled: falsetoken_rotation_enabled: falsediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.pyindex b625a86b33..cb63287364 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.py@@ -11,6 +11,14 @@ def get_signing_secret() -> str:return Settings().secrets.autopilot_bot_slack_signing_secret+def get_client_id() -> str:+ return Settings().secrets.autopilot_bot_slack_client_id+++def get_client_secret() -> str:+ return Settings().secrets.autopilot_bot_slack_client_secret++# Slack's hard cap is 40000 chars per message; 4000 is the practical ceiling# for readability.MAX_MESSAGE_LENGTH = 4000diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.pynew file mode 100644index 0000000000..817e33f5e5--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py@@ -0,0 +1,185 @@+"""Slack OAuth v2 install flow — the multi-workspace "Add to Slack" path.++ GET /install → CSRF-signed state, 302 to Slack's authorize screen.+ GET /oauth/callback → validate state, exchange the code for that workspace's+ bot token (oauth.v2.access), store it encrypted per team.++Enabled only when the app's client id + secret are configured. The state is a+self-contained HMAC-signed nonce (keyed on the client secret) with a short TTL,+so the public, un-authenticated install button needs no server-side session.+"""++import hashlib+import hmac+import logging+import secrets+import time+from typing import Callable, Optional+from urllib.parse import urlencode++from fastapi import FastAPI, Request, Response+from fastapi.responses import PlainTextResponse, RedirectResponse+from slack_sdk.web.async_client import AsyncWebClient++from backend.data.bot_analytics import record_guild_joined+from backend.data.bot_installs import upsert_bot_install+from backend.platform_linking.models import BotGuildInput, Platform+from backend.util.settings import Settings++from . import config++logger = logging.getLogger(__name__)++INSTALL_PATH = "/api/copilot-webhooks/slack/install"+CALLBACK_PATH = "/api/copilot-webhooks/slack/oauth/callback"++# Bot scopes requested at install — must stay in sync with app-manifest.yaml.+_SCOPES = (+ "app_mentions:read",+ "channels:history",+ "channels:read",+ "chat:write",+ "chat:write.public",+ "commands",+ "files:read",+ "files:write",+ "im:history",+ "im:read",+ "im:write",+ "users:read",+ "team:read",+)++_STATE_TTL_SECONDS = 600+++def is_enabled() -> bool:+ """The install flow needs OAuth app credentials; single-workspace mode+ (static token only) runs without them."""+ return bool(config.get_client_id() and config.get_client_secret())+++def register_routes(+ app: FastAPI, on_installed: Optional[Callable[[str], None]] = None+) -> None:+ # on_installed(team_id) fires after a successful (re)install so the adapter+ # can drop any cached client built from the workspace's previous token.+ if not is_enabled():+ return++ async def _callback(request: Request) -> Response:+ return await _handle_callback(request, on_installed)++ app.add_api_route(INSTALL_PATH, _handle_install, methods=["GET"])+ app.add_api_route(CALLBACK_PATH, _callback, methods=["GET"])+++def _redirect_uri() -> str:+ base = Settings().config.platform_base_url.rstrip("/")+ return f"{base}{CALLBACK_PATH}"+++async def _handle_install() -> Response:+ params = urlencode(+ {+ "client_id": config.get_client_id(),+ "scope": ",".join(_SCOPES),+ "redirect_uri": _redirect_uri(),+ "state": _make_state(),+ }+ )+ return RedirectResponse(+ f"https://slack.com/oauth/v2/authorize?{params}", status_code=302+ )+++async def _handle_callback(+ request: Request, on_installed: Optional[Callable[[str], None]] = None+) -> Response:+ if error := request.query_params.get("error"):+ # User declined, or Slack rejected the request.+ return _done(ok=False, detail=error)+ state = request.query_params.get("state", "")+ code = request.query_params.get("code", "")+ if not _verify_state(state):+ return PlainTextResponse("invalid or expired state", status_code=400)+ if not code:+ return PlainTextResponse("missing code", status_code=400)++ resp = await AsyncWebClient().oauth_v2_access(+ client_id=config.get_client_id(),+ client_secret=config.get_client_secret(),+ code=code,+ redirect_uri=_redirect_uri(),+ )+ if not resp.get("ok"):+ logger.warning("Slack oauth.v2.access failed: %s", resp.get("error"))+ return _done(ok=False, detail=resp.get("error") or "exchange failed")++ token = resp.get("access_token") or ""+ team = resp.get("team") or {}+ team_id = team.get("id") or ""+ if not token or not team_id:+ return _done(ok=False, detail="incomplete install response")++ await upsert_bot_install(+ platform=Platform.SLACK,+ team_id=team_id,+ bot_token=token,+ bot_user_id=resp.get("bot_user_id"),+ app_id=resp.get("app_id"),+ name=team.get("name"),+ )+ if on_installed is not None:+ on_installed(team_id)+ try:+ await record_guild_joined(+ BotGuildInput(+ platform=Platform.SLACK, server_id=team_id, name=team.get("name")+ )+ )+ except Exception:+ logger.warning(+ "Failed to record BotGuild for Slack install %s", team_id, exc_info=True+ )+ return _done(ok=True, detail=team.get("name") or team_id)+++def _done(*, ok: bool, detail: str) -> Response:+ """Land the browser back on the settings page (or a plain confirmation if no+ frontend URL is configured)."""+ base = (Settings().config.frontend_base_url or "").rstrip("/")+ if base:+ flag = "slack_installed" if ok else "slack_install_error"+ return RedirectResponse(f"{base}/settings/bots?{flag}=1", status_code=302)+ if ok:+ return PlainTextResponse(+ f"AutoPilot was added to {detail}. You can close this tab and run "+ "/setup in Slack to link your account."+ )+ return PlainTextResponse(f"Slack install failed: {detail}", status_code=400)+++def _make_state() -> str:+ nonce = secrets.token_urlsafe(24)+ payload = f"{nonce}.{int(time.time())}"+ return f"{payload}.{_sign(payload)}"+++def _verify_state(state: str) -> bool:+ try:+ nonce, ts, sig = state.rsplit(".", 2)+ except ValueError:+ return False+ payload = f"{nonce}.{ts}"+ if not hmac.compare_digest(sig, _sign(payload)):+ return False+ try:+ return (int(time.time()) - int(ts)) <= _STATE_TTL_SECONDS+ except ValueError:+ return False+++def _sign(payload: str) -> str:+ key = config.get_client_secret().encode()+ return hmac.new(key, payload.encode(), hashlib.sha256).hexdigest()diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.pynew file mode 100644index 0000000000..b2c0a0af5c--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth_test.py@@ -0,0 +1,130 @@+"""Tests for the Slack OAuth v2 install flow."""++import time+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.bot.adapters.slack import oauth++_O = "backend.copilot.bot.adapters.slack.oauth"+++def _creds():+ return (+ patch(f"{_O}.config.get_client_id", return_value="cid"),+ patch(f"{_O}.config.get_client_secret", return_value="csecret"),+ )+++def _req(params: dict) -> MagicMock:+ r = MagicMock()+ r.query_params = params+ return r+++def test_is_enabled_requires_both_credentials():+ with (+ patch(f"{_O}.config.get_client_id", return_value="cid"),+ patch(f"{_O}.config.get_client_secret", return_value=""),+ ):+ assert oauth.is_enabled() is False+ cid, secret = _creds()+ with cid, secret:+ assert oauth.is_enabled() is True+++def test_state_roundtrip_and_tamper_rejected():+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ state = oauth._make_state()+ assert oauth._verify_state(state) is True+ assert oauth._verify_state(state + "x") is False+ assert oauth._verify_state("garbage") is False+++def test_expired_state_rejected():+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ old_ts = int(time.time()) - oauth._STATE_TTL_SECONDS - 5+ payload = f"nonce.{old_ts}"+ stale = f"{payload}.{oauth._sign(payload)}"+ assert oauth._verify_state(stale) is False+++async def test_callback_exchanges_code_and_stores_install():+ cid, secret = _creds()+ with (+ cid,+ secret,+ patch(f"{_O}.AsyncWebClient") as web_client,+ patch(f"{_O}.upsert_bot_install", new=AsyncMock()) as upsert,+ patch(f"{_O}.record_guild_joined", new=AsyncMock()) as roster,+ patch(f"{_O}.Settings") as settings,+ ):+ settings.return_value.config.platform_base_url = "https://b.example"+ settings.return_value.config.frontend_base_url = ""+ web_client.return_value.oauth_v2_access = AsyncMock(+ return_value={+ "ok": True,+ "access_token": "xoxb-workspace",+ "team": {"id": "T1", "name": "Acme"},+ "bot_user_id": "UBOT",+ "app_id": "A1",+ }+ )+ resp = await oauth._handle_callback(+ _req({"state": oauth._make_state(), "code": "auth-code"})+ )++ upsert.assert_awaited_once()+ kwargs = upsert.await_args.kwargs+ assert kwargs["team_id"] == "T1"+ assert kwargs["bot_token"] == "xoxb-workspace"+ assert kwargs["bot_user_id"] == "UBOT"+ roster.assert_awaited_once()+ assert resp.status_code == 200 # plain success page (no frontend URL configured)+++async def test_callback_fires_on_installed_so_stale_clients_evict():+ cid, secret = _creds()+ evicted: list[str] = []+ with (+ cid,+ secret,+ patch(f"{_O}.AsyncWebClient") as web_client,+ patch(f"{_O}.upsert_bot_install", new=AsyncMock()),+ patch(f"{_O}.record_guild_joined", new=AsyncMock()),+ patch(f"{_O}.Settings") as settings,+ ):+ settings.return_value.config.platform_base_url = "https://b.example"+ settings.return_value.config.frontend_base_url = ""+ web_client.return_value.oauth_v2_access = AsyncMock(+ return_value={+ "ok": True,+ "access_token": "xoxb-new",+ "team": {"id": "T1", "name": "Acme"},+ "bot_user_id": "UBOT",+ "app_id": "A1",+ }+ )+ await oauth._handle_callback(+ _req({"state": oauth._make_state(), "code": "c"}),+ on_installed=evicted.append,+ )+ assert evicted == ["T1"]+++async def test_callback_rejects_invalid_state():+ with patch(f"{_O}.config.get_client_secret", return_value="csecret"):+ resp = await oauth._handle_callback(_req({"state": "forged", "code": "c"}))+ assert resp.status_code == 400+++async def test_callback_handles_user_denied():+ with patch(f"{_O}.Settings") as settings:+ settings.return_value.config.frontend_base_url = ""+ resp = await oauth._handle_callback(_req({"error": "access_denied"}))+ assert resp.status_code == 400diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.pyindex fbfb3b03e2..24ec7a2c99 100644--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py@@ -42,7 +42,13 @@ def _build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:mounts nothing."""adapters: list[WebhookAdapter] = []- if slack_config.get_bot_token() and slack_config.get_signing_secret():+ # Signing secret is always required (inbound verification, one per app). Then+ # either OAuth app creds (multi-workspace "Add to Slack") or a single static+ # token (single-workspace back-compat) is enough to mount the adapter.+ has_credentials = (+ slack_config.get_client_id() and slack_config.get_client_secret()+ ) or slack_config.get_bot_token()+ if slack_config.get_signing_secret() and has_credentials:adapters.append(SlackAdapter(api))logger.info("Slack adapter enabled")return adaptersdiff --git a/autogpt_platform/backend/backend/data/bot_installs.py b/autogpt_platform/backend/backend/data/bot_installs.pynew file mode 100644index 0000000000..356fbef058--- /dev/null+++ b/autogpt_platform/backend/backend/data/bot_installs.py@@ -0,0 +1,118 @@+"""Per-workspace OAuth install credentials for multi-tenant webhook bots.++Each installed workspace (Slack team, and later Teams etc.) gets one row holding+that workspace's bot token, ENCRYPTED at rest via ``JSONCryptor`` — the same+mechanism ``User.integrations`` uses — keyed by the platform's workspace/team ID.++The OAuth install callback writes these; the adapter reads them to call the+workspace's API with its own token. Accessed in-process by the webhook routes+mounted on the main backend API, so it talks to Prisma directly.++Privacy/security: the ``credentials`` column is always an encrypted blob — a raw+token is never persisted.+"""++import logging+from datetime import datetime, timezone+from typing import Optional++from prisma.models import BotInstall+from pydantic import BaseModel++from backend.platform_linking.models import Platform+from backend.util.encryption import JSONCryptor++logger = logging.getLogger(__name__)+++class BotInstallCredentials(BaseModel):+ """Decrypted, ready-to-use credentials for one installed workspace."""++ team_id: str+ bot_token: str+ bot_user_id: Optional[str] = None+ app_id: Optional[str] = None+ name: Optional[str] = None+++def _key(platform: Platform, team_id: str) -> dict:+ return {+ "platform_platformServerId": {+ "platform": platform.value,+ "platformServerId": team_id,+ }+ }+++async def upsert_bot_install(+ *,+ platform: Platform,+ team_id: str,+ bot_token: str,+ bot_user_id: Optional[str] = None,+ app_id: Optional[str] = None,+ name: Optional[str] = None,+) -> None:+ """Store (or refresh) a workspace's encrypted bot token. Clears ``revokedAt``+ so a re-install after an uninstall resurrects the row."""+ fields = {+ "credentials": JSONCryptor().encrypt({"bot_token": bot_token}),+ "botUserId": bot_user_id,+ "appId": app_id,+ "name": name,+ "revokedAt": None,+ }+ await BotInstall.prisma().upsert(+ where=_key(platform, team_id),+ data={+ "create": {+ "platform": platform.value,+ "platformServerId": team_id,+ **fields,+ },+ "update": fields,+ },+ )+++async def get_bot_install(+ platform: Platform, team_id: str+) -> Optional[BotInstallCredentials]:+ """Return decrypted credentials for a live install, or ``None`` if the+ workspace isn't installed, is revoked, or the token can't be decrypted."""+ row = await BotInstall.prisma().find_unique(where=_key(platform, team_id))+ if row is None or row.revokedAt is not None:+ return None+ token = JSONCryptor().decrypt(row.credentials).get("bot_token")+ if not token:+ logger.warning(+ "BotInstall for %s/%s has no decryptable token", platform.value, team_id+ )+ return None+ return BotInstallCredentials(+ team_id=team_id,+ bot_token=token,+ bot_user_id=row.botUserId,+ app_id=row.appId,+ name=row.name,+ )+++async def is_install_revoked(platform: Platform, team_id: str) -> bool:+ """Whether this workspace explicitly uninstalled the app / revoked its+ token. Distinguishes "revoked" from "never installed" — a revoked+ workspace must NOT fall back to any other credential."""+ row = await BotInstall.prisma().find_unique(where=_key(platform, team_id))+ return row is not None and row.revokedAt is not None+++async def revoke_bot_install(platform: Platform, team_id: str) -> None:+ """Mark a workspace's install revoked (app_uninstalled / tokens_revoked)."""+ await BotInstall.prisma().update_many(+ where={+ "platform": platform.value,+ "platformServerId": team_id,+ "revokedAt": None,+ },+ data={"revokedAt": datetime.now(timezone.utc)},+ )diff --git a/autogpt_platform/backend/backend/data/bot_installs_test.py b/autogpt_platform/backend/backend/data/bot_installs_test.pynew file mode 100644index 0000000000..ab226c218e--- /dev/null+++ b/autogpt_platform/backend/backend/data/bot_installs_test.py@@ -0,0 +1,79 @@+"""Tests for the per-workspace bot install store (encryption round-trip)."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.data import bot_installs+from backend.platform_linking.models import Platform++_BI = "backend.data.bot_installs.BotInstall"+++async def test_upsert_encrypts_token_and_get_decrypts_it():+ upsert = AsyncMock()+ with patch(_BI) as model:+ model.prisma.return_value.upsert = upsert+ await bot_installs.upsert_bot_install(+ platform=Platform.SLACK,+ team_id="T1",+ bot_token="xoxb-secret",+ bot_user_id="UBOT",+ )++ data = upsert.await_args.kwargs["data"]+ encrypted = data["create"]["credentials"]+ # The raw token must never be persisted in the clear.+ assert "xoxb-secret" not in encrypted++ row = MagicMock(revokedAt=None, credentials=encrypted, botUserId="UBOT", appId=None)+ row.name = "Acme" # `name` is a reserved MagicMock kwarg — set it explicitly.+ with patch(_BI) as model:+ model.prisma.return_value.find_unique = AsyncMock(return_value=row)+ creds = await bot_installs.get_bot_install(Platform.SLACK, "T1")++ assert creds is not None+ assert creds.bot_token == "xoxb-secret"+ assert creds.bot_user_id == "UBOT"+ assert creds.name == "Acme"+++async def test_get_returns_none_for_revoked_install():+ row = MagicMock(revokedAt=object(), credentials="whatever")+ with patch(_BI) as model:+ model.prisma.return_value.find_unique = AsyncMock(return_value=row)+ assert await bot_installs.get_bot_install(Platform.SLACK, "T1") is None+++async def test_get_returns_none_when_not_installed():+ with patch(_BI) as model:+ model.prisma.return_value.find_unique = AsyncMock(return_value=None)+ assert await bot_installs.get_bot_install(Platform.SLACK, "T1") is None+++async def test_is_install_revoked_true_for_revoked_row():+ row = MagicMock(revokedAt=object())+ with patch(_BI) as model:+ model.prisma.return_value.find_unique = AsyncMock(return_value=row)+ assert await bot_installs.is_install_revoked(Platform.SLACK, "T1") is True+++async def test_is_install_revoked_false_when_never_installed():+ with patch(_BI) as model:+ model.prisma.return_value.find_unique = AsyncMock(return_value=None)+ assert await bot_installs.is_install_revoked(Platform.SLACK, "T1") is False+++async def test_get_returns_none_for_corrupt_credentials():+ # JSONCryptor.decrypt never raises — corrupt ciphertext decrypts to {} and+ # the missing-token path returns None.+ row = MagicMock(revokedAt=None, credentials="not-a-valid-ciphertext")+ with patch(_BI) as model:+ model.prisma.return_value.find_unique = AsyncMock(return_value=row)+ assert await bot_installs.get_bot_install(Platform.SLACK, "T1") is Nonediff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 9586c63c89..364d44eb10 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -779,6 +779,17 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):"signatures (HMAC-SHA256). Required alongside the token to enable the ""Slack adapter.",)+ autopilot_bot_slack_client_id: str = Field(+ default="",+ description="Slack app OAuth client ID. Set together with the client "+ "secret to enable the multi-workspace 'Add to Slack' install flow; each "+ "workspace's bot token is then obtained via OAuth and stored per team.",+ )+ autopilot_bot_slack_client_secret: str = Field(+ default="",+ description="Slack app OAuth client secret — exchanged with the auth "+ "code on the install callback for a per-workspace bot token.",+ )smtp_server: str = Field(default="", description="SMTP server IP")smtp_port: str = Field(default="", description="SMTP server port")diff --git a/autogpt_platform/backend/migrations/20260708120000_add_bot_install/migration.sql b/autogpt_platform/backend/migrations/20260708120000_add_bot_install/migration.sqlnew file mode 100644index 0000000000..18c0a53a6c--- /dev/null+++ b/autogpt_platform/backend/migrations/20260708120000_add_bot_install/migration.sql@@ -0,0 +1,21 @@+-- CreateTable+CREATE TABLE "BotInstall" (+ "id" TEXT NOT NULL,+ "platform" "PlatformType" NOT NULL,+ "platformServerId" TEXT NOT NULL,+ "credentials" TEXT NOT NULL,+ "botUserId" TEXT,+ "appId" TEXT,+ "name" TEXT,+ "installedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3),+ "revokedAt" TIMESTAMP(3),++ CONSTRAINT "BotInstall_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "BotInstall_platform_platformServerId_key" ON "BotInstall"("platform", "platformServerId");++-- CreateIndex+CREATE INDEX "BotInstall_platform_revokedAt_idx" ON "BotInstall"("platform", "revokedAt");diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex cea88ded92..36e63df77f 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -2167,3 +2167,26 @@ model BotGuild {@@unique([platform, serverId])@@index([platform, leftAt])}++// Per-workspace OAuth install credentials for webhook bots that use a+// multi-tenant "Add to <platform>" install flow (Slack Events API, and later+// Teams etc.). One row per installed workspace/team, holding that workspace's+// bot token ENCRYPTED at rest via JSONCryptor — exactly like User.integrations,+// never a raw token. This is the credential the adapter uses to call the+// platform API on that workspace's behalf; distinct from BotGuild (presence /+// analytics) and PlatformLink (account ownership).+model BotInstall {+ id String @id @default(uuid())+ platform PlatformType+ platformServerId String // Workspace/team ID (e.g. Slack team_id)+ credentials String // Encrypted JSON: { bot_token, ... }+ botUserId String? // The bot's own user ID within that workspace+ appId String? // Platform app ID (used to match uninstall events)+ name String? // Workspace display name (best-effort, may go stale)+ installedAt DateTime @default(now())+ updatedAt DateTime? @updatedAt+ revokedAt DateTime? // Set on app_uninstalled / tokens_revoked++ @@unique([platform, platformServerId])+ @@index([platform, revokedAt])+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsxindex 4ed9b0a600..e905a1dec6 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx@@ -75,6 +75,26 @@ describe("SettingsBotsPage", () => {).toBeNull();});+ test("renders an Add to Slack button when an install URL is provided", async () => {+ server.use(+ getListBotPlatformsMockHandler([+ slackPlatform({+ add_bot_url:+ "https://backend.example/api/copilot-webhooks/slack/install",+ }),+ ]),+ );++ render(<SettingsBotsPage />);++ const button = await screen.findByRole("link", {+ name: /add bot to slack/i,+ });+ expect(button.getAttribute("href")).toBe(+ "https://backend.example/api/copilot-webhooks/slack/install",+ );+ });+test("shows the 'no bots enabled' empty state when no platforms are configured", async () => {server.use(getListBotPlatformsMockHandler([]));