Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Let a workspace admin replace a messaging app's token without disconnecting it (#980)
Abel Dantas186613f32e31
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1f5b52233..09f905634 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2026,6 +2026,11 @@ version of their own to them without also giving them a release of their own.### [Unreleased]#### Added+- **Replace a messaging app's token without disconnecting it.** When a bot+ token is rotated or leaked, a workspace admin can paste the new one from the+ connection's menu on the server page. The connection restarts with it and+ keeps its rooms. Offered on connections to your own bot, not on ones that+ came from installing Switch's app.- **Airtable's logo on the Connections grid.**- **Admin → Connector apps sets up Airtable.** Its dialog walks Airtable'sBuilder Hub with the redirect URL to copy and the scopes to tick, and asksdiff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsindex e1b944e04..f4d0f0c2d 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -560,7 +560,9 @@ export const workspacesController = createRPCController({* connection may create channels. Admin-only, like registering one; see* `updateBridgeOnServer` for the recoverable-failure mapping.*/- updateBridge: (params: UpdateBridgeParams): Promise<UpdateBridgeResult> =>+ updateBridge: (+ params: Omit<UpdateBridgeParams, 'connectionConfig'>+ ): Promise<UpdateBridgeResult> =>withReachableWorkspaceSession(params.workspaceId, (server) =>updateBridgeOnServer(server, {bridgeId: params.bridgeId,@@ -568,6 +570,24 @@ export const workspacesController = createRPCController({})),+ /**+ * Put new tokens on a connection to the workspace's own bot, after the old+ * ones were rotated or leaked. The server keeps the rest of the connection's+ * settings and restarts it with them; its rooms are untouched. Admin-only.+ * The tokens go to the server and nowhere else.+ */+ replaceBridgeTokens: (params: {+ workspaceId: string;+ bridgeId: string;+ tokens: Record<string, string>;+ }): Promise<UpdateBridgeResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ updateBridgeOnServer(server, {+ bridgeId: params.bridgeId,+ connectionConfig: params.tokens,+ })+ ),+/*** Disconnect a messaging app from the chosen workspace. Admin-only.*diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex b2ac035e4..c6f868f65 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -32,6 +32,7 @@ import { DeleteAccountModal } from '@renderer/features/switch-servers/delete-accimport { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';import { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';+import { ReplaceTokenModal } from '@renderer/features/switch-servers/ReplaceTokenModal';import { TeamsPlacementModal } from '@renderer/features/switch-servers/TeamsPlacementModal';import { SaveTemplateModal } from '@renderer/features/templates/save-template-modal';import { CreateWorkspaceModal } from '@renderer/features/workspaces/create-workspace-modal';@@ -126,6 +127,10 @@ export const modalRegistry = {size: 'sm',dismissOnOutsideClick: false,}),+ replaceTokenModal: createModal(ReplaceTokenModal, {+ size: 'sm',+ dismissOnOutsideClick: false,+ }),teamsPlacementModal: createModal(TeamsPlacementModal, { size: 'md' }),addAgentsToRoomModal: createModal(AddAgentsToRoomModal, {// The room-side twin of `addAgentToRoomModal`, and sized to match: the twodiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsxindex 17fcc0fa9..4b7b5e148 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx@@ -1,9 +1,10 @@-import { useQueryClient, useQuery } from '@tanstack/react-query';+import { useQueries, useQueryClient, useQuery } from '@tanstack/react-query';import {CircleAlert,Copy,ExternalLink,Info,+ Key,KeyRound,Link2,MessageSquare,@@ -40,6 +41,7 @@ import { Spinner } from '@renderer/lib/ui/spinner';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { log } from '@renderer/utils/logger';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+import { bridgeTypesQueryKey, fetchBridgeTypes } from './bridge-platforms-loader';import { ConnectedChatsList } from './ConnectedChatsList';import { LinkAccountPrompts } from './link-account-prompts';import { orderBridges } from './messaging-apps-order';@@ -49,6 +51,7 @@ import {unrecognisedMessagingApps,unrecognisedMessagingAppsMessage,} from './messaging-apps-warning';+import { mayReplaceToken, offersTokenReplacement, tokenFields } from './replace-token';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';import { useMyIdentities } from './use-my-identities';@@ -95,6 +98,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({const queryClient = useQueryClient();const showConnectMessagingApp = useShowModal('connectMessagingAppModal');const showDisconnectMessagingApp = useShowModal('disconnectMessagingAppModal');+ const showReplaceToken = useShowModal('replaceTokenModal');const showConnectChat = useShowModal('connectChatModal');const workspaceId = workspacesStore.idOnServerInScope(serverId);const isAdmin = administersWorkspaceInScope(serverId);@@ -158,6 +162,33 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({}}, [ownerAgentsError, workspaceId]);+ // Which connections can take a new token: each platform's secret fields come+ // from its schema, and a connection is asked about its install only once it+ // has some, since an install is what marks one on Switch's own app.+ const typesQuery = useQuery({+ queryKey: bridgeTypesQueryKey(workspaceId),+ queryFn: () => fetchBridgeTypes(workspaceId as string),+ enabled: workspaceId !== null && isAdmin,+ });+ const tokenFieldsOf = (bridge: RemoteBridge) =>+ tokenFields(typesQuery.data?.find((t) => t.key === bridge.type)?.fields ?? []);+ const tokenCandidates = isAdmin+ ? bridges.filter((bridge) => mayReplaceToken(bridge, tokenFieldsOf(bridge)))+ : [];+ const installStates = useQueries({+ queries: tokenCandidates.map((bridge) => ({+ queryKey: ['bridge-install-state', workspaceId, bridge.id],+ queryFn: () =>+ rpc.workspaces.bridgeInstallState({+ workspaceId: workspaceId as string,+ bridgeId: bridge.id,+ }),+ enabled: workspaceId !== null,+ })),+ });+ const installStateOf = (bridge: RemoteBridge) =>+ installStates[tokenCandidates.findIndex((b) => b.id === bridge.id)]?.data;+const unrecognisedIn = unrecognisedMessagingApps({bridges,identities,@@ -314,6 +345,23 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({}): null}+ onReplaceToken={+ workspaceId !== null &&+ offersTokenReplacement(bridge, tokenFieldsOf(bridge), installStateOf(bridge))+ ? () =>+ showReplaceToken({+ workspaceId,+ bridgeId: bridge.id,+ bridgeDisplayName: bridge.displayName,+ bridgeType: bridge.type,+ fields: tokenFieldsOf(bridge),+ onSuccess: () =>+ void queryClient.invalidateQueries({+ queryKey: ['remote-bridges', workspaceId],+ }),+ })+ : null+ }onDisconnect={() => {if (workspaceId === null) return;showDisconnectMessagingApp({@@ -367,7 +415,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({* has exactly one thing worth doing to it, and burying that is what would make* the row's warning unactionable. Everything else — changing or dropping the* account, channel creation, the bundled chat's credentials, opening the app,- * disconnecting it — is in the menu.+ * replacing its token, disconnecting it — is in the menu.*/export function MessagingAppRow({workspaceId,@@ -381,6 +429,7 @@ export function MessagingAppRow({savingChannelCreation,onToggleChannelCreation,onConnectChat,+ onReplaceToken,onDisconnect,}: {/** Null while this install has not resolved the server's workspace; the@@ -400,6 +449,8 @@ export function MessagingAppRow({/** Set on a connection whose chats are connected one at a time, for a user* the server lets add one — members too, unlike every other change here. */onConnectChat: (() => void) | null;+ /** Set on a connection to the workspace's own bot, for an admin. */+ onReplaceToken: (() => void) | null;onDisconnect: () => void;}) {const showClaimIdentity = useShowModal('claimIdentityModal');@@ -675,6 +726,12 @@ export function MessagingAppRow({{isAdmin && (<><DropdownMenuSeparator />+ {onReplaceToken !== null && (+ <DropdownMenuItem onClick={onReplaceToken}>+ <Key className="size-4" />+ Replace token…+ </DropdownMenuItem>+ )}<DropdownMenuItem variant="destructive" onClick={onDisconnect}><Trash2 className="size-4" />Disconnect app…diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsxnew file mode 100644index 000000000..661a0ab1e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ReplaceTokenModal.tsx@@ -0,0 +1,180 @@+import { KeyRound } from 'lucide-react';+import { useCallback, useState } from 'react';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import type {+ BridgeConfigField,+ UpdateBridgeResult,+} from '@shared/core/switch-servers/switch-servers';+import { isMissingRequired } from './connect-form-fields';++type ReplaceTokenModalArgs = {+ workspaceId: string;+ bridgeId: string;+ bridgeDisplayName: string;+ bridgeType: string;+ /** The platform's secret fields, from {@link tokenFields}. */+ fields: BridgeConfigField[];+};++type Props = BaseModalProps<void> & ReplaceTokenModalArgs;++/**+ * Put a new token on a messaging app connection, after the old one was rotated+ * or leaked. Disconnecting and connecting again would do it too, at the cost+ * of every room on the connection; this edits the connection in place, and the+ * server restarts it with the new token.+ *+ * Every secret field is asked for, none prefilled: the server never sends a+ * stored credential back, and a token left as it was is not one replaced.+ */+export function ReplaceTokenModal({+ workspaceId,+ bridgeId,+ bridgeDisplayName,+ bridgeType,+ fields,+ onSuccess,+ onClose,+}: Props) {+ const platform = bridgePlatformLabel(bridgeType);+ const noun = fields.length === 1 ? 'token' : 'tokens';+ const [values, setValues] = useState<Record<string, string>>({});+ const [isSaving, setIsSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const canSubmit = !isSaving && !fields.some((field) => isMissingRequired(field, values));++ const handleSubmit = useCallback(async () => {+ if (!canSubmit) return;+ setIsSaving(true);+ setError(null);+ const tokens: Record<string, string> = {};+ for (const field of fields) tokens[field.key] = (values[field.key] ?? '').trim();+ try {+ // The server checks a Slack bot token when it is saved, but not the+ // app-level token, which only fails later when Socket Mode cannot+ // connect. The same check the connect form runs covers both.+ if (bridgeType === 'slack') {+ try {+ await rpc.workspaces.checkSlackTokens({+ workspaceId,+ botToken: tokens.bot_token ?? '',+ appToken: tokens.app_token ?? '',+ });+ } catch (cause) {+ setError(failureText(cause, 'Could not check the tokens with Slack.'));+ return;+ }+ }+ const result = await rpc.workspaces.replaceBridgeTokens({ workspaceId, bridgeId, tokens });+ if (result.kind !== 'updated') {+ setError(messageFor(result));+ return;+ }+ toast({+ title: `${platform} ${noun} replaced`,+ description: `${bridgeDisplayName} restarted with the new ${noun}.`,+ });+ onSuccess();+ } catch (cause) {+ setError(failureText(cause, `Could not replace the ${noun}.`));+ } finally {+ setIsSaving(false);+ }+ }, [+ canSubmit,+ fields,+ values,+ bridgeType,+ workspaceId,+ bridgeId,+ platform,+ noun,+ bridgeDisplayName,+ onSuccess,+ ]);++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <div className="flex items-center gap-2">+ <KeyRound className="size-4 text-foreground-muted" />+ <DialogTitle>+ Replace {platform} {noun}+ </DialogTitle>+ </div>+ </DialogHeader>+ <DialogContentArea className="space-y-3 pt-0">+ <p className="text-sm text-foreground-muted">+ {bridgeDisplayName} reconnects with the new {noun}. Your rooms and conversations stay as+ they are.+ </p>++ <FieldGroup>+ {fields.map((field, index) => (+ <Field key={field.key}>+ <FieldLabel>{field.label}</FieldLabel>+ <Input+ type="password"+ autoComplete="new-password"+ spellCheck={false}+ value={values[field.key] ?? ''}+ onChange={(e) => {+ const { value } = e.target;+ setValues((prev) => ({ ...prev, [field.key]: value }));+ setError(null);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && canSubmit) void handleSubmit();+ }}+ autoFocus={index === 0}+ />+ {field.description && (+ <p className="mt-1 text-xs text-foreground-muted">{field.description}</p>+ )}+ </Field>+ ))}+ </FieldGroup>++ {error && <p className="text-xs text-destructive">{error}</p>}+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={isSaving}>+ Cancel+ </Button>+ <ConfirmButton onClick={() => void handleSubmit()} disabled={!canSubmit}>+ {isSaving ? 'Replacing…' : `Replace ${noun}`}+ </ConfirmButton>+ </DialogFooter>+ </>+ );+}++/** Turn a refused replacement into something the user can act on. The server+ * writes its refusals for the person who typed the token, so they are shown+ * as they are. */+function messageFor(result: Exclude<UpdateBridgeResult, { kind: 'updated' }>): string {+ switch (result.kind) {+ case 'unauthenticated':+ return 'Your session for this server expired. Sign in again, then retry.';+ case 'forbidden':+ return 'Replacing a token requires an owner or admin of this workspace.';+ case 'invalid':+ case 'error':+ return result.message;+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/replace-token.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/replace-token.tsnew file mode 100644index 000000000..5717c1d5b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/replace-token.ts@@ -0,0 +1,40 @@+import type {+ BridgeConfigField,+ BridgeInstallState,+ RemoteBridge,+} from '@shared/core/switch-servers/switch-servers';++/** The credentials a connection on someone's own app holds, all asked for+ * again: the platform's secret fields, as its schema marks them. */+export function tokenFields(fields: readonly BridgeConfigField[]): BridgeConfigField[] {+ return fields+ .filter((field) => field.secret && field.kind === 'string')+ .map((field) => ({ ...field, required: true }));+}++/** Whether this connection may be worth asking about its install at all. A+ * connection on Switch's own app (the distributed Teams app, the Switch+ * Telegram app) says so on the bridge itself, and needs no further question. */+export function mayReplaceToken(+ bridge: RemoteBridge,+ fields: readonly BridgeConfigField[]+): boolean {+ return fields.length > 0 && !bridge.teamPlacementSupported && bridge.channelIdsRefused === null;+}++/**+ * Whether to offer replacing a connection's token.+ *+ * Only on a connection to the workspace's own bot. One that came from+ * installing Switch's app holds the deployment's credential, or none at all,+ * and the server refuses a token pasted onto it. An install is what marks that+ * kind of connection, so a connection is offered the action only once the+ * server has said it has none; not knowing is not offering.+ */+export function offersTokenReplacement(+ bridge: RemoteBridge,+ fields: readonly BridgeConfigField[],+ installState: BridgeInstallState | undefined+): boolean {+ return mayReplaceToken(bridge, fields) && installState === 'not-installed';+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsxindex ed6710607..273cbe513 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/messaging-app-row.test.tsx@@ -110,6 +110,7 @@ function row(savingChannelCreation={false}onToggleChannelCreation={() => {}}onConnectChat={overrides.onConnectChat ?? null}+ onReplaceToken={() => {}}onDisconnect={overrides.onDisconnect ?? (() => {})}/>);diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex 4d7a821b3..27a05a2b6 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -652,9 +652,10 @@ export type UpdateBridgeParams = {workspaceId: string;bridgeId: string;channelCreationEnabled?: boolean;- /** Connection-config fields to merge into the bridge's stored config — today- * only the distributed Teams app's default-team choice (`{ team_id }`).- * Left unset, the gateway leaves the stored config untouched. */+ /** Connection-config fields to merge into the bridge's stored config: the+ * distributed Teams app's default-team choice (`{ team_id }`), or new tokens+ * for a connection to the workspace's own bot. Left unset, the gateway+ * leaves the stored config untouched. */connectionConfig?: Record<string, string>;};diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 214a71ed7..10d706c12 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -11,6 +11,7 @@ from dataclasses import replacefrom datetime import UTC, datetime, timedeltafrom typing import Any, ClassVar, Literal+import aiohttpimport discordfrom discord.http import Routefrom pydantic import ConfigDict, Field, model_validator@@ -50,6 +51,7 @@ from switch_core.bridges.collaboration.models import (Attachment,AttachmentFailure,BridgeConnectionConfig,+ BridgeCredentialError,ChannelType,DirectoryUser,FailureReason,@@ -532,6 +534,37 @@ class DiscordAdapter(PlatformAdapter):return (DISCORD_GATEWAY, DISCORD_GATEWAY_KEY)return None+ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ """Log in with the bot token, which fetches the bot's own user.++ A bridge on the distributed app holds no token of its own; the+ deployment's is checked when its shared connection opens.+ """+ config = DiscordConnectionConfig.model_validate(connection_config)+ if config.event_delivery == "shared":+ return+ assert config.bot_token is not None # guaranteed by the validator+ client = discord.Client(intents=discord.Intents.none())+ try:+ await client.login(config.bot_token)+ except discord.LoginFailure as exc:+ raise BridgeCredentialError(+ "Discord rejected the bot token. Copy it again from the "+ "Developer Portal (your application -> Bot -> Reset Token)."+ ) from exc+ except discord.HTTPException as exc:+ raise BridgeCredentialError(+ f"Discord did not accept the bot token: {exc}"+ ) from exc+ except (aiohttp.ClientError, TimeoutError) as exc:+ raise BridgeCredentialError(+ f"Could not reach Discord to check the bot token: "+ f"{exc or type(exc).__name__}. Try again."+ ) from exc+ finally:+ await client.close()+@classmethoddef classify_failure(cls, exc: BaseException) -> FailureReason | None:if isinstance(exc, discord.LoginFailure):diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex ea60672ae..85858daaf 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -676,13 +676,19 @@ class CollaborationBridgeLifecycleService:An edit can change what registration checked — which workspace thebridge claims, or the credentials proving it — so it is checked thesame way before it is stored: valid for the type, no claim another- bridge holds, and credentials the platform accepts. Raises- `ValidationError`, `BridgeClaimConflict` or `BridgeCredentialError`.+ bridge holds, a URL Switch may reach, and credentials the platform+ accepts. The URL is checked first because checking the credentials+ sends them to it. Raises `ValidationError`, `BridgeClaimConflict`,+ `BridgeStartRefused` or `BridgeCredentialError`."""self.validate_connection_config(bridge_type, connection_config)await self.reject_claim_conflict(bridge_type, connection_config, exclude_bridge_id=bridge_id)+ try:+ await self.check_outbound_urls(bridge_type, connection_config)+ except OutboundURLRefused as exc:+ raise BridgeStartRefused(f"Bridge {bridge_id}: {exc}") from excadapter_cls = self._adapter_registry.get(bridge_type)if adapter_cls is not None:await adapter_cls.verify_credentials(connection_config)diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex 909a71639..b2f44caf2 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -61,6 +61,7 @@ from switch_core.bridges.collaboration.models import (Attachment,AttachmentFailure,BridgeConnectionConfig,+ BridgeCredentialError,ChannelType,DirectoryUser,FailureReason,@@ -361,6 +362,51 @@ class MattermostAdapter(PlatformAdapter):# in each process would hand each process every post.keeps_quiet_unless_listening: ClassVar[bool] = True+ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ """Sign in as the admin user and find the team, as `start` will.++ `url` has been through the outbound policy before this is called, so+ the credentials are only sent where Switch may connect.+ """+ config = MattermostConnectionConfig.model_validate(connection_config)+ driver = cls(config=config)._create_driver(+ login_id=config.admin_user, password=config.admin_password+ )+ try:+ await asyncio.to_thread(driver.login)+ except NoAccessTokenProvided as exc:+ raise BridgeCredentialError(+ f"Mattermost refused the sign-in for {config.admin_user}: {exc}. "+ "Check admin_user and admin_password."+ ) from exc+ except sync_requests.RequestException as exc:+ raise BridgeCredentialError(+ f"Could not sign in to Mattermost at {config.url} to check the "+ f"credentials: {exc}"+ ) from exc+ try:+ await asyncio.to_thread(driver.teams.get_team_by_name, config.team_name)+ except (ResourceNotFound, NotEnoughPermissions) as exc:+ raise BridgeCredentialError(+ f"{config.admin_user} signed in, but Mattermost has no team "+ f"named {config.team_name!r} it can see: {exc}"+ ) from exc+ except sync_requests.RequestException as exc:+ raise BridgeCredentialError(+ f"Could not look up the Mattermost team {config.team_name!r}: {exc}"+ ) from exc+ finally:+ try:+ await asyncio.to_thread(driver.logout)+ except sync_requests.RequestException:+ logger.warning(+ "Could not sign out the Mattermost session opened to check "+ "%s's credentials; it lasts until the server expires it",+ config.admin_user,+ exc_info=True,+ )+@classmethoddef classify_failure(cls, exc: BaseException) -> FailureReason | None:"""`mattermostdriver` raises its named exceptions only for the statusdiff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.pyindex 026fd1a44..281d078cf 100644--- a/core/switch_core/bridges/collaboration/models.py+++ b/core/switch_core/bridges/collaboration/models.py@@ -1,6 +1,6 @@from typing import Annotated, Literal, Self-from pydantic import AfterValidator, BaseModel+from pydantic import AfterValidator, BaseModel, ConfigDictfrom switch_core.sessions.attachments import normalise_mime_type@@ -235,7 +235,9 @@ FailureReason = Literal[class BridgeConnectionConfig(BaseModel):- pass+ # Validation errors reach the operator as the HTTP error, and a field's+ # input is often a token.+ model_config = ConfigDict(hide_input_in_errors=True)class BridgeCredentialError(Exception):diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex 4e7288d9f..314cb9d56 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -14,6 +14,7 @@ from typing import Any, ClassVar, Literal, NamedTuplefrom pydantic import ConfigDict, model_validatorfrom pydantic.json_schema import SkipJsonSchemafrom telegram import (+ Bot,ForceReply,InlineKeyboardButton,InlineKeyboardMarkup,@@ -56,6 +57,7 @@ from switch_core.bridges.collaboration.models import (Attachment,AttachmentFailure,BridgeConnectionConfig,+ BridgeCredentialError,BridgeInstallLink,ChannelCreationUnsupported,ChannelType,@@ -89,6 +91,7 @@ from switch_core.bridges.collaboration.telegram.app_client import (TelegramAppClient,bot_id_of,bot_resource,+ initialize_bot,)from switch_core.bridges.collaboration.telegram.chunking import (MAX_MESSAGE,@@ -522,6 +525,29 @@ class TelegramAdapter(PlatformAdapter):# nowhere; its updates reach any process as webhooks.keeps_quiet_unless_listening: ClassVar[bool] = True+ @classmethod+ async def verify_credentials(cls, connection_config: dict[str, object]) -> None:+ """Ask Telegram who the bot token belongs to (`getMe`).++ A bridge on the shared app bot holds no token of its own; the+ deployment's is checked when the app starts.+ """+ config = TelegramConnectionConfig.model_validate(connection_config)+ if config.event_delivery == "shared":+ return+ assert config.bot_token is not None # guaranteed by the validator+ bot = Bot(config.bot_token)+ try:+ await initialize_bot(bot.initialize())+ except InvalidToken as exc:+ raise BridgeCredentialError(str(exc)) from exc+ except TelegramError as exc:+ raise BridgeCredentialError(+ f"Could not check the bot token with Telegram: {exc}. Try again."+ ) from exc+ finally:+ await bot.shutdown()+@classmethoddef classify_failure(cls, exc: BaseException) -> FailureReason | None:"""`BadRequest` is a subclass of `NetworkError` in python-telegram-bot,@@ -681,7 +707,7 @@ class TelegramAdapter(PlatformAdapter):self._app = appself._bot = app.bot- await app.initialize()+ await initialize_bot(app.initialize())me = await app.bot.get_me()self._bot_user_id = me.idif me.username and me.username != self._bot_username:diff --git a/core/switch_core/bridges/collaboration/telegram/app_client.py b/core/switch_core/bridges/collaboration/telegram/app_client.pyindex 000929a4b..d92c6ea4e 100644--- a/core/switch_core/bridges/collaboration/telegram/app_client.py+++ b/core/switch_core/bridges/collaboration/telegram/app_client.py@@ -23,6 +23,7 @@ import loggingfrom collections.abc import Awaitable, Callableimport telegram+from telegram.error import InvalidTokenfrom switch_core.bridges.collaboration.cooldown import Cooldownfrom switch_core.bridges.collaboration.install import MessagingInstallError@@ -71,6 +72,26 @@ def bot_id_of(token: str) -> str:return bot_id+async def initialize_bot(initialize: Awaitable[None]) -> None:+ """Await a bot's `initialize`, refusing a bad token without repeating it.++ python-telegram-bot reports a token Telegram turned down as an+ `InvalidToken` whose message quotes the token, and the bridge's start logs+ that with its traceback. The replacement keeps the type, so it is still+ classified as an authentication failure, and is raised outside the handler+ so the original is not attached to it as context either.+ """+ try:+ await initialize+ return+ except InvalidToken:+ pass+ raise InvalidToken(+ "Telegram rejected the bot token. Copy it again from BotFather "+ "(/mybots -> the bot -> API Token)."+ )++def bot_resource(bot_id: str) -> str:"""The exclusive resource a Telegram bot is, as bridges and the app name it.@@ -139,7 +160,7 @@ class TelegramAppClient:the URL, the secret and the update types always match this build'sconfig — rotating the secret is a redeploy, not a manual call."""- await self._bot.initialize()+ await initialize_bot(self._bot.initialize())me = await self._bot.get_me()if not me.username:raise MessagingInstallError(diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.py b/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.pyindex be4bfe55d..a24b466ec 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_workspace_claims.py@@ -299,7 +299,10 @@ class TestAnEditIsHeldToTheSameRules:if b.tenant_id == tenant]- with tenant_scope(tenant):+ with (+ tenant_scope(tenant),+ patch.object(DiscordAdapter, "verify_credentials", AsyncMock()),+ ):await _service(session_factory).check_edited_connection_config(bridge_id=bridge.id,bridge_type="discord",diff --git a/core/tests/switch_core/bridges/collaboration/test_connection_config_errors.py b/core/tests/switch_core/bridges/collaboration/test_connection_config_errors.pynew file mode 100644index 000000000..8800407e1--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_connection_config_errors.py@@ -0,0 +1,21 @@+"""A rejected connection config must not echo what was typed: the 422 detail+is the validation error's text, and the input is usually a token."""++import pytest+from pydantic import ValidationError++from switch_core.bridges.collaboration.discord.adapter import DiscordConnectionConfig+from switch_core.bridges.collaboration.slack.adapter import SlackConnectionConfig+from switch_core.bridges.collaboration.telegram.adapter import TelegramConnectionConfig++SECRET = "xoxb-0000-not-a-real-token"+++ "config_type",+ [SlackConnectionConfig, DiscordConnectionConfig, TelegramConnectionConfig],+)+def test_a_validation_error_leaves_the_token_out(config_type: type) -> None:+ with pytest.raises(ValidationError) as caught:+ config_type.model_validate({"bot_token": [SECRET]})+ assert SECRET not in str(caught.value)diff --git a/core/tests/switch_core/bridges/collaboration/test_platform_token_checks.py b/core/tests/switch_core/bridges/collaboration/test_platform_token_checks.pynew file mode 100644index 000000000..456f028f5--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_platform_token_checks.py@@ -0,0 +1,223 @@+"""Telegram, Discord and Mattermost credentials are checked before they are kept.++Without the check, a token the platform refuses was saved, the bridge was+restarted with it and reported as replaced, and only then failed in the+background with the old, working token already gone.+"""++from __future__ import annotations++import json+import traceback+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import discord+import pytest+from mattermostdriver.exceptions import NoAccessTokenProvided, ResourceNotFound+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from telegram.request import HTTPXRequest++from switch_core.bridges.collaboration.discord.adapter import DiscordAdapter+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+from switch_core.bridges.collaboration.models import (+ BridgeCredentialError,+ BridgeStartRefused,+)+from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.outbound import OutboundURLRefused+from tests.ownership import SoleOwner++TELEGRAM_SECRET = "placeholder-secret-part-of-the-token"+TELEGRAM = {"bot_token": f"123456789:{TELEGRAM_SECRET}", "bot_username": "switch_bot"}+DISCORD = {"bot_token": "placeholder-discord-token", "guild_id": "111"}+MATTERMOST = {+ "url": "https://chat.example.invalid",+ "admin_user": "switch-admin",+ "admin_password": "placeholder", # gitleaks:allow+ "team_name": "eng",+}+_ME = {+ "id": 123456789,+ "is_bot": True,+ "first_name": "Switch",+ "username": "switch_bot",+ "can_join_groups": True,+ "can_read_all_group_messages": True,+ "supports_inline_queries": False,+}+++def _telegram_answers(monkeypatch: pytest.MonkeyPatch, status: int) -> list[str]:+ """Answer every Bot API call with `status`, recording the URLs asked for."""+ asked: list[str] = []++ async def do_request(+ self: HTTPXRequest, url: str, *args: Any, **kwargs: Any+ ) -> Any:+ asked.append(url)+ if status == 200:+ return 200, json.dumps({"ok": True, "result": _ME}).encode()+ body = {"ok": False, "error_code": status, "description": "Unauthorized"}+ return status, json.dumps(body).encode()++ monkeypatch.setattr(HTTPXRequest, "do_request", do_request)+ return asked+++class TestTelegram:+ async def test_a_token_telegram_refuses_is_a_credential_error(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _telegram_answers(monkeypatch, 401)++ with pytest.raises(+ BridgeCredentialError, match="rejected the bot token"+ ) as caught:+ await TelegramAdapter.verify_credentials(dict(TELEGRAM))++ assert TELEGRAM_SECRET not in "".join(traceback.format_exception(caught.value))++ async def test_a_token_telegram_knows_is_accepted(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ asked = _telegram_answers(monkeypatch, 200)++ await TelegramAdapter.verify_credentials(dict(TELEGRAM))++ assert [url.rsplit("/", 1)[-1] for url in asked] == ["getMe"]++ async def test_a_bridge_on_the_shared_bot_asks_nothing(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ asked = _telegram_answers(monkeypatch, 401)++ await TelegramAdapter.verify_credentials({"event_delivery": "shared"})++ assert asked == []+++class TestDiscord:+ async def test_a_token_discord_refuses_is_a_credential_error(self) -> None:+ refused = AsyncMock(side_effect=discord.LoginFailure("Improper token"))+ with patch.object(discord.Client, "login", refused):+ with pytest.raises(BridgeCredentialError, match="rejected the bot token"):+ await DiscordAdapter.verify_credentials(dict(DISCORD))++ refused.assert_awaited_once_with(DISCORD["bot_token"])++ async def test_a_token_discord_knows_is_accepted(self) -> None:+ with patch.object(discord.Client, "login", AsyncMock()) as login:+ await DiscordAdapter.verify_credentials(dict(DISCORD))++ login.assert_awaited_once_with(DISCORD["bot_token"])++ async def test_a_bridge_on_the_shared_connection_asks_nothing(self) -> None:+ with patch.object(discord.Client, "login", AsyncMock()) as login:+ await DiscordAdapter.verify_credentials(+ {"guild_id": "111", "event_delivery": "shared"}+ )++ login.assert_not_awaited()+++class _Driver:+ def __init__(self, *, login: Exception | None, team: Exception | None) -> None:+ self._login = login+ self.teams = MagicMock()+ self.teams.get_team_by_name.side_effect = team+ self.logged_out = False++ def login(self) -> None:+ if self._login is not None:+ raise self._login++ def logout(self) -> None:+ self.logged_out = True+++def _mattermost_driver(driver: _Driver) -> Any:+ return patch.object(MattermostAdapter, "_create_driver", lambda *_, **__: driver)+++class TestMattermost:+ async def test_a_refused_sign_in_is_a_credential_error(self) -> None:+ driver = _Driver(login=NoAccessTokenProvided("Invalid credentials"), team=None)+ with _mattermost_driver(driver):+ with pytest.raises(BridgeCredentialError, match="refused the sign-in"):+ await MattermostAdapter.verify_credentials(dict(MATTERMOST))++ async def test_a_team_it_cannot_find_is_a_credential_error(self) -> None:+ driver = _Driver(login=None, team=ResourceNotFound("not found"))+ with _mattermost_driver(driver):+ with pytest.raises(BridgeCredentialError, match="no team named 'eng'"):+ await MattermostAdapter.verify_credentials(dict(MATTERMOST))+ assert driver.logged_out++ async def test_a_working_sign_in_is_accepted_and_signed_out(self) -> None:+ driver = _Driver(login=None, team=None)+ with _mattermost_driver(driver):+ await MattermostAdapter.verify_credentials(dict(MATTERMOST))++ driver.teams.get_team_by_name.assert_called_once_with("eng")+ assert driver.logged_out+++def _service(+ session_factory: async_sessionmaker[AsyncSession], config: Any+) -> CollaborationBridgeLifecycleService:+ service = CollaborationBridgeLifecycleService(+ bridge_store=CollaborationBridgeStore(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=RoomStore(),+ agent_store=MagicMock(),+ client_store=ClientStore(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ provisioning=MagicMock(),+ session_factory=session_factory,+ config=config,+ client_factory=MagicMock(),+ session_activity_listener=MagicMock(),+ session_activity_service=MagicMock(),+ connections=MagicMock(),+ ownership=SoleOwner(),+ cursor_writer=SoleOwner.cursor_writer(session_factory),+ )+ service.register_adapter(+ "mattermost", MattermostAdapter, MattermostConnectionConfig+ )+ return service+++async def test_an_edit_is_not_signed_in_with_at_a_url_switch_may_not_reach(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Checking the credentials sends them to `url`, so the outbound policy+ decides first."""+ config = MagicMock()+ config.outbound_policy.check_url = AsyncMock(+ side_effect=OutboundURLRefused("chat.example.invalid is a private address")+ )+ driver = _Driver(login=None, team=None)+ driver.login = MagicMock() # type: ignore[method-assign]++ with _mattermost_driver(driver):+ with pytest.raises(BridgeStartRefused, match="private address"):+ await _service(session_factory, config).check_edited_connection_config(+ bridge_id="the-edited-bridge",+ bridge_type="mattermost",+ connection_config=dict(MATTERMOST),+ )++ driver.login.assert_not_called()diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_token_refused.py b/core/tests/switch_core/bridges/collaboration/test_telegram_token_refused.pynew file mode 100644index 000000000..29a81c857--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_token_refused.py@@ -0,0 +1,76 @@+"""A token Telegram refuses must not reach the server log.++python-telegram-bot quotes the token in the `InvalidToken` it raises from+`initialize`, and a bridge that fails to start is logged with its traceback.+These run the library's own request path against a canned 401, so they fail+again if its wording or the place it raises from changes.+"""++from __future__ import annotations++import logging+import traceback+from typing import Any++import pytest+import telegram+from telegram.error import InvalidToken+from telegram.request import HTTPXRequest++from switch_core.bridges.collaboration.telegram.adapter import (+ TelegramAdapter,+ TelegramConnectionConfig,+)+from switch_core.bridges.collaboration.telegram.app_client import TelegramAppClient++TOKEN = "123456789:placeholder-secret-part-of-the-token"+SECRET = "placeholder-secret-part-of-the-token"+UNAUTHORIZED = b'{"ok": false, "error_code": 401, "description": "Unauthorized"}'++[email protected](autouse=True)+def telegram_refuses_the_token(monkeypatch: pytest.MonkeyPatch) -> None:+ async def do_request(self: HTTPXRequest, *args: Any, **kwargs: Any) -> Any:+ return 401, UNAUTHORIZED++ monkeypatch.setattr(HTTPXRequest, "do_request", do_request)+++def _everything_logged_about(exc: BaseException) -> str:+ """What `logger.exception` would write: the message and the whole chain."""+ return "".join(traceback.format_exception(exc))+++async def _nothing(*_: Any) -> None:+ return None+++async def test_the_bridge_start_failure_does_not_carry_the_token(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter = TelegramAdapter(+ config=TelegramConnectionConfig(bot_token=TOKEN, bot_username="switch_bot")+ )++ with pytest.raises(InvalidToken) as caught:+ await adapter.start(_nothing, _nothing, _nothing, _nothing, _nothing)++ assert SECRET not in _everything_logged_about(caught.value)+ assert TelegramAdapter.classify_failure(caught.value) == "auth_failed"+ with caplog.at_level(logging.DEBUG):+ logging.getLogger("test").exception("Bridge crashed", exc_info=caught.value)+ assert SECRET not in caplog.text+++async def test_the_shared_app_start_failure_does_not_carry_the_token() -> None:+ client = TelegramAppClient(+ bot=telegram.Bot(TOKEN),+ webhook_url="https://switch.example/messaging/telegram/events",+ webhook_secret="placeholder-webhook-secret",+ on_connected=_nothing,+ )++ with pytest.raises(InvalidToken) as caught:+ await client.start()++ assert SECRET not in _everything_logged_about(caught.value)diff --git a/core/tests/switch_core/gateway/test_bridge_token_replacement.py b/core/tests/switch_core/gateway/test_bridge_token_replacement.pynew file mode 100644index 000000000..951bea45b--- /dev/null+++ b/core/tests/switch_core/gateway/test_bridge_token_replacement.py@@ -0,0 +1,122 @@+"""Replacing a messaging app's token with one the platform refuses changes nothing.++The edit used to be stored and the bridge restarted before anything asked the+platform, so Console reported the token replaced while the connection went+down in the background. Run through the real lifecycle service and Telegram+adapter, with only Telegram's answer canned.+"""++from __future__ import annotations++import json+import uuid+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+from fastapi import HTTPException+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from telegram.request import HTTPXRequest++from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.telegram.adapter import (+ TelegramAdapter,+ TelegramConnectionConfig,+)+from switch_core.db.models import Client, CollaborationBridge, User+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.gateway.collaborations import update_bridge+from switch_core.gateway.schemas import BridgeUpdateRequest+from tests.ownership import SoleOwner++OLD_TOKEN = "123456789:placeholder-old-secret"+NEW_SECRET = "placeholder-new-secret"+NEW_TOKEN = f"123456789:{NEW_SECRET}"+++def _lifecycle(+ session_factory: async_sessionmaker[AsyncSession],+) -> CollaborationBridgeLifecycleService:+ service = CollaborationBridgeLifecycleService(+ bridge_store=CollaborationBridgeStore(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=RoomStore(),+ agent_store=MagicMock(),+ client_store=ClientStore(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ provisioning=MagicMock(),+ session_factory=session_factory,+ config=MagicMock(),+ client_factory=MagicMock(),+ session_activity_listener=MagicMock(),+ session_activity_service=MagicMock(),+ connections=MagicMock(),+ ownership=SoleOwner(),+ cursor_writer=SoleOwner.cursor_writer(session_factory),+ )+ service.register_adapter("telegram", TelegramAdapter, TelegramConnectionConfig)+ service.restart = AsyncMock() # type: ignore[method-assign]+ return service+++async def _telegram_bridge(session_factory: async_sessionmaker[AsyncSession]) -> str:+ async with session_factory() as session:+ client = Client(+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type="telegram",+ display_name="Acme",+ client_id=client.id,+ status="active",+ connection_config={"bot_token": OLD_TOKEN, "bot_username": "switch_bot"},+ )+ session.add(bridge)+ await session.commit()+ return bridge.id+++async def test_a_token_telegram_refuses_is_refused_and_nothing_changes(+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def unauthorized(self: HTTPXRequest, *args: Any, **kwargs: Any) -> Any:+ body = {"ok": False, "error_code": 401, "description": "Unauthorized"}+ return 401, json.dumps(body).encode()++ monkeypatch.setattr(HTTPXRequest, "do_request", unauthorized)+ bridge_id = await _telegram_bridge(session_factory)+ lifecycle = _lifecycle(session_factory)++ async with session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await update_bridge(+ bridge_id=bridge_id,+ payload=BridgeUpdateRequest(connection_config={"bot_token": NEW_TOKEN}),+ session=session,+ bridge_store=CollaborationBridgeStore(),+ room_store=RoomStore(),+ collab_lifecycle=lifecycle,+ user=User(+ id="admin", name="admin", email="[email protected]", role="admin"+ ),+ )++ assert refused.value.status_code == 400+ assert "rejected the bot token" in str(refused.value.detail)+ assert NEW_SECRET not in str(refused.value.detail)+ async with session_factory() as session:+ bridge = await CollaborationBridgeStore().get(session, bridge_id)+ assert bridge is not None+ assert (bridge.connection_config or {})["bot_token"] == OLD_TOKEN+ lifecycle.restart.assert_not_awaited() # type: ignore[attr-defined]