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
feat(teams): distributed Teams app any organisation installs (CHOO-3017) (#632)
Christian McDermottad4fd4527ae4
diff --git a/.env.example b/.env.exampleindex c1ba5ac7d..80bb4119a 100644--- a/.env.example+++ b/.env.example@@ -211,7 +211,8 @@ FRONTEND_BASE_URL=http://localhost:5173# GATEWAY_PUBLIC_URL=http://localhost:8000# Public origin a messaging platform reaches Switch on: the base of the OAuth-# redirect and the event URLs under /messaging for the distributed Slack app.+# redirect and the event URLs under /messaging for the distributed Slack,+# Discord and Teams apps.# Must be https and must resolve from the internet, so it is usually a# different host from GATEWAY_PUBLIC_URL. Required to offer workspace installs.# MESSAGING_PUBLIC_URL=https://switch.example.com@@ -239,6 +240,31 @@ FRONTEND_BASE_URL=http://localhost:5173# DISCORD_APP_MESSAGE_CONTENT=false# DISCORD_APP_MEMBERS=false+# The distributed Teams app — one multi-tenant Entra app backing a SingleTenant+# Azure Bot in your own directory, which a customer's Microsoft admin approves+# for their organisation from Switch; not the bring-your-own app an operator+# registers per bridge (TEAMS_SETUP.md). The client id, tenant id, notification+# keypair and privacy/terms URLs are all required together, with exactly one+# credential (a secret, a certificate and its key, or a federated token file)+# and MESSAGING_PUBLIC_URL. One app per environment, never shared. See+# docs/old/bridges/TEAMS_DISTRIBUTED_APP.md.+# TEAMS_APP_CLIENT_ID=+# TEAMS_APP_TENANT_ID=+# TEAMS_APP_CLIENT_SECRET=+# TEAMS_APP_CERTIFICATE=+# TEAMS_APP_CERTIFICATE_PRIVATE_KEY=+# TEAMS_APP_FEDERATED_TOKEN_FILE=+# TEAMS_APP_NOTIFICATION_CERTIFICATE=+# TEAMS_APP_NOTIFICATION_PRIVATE_KEY=+# TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY=+# TEAMS_APP_PRIVACY_URL=+# TEAMS_APP_TERMS_URL=+# Optional: the app's name in Teams (30 characters at most; default "Agent+# Switch"). Give each non-production environment's app its own, e.g.+# "Agent Switch (dev)", so an organisation approving more than one can tell+# them apart.+# TEAMS_APP_NAME=+# ── Mattermost (local dev) ───────────────────────────────────────────────────MATTERMOST_ADMIN_USER=adminMATTERMOST_ADMIN_PASSWORD=diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.tsindex 3f90a2f9b..a8307f66b 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts@@ -132,6 +132,21 @@ describe('buildEnvFile', () => {// compose file always allows the bundled Mattermost; a managed stack// allows nothing more until its operator says so.'OUTBOUND_ALLOWED_PRIVATE_HOSTS',+ // The distributed Teams app's credential, notification keypair and+ // package pages are deployment config too, and a loopback stack can+ // hold none of them for the same reason.+ 'TEAMS_APP_CLIENT_ID',+ 'TEAMS_APP_TENANT_ID',+ 'TEAMS_APP_CLIENT_SECRET',+ 'TEAMS_APP_CERTIFICATE',+ 'TEAMS_APP_CERTIFICATE_PRIVATE_KEY',+ 'TEAMS_APP_FEDERATED_TOKEN_FILE',+ 'TEAMS_APP_NOTIFICATION_CERTIFICATE',+ 'TEAMS_APP_NOTIFICATION_PRIVATE_KEY',+ 'TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY',+ 'TEAMS_APP_PRIVACY_URL',+ 'TEAMS_APP_TERMS_URL',+ 'TEAMS_APP_NAME',]);const missing = [...interpolated]diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex 1a7d73bcc..999015dd1 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -243,6 +243,18 @@ services:DISCORD_APP_CLIENT_SECRET: ${DISCORD_APP_CLIENT_SECRET:-}DISCORD_APP_BOT_TOKEN: ${DISCORD_APP_BOT_TOKEN:-}DISCORD_APP_APPLICATION_ID: ${DISCORD_APP_APPLICATION_ID:-}+ TEAMS_APP_CLIENT_ID: ${TEAMS_APP_CLIENT_ID:-}+ TEAMS_APP_TENANT_ID: ${TEAMS_APP_TENANT_ID:-}+ TEAMS_APP_CLIENT_SECRET: ${TEAMS_APP_CLIENT_SECRET:-}+ TEAMS_APP_CERTIFICATE: ${TEAMS_APP_CERTIFICATE:-}+ TEAMS_APP_CERTIFICATE_PRIVATE_KEY: ${TEAMS_APP_CERTIFICATE_PRIVATE_KEY:-}+ TEAMS_APP_FEDERATED_TOKEN_FILE: ${TEAMS_APP_FEDERATED_TOKEN_FILE:-}+ TEAMS_APP_NOTIFICATION_CERTIFICATE: ${TEAMS_APP_NOTIFICATION_CERTIFICATE:-}+ TEAMS_APP_NOTIFICATION_PRIVATE_KEY: ${TEAMS_APP_NOTIFICATION_PRIVATE_KEY:-}+ TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY: ${TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY:-}+ TEAMS_APP_PRIVACY_URL: ${TEAMS_APP_PRIVACY_URL:-}+ TEAMS_APP_TERMS_URL: ${TEAMS_APP_TERMS_URL:-}+ TEAMS_APP_NAME: ${TEAMS_APP_NAME:-Agent Switch}# True/false flags, so bare keys for the reason given under LOG_FORMAT# below: `${VAR:-}` would hand them an empty string, which fails boot.DISCORD_APP_MESSAGE_CONTENT:diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.tsindex dc3940e26..5844dcdaa 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/bridge-home-url.test.ts@@ -20,6 +20,8 @@ function bridge(overrides: Partial<RemoteBridge>): RemoteBridge {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,...overrides,};}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.tsindex 4e9c28984..077b2d4bc 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts@@ -97,6 +97,8 @@ describe('createBridgeOnServer', () => {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,},});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.tsnew file mode 100644index 000000000..3df7fdee5--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.test.ts@@ -0,0 +1,238 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const getSessionCookie = vi.hoisted(() => vi.fn());+const refreshSession = vi.hoisted(() => vi.fn());+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());++const managedServerHostBlocked = vi.hoisted(() => vi.fn(() => null));+const managedServerStoppedPhase = vi.hoisted(() => vi.fn(() => null));+const noteManagedServerUnanswered = vi.hoisted(() => vi.fn());++vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({+ managedServerHostBlocked,+ managedServerStoppedPhase,+ noteManagedServerUnanswered,+}));++vi.mock('./servers-store', () => ({ getSessionCookie }));+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));++const { bridgeInstallState, disconnectBridgeOnServer } = await import('./disconnect-bridge');++const SERVER = {+ id: 'srv-1',+ name: 'S',+ gatewayUrl: 'https://switch.example.com',+ managed: false,+} as never;++/** A far-from-expiry JWT, so no renewal path is exercised here. */+function validJwt(): string {+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');+ return `${header}.${payload}.sig`;+}++function response(status: number, body: unknown): Response {+ const text = typeof body === 'string' ? body : JSON.stringify(body);+ return {+ status,+ ok: status >= 200 && status < 300,+ json: async () => (typeof body === 'string' ? {} : body),+ headers: { getSetCookie: () => [] },+ text: async () => text,+ } as unknown as Response;+}++const INSTALL = {+ id: 'install-1',+ platform: 'teams',+ external_workspace_id: 'tenant-1',+ status: 'active',+ scopes: '',+ bridge_id: 'b1',+ installed_at: '2026-01-01T00:00:00Z',+ ended_at: null,+};++const fetchMock = vi.fn();++describe('disconnectBridgeOnServer', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(validJwt());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('ends the install backing the bridge, rather than deleting the bridge directly', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [INSTALL] });+ }+ if (url.includes('/messaging-apps/installs/install-1')) {+ return response(200, {});+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });++ const urls = fetchMock.mock.calls.map((call) => call[0] as string);+ expect(urls).toEqual([+ 'https://switch.example.com/gateway/messaging-apps/installs',+ 'https://switch.example.com/gateway/messaging-apps/installs/install-1',+ ]);+ // Never the plain bridge delete — the server refuses that with 409 for an+ // install-backed bridge, so this must not even try it.+ expect(urls.some((u) => u.includes('/collaborations/'))).toBe(false);+ });++ it('ignores an ended install for this bridge and falls back to deleting the bridge', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [{ ...INSTALL, ended_at: '2026-02-01T00:00:00Z' }] });+ }+ if (url.includes('/collaborations/b1')) {+ return response(200, {});+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });++ const urls = fetchMock.mock.calls.map((call) => call[0] as string);+ expect(urls).toContain('https://switch.example.com/gateway/collaborations/b1');+ });++ it('deletes the bridge directly when no install names it', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [{ ...INSTALL, bridge_id: 'some-other-bridge' }] });+ }+ if (url.includes('/collaborations/b1')) {+ return response(200, {});+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });+ });++ it('falls back to deleting the bridge when the server predates installs (404)', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(404, { detail: 'Not Found' });+ }+ if (url.includes('/collaborations/b1')) {+ return response(200, {});+ }+ throw new Error(`unexpected request: ${url}`);+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'deleted' });+ });++ it('maps a non-admin ending the install onto forbidden', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [INSTALL] });+ }+ return response(403, { detail: 'Admin only' });+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'forbidden' });+ });++ it('maps an already-ended install onto not-found rather than claiming success', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [INSTALL] });+ }+ return response(404, { detail: 'Install not found' });+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'not-found' });+ });++ it('rethrows a server fault rather than flattening it into a result', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [INSTALL] });+ }+ return response(500, 'Internal Server Error');+ });++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).rejects.toMatchObject({ status: 500 });+ });++ it('maps an expired session while looking up the install onto unauthenticated', async () => {+ fetchMock.mockImplementation(async () => response(401, { detail: 'expired' }));+ refreshSession.mockResolvedValue(null);++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({+ kind: 'unauthenticated',+ });+ });++ it('maps a non-admin looking up the install onto forbidden', async () => {+ fetchMock.mockImplementation(async () => response(403, { detail: 'admins only' }));++ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({ kind: 'forbidden' });+ });++ it('reports the platform refusing to let go, in its own words', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/messaging-apps/installs')) {+ return response(200, { installs: [INSTALL] });+ }+ return response(502, { detail: 'Slack refused to revoke the token' });+ });++ // The server's own sentence (`detail`), not the raw+ // "Switch gateway returned 502: {...}" status-line message.+ await expect(disconnectBridgeOnServer(SERVER, 'b1')).resolves.toEqual({+ kind: 'error',+ message: 'Slack refused to revoke the token',+ });+ });+});++describe('bridgeInstallState', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(validJwt());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('says a bridge backed by a live install is installed', async () => {+ fetchMock.mockImplementation(async () => response(200, { installs: [INSTALL] }));+ await expect(bridgeInstallState(SERVER, 'b1')).resolves.toBe('installed');+ });++ it('says a bridge no live install names is not installed', async () => {+ fetchMock.mockImplementation(async () =>+ response(200, { installs: [{ ...INSTALL, ended_at: '2026-02-01T00:00:00Z' }] })+ );+ await expect(bridgeInstallState(SERVER, 'b1')).resolves.toBe('not-installed');+ });++ it('says it does not know when it could not ask', async () => {+ fetchMock.mockImplementation(async () => response(403, { detail: 'admins only' }));+ await expect(bridgeInstallState(SERVER, 'b1')).resolves.toBe('unknown');+ });++ it('rethrows a server fault rather than flattening it into "unknown"', async () => {+ fetchMock.mockImplementation(async () => response(500, 'Internal Server Error'));+ await expect(bridgeInstallState(SERVER, 'b1')).rejects.toMatchObject({ status: 500 });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.tsnew file mode 100644index 000000000..df0ca6572--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/disconnect-bridge.ts@@ -0,0 +1,82 @@+import {+ deleteBridge,+ deleteMessagingAppInstall,+ fetchMessagingAppInstalls,+ GatewayError,+} from '@main/core/switch-servers/gateway-client';+import type {+ BridgeInstallState,+ DeleteBridgeResult,+ SwitchServer,+} from '@shared/core/switch-servers/switch-servers';++/**+ * Disconnect a bridge, going through whichever endpoint the gateway actually+ * accepts for it.+ *+ * A bridge created by installing Switch's own app refuses plain+ * `DELETE /collaborations/{id}` with 409 while its install is live: ending the+ * install is what tells the platform and releases the workspace, and it+ * removes the bridge as part of that. So this finds the active install naming+ * this bridge and ends it through `DELETE /messaging-apps/installs/{id}`; a+ * bridge with no such install (every bridge registered with pasted-in+ * credentials) is deleted the ordinary way.+ *+ * The installs list is read with the same 404-tolerance as everywhere else a+ * server might predate a route: an older server has no installs to find, so+ * this falls back to the ordinary delete rather than failing.+ */+export async function disconnectBridgeOnServer(+ server: SwitchServer,+ bridgeId: string+): Promise<DeleteBridgeResult> {+ try {+ const active = await activeInstallFor(server, bridgeId);+ if (!active) {+ return await deleteBridge(server, bridgeId);+ }+ await deleteMessagingAppInstall(server, active.id);+ return { kind: 'deleted' };+ } catch (cause) {+ const result = resultFor(cause);+ if (result) return result;+ throw cause;+ }+}++/**+ * Whether a bridge is backed by a live install, which decides both how it is+ * disconnected and what disconnecting it does to its rooms: an install's end+ * keeps them as internal-only rooms, a bridge delete removes them.+ */+export async function bridgeInstallState(+ server: SwitchServer,+ bridgeId: string+): Promise<BridgeInstallState> {+ try {+ return (await activeInstallFor(server, bridgeId)) ? 'installed' : 'not-installed';+ } catch (cause) {+ if (resultFor(cause)) return 'unknown';+ throw cause;+ }+}++async function activeInstallFor(server: SwitchServer, bridgeId: string) {+ const installs = await fetchMessagingAppInstalls(server);+ return installs.find((i) => i.bridgeId === bridgeId && i.endedAt === null) ?? null;+}++function resultFor(cause: unknown): DeleteBridgeResult | null {+ if (!(cause instanceof GatewayError)) return null;+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };+ if (cause.kind === 'http') {+ if (cause.status === 403) return { kind: 'forbidden' };+ if (cause.status === 404) return { kind: 'not-found' };+ // The platform refusing to let go (a revocation it did not accept) is the+ // server's 502, in the platform's own words. A fault of the server's own+ // is left to raise as itself.+ if (cause.status === 502) return { kind: 'error', message: cause.detail ?? cause.message };+ }+ return null;+}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex b7dd970db..444b3f108 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -59,14 +59,20 @@ const {disconnectClaude,acceptInvitation,acceptPendingInvitation,+ addBridgeTeam,beginMessagingAppInstall,+ deleteMessagingAppInstall,fetchInstallablePlatforms,fetchPendingInvitations,fetchJoinableWorkspaces,+ fetchBridgeTeams,+ fetchMessagingAppInstalls,+ fetchTeamsPackage,joinWorkspaceByDomain,fetchJoinDomains,addJoinDomain,removeJoinDomain,+ removeBridgeTeam,createInvitation,fetchInvitations,fetchInviteEmailEnabled,@@ -462,6 +468,8 @@ describe('room creation', () => {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,},{id: 'b2',@@ -476,10 +484,34 @@ describe('room creation', () => {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,},]);});+ it('carries an attention note and the distributed-Teams flag when the server reports them', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse([+ {+ bridge_id: 'b1',+ bridge_type: 'teams',+ display_name: 'Contoso Teams',+ status: 'active',+ attention: 'The organisation’s admin withdrew approval for this app.',+ team_placement_supported: true,+ },+ ]) as never+ );++ const [bridge] = await fetchBridges(SERVER);++ expect(bridge).toMatchObject({+ attention: 'The organisation’s admin withdrew approval for this app.',+ teamPlacementSupported: true,+ });+ });+it('reads the effective answer as the platform ceiling ANDed with the operator switch', async () => {fetchMock.mockResolvedValue(jsonResponse([@@ -919,6 +951,28 @@ describe('updateBridge', () => {const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];expect(JSON.parse(init.body)).toEqual({});});++ it('sends connection_config only when given, for choosing a distributed Teams default team', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ bridge_id: 'b1',+ bridge_type: 'teams',+ display_name: 'Contoso Teams',+ status: 'active',+ }) as never+ );++ await updateBridge(SERVER, 'b1', {+ channelCreationEnabled: true,+ connectionConfig: { team_id: 'team-1' },+ });++ const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];+ expect(JSON.parse(init.body)).toEqual({+ channel_creation_enabled: true,+ connection_config: { team_id: 'team-1' },+ });+ });});describe('deleteBridge', () => {@@ -1212,6 +1266,302 @@ describe('sign-up support', () => {});});+describe('distributed Teams team placement', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('lists the teams, the chosen default, and the catalogue state', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ teams: [+ { team_id: 't1', name: 'Engineering', has_switch: true, is_default: true },+ { team_id: 't2', name: 'Sales', has_switch: false, is_default: false },+ ],+ default_team_id: 't1',+ in_catalog: true,+ catalog_problem: null,+ }) as never+ );++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toEqual({+ kind: 'listed',+ teams: [+ { teamId: 't1', name: 'Engineering', hasSwitch: true, isDefault: true },+ { teamId: 't2', name: 'Sales', hasSwitch: false, isDefault: false },+ ],+ defaultTeamId: 't1',+ inCatalog: true,+ catalogProblem: null,+ });+ expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(+ 'https://switch.example.com/gateway/collaborations/b1/teams'+ );+ });++ it('reports a bridge this never applies to, rather than throwing', async () => {+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toEqual({+ kind: 'not-distributed-teams',+ });+ });++ it('reports a stopped bridge with the detail naming it', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(503, '{"detail":"The bridge is not running"}') as never+ );++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toEqual({+ kind: 'not-running',+ message: 'The bridge is not running',+ });+ });++ it("reports Microsoft Graph's own refusal in its words", async () => {+ fetchMock.mockResolvedValue(+ errorResponse(502, '{"detail":"Microsoft Graph refused the request"}') as never+ );++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toEqual({+ kind: 'microsoft-refused',+ message: 'Microsoft Graph refused the request',+ });+ });++ it('reports a non-admin as forbidden', async () => {+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Admin only"}') as never);++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toEqual({ kind: 'forbidden' });+ });++ it('reports an expired session as unauthenticated', async () => {+ fetchMock.mockResolvedValue(unauthorizedResponse() as never);++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toEqual({ kind: 'unauthenticated' });+ });++ it('reports an unreachable gateway as an error rather than throwing', async () => {+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ await expect(fetchBridgeTeams(SERVER, 'b1')).resolves.toMatchObject({ kind: 'error' });+ });++ it('rethrows a server fault rather than flattening it into a result', async () => {+ fetchMock.mockResolvedValue(errorResponse(500, 'Internal Server Error') as never);++ await expect(fetchBridgeTeams(SERVER, 'b1')).rejects.toMatchObject({ status: 500 });+ });++ it('adds Switch to a team', async () => {+ fetchMock.mockResolvedValue(jsonResponse({}) as never);++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).resolves.toEqual({ kind: 'added' });++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1/teams/t2');+ expect(init.method).toBe('POST');+ });++ it('reports a team outside the catalogued app as its own case, with the next step', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(+ 409,+ '{"detail":"The app is not yet in this organisation\'s catalogue"}'+ ) as never+ );++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).resolves.toEqual({+ kind: 'not-in-catalog',+ message: "The app is not yet in this organisation's catalogue",+ });+ });++ it.each([+ [503, 'The Teams connection is not running; try again in a moment.'],+ [502, 'Microsoft refused: AADSTS7000112'],+ [404, 'No connection on the distributed Teams app has that id.'],+ ])(+ 'reports a %s adding a team as an error in the gateway’s words, not a catalogue problem',+ async (status, detail) => {+ fetchMock.mockResolvedValue(errorResponse(status, JSON.stringify({ detail })) as never);++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).resolves.toEqual({+ kind: 'error',+ message: detail,+ });+ }+ );++ it.each([+ [503, 'The Teams connection is not running; try again in a moment.'],+ [502, 'Microsoft refused: AADSTS7000112'],+ [404, 'No connection on the distributed Teams app has that id.'],+ ])('reports a %s removing a team as an error in the gateway’s words', async (status, detail) => {+ fetchMock.mockResolvedValue(errorResponse(status, JSON.stringify({ detail })) as never);++ await expect(removeBridgeTeam(SERVER, 'b1', 't1')).resolves.toEqual({+ kind: 'error',+ message: detail,+ });+ });++ it('reports a non-admin adding a team as forbidden', async () => {+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Admin only"}') as never);++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).resolves.toEqual({ kind: 'forbidden' });+ });++ it('reports an expired session adding a team as unauthenticated', async () => {+ fetchMock.mockResolvedValue(unauthorizedResponse() as never);++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).resolves.toEqual({ kind: 'unauthenticated' });+ });++ it('reports an unreachable gateway adding a team as an error rather than throwing', async () => {+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).resolves.toMatchObject({ kind: 'error' });+ });++ it('rethrows a server fault adding a team rather than flattening it into a result', async () => {+ fetchMock.mockResolvedValue(errorResponse(500, 'Internal Server Error') as never);++ await expect(addBridgeTeam(SERVER, 'b1', 't2')).rejects.toMatchObject({ status: 500 });+ });++ it('removes Switch from a team', async () => {+ fetchMock.mockResolvedValue(jsonResponse({}) as never);++ await expect(removeBridgeTeam(SERVER, 'b1', 't1')).resolves.toEqual({ kind: 'removed' });++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1/teams/t1');+ expect(init.method).toBe('DELETE');+ });++ it('reports a non-admin removing a team as forbidden', async () => {+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Admin only"}') as never);++ await expect(removeBridgeTeam(SERVER, 'b1', 't1')).resolves.toEqual({ kind: 'forbidden' });+ });++ it('reports an expired session removing a team as unauthenticated', async () => {+ fetchMock.mockResolvedValue(unauthorizedResponse() as never);++ await expect(removeBridgeTeam(SERVER, 'b1', 't1')).resolves.toEqual({+ kind: 'unauthenticated',+ });+ });++ it('reports an unreachable gateway removing a team as an error rather than throwing', async () => {+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ await expect(removeBridgeTeam(SERVER, 'b1', 't1')).resolves.toMatchObject({ kind: 'error' });+ });++ it('rethrows a server fault removing a team rather than flattening it into a result', async () => {+ fetchMock.mockResolvedValue(errorResponse(500, 'Internal Server Error') as never);++ await expect(removeBridgeTeam(SERVER, 'b1', 't1')).rejects.toMatchObject({ status: 500 });+ });++ it('reads the install package as raw bytes', async () => {+ const bytes = new TextEncoder().encode('zip-bytes').buffer;+ fetchMock.mockResolvedValue({+ status: 200,+ ok: true,+ json: async () => ({}),+ headers: { getSetCookie: () => [] },+ text: async () => '',+ arrayBuffer: async () => bytes,+ } as unknown as Response);++ await expect(fetchTeamsPackage(SERVER, 'b1')).resolves.toBe(bytes);++ const [url] = fetchMock.mock.calls[0] as unknown as [string];+ expect(url).toBe('https://switch.example.com/gateway/collaborations/b1/teams-package');+ });++ it('leaves a bridge this does not apply to as a throw — there is no result form for it', async () => {+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);++ await expect(fetchTeamsPackage(SERVER, 'b1')).rejects.toMatchObject({ status: 404 });+ });+});++describe('messaging-app installs', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('lists installs, active and ended alike', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ installs: [+ {+ id: 'install-1',+ platform: 'teams',+ external_workspace_id: 'tenant-1',+ status: 'active',+ scopes: 'Team.Create',+ bridge_id: 'b1',+ installed_at: '2026-01-01T00:00:00Z',+ ended_at: null,+ },+ ],+ }) as never+ );++ await expect(fetchMessagingAppInstalls(SERVER)).resolves.toEqual([+ {+ id: 'install-1',+ platform: 'teams',+ externalWorkspaceId: 'tenant-1',+ status: 'active',+ scopes: 'Team.Create',+ bridgeId: 'b1',+ installedAt: '2026-01-01T00:00:00Z',+ endedAt: null,+ },+ ]);+ });++ it('reads a server without the route as having no installs to report', async () => {+ fetchMock.mockResolvedValue(errorResponse(404, '{"detail":"Not Found"}') as never);++ await expect(fetchMessagingAppInstalls(SERVER)).resolves.toEqual([]);+ });++ it('raises on any other failure', async () => {+ fetchMock.mockResolvedValue(errorResponse(403, '{"detail":"Forbidden"}') as never);++ await expect(fetchMessagingAppInstalls(SERVER)).rejects.toMatchObject({ status: 403 });+ });++ it('ends an install by id', async () => {+ fetchMock.mockResolvedValue(jsonResponse({}) as never);++ await deleteMessagingAppInstall(SERVER, 'install-1');++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];+ expect(url).toBe('https://switch.example.com/gateway/messaging-apps/installs/install-1');+ expect(init.method).toBe('DELETE');+ });+});+describe('acceptInvitation', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex 934571659..f67e7610c 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -32,10 +32,12 @@ import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';import { cloudProviderConnectionSchema } from '@shared/core/switch-servers/provider-credential';import type {AddressingPolicy,+ AddTeamsTeamResult,BridgeConfigField,BridgeDirectoryUser,DeleteBridgeResult,LinkedIdentity,+ MessagingAppInstall,RemoteAgentRoom,RemoteAgentSummary,RemoteBridge,@@ -45,10 +47,13 @@ import type {RemoteRoomGroup,RemoteRoomRole,RemoteRoomSummary,+ RemoveTeamsTeamResult,SwitchAuthConfig,SwitchServer,SwitchServerDeclaration,SwitchUser,+ TeamsTeam,+ TeamsTeamsResult,} from '@shared/core/switch-servers/switch-servers';import type {Invitation,@@ -1153,6 +1158,11 @@ type BridgeJson = {channel_creation_enabled?: boolean;// Absent on a server predating Telegram, where every bridge had a directory.directory_search_supported?: boolean;+ // Both absent on a server predating this pair of fields — read as "nothing+ // to warn about" and "not the distributed Teams app", which is how every+ // bridge behaved before either existed.+ attention?: string | null;+ team_placement_supported?: boolean;};function mapBridge(b: BridgeJson): RemoteBridge {@@ -1168,6 +1178,8 @@ function mapBridge(b: BridgeJson): RemoteBridge {channelCreationSupported,canCreateChannels: channelCreationSupported && channelCreationEnabled,directorySearchSupported: b.directory_search_supported ?? true,+ attention: b.attention ?? null,+ teamPlacementSupported: b.team_placement_supported ?? false,};}@@ -1357,16 +1369,26 @@ export async function createBridge(* create channels at all returns 400 with a message naming the platform;* callers map that like any other rejected edit rather than a bridge-specific* case.+ *+ * `connectionConfig`, when given, merges into the bridge's stored config —+ * today only the distributed Teams app's `{ team_id }` default-team choice.+ * Left unset, the field is omitted from the request and the gateway leaves the+ * stored config untouched, same as any other field here.*/export async function updateBridge(server: SwitchServer,bridgeId: string,- params: { channelCreationEnabled?: boolean }+ params: { channelCreationEnabled?: boolean; connectionConfig?: Record<string, string> }): Promise<RemoteBridge> {const res = await gatewayFetch(server, `/collaborations/${encodeURIComponent(bridgeId)}`, {authenticated: true,method: 'PATCH',- body: { channel_creation_enabled: params.channelCreationEnabled },+ body: {+ channel_creation_enabled: params.channelCreationEnabled,+ ...(params.connectionConfig !== undefined+ ? { connection_config: params.connectionConfig }+ : {}),+ },});return mapBridge((await res.json()) as BridgeJson);}@@ -1407,6 +1429,228 @@ export async function deleteBridge(}}+// ── Microsoft Teams team placement ──────────────────────────────────────────++/** The gateway `TeamsTeamSummary` wire shape. */+type TeamsTeamJson = {+ team_id: string;+ name: string;+ has_switch: boolean | null;+ is_default: boolean;+};++function mapTeamsTeam(t: TeamsTeamJson): TeamsTeam {+ return { teamId: t.team_id, name: t.name, hasSwitch: t.has_switch, isDefault: t.is_default };+}++/**+ * Read a distributed Teams bridge's team placement+ * (`GET /collaborations/{id}/teams`, admin-only).+ *+ * Every failure this call can report is recoverable and bridge-specific, so+ * each becomes a typed result instead of a raw throw: 404 means this bridge is+ * not (or is no longer) a running distributed Teams connection, 503 means it+ * exists but is not running right now, and 502 is Microsoft Graph itself+ * refusing the request — its `detail` is already written for a human.+ */+export async function fetchBridgeTeams(+ server: SwitchServer,+ bridgeId: string+): Promise<TeamsTeamsResult> {+ try {+ const res = await gatewayFetch(+ server,+ `/collaborations/${encodeURIComponent(bridgeId)}/teams`,+ { authenticated: true }+ );+ const json = (await res.json()) as {+ teams: TeamsTeamJson[];+ default_team_id: string | null;+ in_catalog: boolean;+ catalog_problem: string | null;+ };+ return {+ kind: 'listed',+ teams: json.teams.map(mapTeamsTeam),+ defaultTeamId: json.default_team_id,+ inCatalog: json.in_catalog,+ catalogProblem: json.catalog_problem,+ };+ } catch (cause) {+ if (cause instanceof GatewayError) {+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };+ if (cause.kind === 'http' && cause.status === 404) return { kind: 'not-distributed-teams' };+ if (cause.kind === 'http' && cause.status === 503) {+ return { kind: 'not-running', message: cause.detail ?? cause.message };+ }+ if (cause.kind === 'http' && cause.status === 502) {+ return { kind: 'microsoft-refused', message: cause.detail ?? cause.message };+ }+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };+ }+ throw cause;+ }+}++/** The connection restarting (503), Microsoft refusing (502), or the+ * connection gone (404): each written for a person in the gateway's `detail`. */+function isTeamsConnectionFailure(status: number | undefined): boolean {+ return status === 404 || status === 502 || status === 503;+}++/**+ * Add Switch's distributed app to a team (`POST /collaborations/{id}/teams/{teamId}`,+ * admin-only). A 409 means the app is not in the organisation's catalogue yet —+ * the one failure here with a next step, so it carries the gateway's own+ * explanation rather than being folded into a generic error. The connection+ * restarting (503), Microsoft refusing (502) and a connection that is gone+ * (404) are errors in the gateway's own words.+ */+export async function addBridgeTeam(+ server: SwitchServer,+ bridgeId: string,+ teamId: string+): Promise<AddTeamsTeamResult> {+ try {+ await gatewayFetch(+ server,+ `/collaborations/${encodeURIComponent(bridgeId)}/teams/${encodeURIComponent(teamId)}`,+ { authenticated: true, method: 'POST' }+ );+ return { kind: 'added' };+ } catch (cause) {+ if (cause instanceof GatewayError) {+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };+ if (cause.kind === 'http' && cause.status === 409) {+ return { kind: 'not-in-catalog', message: cause.detail ?? cause.message };+ }+ if (cause.kind === 'http' && isTeamsConnectionFailure(cause.status)) {+ return { kind: 'error', message: cause.detail ?? cause.message };+ }+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };+ }+ throw cause;+ }+}++/** Remove Switch's distributed app from a team+ * (`DELETE /collaborations/{id}/teams/{teamId}`, admin-only). The connection+ * restarting (503), Microsoft refusing (502) and a connection that is gone+ * (404) are errors in the gateway's own words. */+export async function removeBridgeTeam(+ server: SwitchServer,+ bridgeId: string,+ teamId: string+): Promise<RemoveTeamsTeamResult> {+ try {+ await gatewayFetch(+ server,+ `/collaborations/${encodeURIComponent(bridgeId)}/teams/${encodeURIComponent(teamId)}`,+ { authenticated: true, method: 'DELETE' }+ );+ return { kind: 'removed' };+ } catch (cause) {+ if (cause instanceof GatewayError) {+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };+ if (cause.kind === 'http' && isTeamsConnectionFailure(cause.status)) {+ return { kind: 'error', message: cause.detail ?? cause.message };+ }+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };+ }+ throw cause;+ }+}++/**+ * The distributed Teams app's install package, as raw bytes+ * (`GET /collaborations/{id}/teams-package`, admin-only) — for a Teams admin to+ * upload by hand, in the Teams admin center, when the app is not yet in the+ * organisation's catalogue. Unmapped: a bridge this does not apply to still+ * raises, since there is no form here for a recoverable failure to improve.+ */+export async function fetchTeamsPackage(+ server: SwitchServer,+ bridgeId: string+): Promise<ArrayBuffer> {+ const res = await gatewayFetch(+ server,+ `/collaborations/${encodeURIComponent(bridgeId)}/teams-package`,+ { authenticated: true }+ );+ return res.arrayBuffer();+}++// ── Messaging-app installs ──────────────────────────────────────────────────++/** The gateway `MessagingAppInstallSummary` wire shape. */+type MessagingAppInstallJson = {+ id: string;+ platform: string;+ external_workspace_id: string;+ status: string;+ scopes: string;+ bridge_id: string | null;+ installed_at: string;+ ended_at: string | null;+};++function mapMessagingAppInstall(i: MessagingAppInstallJson): MessagingAppInstall {+ return {+ id: i.id,+ platform: i.platform,+ externalWorkspaceId: i.external_workspace_id,+ status: i.status,+ scopes: i.scopes,+ bridgeId: i.bridge_id,+ installedAt: i.installed_at,+ endedAt: i.ended_at,+ };+}++/**+ * Every messaging-app install recorded for this workspace+ * (`GET /messaging-apps/installs`), active and ended alike.+ *+ * A 404 is a server from before installs were tracked this way; it answers+ * empty rather than failing, since the one caller today+ * ({@link disconnectBridgeOnServer} in `disconnect-bridge.ts`) falls back to+ * deleting the bridge directly when it finds no matching install.+ */+export async function fetchMessagingAppInstalls(+ server: SwitchServer+): Promise<MessagingAppInstall[]> {+ let res: Response;+ try {+ res = await gatewayFetch(server, '/messaging-apps/installs', { authenticated: true });+ } catch (cause) {+ if (cause instanceof GatewayError && cause.status === 404) return [];+ throw cause;+ }+ const json = (await res.json()) as { installs: MessagingAppInstallJson[] };+ return json.installs.map(mapMessagingAppInstall);+}++/**+ * End a messaging-app install (`DELETE /messaging-apps/installs/{id}`).+ *+ * This is what actually removes Switch's standing registration from the+ * platform organisation it was approved into — plain `DELETE+ * /collaborations/{id}` on an install-backed bridge is refused (409) because+ * the server has no way to tell, from a bridge id alone, which install to end.+ */+export async function deleteMessagingAppInstall(+ server: SwitchServer,+ installId: string+): Promise<void> {+ await gatewayFetch(server, `/messaging-apps/installs/${encodeURIComponent(installId)}`, {+ authenticated: true,+ method: 'DELETE',+ });+}+/** The gateway `IdentityClaimant` wire shape. */type IdentityClaimantJson = {user_id: string;diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.tsnew file mode 100644index 000000000..ece931ab0--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.test.ts@@ -0,0 +1,78 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const showSaveDialog = vi.hoisted(() => vi.fn());+const getMainWindow = vi.hoisted(() => vi.fn());+const writeFile = vi.hoisted(() => vi.fn());+const fetchTeamsPackage = vi.hoisted(() => vi.fn());++vi.mock('electron', () => ({+ dialog: { showSaveDialog },+}));+vi.mock('@main/app/window', () => ({ getMainWindow }));+vi.mock('node:fs/promises', () => ({ writeFile }));+vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchTeamsPackage }));++const { saveTeamsPackage } = await import('./teams-package');++const SERVER = {+ id: 'srv-1',+ name: 'S',+ gatewayUrl: 'https://switch.example.com',+ managed: false,+} as never;++const WINDOW = {} as never;++describe('saveTeamsPackage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getMainWindow.mockReturnValue(WINDOW);+ writeFile.mockResolvedValue(undefined);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('shows the save dialog before fetching the package, so cancelling costs no round trip', async () => {+ showSaveDialog.mockResolvedValue({ canceled: true, filePath: undefined });++ await expect(saveTeamsPackage(SERVER, 'b1', 'switch-teams-acme.zip')).resolves.toBeNull();++ expect(showSaveDialog).toHaveBeenCalledWith(+ WINDOW,+ expect.objectContaining({ defaultPath: 'switch-teams-acme.zip' })+ );+ expect(fetchTeamsPackage).not.toHaveBeenCalled();+ expect(writeFile).not.toHaveBeenCalled();+ });++ it('returns null without opening a dialog when there is no window to own it', async () => {+ getMainWindow.mockReturnValue(null);++ await expect(saveTeamsPackage(SERVER, 'b1', 'switch-teams-acme.zip')).resolves.toBeNull();++ expect(showSaveDialog).not.toHaveBeenCalled();+ });++ it('returns null when the dialog resolves with no path, even if not formally cancelled', async () => {+ showSaveDialog.mockResolvedValue({ canceled: false, filePath: undefined });++ await expect(saveTeamsPackage(SERVER, 'b1', 'switch-teams-acme.zip')).resolves.toBeNull();++ expect(fetchTeamsPackage).not.toHaveBeenCalled();+ });++ it('fetches the package and writes it to the chosen path on save', async () => {+ showSaveDialog.mockResolvedValue({ canceled: false, filePath: '/tmp/switch-teams-acme.zip' });+ const bytes = new TextEncoder().encode('zip-bytes').buffer;+ fetchTeamsPackage.mockResolvedValue(bytes);++ await expect(saveTeamsPackage(SERVER, 'b1', 'switch-teams-acme.zip')).resolves.toBe(+ '/tmp/switch-teams-acme.zip'+ );++ expect(fetchTeamsPackage).toHaveBeenCalledWith(SERVER, 'b1');+ expect(writeFile).toHaveBeenCalledWith('/tmp/switch-teams-acme.zip', Buffer.from(bytes));+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.tsnew file mode 100644index 000000000..cdcfa2a30--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/teams-package.ts@@ -0,0 +1,31 @@+import { writeFile } from 'node:fs/promises';+import { dialog } from 'electron';+import { getMainWindow } from '@main/app/window';+import { fetchTeamsPackage } from '@main/core/switch-servers/gateway-client';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';++/**+ * Let the user save the distributed Teams app's install package to disk, for a+ * Teams admin to upload by hand (Teams admin center → Teams apps → Manage apps+ * → Upload new app) when the app is not yet in the organisation's catalogue.+ *+ * The save dialog is shown before the package is fetched, so cancelling costs+ * no round trip. Returns the saved path, or null if the user cancelled.+ */+export async function saveTeamsPackage(+ server: SwitchServer,+ bridgeId: string,+ defaultFileName: string+): Promise<string | null> {+ const win = getMainWindow();+ if (!win) return null;+ const result = await dialog.showSaveDialog(win, {+ title: 'Save Microsoft Teams app package',+ defaultPath: defaultFileName,+ filters: [{ name: 'Teams app package', extensions: ['zip'] }],+ });+ if (result.canceled || !result.filePath) return null;+ const bytes = await fetchTeamsPackage(server, bridgeId);+ await writeFile(result.filePath, Buffer.from(bytes));+ return result.filePath;+}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.tsindex ac43e82ca..644157b36 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.test.ts@@ -89,6 +89,8 @@ describe('updateBridgeOnServer', () => {channelCreationSupported: true,canCreateChannels: false,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,},});});@@ -141,6 +143,53 @@ describe('updateBridgeOnServer', () => {});});+ it('reports a rejected default-team choice as invalid, with the server’s own sentence', async () => {+ // Setting a default team that Switch is not in, or that does not exist,+ // comes back 422 from the PATCH.+ fetchMock.mockResolvedValue(+ response(422, {+ detail: 'Switch is not in that team. Add it to the team first, then make it the default.',+ })+ );++ await expect(+ updateBridgeOnServer(SERVER, { ...PARAMS, connectionConfig: { team_id: 't2' } })+ ).resolves.toEqual({+ kind: 'invalid',+ message: 'Switch is not in that team. Add it to the team first, then make it the default.',+ });+ });++ it('reports a stopped bridge’s refusal to check a default-team change, not a thrown error', async () => {+ fetchMock.mockResolvedValue(+ response(503, {+ detail:+ 'The connection is not running, so Switch cannot check this change with the platform; try again in a moment.',+ })+ );++ await expect(+ updateBridgeOnServer(SERVER, { ...PARAMS, connectionConfig: { team_id: 't2' } })+ ).resolves.toEqual({+ kind: 'error',+ message:+ 'The connection is not running, so Switch cannot check this change with the platform; try again in a moment.',+ });+ });++ it('reports Microsoft Graph’s own refusal of a default-team change, not a thrown error', async () => {+ fetchMock.mockResolvedValue(+ response(502, { detail: 'Microsoft could not be asked whether Switch is in team t2' })+ );++ await expect(+ updateBridgeOnServer(SERVER, { ...PARAMS, connectionConfig: { team_id: 't2' } })+ ).resolves.toEqual({+ kind: 'error',+ message: 'Microsoft could not be asked whether Switch is in team t2',+ });+ });+it('surfaces an unreachable gateway rather than failing silently', async () => {fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.tsindex d1e3fa08a..bc97ceb6d 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-bridge.ts@@ -20,6 +20,7 @@ export async function updateBridgeOnServer(try {const bridge = await updateBridge(server, params.bridgeId, {channelCreationEnabled: params.channelCreationEnabled,+ connectionConfig: params.connectionConfig,});return { kind: 'updated', bridge };} catch (cause) {@@ -32,6 +33,14 @@ export async function updateBridgeOnServer(if (cause.kind === 'http' && (cause.status === 400 || cause.status === 422)) {return { kind: 'invalid', message: cause.detail ?? cause.message };}+ // A distributed Teams bridge editing its default team can also fail with+ // 503 (restarting right now) or 502 (Microsoft Graph itself refusing+ // the request) — both recoverable and both already written for a human+ // in `detail`, so they get the same treatment as 400/422 rather than+ // falling through to the generic throw below.+ if (cause.kind === 'http' && (cause.status === 503 || cause.status === 502)) {+ return { kind: 'error', message: cause.detail ?? cause.message };+ }if (cause.kind === 'network') return { kind: 'error', message: cause.message };}throw cause;diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.tsindex e6b84d82b..b5e39443e 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts@@ -4,9 +4,15 @@ import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';const managedServerHostBlocked = vi.hoisted(() => vi.fn((): unknown => null));const trackEvent = vi.hoisted(() => vi.fn());const createRoomOnServer = vi.hoisted(() => vi.fn());-const deleteBridge = vi.hoisted(() => vi.fn());+const disconnectBridgeOnServer = vi.hoisted(() => vi.fn());+const bridgeInstallState = vi.hoisted(() => vi.fn());const deleteRoom = vi.hoisted(() => vi.fn());const fetchBridges = vi.hoisted(() => vi.fn());+const fetchBridgeTeams = vi.hoisted(() => vi.fn());+const addBridgeTeam = vi.hoisted(() => vi.fn());+const removeBridgeTeam = vi.hoisted(() => vi.fn());+const updateBridgeOnServer = vi.hoisted(() => vi.fn());+const saveTeamsPackage = vi.hoisted(() => vi.fn());const getServer = vi.hoisted(() => vi.fn());const getSessionCookie = vi.hoisted(() => vi.fn());const requireWorkspace = vi.hoisted(() => vi.fn());@@ -46,17 +52,22 @@ vi.mock('@main/core/switch-servers/backfill-agent-icons', () => ({ backfillAgentvi.mock('@main/core/switch-servers/bridge-home-url', () => ({ withResolvedHomeUrls: vi.fn() }));vi.mock('@main/core/switch-servers/create-bridge', () => ({ createBridgeOnServer: vi.fn() }));vi.mock('@main/core/switch-servers/create-room', () => ({ createRoomOnServer }));+vi.mock('@main/core/switch-servers/disconnect-bridge', () => ({+ disconnectBridgeOnServer,+ bridgeInstallState,+}));vi.mock('@main/core/switch-servers/identities', () => ({claimIdentityOnServer: vi.fn(),searchDirectoryOnServer: vi.fn(),}));-vi.mock('@main/core/switch-servers/update-bridge', () => ({ updateBridgeOnServer: vi.fn() }));+vi.mock('@main/core/switch-servers/teams-package', () => ({ saveTeamsPackage }));+vi.mock('@main/core/switch-servers/update-bridge', () => ({ updateBridgeOnServer }));vi.mock('@main/core/switch-servers/gateway-client', () => ({+ addBridgeTeam,addRoomAgents: vi.fn(),agentExistsOnServer: vi.fn(),createRoomFromTemplate: vi.fn(),decodeJwtTenantId: vi.fn(() => null),- deleteBridge,deleteRoom,fetchAddressingPolicy: vi.fn(),fetchAgentDetail: vi.fn(),@@ -64,6 +75,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({fetchAgents: vi.fn(),fetchAllExternalUsers: vi.fn(),fetchBridges,+ fetchBridgeTeams,fetchBridgeTypes: vi.fn(),fetchMyIdentities: vi.fn(),fetchRoomAgentIds: vi.fn(),@@ -75,6 +87,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({GatewayError: class GatewayError extends Error {},ownsOwnerAddressedAgent: vi.fn(),releaseBridgeIdentity: vi.fn(),+ removeBridgeTeam,removeRoomAgent: vi.fn(),switchTenant,updateAddressingPolicy: vi.fn(),@@ -126,7 +139,7 @@ describe('disconnecting a bridge', () => {});it('reports a disconnection the gateway carried out', async () => {- deleteBridge.mockResolvedValue({ kind: 'deleted' });+ disconnectBridgeOnServer.mockResolvedValue({ kind: 'deleted' });await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });@@ -141,7 +154,7 @@ describe('disconnecting a bridge', () => {it('reports a refusal as a failure rather than as a disconnection', async () => {// Admin-only, and the gateway hands back the refusal instead of throwing// it — so the await returns exactly as it does for a bridge that went.- deleteBridge.mockResolvedValue({ kind: 'forbidden' });+ disconnectBridgeOnServer.mockResolvedValue({ kind: 'forbidden' });await workspacesController.deleteBridge({ workspaceId: 'ws', bridgeId: 'b1' });@@ -154,6 +167,111 @@ describe('disconnecting a bridge', () => {});});+describe('distributed Microsoft Teams team placement', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ managedServerHostBlocked.mockReturnValue(null);+ getServer.mockResolvedValue(server({}));+ requireWorkspace.mockResolvedValue(workspace());+ });++ it('reads whether a bridge is backed by a live install, scoped to the workspace’s server', async () => {+ bridgeInstallState.mockResolvedValue('installed');++ await expect(+ workspacesController.bridgeInstallState({ workspaceId: 'ws', bridgeId: 'b1' })+ ).resolves.toBe('installed');++ expect(bridgeInstallState).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'b1');+ });++ it('lists a bridge’s team placement', async () => {+ const result = {+ kind: 'listed' as const,+ teams: [],+ defaultTeamId: null,+ inCatalog: true,+ catalogProblem: null,+ };+ fetchBridgeTeams.mockResolvedValue(result);++ await expect(+ workspacesController.listBridgeTeams({ workspaceId: 'ws', bridgeId: 'b1' })+ ).resolves.toEqual(result);++ expect(fetchBridgeTeams).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'b1');+ });++ it('adds Switch to a team', async () => {+ addBridgeTeam.mockResolvedValue({ kind: 'added' });++ await expect(+ workspacesController.addBridgeTeam({ workspaceId: 'ws', bridgeId: 'b1', teamId: 't1' })+ ).resolves.toEqual({ kind: 'added' });++ expect(addBridgeTeam).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), 'b1', 't1');+ });++ it('removes Switch from a team', async () => {+ removeBridgeTeam.mockResolvedValue({ kind: 'removed' });++ await expect(+ workspacesController.removeBridgeTeam({ workspaceId: 'ws', bridgeId: 'b1', teamId: 't1' })+ ).resolves.toEqual({ kind: 'removed' });++ expect(removeBridgeTeam).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'srv' }),+ 'b1',+ 't1'+ );+ });++ it('chooses a default team by editing the bridge, turning channel creation on with it', async () => {+ const updated = { kind: 'updated' as const, bridge: { id: 'b1' } as never };+ updateBridgeOnServer.mockResolvedValue(updated);++ await expect(+ workspacesController.setDefaultTeamsTeam({ workspaceId: 'ws', bridgeId: 'b1', teamId: 't1' })+ ).resolves.toEqual(updated);++ expect(updateBridgeOnServer).toHaveBeenCalledWith(expect.objectContaining({ id: 'srv' }), {+ bridgeId: 'b1',+ channelCreationEnabled: true,+ connectionConfig: { team_id: 't1' },+ });+ });++ it('saves the Teams app package to disk under the chosen file name', async () => {+ saveTeamsPackage.mockResolvedValue('/tmp/switch-teams.zip');++ await expect(+ workspacesController.downloadTeamsPackage({+ workspaceId: 'ws',+ bridgeId: 'b1',+ defaultFileName: 'switch-teams.zip',+ })+ ).resolves.toBe('/tmp/switch-teams.zip');++ expect(saveTeamsPackage).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'srv' }),+ 'b1',+ 'switch-teams.zip'+ );+ });++ it('reports a cancelled save as null rather than a path', async () => {+ saveTeamsPackage.mockResolvedValue(null);++ await expect(+ workspacesController.downloadTeamsPackage({+ workspaceId: 'ws',+ bridgeId: 'b1',+ defaultFileName: 'switch-teams.zip',+ })+ ).resolves.toBeNull();+ });+});+describe('an action a workspace whose host has gone down cannot take', () => {const blocked = {sshHost: 'h',diff --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 ca9473c4a..740d4c7e9 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@@ -3,12 +3,16 @@ import { withResolvedHomeUrls } from '@main/core/switch-servers/bridge-home-url'import { createBridgeOnServer } from '@main/core/switch-servers/create-bridge';import { createRoomOnServer } from '@main/core/switch-servers/create-room';import {+ bridgeInstallState,+ disconnectBridgeOnServer,+} from '@main/core/switch-servers/disconnect-bridge';+import {+ addBridgeTeam,addRoomAgents,agentExistsOnServer,changeTemplateRun,createRoomFromTemplate,createTemplate,- deleteBridge,deleteRoom,deleteTemplate,exportRoomYaml,@@ -18,6 +22,7 @@ import {fetchAgents,fetchAllExternalUsers,fetchBridges,+ fetchBridgeTeams,beginMessagingAppInstall,fetchBridgeTypes,fetchInstallablePlatforms,@@ -34,6 +39,7 @@ import {GatewayError,ownsOwnerAddressedAgent,releaseBridgeIdentity,+ removeBridgeTeam,removeRoomAgent,type StoredTemplateDetail,type StoredTemplateSummary,@@ -54,6 +60,7 @@ import {} from '@main/core/switch-servers/identities';import { hostUnreachable } from '@main/core/switch-servers/require-server';import { serverKindOf } from '@main/core/switch-servers/servers-store';+import { saveTeamsPackage } from '@main/core/switch-servers/teams-package';import { updateBridgeOnServer } from '@main/core/switch-servers/update-bridge';import { bridgePlatformOfType } from '@main/core/telemetry/bridge-platform';import type {@@ -67,7 +74,9 @@ import type {import { roomAgentsDirectionOf } from '@main/core/telemetry/narrow';import { trackEvent } from '@main/core/telemetry/telemetry-service';import type {+ BridgeInstallState,AddressingPolicy,+ AddTeamsTeamResult,AgentIconBackfill,AgentVerifyResult,BridgeDirectorySearchResult,@@ -89,7 +98,9 @@ import type {RemoteRoomGroup,RemoteRoomRole,RemoteRoomSummary,+ RemoveTeamsTeamResult,SwitchServer,+ TeamsTeamsResult,UpdateBridgeParams,UpdateBridgeResult,UpdateRoomParams,@@ -331,10 +342,16 @@ export const workspacesController = createRPCController({),/**- * Disconnect a messaging app from the chosen workspace. Admin-only, and the- * gateway deletes every Switch room on the bridge on the way — see- * `deleteBridge`. The renderer owns the confirmation; by the time this runs- * the rooms are being given up deliberately.+ * Disconnect a messaging app from the chosen workspace. Admin-only.+ *+ * For a bridge created by pasting in credentials, the gateway deletes every+ * Switch room on the bridge on the way — see `deleteBridge`. For one created+ * by approving Switch's own app (an "install"), there are no rooms taken+ * with it: `disconnectBridgeOnServer` ends the install instead, which only+ * stops Switch listening in that organisation and leaves the rooms as+ * internal-only. Either way the renderer owns the confirmation, with copy+ * matching which of the two is about to happen; by the time this runs it is+ * deliberate.*/deleteBridge: (params: DeleteBridgeParams): Promise<DeleteBridgeResult> =>withReachableWorkspaceSession(params.workspaceId, async (server) => {@@ -344,7 +361,7 @@ export const workspacesController = createRPCController({// workspace. A disconnect is a confirmed, destructive action, not a hot// path, so it can afford the round trip.const platform = await bridgePlatformOnServer(server, params.bridgeId);- const result = await deleteBridge(server, params.bridgeId);+ const result = await disconnectBridgeOnServer(server, params.bridgeId);trackEvent('bridge_disconnected', {bridge_platform: platform,outcome: result.kind === 'deleted' ? 'success' : 'failure',@@ -352,6 +369,78 @@ export const workspacesController = createRPCController({return result;}),+ /** Whether a bridge is backed by a live install, which decides what the+ * disconnect dialog says happens to its rooms. Admin-only. */+ bridgeInstallState: (params: {+ workspaceId: string;+ bridgeId: string;+ }): Promise<BridgeInstallState> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ bridgeInstallState(server, params.bridgeId)+ ),++ /** A distributed Teams bridge's team placement — which teams Switch can see,+ * which it is already in, and its chosen default. Admin-only. */+ listBridgeTeams: (params: { workspaceId: string; bridgeId: string }): Promise<TeamsTeamsResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ fetchBridgeTeams(server, params.bridgeId)+ ),++ /** Add Switch's distributed app to a team. Admin-only. */+ addBridgeTeam: (params: {+ workspaceId: string;+ bridgeId: string;+ teamId: string;+ }): Promise<AddTeamsTeamResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ addBridgeTeam(server, params.bridgeId, params.teamId)+ ),++ /** Remove Switch's distributed app from a team. Admin-only. */+ removeBridgeTeam: (params: {+ workspaceId: string;+ bridgeId: string;+ teamId: string;+ }): Promise<RemoveTeamsTeamResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ removeBridgeTeam(server, params.bridgeId, params.teamId)+ ),++ /**+ * Choose a distributed Teams bridge's default team — the one a channel+ * lands in when a room is created without naming one. Picking a default+ * also turns channel creation on: an installed bridge starts with it off,+ * and a default team with no way to create a channel in it would be a+ * setting with nothing it could do.+ */+ setDefaultTeamsTeam: (params: {+ workspaceId: string;+ bridgeId: string;+ teamId: string;+ }): Promise<UpdateBridgeResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ updateBridgeOnServer(server, {+ bridgeId: params.bridgeId,+ channelCreationEnabled: true,+ connectionConfig: { team_id: params.teamId },+ })+ ),++ /**+ * Save the distributed Teams app's install package to disk, for a Teams+ * admin to upload by hand when the app is not yet in the organisation's+ * catalogue. Returns the saved path, or null if the user cancelled the save+ * dialog.+ */+ downloadTeamsPackage: (params: {+ workspaceId: string;+ bridgeId: string;+ defaultFileName: string;+ }): Promise<string | null> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ saveTeamsPackage(server, params.bridgeId, params.defaultFileName)+ ),+/*** Create a room in the chosen workspace, owned by the signed-in user. Room* provisioning stays server-side (`POST /gateway/rooms`); this only mapsdiff --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 35b72007a..a863fc155 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@@ -21,6 +21,7 @@ import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModimport { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';import { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';+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';import { InvitePeopleModal } from '@renderer/features/workspaces/invite-people-modal';@@ -103,6 +104,7 @@ export const modalRegistry = {size: 'sm',dismissOnOutsideClick: false,}),+ teamsPlacementModal: createModal(TeamsPlacementModal, { size: 'md' }),addAgentsToRoomModal: createModal(AddAgentsToRoomModal, {// The room-side twin of `addAgentToRoomModal`, and sized to match: the two// do the same job from opposite ends and should not feel like two dialogs.diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsxindex aea92eeed..88c63afb5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx@@ -1,6 +1,6 @@import { TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useCallback, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { failureText } from '@renderer/lib/errors/describe-failure';import { rpc } from '@renderer/lib/ipc';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';@@ -14,12 +14,17 @@ import {} from '@renderer/lib/ui/dialog';import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';-import type { DeleteBridgeResult } from '@shared/core/switch-servers/switch-servers';+import type {+ BridgeInstallState,+ DeleteBridgeResult,+} from '@shared/core/switch-servers/switch-servers';+import { disconnectMessagingAppParagraphs } from './disconnect-messaging-app-copy';type DisconnectMessagingAppModalArgs = {workspaceId: string;bridgeId: string;bridgeDisplayName: string;+ bridgeType: string;};type Props = BaseModalProps<void> & DisconnectMessagingAppModalArgs;@@ -41,9 +46,33 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessagingbridgeDisplayName,bridgeId,workspaceId,+ bridgeType,onSuccess,onClose,}: Props) {+ // Whether the bridge is backed by an install decides what disconnecting it+ // does to its rooms; asked as the dialog opens, and treated as the more+ // destructive case until the answer is in.+ const [installState, setInstallState] = useState<BridgeInstallState | null>(null);+ useEffect(() => {+ let current = true;+ void rpc.workspaces+ .bridgeInstallState({ workspaceId, bridgeId })+ .then((state) => {+ if (current) setInstallState(state);+ })+ .catch(() => {+ if (current) setInstallState('unknown');+ });+ return () => {+ current = false;+ };+ }, [workspaceId, bridgeId]);+ const paragraphs = disconnectMessagingAppParagraphs({+ bridgeDisplayName,+ bridgeType,+ installState,+ });const [confirmText, setConfirmText] = useState('');const [isDeleting, setIsDeleting] = useState(false);const [error, setError] = useState<string | null>(null);@@ -77,14 +106,11 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessaging</div></DialogHeader><DialogContentArea className="space-y-3 pt-0">- <p className="text-sm text-foreground-muted">- This deletes <strong className="text-foreground">every Switch room on this app</strong>,- along with their history, and then removes the connection. This can’t be undone.- </p>- <p className="text-sm text-foreground-muted">- The channels in {bridgeDisplayName} are not deleted — they stay where they are, with- nothing bridging them to Switch.- </p>+ {paragraphs.map((p) => (+ <p key={p} className="text-sm text-foreground-muted">+ {p}+ </p>+ ))}<FieldGroup><Field>diff --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 cfa219ecd..63807ac12 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@@ -11,6 +11,7 @@ import {Trash2,TriangleAlert,Unlink,+ Users,} from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useMemo, useState } from 'react';@@ -22,6 +23,7 @@ import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { openExternalUrl } from '@renderer/lib/open-external';+import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';import { Badge } from '@renderer/lib/ui/badge';import { Button } from '@renderer/lib/ui/button';import {@@ -309,6 +311,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({workspaceId,bridgeId: bridge.id,bridgeDisplayName: bridge.displayName,+ bridgeType: bridge.type,onSuccess: () => {void queryClient.invalidateQueries({queryKey: ['remote-bridges', workspaceId],@@ -370,6 +373,7 @@ export function MessagingAppRow({}) {const showClaimIdentity = useShowModal('claimIdentityModal');const showBundledChatSignIn = useShowModal('bundledChatSignInModal');+ const showTeamsPlacement = useShowModal('teamsPlacementModal');const [releasing, setReleasing] = useState(false);const [releaseError, setReleaseError] = useState<string | null>(null);@@ -380,6 +384,40 @@ export function MessagingAppRow({showClaimIdentity({ workspaceId, bridgeId: bridge.id });};+ // Offered only for the distributed Teams app: re-approving is exactly the+ // "Add to Microsoft Teams" install flow run again, which only makes sense+ // for a connection that came from that flow in the first place. A Teams+ // bridge registered with pasted-in credentials would get a fresh, unrelated+ // install out of this button rather than a fix. An attention note only ever+ // comes from a running bridge, so `teamPlacementSupported` is known for it.+ const offerReapprove = isAdmin && bridge.teamPlacementSupported && bridge.attention !== null;+ const [reapprovePhase, setReapprovePhase] = useState<'idle' | 'starting' | 'opened'>('idle');+ const [reapproveError, setReapproveError] = useState<string | null>(null);+ // A different (or cleared) attention note is a new problem: what was done+ // about the last one says nothing about it.+ const [reapprovalFor, setReapprovalFor] = useState(bridge.attention);+ if (bridge.attention !== reapprovalFor) {+ setReapprovalFor(bridge.attention);+ setReapprovePhase('idle');+ setReapproveError(null);+ }+ const reapprove = async () => {+ if (workspaceId === null) return;+ setReapprovePhase('starting');+ setReapproveError(null);+ try {+ const url = await rpc.workspaces.beginMessagingAppInstall({+ workspaceId,+ platform: bridge.type,+ });+ const opened = await openExternalUrl(url, `Could not open ${platform}`);+ setReapprovePhase(opened ? 'opened' : 'idle');+ } catch (cause) {+ setReapprovePhase('idle');+ setReapproveError(failureText(cause, `Could not start re-approving ${platform}.`));+ }+ };+const release = async (identityId: string) => {if (workspaceId === null) return;setReleasing(true);@@ -419,149 +457,204 @@ export function MessagingAppRow({: null;return (- <div className="flex items-center gap-3 py-2 text-sm">- <span className="flex size-5 shrink-0 items-center justify-center">- {hasBridgeIcon(bridge.type) ? (- <BridgeIcon bridgeType={bridge.type} size={16} />- ) : (- <MessageSquare className="size-4 text-foreground-muted" />- )}- </span>+ <div className="flex flex-col gap-1.5 py-2">+ <div className="flex items-center gap-3 text-sm">+ <span className="flex size-5 shrink-0 items-center justify-center">+ {hasBridgeIcon(bridge.type) ? (+ <BridgeIcon bridgeType={bridge.type} size={16} />+ ) : (+ <MessageSquare className="size-4 text-foreground-muted" />+ )}+ </span>- {/* Name over account: the account is a property of the app, so it reads+ {/* Name over account: the account is a property of the app, so it readsunder its name rather than in a column of its own. */}- <div className="flex min-w-0 flex-1 flex-col">- <div className="flex min-w-0 items-center gap-2">- <span className="truncate text-foreground">{bridge.displayName}</span>- {bridge.isDefault && <Badge variant="secondary">Default</Badge>}- {/* Only when it is NOT active, and never otherwise. A bridge that is+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-foreground">{bridge.displayName}</span>+ {bridge.isDefault && <Badge variant="secondary">Default</Badge>}+ {/* Only when it is NOT active, and never otherwise. A bridge that isdown cannot back a new room and the room-creation picker omits itsilently, so without this the app simply is not in the list andnothing anywhere says why. */}- {bridge.status !== 'active' && (- <span className="shrink-0 text-xs text-destructive">{bridge.status}</span>+ {bridge.status !== 'active' && (+ <span className="shrink-0 text-xs text-destructive">{bridge.status}</span>+ )}+ </div>+ {identities === null ? null : identity === null ? (+ <span className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-500">+ <TriangleAlert className="size-3 shrink-0" />+ No account linked+ <Tooltip>+ <TooltipTrigger+ render={+ <span+ tabIndex={0}+ aria-label={noAccountHelp}+ className="inline-flex text-foreground-muted"+ >+ <Info className="size-3" />+ </span>+ }+ />+ <TooltipContent className="max-w-xs">{noAccountHelp}</TooltipContent>+ </Tooltip>+ </span>+ ) : (+ <span className="truncate font-mono text-xs text-foreground-muted">+ {handleOf(identity)}+ </span>+ )}+ {releaseError !== null && (+ <p className="mt-0.5 text-xs text-destructive">{releaseError}</p>)}</div>- {identities === null ? null : identity === null ? (- <span className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-500">- <TriangleAlert className="size-3 shrink-0" />- No account linked- <Tooltip>- <TooltipTrigger- render={- <span- tabIndex={0}- aria-label={noAccountHelp}- className="inline-flex text-foreground-muted"- >- <Info className="size-3" />- </span>- }- />- <TooltipContent className="max-w-xs">{noAccountHelp}</TooltipContent>- </Tooltip>- </span>- ) : (- <span className="truncate font-mono text-xs text-foreground-muted">- {handleOf(identity)}- </span>- )}- {releaseError !== null && <p className="mt-0.5 text-xs text-destructive">{releaseError}</p>}- </div>- {/* Linking is the one thing an unlinked app needs, so it stays a button+ {/* Linking is the one thing an unlinked app needs, so it stays a buttonrather than going into the menu with the rest. A linked app shows nobutton at all: the only thing left to do to it is destructive, and acontrol next to the handle would sit one mis-click from the actionthat *changes* the account (CHOO-2137). */}- {identities !== null && identity === null && (- <Button variant="outline" size="xs" className="shrink-0" onClick={claim}>- <Link2 className="size-3" />- Link- </Button>- )}+ {identities !== null && identity === null && (+ <Button variant="outline" size="xs" className="shrink-0" onClick={claim}>+ <Link2 className="size-3" />+ Link+ </Button>+ )}- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="ghost"- size="icon-xs"- className="shrink-0"- aria-label={`${bridge.displayName} actions`}- disabled={releasing}- >- <MoreVertical className="size-3" />- </Button>- }- />- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={claim}>- <Link2 className="size-4" />- {identity === null ? 'Link my account…' : 'Change my account…'}- </DropdownMenuItem>- {identity !== null && (- <DropdownMenuItem onClick={() => void release(identity.id)}>- <Unlink className="size-4" />- Unlink {handleOf(identity)}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ className="shrink-0"+ aria-label={`${bridge.displayName} actions`}+ disabled={releasing}+ >+ <MoreVertical className="size-3" />+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={claim}>+ <Link2 className="size-4" />+ {identity === null ? 'Link my account…' : 'Change my account…'}</DropdownMenuItem>- )}+ {identity !== null && (+ <DropdownMenuItem onClick={() => void release(identity.id)}>+ <Unlink className="size-4" />+ Unlink {handleOf(identity)}+ </DropdownMenuItem>+ )}- <DropdownMenuSeparator />- {/* "Off" and "this platform has no such thing" are different claims,+ <DropdownMenuSeparator />+ {/* "Off" and "this platform has no such thing" are different claims,and an unticked box makes them look the same (CHOO-2137). Aplatform that cannot do it at all gets a plain disabled linesaying so, never an unchecked box. */}- {bridge.channelCreationSupported ? (- <DropdownMenuCheckboxItem- checked={bridge.canCreateChannels}- disabled={!isAdmin || savingChannelCreation}- onCheckedChange={(next) => onToggleChannelCreation(next)}- >- Create channels on {platform}- </DropdownMenuCheckboxItem>- ) : (- <DropdownMenuItem disabled>Channels not supported on {platform}</DropdownMenuItem>- )}- {channelsLockedReason !== null && (- <p className="px-2 py-1 text-xs text-foreground-muted">{channelsLockedReason}</p>- )}+ {bridge.channelCreationSupported ? (+ <DropdownMenuCheckboxItem+ checked={bridge.canCreateChannels}+ disabled={!isAdmin || savingChannelCreation}+ onCheckedChange={(next) => onToggleChannelCreation(next)}+ >+ Create channels on {platform}+ </DropdownMenuCheckboxItem>+ ) : (+ <DropdownMenuItem disabled>Channels not supported on {platform}</DropdownMenuItem>+ )}+ {channelsLockedReason !== null && (+ <p className="px-2 py-1 text-xs text-foreground-muted">{channelsLockedReason}</p>+ )}- {(showBundledSignIn || bridge.homeUrl) && <DropdownMenuSeparator />}- {showBundledSignIn && (- <DropdownMenuItem- onClick={() =>- showBundledChatSignIn({ serverId, bridgeDisplayName: bridge.displayName })- }- >- <KeyRound className="size-4" />- Sign-in details…- </DropdownMenuItem>- )}- {/* Offered only when the link resolves — an older server, or a bridge+ {(showBundledSignIn || bridge.homeUrl) && <DropdownMenuSeparator />}+ {showBundledSignIn && (+ <DropdownMenuItem+ onClick={() =>+ showBundledChatSignIn({ serverId, bridgeDisplayName: bridge.displayName })+ }+ >+ <KeyRound className="size-4" />+ Sign-in details…+ </DropdownMenuItem>+ )}+ {/* Offered only when the link resolves — an older server, or a bridgethat is down, reports none. */}- {bridge.homeUrl && (- <DropdownMenuItem- onClick={() =>- void openExternalUrl(bridge.homeUrl as string, `Could not open ${platform}`)- }- >- <ExternalLink className="size-4" />- Open in {platform}- </DropdownMenuItem>- )}-- {isAdmin && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" onClick={onDisconnect}>- <Trash2 className="size-4" />- Disconnect app…+ {bridge.homeUrl && (+ <DropdownMenuItem+ onClick={() =>+ void openExternalUrl(bridge.homeUrl as string, `Could not open ${platform}`)+ }+ >+ <ExternalLink className="size-4" />+ Open in {platform}</DropdownMenuItem>- </>+ )}++ {bridge.teamPlacementSupported && isAdmin && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ if (workspaceId === null) return;+ showTeamsPlacement({+ workspaceId,+ bridgeId: bridge.id,+ bridgeDisplayName: bridge.displayName,+ });+ }}+ >+ <Users className="size-4" />+ Manage Microsoft Teams…+ </DropdownMenuItem>+ </>+ )}++ {isAdmin && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={onDisconnect}>+ <Trash2 className="size-4" />+ Disconnect app…+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ {/* Generic across every bridge type: something only the platform's side+ can fix, worded by the server (approval withdrawn, the app blocked by+ the organisation's admin). "Approve again" is offered only for the+ distributed Teams app, whose attention notes are the ones a re-run of+ the install flow can actually resolve. */}+ {bridge.attention !== null && (+ <Alert variant="warning" className="ml-8">+ <TriangleAlert className="size-4" />+ <AlertDescription>+ <p>{bridge.attention}</p>+ {offerReapprove && reapprovePhase === 'opened' && (+ <p>+ Approve again in the browser window that opened. This warning clears once Switch+ sees the renewed approval.+ </p>+ )}+ {reapproveError !== null && <p className="text-destructive">{reapproveError}</p>}+ </AlertDescription>+ {offerReapprove && (+ <AlertAction>+ <Button+ size="sm"+ disabled={reapprovePhase === 'starting' || workspaceId === null}+ onClick={() => void reapprove()}+ >+ {reapprovePhase === 'starting' ? 'Opening…' : 'Approve again'}+ </Button>+ </AlertAction>)}- </DropdownMenuContent>- </DropdownMenu>+ </Alert>+ )}</div>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsxnew file mode 100644index 000000000..994233efa--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TeamsPlacementModal.tsx@@ -0,0 +1,428 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { CircleAlert } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { useToast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Spinner } from '@renderer/lib/ui/spinner';+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';+import type {+ AddTeamsTeamResult,+ RemoveTeamsTeamResult,+ TeamsTeam,+ TeamsTeamsResult,+ UpdateBridgeResult,+} from '@shared/core/switch-servers/switch-servers';++type TeamsPlacementModalArgs = {+ workspaceId: string;+ bridgeId: string;+ bridgeDisplayName: string;+};++type Props = BaseModalProps<void> & TeamsPlacementModalArgs;++const QUERY_KEY = (workspaceId: string, bridgeId: string) => [+ 'bridge-teams',+ workspaceId,+ bridgeId,+];++/**+ * Choosing or clearing the default team restarts the connection, which says it+ * is not running until it is back: something to wait out, not a failure. The+ * server's sentence is kept for when it does not come back.+ */+class ConnectionRestarting extends Error {}+const RESTART_RETRY_MS = 1500;+const RESTART_RETRIES = 20;++/**+ * Where Switch's distributed Microsoft Teams app is placed: which teams it can+ * see, whether it is in each one, and which is the default for new rooms.+ *+ * Offered only for a connection `team_placement_supported` already says is a+ * running distributed Teams bridge, so every failure case here is either a+ * transient one (the bridge just stopped) or Microsoft Graph itself declining+ * — never "this bridge does not support teams", which the caller has already+ * ruled out before opening this.+ */+export const TeamsPlacementModal = observer(function TeamsPlacementModal({+ workspaceId,+ bridgeId,+ bridgeDisplayName,+ onClose,+}: Props) {+ const queryClient = useQueryClient();+ const { toast } = useToast();+ const queryKey = QUERY_KEY(workspaceId, bridgeId);++ const teamsQuery = useQuery({+ queryKey,+ queryFn: async () => {+ const result = await rpc.workspaces.listBridgeTeams({ workspaceId, bridgeId });+ if (result.kind === 'not-running') throw new ConnectionRestarting(result.message);+ return result;+ },+ retry: (failureCount, error) =>+ error instanceof ConnectionRestarting && failureCount < RESTART_RETRIES,+ retryDelay: RESTART_RETRY_MS,+ });+ const restarting =+ teamsQuery.isFetching && teamsQuery.failureReason instanceof ConnectionRestarting;++ const [mutatingTeamId, setMutatingTeamId] = useState<string | null>(null);+ const [actionError, setActionError] = useState<string | null>(null);+ const [savingPackage, setSavingPackage] = useState(false);++ const refresh = () => queryClient.invalidateQueries({ queryKey });+ const refreshBridges = () =>+ queryClient.invalidateQueries({ queryKey: ['remote-bridges', workspaceId] });++ const handleAdd = async (team: TeamsTeam) => {+ setMutatingTeamId(team.teamId);+ setActionError(null);+ try {+ const result = await rpc.workspaces.addBridgeTeam({+ workspaceId,+ bridgeId,+ teamId: team.teamId,+ });+ if (result.kind !== 'added') {+ setActionError(addTeamFailureText(result));+ return;+ }+ await refresh();+ } catch (cause) {+ setActionError(failureText(cause, `Could not add Switch to ${team.name}.`));+ } finally {+ setMutatingTeamId(null);+ }+ };++ const handleRemove = async (team: TeamsTeam) => {+ setMutatingTeamId(team.teamId);+ setActionError(null);+ try {+ const result = await rpc.workspaces.removeBridgeTeam({+ workspaceId,+ bridgeId,+ teamId: team.teamId,+ });+ if (result.kind !== 'removed') {+ setActionError(removeTeamFailureText(result));+ return;+ }+ // Removing Switch from the connection's current default team clears the+ // default and turns channel creation off on the server, restarting the+ // bridge — the same side effect making a team the default has, so the+ // bridge list needs the same refresh.+ await Promise.all([refresh(), refreshBridges()]);+ } catch (cause) {+ setActionError(failureText(cause, `Could not remove Switch from ${team.name}.`));+ } finally {+ setMutatingTeamId(null);+ }+ };++ const handleMakeDefault = async (team: TeamsTeam) => {+ setMutatingTeamId(team.teamId);+ setActionError(null);+ try {+ const result = await rpc.workspaces.setDefaultTeamsTeam({+ workspaceId,+ bridgeId,+ teamId: team.teamId,+ });+ if (result.kind !== 'updated') {+ setActionError(setDefaultFailureText(result));+ return;+ }+ await Promise.all([refresh(), refreshBridges()]);+ } catch (cause) {+ setActionError(failureText(cause, `Could not make ${team.name} the default.`));+ } finally {+ setMutatingTeamId(null);+ }+ };++ const handleSavePackage = async () => {+ setSavingPackage(true);+ setActionError(null);+ try {+ const safeName = bridgeDisplayName.trim().replace(/[^\w.-]+/g, '-') || 'switch-teams-app';+ const path = await rpc.workspaces.downloadTeamsPackage({+ workspaceId,+ bridgeId,+ defaultFileName: `${safeName}.zip`,+ });+ if (path !== null) {+ toast({ title: 'Package saved', description: path });+ }+ } catch (cause) {+ setActionError(failureText(cause, 'Could not save the Teams app package.'));+ } finally {+ setSavingPackage(false);+ }+ };++ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Microsoft Teams teams for {bridgeDisplayName}</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="pt-0">+ <div className="flex w-full flex-col gap-4">+ <p className="text-xs text-foreground-muted">+ Choose which teams Switch is added to, and which one new rooms land in by default.+ </p>++ {restarting && (+ <p className="flex items-center gap-2 text-xs text-foreground-muted">+ <Spinner className="size-3.5" />+ The connection is restarting with your change…+ </p>+ )}++ <TeamsPlacementBody+ result={teamsQuery.data ?? null}+ isLoading={teamsQuery.isLoading && !restarting}+ fetchError={teamsQuery.error}+ mutatingTeamId={mutatingTeamId}+ savingPackage={savingPackage}+ onAdd={(team) => void handleAdd(team)}+ onRemove={(team) => void handleRemove(team)}+ onMakeDefault={(team) => void handleMakeDefault(team)}+ onSavePackage={() => void handleSavePackage()}+ />++ {actionError && <p className="text-xs text-destructive">{actionError}</p>}+ </div>+ </DialogContentArea>+ <DialogFooter>+ {/* An add/remove/make-default or package save in flight has its own+ error to show on failure; closing mid-request would lose it. */}+ <Button+ variant="outline"+ onClick={onClose}+ disabled={mutatingTeamId !== null || savingPackage}+ >+ Close+ </Button>+ </DialogFooter>+ </>+ );+});++function TeamsPlacementBody({+ result,+ isLoading,+ fetchError,+ mutatingTeamId,+ savingPackage,+ onAdd,+ onRemove,+ onMakeDefault,+ onSavePackage,+}: {+ result: TeamsTeamsResult | null;+ isLoading: boolean;+ fetchError: unknown;+ mutatingTeamId: string | null;+ savingPackage: boolean;+ onAdd: (team: TeamsTeam) => void;+ onRemove: (team: TeamsTeam) => void;+ onMakeDefault: (team: TeamsTeam) => void;+ onSavePackage: () => void;+}) {+ if (isLoading) {+ return (+ <p className="flex items-center gap-2 text-xs text-foreground-muted">+ <Spinner className="size-3.5" />+ Loading teams…+ </p>+ );+ }+ if (fetchError) {+ return (+ <p className="text-xs text-destructive">+ {fetchError instanceof ConnectionRestarting+ ? fetchError.message+ : failureText(fetchError, 'Could not read this connection’s teams.')}+ </p>+ );+ }+ if (result === null) return null;+ if (result.kind !== 'listed') {+ return <p className="text-xs text-destructive">{teamsResultFailureText(result)}</p>;+ }++ const pending = mutatingTeamId !== null;+ // `catalogProblem` is only ever populated once the server has a reason to+ // give; `inCatalog === false` with no problem yet is still a real state+ // (nothing has tried to catalogue the app), so this is a fact about Switch+ // rather than an empty hole where the server's sentence would go.+ const catalogProblemText =+ result.catalogProblem ?? 'Switch is not in your organisation’s Teams app list yet.';++ return (+ <div className="flex flex-col gap-3">+ {!result.inCatalog && (+ <div className="flex items-start gap-2 rounded-md border border-border bg-background-1 px-2 py-1.5 text-xs">+ <CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />+ <div className="flex flex-col gap-1.5">+ <span>{catalogProblemText}</span>+ <span>+ A Teams admin uploads this app in the Teams admin center, under Teams apps → Manage+ apps → Upload new app.+ </span>+ <Button+ variant="outline"+ size="xs"+ className="w-fit"+ disabled={savingPackage}+ onClick={onSavePackage}+ >+ {savingPackage ? 'Saving…' : 'Save Teams app package'}+ </Button>+ </div>+ </div>+ )}++ {result.teams.length === 0 ? (+ <p className="text-xs text-foreground-muted">+ Switch cannot see any teams in this organisation yet.+ </p>+ ) : (+ <ul className="flex max-h-72 flex-col gap-1 overflow-y-auto">+ {result.teams.map((team) => (+ <li+ key={team.teamId}+ className="flex items-center justify-between gap-3 rounded-md border border-border p-2"+ >+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm text-foreground">{team.name}</span>+ {team.isDefault && <Badge variant="secondary">Default</Badge>}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {team.hasSwitch === null ? (+ <span className="text-xs text-foreground-muted">+ Switch could not read this team’s apps+ </span>+ ) : team.hasSwitch ? (+ <>+ {!team.isDefault && (+ <Button+ variant="outline"+ size="sm"+ disabled={pending}+ onClick={() => onMakeDefault(team)}+ >+ {mutatingTeamId === team.teamId ? 'Saving…' : 'Make default'}+ </Button>+ )}+ <Button+ variant="outline"+ size="sm"+ disabled={pending}+ onClick={() => onRemove(team)}+ >+ {mutatingTeamId === team.teamId ? 'Removing…' : 'Remove'}+ </Button>+ </>+ ) : result.inCatalog ? (+ <Button size="sm" disabled={pending} onClick={() => onAdd(team)}>+ {mutatingTeamId === team.teamId ? 'Adding…' : 'Add'}+ </Button>+ ) : (+ // A disabled button gets `pointer-events-none`, so it never+ // fires the hover/focus that would open a tooltip wrapped+ // directly around it — the span catches those instead.+ <Tooltip>+ <TooltipTrigger+ render={+ <span tabIndex={0} aria-label={catalogProblemText} className="inline-flex">+ <Button size="sm" disabled>+ Add+ </Button>+ </span>+ }+ />+ <TooltipContent className="max-w-xs">{catalogProblemText}</TooltipContent>+ </Tooltip>+ )}+ </div>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++/** Turn a result other than `listed` into something the user can act on. */+function teamsResultFailureText(result: Exclude<TeamsTeamsResult, { kind: 'listed' }>): string {+ switch (result.kind) {+ case 'not-distributed-teams':+ return 'This connection no longer supports Microsoft Teams team placement.';+ case 'not-running':+ return result.message;+ case 'microsoft-refused':+ return result.message;+ case 'unauthenticated':+ return 'Your session for this server expired. Sign in again, then retry.';+ case 'forbidden':+ return 'Managing teams requires an owner or admin of this workspace.';+ case 'error':+ return result.message;+ }+}++function addTeamFailureText(result: Exclude<AddTeamsTeamResult, { kind: 'added' }>): string {+ switch (result.kind) {+ case 'not-in-catalog':+ return result.message;+ case 'unauthenticated':+ return 'Your session for this server expired. Sign in again, then retry.';+ case 'forbidden':+ return 'Managing teams requires an owner or admin of this workspace.';+ case 'error':+ return result.message;+ }+}++function removeTeamFailureText(+ result: Exclude<RemoveTeamsTeamResult, { kind: 'removed' }>+): string {+ switch (result.kind) {+ case 'unauthenticated':+ return 'Your session for this server expired. Sign in again, then retry.';+ case 'forbidden':+ return 'Managing teams requires an owner or admin of this workspace.';+ case 'error':+ return result.message;+ }+}++function setDefaultFailureText(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 'Managing teams requires an owner or admin of this workspace.';+ case 'invalid':+ return result.message;+ case 'error':+ return result.message;+ }+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.tsnew file mode 100644index 000000000..720f861db--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { disconnectMessagingAppParagraphs } from './disconnect-messaging-app-copy';++describe('disconnectMessagingAppParagraphs', () => {+ it('warns that a bridge registered with credentials takes its rooms with it', () => {+ const text = disconnectMessagingAppParagraphs({+ bridgeDisplayName: 'Acme',+ bridgeType: 'slack',+ installState: 'not-installed',+ }).join(' ');+ expect(text).toContain('deletes every Switch room');+ });++ it('says an installed app keeps its rooms as internal-only', () => {+ const text = disconnectMessagingAppParagraphs({+ bridgeDisplayName: 'Acme',+ bridgeType: 'slack',+ installState: 'installed',+ }).join(' ');+ expect(text).toContain('not deleted');+ expect(text).not.toContain('deletes every Switch room');+ });++ it('says what disconnecting the distributed Teams app does and does not remove', () => {+ const text = disconnectMessagingAppParagraphs({+ bridgeDisplayName: 'Contoso',+ bridgeType: 'teams',+ installState: 'installed',+ }).join(' ');+ expect(text).toContain('leaves every team');+ expect(text).toContain('Microsoft Entra admin center');+ });++ it('shows the strongest warning until it is known which it is', () => {+ for (const installState of [null, 'unknown'] as const) {+ const text = disconnectMessagingAppParagraphs({+ bridgeDisplayName: 'Acme',+ bridgeType: 'teams',+ installState,+ }).join(' ');+ expect(text).toContain('deletes every Switch room');+ }+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.tsnew file mode 100644index 000000000..3220573e8--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/disconnect-messaging-app-copy.ts@@ -0,0 +1,42 @@+import type { BridgeInstallState } from '@shared/core/switch-servers/switch-servers';++/**+ * What disconnecting a messaging app actually does, which is not the same+ * action for every bridge.+ *+ * A bridge registered with credentials pasted into the connect form is+ * deleted, and every Switch room on it with it, which is why the dialog warns+ * about that in the strongest terms it has.+ *+ * A bridge backed by an install — Switch's own app added to a workspace, or+ * approved into a Microsoft organisation — is disconnected by ending the+ * install instead, which keeps its rooms as internal-only rooms. On the+ * distributed Teams app it also means Switch stops listening in the+ * organisation and leaves its teams, while removing the app from the+ * organisation entirely stays a Microsoft admin's job.+ *+ * Until the install state is known, the strongest warning is shown: saying+ * rooms are kept when they are about to be deleted is the mistake that cannot+ * be taken back.+ */+export function disconnectMessagingAppParagraphs(params: {+ bridgeDisplayName: string;+ bridgeType: string;+ installState: BridgeInstallState | null;+}): string[] {+ const { bridgeDisplayName, bridgeType, installState } = params;+ if (installState === 'installed') {+ const kept = `The Switch rooms bridged to ${bridgeDisplayName} are not deleted — they become internal-only, reachable only from inside Switch.`;+ if (bridgeType === 'teams') {+ return [+ `Switch stops listening in this Microsoft organisation and leaves every team it was added to. ${kept}`,+ 'Removing the app from the organisation entirely is a Microsoft admin’s job, done by hand in the Teams admin center and the Microsoft Entra admin center.',+ ];+ }+ return [`This ends Switch’s install in ${bridgeDisplayName}. ${kept}`];+ }+ return [+ 'This deletes every Switch room on this app, along with their history, and then removes the connection. This can’t be undone.',+ `The channels in ${bridgeDisplayName} are not deleted — they stay where they are, with nothing bridging them to Switch.`,+ ];+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.tsindex aad821951..4e0a4b765 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-order.test.ts@@ -13,6 +13,8 @@ function bridge(id: string, displayName: string): RemoteBridge {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,};}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.tsindex 7e3aa9a9f..73f74e731 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/messaging-apps-warning.test.ts@@ -19,6 +19,8 @@ function bridge(id: string, displayName: string): RemoteBridge {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,};}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsxnew file mode 100644index 000000000..0ebca3679--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/disconnect-messaging-app-modal.test.tsx@@ -0,0 +1,231 @@+/**+ * Confirming disconnection of a messaging app (CHOO-2137).+ *+ * The warning shown depends on whether the bridge is backed by a live+ * install — asked as the dialog opens — since that decides whether its rooms+ * are deleted or kept as internal-only. Until the answer is in, or if asking+ * fails, the strongest warning stays up rather than understating what is+ * about to happen.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const bridgeInstallState = vi.hoisted(() => vi.fn());+const deleteBridge = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: { workspaces: { bridgeInstallState, deleteBridge } },+ events: { on: () => () => {}, emit: () => {} },+}));++import { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';+import { Dialog } from '@renderer/lib/ui/dialog';++const onSuccess = vi.fn();+const onClose = vi.fn();++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ bridgeInstallState.mockReset();+ deleteBridge.mockReset();+ onSuccess.mockReset();+ onClose.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(props: { bridgeType?: string } = {}): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <Dialog open onOpenChange={() => {}}>+ <DisconnectMessagingAppModal+ workspaceId="ws-1"+ bridgeId="b-1"+ bridgeDisplayName="Acme"+ bridgeType={props.bridgeType ?? 'slack'}+ onSuccess={onSuccess}+ onClose={onClose}+ />+ </Dialog>+ )+ );+ await settle();+ return document.body;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+}++function confirmButton(el: HTMLElement): HTMLButtonElement {+ const found = [...el.querySelectorAll('button')].find((b) =>+ (b.textContent ?? '').includes('Disconnect app')+ );+ expect(found, 'no disconnect button').toBeDefined();+ return found!;+}++async function type(input: HTMLInputElement, value: string): Promise<void> {+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ window.HTMLInputElement.prototype,+ 'value'+ )!.set!;+ setter.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++async function confirmName(el: HTMLElement, name: string): Promise<void> {+ const input = el.querySelector('input') as HTMLInputElement;+ await type(input, name);+}++async function click(element: HTMLElement): Promise<void> {+ await act(async () => element.click());+}++describe('the install-state copy', () => {+ it('warns that a bridge with no install takes its rooms with it', async () => {+ bridgeInstallState.mockResolvedValue('not-installed');+ const el = await render();++ expect(el.textContent).toContain('deletes every Switch room');+ });++ it('says an installed bridge keeps its rooms as internal-only', async () => {+ bridgeInstallState.mockResolvedValue('installed');+ const el = await render({ bridgeType: 'slack' });++ expect(el.textContent).toContain('not deleted');+ expect(el.textContent).not.toContain('deletes every Switch room');+ });++ it('says the distributed Teams app also leaves every team it was added to', async () => {+ bridgeInstallState.mockResolvedValue('installed');+ const el = await render({ bridgeType: 'teams' });++ expect(el.textContent).toContain('leaves every team');+ expect(el.textContent).toContain('Microsoft Entra admin center');+ });++ it('keeps the strongest warning up when the install state could not be read', async () => {+ bridgeInstallState.mockResolvedValue('unknown');+ const el = await render();++ expect(el.textContent).toContain('deletes every Switch room');+ });++ it('falls back to "unknown" rather than leaving the state unset when the lookup throws', async () => {+ bridgeInstallState.mockRejectedValue(new Error('boom'));+ const el = await render();++ // Thrown or resolved 'unknown' read the same: the strongest warning.+ expect(el.textContent).toContain('deletes every Switch room');+ });+});++describe('confirming and disconnecting', () => {+ beforeEach(() => {+ bridgeInstallState.mockResolvedValue('not-installed');+ });++ it('keeps Disconnect disabled until the exact name is typed', async () => {+ const el = await render();++ expect(confirmButton(el).disabled).toBe(true);++ await confirmName(el, 'not quite Acme');+ expect(confirmButton(el).disabled).toBe(true);++ await confirmName(el, 'Acme');+ expect(confirmButton(el).disabled).toBe(false);+ });++ it('calls the RPC with the workspace and bridge, and reports success', async () => {+ deleteBridge.mockResolvedValue({ kind: 'deleted' });+ const el = await render();+ await confirmName(el, 'Acme');++ await click(confirmButton(el));+ await settle();++ expect(deleteBridge).toHaveBeenCalledWith({ workspaceId: 'ws-1', bridgeId: 'b-1' });+ expect(onSuccess).toHaveBeenCalled();+ });++ it('prompts a sign-in for an expired session rather than claiming success', async () => {+ deleteBridge.mockResolvedValue({ kind: 'unauthenticated' });+ const el = await render();+ await confirmName(el, 'Acme');++ await click(confirmButton(el));+ await settle();++ expect(el.textContent).toContain('Your session for this server expired');+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it('names the admin requirement when forbidden', async () => {+ deleteBridge.mockResolvedValue({ kind: 'forbidden' });+ const el = await render();+ await confirmName(el, 'Acme');++ await click(confirmButton(el));+ await settle();++ expect(el.textContent).toContain('requires an owner or admin of this workspace');+ });++ it('says the app is already gone rather than retrying a disconnect', async () => {+ deleteBridge.mockResolvedValue({ kind: 'not-found' });+ const el = await render();+ await confirmName(el, 'Acme');++ await click(confirmButton(el));+ await settle();++ expect(el.textContent).toContain('no longer connected to this server');+ });++ it('shows a generic failure’s own message', async () => {+ deleteBridge.mockResolvedValue({ kind: 'error', message: 'adapter shutdown failed' });+ const el = await render();+ await confirmName(el, 'Acme');++ await click(confirmButton(el));+ await settle();++ expect(el.textContent).toContain('adapter shutdown failed');+ });++ it('shows a fallback message when the call throws rather than resolves', async () => {+ deleteBridge.mockRejectedValue(new Error('rpc exploded'));+ const el = await render();+ await confirmName(el, 'Acme');++ await click(confirmButton(el));+ await settle();++ expect(el.textContent).toContain('Could not disconnect the messaging app.');+ });+});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 430ecf91b..817e759a0 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@@ -1,6 +1,6 @@import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// The row's siblings reach the renderer IPC bridge at import time, which only// exists inside Electron. Hoisted so it is in place before those modules are@@ -13,6 +13,19 @@ vi.hoisted(() => {} as unknown as typeof window.electronAPI;});+const beginMessagingAppInstall = vi.hoisted(() => vi.fn());+const openExternalUrl = vi.hoisted(() => vi.fn());+const showModal = vi.hoisted(() => vi.fn());++vi.mock('@renderer/lib/ipc', () => ({+ rpc: { workspaces: { beginMessagingAppInstall } },+ events: { on: () => () => {}, emit: () => {} },+}));+vi.mock('@renderer/lib/open-external', () => ({ openExternalUrl }));+vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: (id: string) => (args: unknown) => showModal(id, args),+}));+/*** One messaging app, one line (CHOO-2137).*@@ -56,6 +69,8 @@ function bridge(patch: Partial<RemoteBridge> = {}): RemoteBridge {channelCreationSupported: true,canCreateChannels: true,directorySearchSupported: true,+ attention: null,+ teamPlacementSupported: false,...patch,};}@@ -71,6 +86,7 @@ const IDENTITY: LinkedIdentity = {function row(overrides: {+ workspaceId?: string | null;bridge?: RemoteBridge;identities?: LinkedIdentity[] | null;isAdmin?: boolean;@@ -79,7 +95,7 @@ function row() {return (<MessagingAppRow- workspaceId="ws-1"+ workspaceId={overrides.workspaceId === undefined ? 'ws-1' : overrides.workspaceId}serverId="srv-1"bridge={overrides.bridge ?? bridge()}identities={overrides.identities === undefined ? [] : overrides.identities}@@ -296,3 +312,250 @@ describe('channel creation', () => {).toBeNull();});});++/** A promise the test resolves on its own schedule, to pin a request mid-flight. */+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++async function settle(): Promise<void> {+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+}++/**+ * The generic attention warning, and "Approve again" on top of it for the+ * distributed Teams app alone.+ *+ * "Approve again" re-runs the same install flow a first approval does, which+ * only makes sense for a connection that came from it — gating it on+ * `teamPlacementSupported` is what keeps it off a Teams bridge registered with+ * pasted-in credentials, and off every other platform.+ */+describe('the attention warning', () => {+ beforeEach(() => {+ beginMessagingAppInstall.mockReset().mockResolvedValue('https://teams.example/consent');+ openExternalUrl.mockReset().mockResolvedValue(true);+ });++ it('shows the server’s own sentence when a bridge has something wrong with it', async () => {+ const el = await render(row({ bridge: bridge({ attention: 'Approval was withdrawn.' }) }));++ expect(el.textContent).toContain('Approval was withdrawn.');+ });++ it('shows nothing extra when there is nothing to warn about', async () => {+ const el = await render(row({ bridge: bridge({ attention: null }) }));++ expect(el.textContent).not.toContain('Approve again');+ });++ it('offers Approve again to an admin on a team-placement connection', async () => {+ const el = await render(+ row({+ isAdmin: true,+ bridge: bridge({ attention: 'Approval was withdrawn.', teamPlacementSupported: true }),+ })+ );++ expect(buttonLabels(el)).toContain('Approve again');+ });++ it('does not offer it to a non-admin, even on a team-placement connection', async () => {+ const el = await render(+ row({+ isAdmin: false,+ bridge: bridge({ attention: 'Approval was withdrawn.', teamPlacementSupported: true }),+ })+ );++ expect(buttonLabels(el)).not.toContain('Approve again');+ });++ it('does not offer it on a connection that does not support team placement', async () => {+ const el = await render(+ row({+ isAdmin: true,+ bridge: bridge({ attention: 'Approval was withdrawn.', teamPlacementSupported: false }),+ })+ );++ expect(buttonLabels(el)).not.toContain('Approve again');+ });++ it('starts the install and opens the consent page on click', async () => {+ const el = await render(+ row({+ isAdmin: true,+ bridge: bridge({+ type: 'teams',+ attention: 'Approval was withdrawn.',+ teamPlacementSupported: true,+ }),+ })+ );++ const approve = [...el.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === 'Approve again'+ );+ await act(async () => approve!.click());+ await settle();++ expect(beginMessagingAppInstall).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ platform: 'teams',+ });+ expect(openExternalUrl).toHaveBeenCalledWith(+ 'https://teams.example/consent',+ 'Could not open Microsoft Teams'+ );+ expect(el.textContent).toContain('Approve again in the browser window');+ });++ it('forgets an earlier re-approval once a different warning replaces it', async () => {+ const withdrawn = bridge({+ type: 'teams',+ attention: 'Approval was withdrawn.',+ teamPlacementSupported: true,+ });+ const el = await render(row({ isAdmin: true, bridge: withdrawn }));+ const approve = [...el.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === 'Approve again'+ );+ await act(async () => approve!.click());+ await settle();+ expect(el.textContent).toContain('Approve again in the browser window');++ await act(async () =>+ root!.render(+ row({+ isAdmin: true,+ bridge: { ...withdrawn, attention: 'The app was blocked by your Teams admin.' },+ })+ )+ );++ expect(el.textContent).toContain('The app was blocked by your Teams admin.');+ expect(el.textContent).not.toContain('Approve again in the browser window');+ expect(buttonLabels(el)).toContain('Approve again');+ });++ it('shows why re-approving could not start, rather than leaving it unexplained', async () => {+ beginMessagingAppInstall.mockRejectedValue(new Error('install refused'));+ const el = await render(+ row({+ isAdmin: true,+ bridge: bridge({+ type: 'teams',+ attention: 'Approval was withdrawn.',+ teamPlacementSupported: true,+ }),+ })+ );++ const approve = [...el.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === 'Approve again'+ );+ await act(async () => approve!.click());+ await settle();++ expect(el.textContent).toContain('Could not start re-approving Microsoft Teams');+ expect(openExternalUrl).not.toHaveBeenCalled();+ });++ it('disables the button while the install is starting', async () => {+ const { promise, resolve } = deferred<string>();+ beginMessagingAppInstall.mockReturnValue(promise);+ const el = await render(+ row({+ isAdmin: true,+ bridge: bridge({+ type: 'teams',+ attention: 'Approval was withdrawn.',+ teamPlacementSupported: true,+ }),+ })+ );++ const approve = [...el.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === 'Approve again'+ ) as HTMLButtonElement;+ await act(async () => approve.click());+ await settle();++ expect(+ [...el.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'Opening…')?.disabled+ ).toBe(true);++ await act(async () => resolve('https://teams.example/consent'));+ await settle();+ });+});++describe('the Teams placement button', () => {+ it('is offered to an admin on a connection that supports team placement', async () => {+ const el = await render(+ row({ isAdmin: true, bridge: bridge({ teamPlacementSupported: true }) })+ );++ expect(await openMenu(el)).toContain('Manage Microsoft Teams…');+ });++ it('is withheld from a non-admin', async () => {+ const el = await render(+ row({ isAdmin: false, bridge: bridge({ teamPlacementSupported: true }) })+ );++ expect(await openMenu(el)).not.toContain('Manage Microsoft Teams…');+ });++ it('is withheld on a connection that does not support team placement', async () => {+ const el = await render(+ row({ isAdmin: true, bridge: bridge({ teamPlacementSupported: false }) })+ );++ expect(await openMenu(el)).not.toContain('Manage Microsoft Teams…');+ });++ it('opens the Teams placement modal for this bridge', async () => {+ const el = await render(+ row({+ isAdmin: true,+ bridge: bridge({+ id: 'b-teams',+ displayName: 'Contoso Teams',+ teamPlacementSupported: true,+ }),+ })+ );+ await openMenu(el);++ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (i) => i.textContent?.trim() === 'Manage Microsoft Teams…'+ );+ await act(async () => item!.click());++ expect(showModal).toHaveBeenCalledWith('teamsPlacementModal', {+ workspaceId: 'ws-1',+ bridgeId: 'b-teams',+ bridgeDisplayName: 'Contoso Teams',+ });+ });++ it('does nothing while the workspace has not resolved yet', async () => {+ const el = await render(+ row({ workspaceId: null, isAdmin: true, bridge: bridge({ teamPlacementSupported: true }) })+ );+ await openMenu(el);++ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (i) => i.textContent?.trim() === 'Manage Microsoft Teams…'+ );+ await act(async () => item!.click());++ expect(showModal).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsxnew file mode 100644index 000000000..f891e7c56--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/teams-placement-modal.test.tsx@@ -0,0 +1,710 @@+/**+ * Where Switch's distributed Microsoft Teams app is placed: which teams it is+ * in, which is the default, and what to do when it is not catalogued yet.+ *+ * Offered only for a connection already known to be a running distributed+ * Teams bridge, so every failure case here is either transient (the bridge+ * just stopped) or Microsoft Graph itself declining — covered rather than+ * assumed, since each reads as its own sentence to an admin.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const listBridgeTeams = vi.hoisted(() => vi.fn());+const addBridgeTeam = vi.hoisted(() => vi.fn());+const removeBridgeTeam = vi.hoisted(() => vi.fn());+const setDefaultTeamsTeam = vi.hoisted(() => vi.fn());+const downloadTeamsPackage = vi.hoisted(() => vi.fn());+const toast = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ workspaces: {+ listBridgeTeams,+ addBridgeTeam,+ removeBridgeTeam,+ setDefaultTeamsTeam,+ downloadTeamsPackage,+ },+ },+ events: { on: () => () => {}, emit: () => {} },+}));+vi.mock('@renderer/lib/hooks/use-toast', () => ({ useToast: () => ({ toast }) }));++import { TeamsPlacementModal } from '@renderer/features/switch-servers/TeamsPlacementModal';+import { Dialog } from '@renderer/lib/ui/dialog';+import type { TeamsTeam } from '@shared/core/switch-servers/switch-servers';++const onSuccess = vi.fn();+const onClose = vi.fn();++function team(overrides: Partial<TeamsTeam> = {}): TeamsTeam {+ return {+ teamId: 't1',+ name: 'Engineering',+ hasSwitch: true,+ isDefault: false,+ ...overrides,+ };+}++let container: HTMLDivElement | null = null;+let root: Root | null = null;+let queryClient: QueryClient;++beforeEach(() => {+ listBridgeTeams.mockReset();+ addBridgeTeam.mockReset();+ removeBridgeTeam.mockReset();+ setDefaultTeamsTeam.mockReset();+ downloadTeamsPackage.mockReset();+ toast.mockReset();+ onSuccess.mockReset();+ onClose.mockReset();+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <QueryClientProvider client={queryClient}>+ <Dialog open onOpenChange={() => {}}>+ <TeamsPlacementModal+ workspaceId="ws-1"+ bridgeId="b-1"+ bridgeDisplayName="Contoso Teams"+ onSuccess={onSuccess}+ onClose={onClose}+ />+ </Dialog>+ </QueryClientProvider>+ )+ );+ await settle();+ return document.body;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+}++/** Under fake timers: let `ms` pass, including React Query's own scheduling. */+async function tick(ms: number): Promise<void> {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+ await settle();+}++function findButton(el: HTMLElement, label: string): HTMLButtonElement | undefined {+ return [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(label)+ );+}++function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = findButton(el, label);+ expect(found, `no ${label} button`).toBeDefined();+ return found!;+}++/** A promise the test resolves on its own schedule, to pin a request mid-flight. */+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++describe('loading and fetch failure', () => {+ it('shows a loading state while the teams list is in flight', async () => {+ const { promise } = deferred<unknown>();+ listBridgeTeams.mockReturnValue(promise);++ const el = await render();++ expect(el.textContent).toContain('Loading teams');+ });++ it('reports a transport failure reading the teams list', async () => {+ listBridgeTeams.mockRejectedValue(new Error('network down'));++ const el = await render();++ expect(el.textContent).toContain('Could not read this connection’s teams.');+ });+});++describe('non-listed results', () => {+ it('says a connection no longer on the distributed app does not support this', async () => {+ listBridgeTeams.mockResolvedValue({ kind: 'not-distributed-teams' });+ const el = await render();+ expect(el.textContent).toContain('no longer supports Microsoft Teams team placement');+ });++ it('shows the server’s own sentence for a bridge that does not come back', async () => {+ vi.useFakeTimers();+ try {+ listBridgeTeams.mockResolvedValue({+ kind: 'not-running',+ message: 'The connection is not running; try again in a moment.',+ });+ const el = await render();+ await tick(0);+ expect(el.textContent).toContain('The connection is restarting with your change');+ expect(el.textContent).not.toContain('not running');++ for (let i = 0; i < 21; i++) await tick(1500);++ expect(el.textContent).toContain('The connection is not running; try again in a moment.');+ expect(el.textContent).not.toContain('restarting with your change');+ } finally {+ vi.useRealTimers();+ }+ });++ it('waits out a restart, then lists the teams', async () => {+ vi.useFakeTimers();+ try {+ listBridgeTeams+ .mockResolvedValueOnce({ kind: 'not-running', message: 'not running' })+ .mockResolvedValue({+ kind: 'listed',+ teams: [team({ teamId: 't1', name: 'Engineering', isDefault: true })],+ defaultTeamId: 't1',+ inCatalog: true,+ catalogProblem: null,+ });+ const el = await render();+ await tick(0);+ expect(el.textContent).toContain('The connection is restarting with your change');++ await tick(2000);++ expect(el.textContent).toContain('Engineering');+ expect(el.textContent).not.toContain('not running');+ expect(el.textContent).not.toContain('restarting with your change');+ } finally {+ vi.useRealTimers();+ }+ });++ it('shows the server’s own sentence for Microsoft Graph’s refusal', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'microsoft-refused',+ message: 'Microsoft refused: too many requests',+ });+ const el = await render();+ expect(el.textContent).toContain('Microsoft refused: too many requests');+ });++ it('prompts a sign-in for an expired session', async () => {+ listBridgeTeams.mockResolvedValue({ kind: 'unauthenticated' });+ const el = await render();+ expect(el.textContent).toContain('Your session for this server expired');+ });++ it('names the admin requirement for a non-admin', async () => {+ listBridgeTeams.mockResolvedValue({ kind: 'forbidden' });+ const el = await render();+ expect(el.textContent).toContain('requires an owner or admin of this workspace');+ });++ it('shows a generic error’s own message', async () => {+ listBridgeTeams.mockResolvedValue({ kind: 'error', message: 'boom' });+ const el = await render();+ expect(el.textContent).toContain('boom');+ });+});++describe('listing teams', () => {+ it('badges the chosen default', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ teamId: 't1', name: 'Engineering', isDefault: true })],+ defaultTeamId: 't1',+ inCatalog: true,+ catalogProblem: null,+ });++ const el = await render();++ const row = [...el.querySelectorAll('li')].find((li) =>+ li.textContent?.includes('Engineering')+ );+ expect(row?.textContent).toContain('Default');+ // A default team offers no "Make default" of its own.+ expect(row?.textContent).not.toContain('Make default');+ });++ it('says when a team’s own apps could not be read', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ hasSwitch: null })],+ defaultTeamId: null,+ inCatalog: true,+ catalogProblem: null,+ });++ const el = await render();++ expect(el.textContent).toContain('Switch could not read this team’s apps');+ });++ it('falls back to a plain sentence when the app is not catalogued and the server gives no reason', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ hasSwitch: false })],+ defaultTeamId: null,+ inCatalog: false,+ catalogProblem: null,+ });++ const el = await render();++ expect(el.textContent).toContain('Switch is not in your organisation’s Teams app list yet.');+ });++ it('shows the server’s own catalogue problem when it has one', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ hasSwitch: false })],+ defaultTeamId: null,+ inCatalog: false,+ catalogProblem: 'Publishing failed: the manifest was rejected.',+ });++ const el = await render();++ expect(el.textContent).toContain('Publishing failed: the manifest was rejected.');+ });+});++describe('adding Switch to a team', () => {+ function listed(overrides: { inCatalog?: boolean; catalogProblem?: string | null } = {}) {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ hasSwitch: false, isDefault: false })],+ defaultTeamId: null,+ inCatalog: overrides.inCatalog ?? true,+ catalogProblem: overrides.catalogProblem ?? null,+ });+ }++ it('calls the RPC with the right ids and refreshes the list on success', async () => {+ listed();+ addBridgeTeam.mockResolvedValue({ kind: 'added' });+ const el = await render();+ const spy = vi.spyOn(queryClient, 'invalidateQueries');++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(addBridgeTeam).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ bridgeId: 'b-1',+ teamId: 't1',+ });+ expect(spy).toHaveBeenCalledWith({ queryKey: ['bridge-teams', 'ws-1', 'b-1'] });+ });++ it('shows the catalogue failure’s own message', async () => {+ listed();+ addBridgeTeam.mockResolvedValue({ kind: 'not-in-catalog', message: 'Not catalogued yet.' });+ const el = await render();++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(el.textContent).toContain('Not catalogued yet.');+ });++ it('prompts a sign-in on an expired session', async () => {+ listed();+ addBridgeTeam.mockResolvedValue({ kind: 'unauthenticated' });+ const el = await render();++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(el.textContent).toContain('Your session for this server expired');+ });++ it('names the admin requirement when forbidden', async () => {+ listed();+ addBridgeTeam.mockResolvedValue({ kind: 'forbidden' });+ const el = await render();++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(el.textContent).toContain('requires an owner or admin of this workspace');+ });++ it('shows a generic error’s own message', async () => {+ listed();+ addBridgeTeam.mockResolvedValue({ kind: 'error', message: 'add failed' });+ const el = await render();++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(el.textContent).toContain('add failed');+ });++ it('shows a fallback message when the call throws rather than resolves', async () => {+ listed();+ addBridgeTeam.mockRejectedValue(new Error('rpc exploded'));+ const el = await render();++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(el.textContent).toContain('Could not add Switch to Engineering.');+ });++ it('wraps a disabled Add in a span so the tooltip still fires when the app is not catalogued', async () => {+ listed({ inCatalog: false, catalogProblem: 'Not catalogued yet.' });+ const el = await render();++ const addButton = button(el, 'Add');+ expect(addButton.disabled).toBe(true);+ const wrapper = addButton.closest('span[tabindex="0"]');+ expect(wrapper).not.toBeNull();+ expect(wrapper?.getAttribute('aria-label')).toBe('Not catalogued yet.');+ });+});++describe('removing Switch from a team', () => {+ function listedWithSwitch(overrides: Partial<TeamsTeam> = {}) {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ hasSwitch: true, ...overrides })],+ defaultTeamId: overrides.isDefault ? 't1' : null,+ inCatalog: true,+ catalogProblem: null,+ });+ }++ it('calls the RPC and refreshes both the team list and the bridge list', async () => {+ // Removing Switch from the current default also clears the default and+ // turns channel creation off on the server, so the bridge list (which+ // shows "Default" and channel-creation state) needs refreshing too.+ listedWithSwitch({ isDefault: true });+ removeBridgeTeam.mockResolvedValue({ kind: 'removed' });+ const el = await render();+ const spy = vi.spyOn(queryClient, 'invalidateQueries');++ await act(async () => button(el, 'Remove').click());+ await settle();++ expect(removeBridgeTeam).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ bridgeId: 'b-1',+ teamId: 't1',+ });+ expect(spy).toHaveBeenCalledWith({ queryKey: ['bridge-teams', 'ws-1', 'b-1'] });+ expect(spy).toHaveBeenCalledWith({ queryKey: ['remote-bridges', 'ws-1'] });+ });++ it('prompts a sign-in on an expired session', async () => {+ listedWithSwitch();+ removeBridgeTeam.mockResolvedValue({ kind: 'unauthenticated' });+ const el = await render();++ await act(async () => button(el, 'Remove').click());+ await settle();++ expect(el.textContent).toContain('Your session for this server expired');+ });++ it('names the admin requirement when forbidden', async () => {+ listedWithSwitch();+ removeBridgeTeam.mockResolvedValue({ kind: 'forbidden' });+ const el = await render();++ await act(async () => button(el, 'Remove').click());+ await settle();++ expect(el.textContent).toContain('requires an owner or admin of this workspace');+ });++ it('shows a generic error’s own message', async () => {+ listedWithSwitch();+ removeBridgeTeam.mockResolvedValue({ kind: 'error', message: 'remove failed' });+ const el = await render();++ await act(async () => button(el, 'Remove').click());+ await settle();++ expect(el.textContent).toContain('remove failed');+ });++ it('shows a fallback message when the call throws rather than resolves', async () => {+ listedWithSwitch();+ removeBridgeTeam.mockRejectedValue(new Error('rpc exploded'));+ const el = await render();++ await act(async () => button(el, 'Remove').click());+ await settle();++ expect(el.textContent).toContain('Could not remove Switch from Engineering.');+ });+});++describe('making a team the default', () => {+ function listedTwoTeams() {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [+ team({ teamId: 't1', name: 'Engineering', hasSwitch: true, isDefault: false }),+ team({ teamId: 't2', name: 'Sales', hasSwitch: true, isDefault: true }),+ ],+ defaultTeamId: 't2',+ inCatalog: true,+ catalogProblem: null,+ });+ }++ it('calls the RPC with the chosen team and refreshes both queries on success', async () => {+ listedTwoTeams();+ setDefaultTeamsTeam.mockResolvedValue({ kind: 'updated', bridge: {} });+ const el = await render();+ const spy = vi.spyOn(queryClient, 'invalidateQueries');++ await act(async () => button(el, 'Make default').click());+ await settle();++ expect(setDefaultTeamsTeam).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ bridgeId: 'b-1',+ teamId: 't1',+ });+ expect(spy).toHaveBeenCalledWith({ queryKey: ['bridge-teams', 'ws-1', 'b-1'] });+ expect(spy).toHaveBeenCalledWith({ queryKey: ['remote-bridges', 'ws-1'] });+ });++ it('keeps the choice saving through the restart it causes, then shows the new default', async () => {+ vi.useFakeTimers();+ try {+ listedTwoTeams();+ setDefaultTeamsTeam.mockResolvedValue({ kind: 'updated', bridge: {} });+ const el = await render();+ await tick(0);+ listBridgeTeams+ .mockResolvedValueOnce({ kind: 'not-running', message: 'not running' })+ .mockResolvedValue({+ kind: 'listed',+ teams: [+ team({ teamId: 't1', name: 'Engineering', hasSwitch: true, isDefault: true }),+ team({ teamId: 't2', name: 'Sales', hasSwitch: true, isDefault: false }),+ ],+ defaultTeamId: 't1',+ inCatalog: true,+ catalogProblem: null,+ });++ await act(async () => button(el, 'Make default').click());+ await tick(0);+ expect(el.textContent).toContain('The connection is restarting with your change');+ expect(el.textContent).toContain('Saving…');+ expect(el.textContent).not.toContain('not running');++ await tick(2000);++ expect(el.textContent).not.toContain('Saving…');+ expect(el.textContent).not.toContain('restarting with your change');+ // Sales is no longer the default, so it is the one offered the choice.+ const sales = [...el.querySelectorAll('li')].find((li) => li.textContent?.includes('Sales'));+ expect(sales?.textContent).toContain('Make default');+ } finally {+ vi.useRealTimers();+ }+ });++ it('prompts a sign-in on an expired session', async () => {+ listedTwoTeams();+ setDefaultTeamsTeam.mockResolvedValue({ kind: 'unauthenticated' });+ const el = await render();++ await act(async () => button(el, 'Make default').click());+ await settle();++ expect(el.textContent).toContain('Your session for this server expired');+ });++ it('names the admin requirement when forbidden', async () => {+ listedTwoTeams();+ setDefaultTeamsTeam.mockResolvedValue({ kind: 'forbidden' });+ const el = await render();++ await act(async () => button(el, 'Make default').click());+ await settle();++ expect(el.textContent).toContain('requires an owner or admin of this workspace');+ });++ it('shows the server’s own sentence for a rejected choice (422 → invalid)', async () => {+ listedTwoTeams();+ setDefaultTeamsTeam.mockResolvedValue({+ kind: 'invalid',+ message: 'Switch is not in that team. Add it to the team first, then make it the default.',+ });+ const el = await render();++ await act(async () => button(el, 'Make default').click());+ await settle();++ expect(el.textContent).toContain(+ 'Switch is not in that team. Add it to the team first, then make it the default.'+ );+ });++ it('shows the server’s own sentence for a transient failure (503/502 → error)', async () => {+ listedTwoTeams();+ setDefaultTeamsTeam.mockResolvedValue({+ kind: 'error',+ message: 'Microsoft could not be asked whether Switch is in team t1',+ });+ const el = await render();++ await act(async () => button(el, 'Make default').click());+ await settle();++ expect(el.textContent).toContain('Microsoft could not be asked whether Switch is in team t1');+ });++ it('shows a fallback message when the call throws rather than resolves', async () => {+ listedTwoTeams();+ setDefaultTeamsTeam.mockRejectedValue(new Error('rpc exploded'));+ const el = await render();++ await act(async () => button(el, 'Make default').click());+ await settle();++ expect(el.textContent).toContain('Could not make Engineering the default.');+ });+});++describe('saving the Teams app package', () => {+ function notCatalogued() {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [],+ defaultTeamId: null,+ inCatalog: false,+ catalogProblem: 'Not catalogued yet.',+ });+ }++ it('toasts the saved path on success', async () => {+ notCatalogued();+ downloadTeamsPackage.mockResolvedValue('/tmp/switch-teams-contoso-teams.zip');+ const el = await render();++ await act(async () => button(el, 'Save Teams app package').click());+ await settle();++ expect(downloadTeamsPackage).toHaveBeenCalledWith({+ workspaceId: 'ws-1',+ bridgeId: 'b-1',+ defaultFileName: 'Contoso-Teams.zip',+ });+ expect(toast).toHaveBeenCalledWith({+ title: 'Package saved',+ description: '/tmp/switch-teams-contoso-teams.zip',+ });+ });++ it('shows nothing when the save was cancelled', async () => {+ notCatalogued();+ downloadTeamsPackage.mockResolvedValue(null);+ const el = await render();++ await act(async () => button(el, 'Save Teams app package').click());+ await settle();++ expect(toast).not.toHaveBeenCalled();+ expect(el.textContent).not.toContain('Could not save');+ });++ it('shows a failure message when saving throws', async () => {+ notCatalogued();+ downloadTeamsPackage.mockRejectedValue(new Error('disk full'));+ const el = await render();++ await act(async () => button(el, 'Save Teams app package').click());+ await settle();++ expect(el.textContent).toContain('Could not save the Teams app package.');+ });+});++describe('closing while a request is in flight', () => {+ it('disables Close during an add/remove/make-default call, and re-enables it after', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [team({ hasSwitch: false, isDefault: false })],+ defaultTeamId: null,+ inCatalog: true,+ catalogProblem: null,+ });+ const { promise, resolve } = deferred<{ kind: 'added' }>();+ addBridgeTeam.mockReturnValue(promise);+ const el = await render();++ await act(async () => button(el, 'Add').click());+ await settle();++ expect(button(el, 'Close').disabled).toBe(true);++ await act(async () => resolve({ kind: 'added' }));+ await settle();++ expect(button(el, 'Close').disabled).toBe(false);+ });++ it('disables Close while the package save is in flight, and re-enables it after', async () => {+ listBridgeTeams.mockResolvedValue({+ kind: 'listed',+ teams: [],+ defaultTeamId: null,+ inCatalog: false,+ catalogProblem: null,+ });+ const { promise, resolve } = deferred<string | null>();+ downloadTeamsPackage.mockReturnValue(promise);+ const el = await render();++ await act(async () => button(el, 'Save Teams app package').click());+ await settle();++ expect(button(el, 'Close').disabled).toBe(true);++ await act(async () => resolve(null));+ await settle();++ expect(button(el, 'Close').disabled).toBe(false);+ });+});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 0ce361be3..d627e927c 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@@ -360,6 +360,22 @@ export type RemoteBridge = {* before Telegram had one.*/directorySearchSupported: boolean;+ /**+ * Plain-text description of something only the platform's side can fix —+ * the organisation's admin withdrew approval, or blocked the app outright.+ * Shown as a visible warning on the connection regardless of its type. Null+ * when there is nothing to say, which is also what a server predating the+ * field reports.+ */+ attention: string | null;+ /**+ * True only for a running bridge on Switch's distributed Microsoft Teams+ * app — the one installed by a Microsoft admin approving Switch's own app,+ * rather than a workspace pasting in its own bot credentials. Drives+ * whether the Teams team-placement panel is offered for this connection.+ * False for every other bridge, and for a server predating the field.+ */+ teamPlacementSupported: boolean;};/**@@ -474,6 +490,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. */+ connectionConfig?: Record<string, string>;};/** Outcome of editing a bridge. Mirrors {@link CreateBridgeResult}'s recoverable@@ -802,3 +822,106 @@ export type RemoteRoomRole = {/** Display names of agents currently holding the role (empty if free). */heldBy: string[];};++/**+ * Whether a bridge is backed by a live messaging-app install, which decides+ * what disconnecting it does to its rooms. `unknown` when the server could+ * not be asked (an older server answers `not-installed`).+ */+export type BridgeInstallState = 'installed' | 'not-installed' | 'unknown';++// ── Microsoft Teams team placement ──────────────────────────────────────────++/**+ * One Microsoft Teams team, from the distributed Teams app's own view of the+ * organisation (mirrors the gateway `TeamsTeamSummary`).+ */+export type TeamsTeam = {+ teamId: string;+ name: string;+ /** Whether Switch's app is already added to this team; null when the+ * team's apps could not be read (archived, being deleted, restricted). */+ hasSwitch: boolean | null;+ /** Whether this is the bridge's default team — the one a channel lands in+ * when a room is created without naming one. At most one team is default,+ * and only a team with `hasSwitch` can be. */+ isDefault: boolean;+};++/**+ * Outcome of reading a distributed Teams bridge's team placement+ * (`GET /collaborations/{id}/teams`, admin-only).+ *+ * The failure cases mirror what only this call's host — a running distributed+ * Teams bridge talking to Microsoft Graph — can refuse: `not-distributed-teams`+ * is a bridge this never applies to (a server older than the feature, or a+ * bridge `team_placement_supported` already said no about), `not-running` is+ * the bridge being stopped right now, and `microsoft-refused` is Graph itself+ * declining the request, in its own words.+ */+export type TeamsTeamsResult =+ | {+ kind: 'listed';+ teams: TeamsTeam[];+ /** Redundant with `teams[].isDefault`, carried separately so "no default+ * chosen yet" (null) is distinguishable without scanning the list. */+ defaultTeamId: string | null;+ /** Whether Switch's distributed app is in this organisation's own app+ * catalogue yet. False until a Teams admin uploads the package by hand. */+ inCatalog: boolean;+ /** Why the app is not catalogued yet, as a sentence — present only when+ * `inCatalog` is false. */+ catalogProblem: string | null;+ }+ | { kind: 'not-distributed-teams' }+ | { kind: 'not-running'; message: string }+ | { kind: 'microsoft-refused'; message: string }+ | { kind: 'unauthenticated' }+ | { kind: 'forbidden' }+ | { kind: 'error'; message: string };++/**+ * Outcome of adding Switch's distributed app to a team+ * (`POST /collaborations/{id}/teams/{teamId}`, admin-only). `not-in-catalog` is+ * its own case because it is the one failure with a next step: save the+ * package and have a Teams admin upload it by hand.+ */+export type AddTeamsTeamResult =+ | { kind: 'added' }+ | { kind: 'not-in-catalog'; message: string }+ | { kind: 'unauthenticated' }+ | { kind: 'forbidden' }+ | { kind: 'error'; message: string };++/** Outcome of removing Switch's distributed app from a team+ * (`DELETE /collaborations/{id}/teams/{teamId}`, admin-only). */+export type RemoveTeamsTeamResult =+ | { kind: 'removed' }+ | { kind: 'unauthenticated' }+ | { kind: 'forbidden' }+ | { kind: 'error'; message: string };++// ── Messaging-app installs ──────────────────────────────────────────────────++/**+ * One OAuth-consent install of a deployment's own messaging app into a+ * workspace (mirrors the gateway `MessagingAppInstallSummary`). The bridge it+ * backs is deleted the ordinary way; the install itself — the organisation-side+ * registration that keeps Switch able to listen there at all — is only ended+ * by name, which is what `endedAt === null` installs are for finding.+ */+export type MessagingAppInstall = {+ id: string;+ platform: string;+ externalWorkspaceId: string;+ status: string;+ /** The platform's own spelling of what was granted, kept verbatim — the+ * server stores and sends it as one string, not a list Switch parses. */+ scopes: string;+ /** The bridge this install backs, or null if none was ever created (or it+ * was deleted without ending the install, leaving the install orphaned). */+ bridgeId: string | null;+ installedAt: string;+ /** Null while the install is still active. */+ endedAt: string | null;+};diff --git a/core/pyproject.toml b/core/pyproject.tomlindex e73f90cfe..63e3b4142 100644--- a/core/pyproject.toml+++ b/core/pyproject.toml@@ -34,7 +34,7 @@ dependencies = ["cryptography>=50.0.0,<51","fastmcp>=3.2.0,<4","bcrypt>=4.0,<5",- "PyJWT>=2.9,<3",+ "PyJWT>=2.14,<3","authlib>=1.3,<2","itsdangerous>=2.1,<3","PyYAML>=6,<7",diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex df800b4d2..b06394c63 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport loggingimport mathfrom abc import ABC, abstractmethod-from collections.abc import Awaitable, Callable+from collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import Any, ClassVar, Literal, Protocol, final, runtime_checkable@@ -207,6 +207,14 @@ class ChannelNotBindable(ValueError):"""+class ConfigEditRefused(ValueError):+ """An edit of a connection's settings that the platform says is wrong.++ A `ValueError` for the same reason as `ChannelNotBindable`: it is the+ caller's input, answered as a bad request.+ """++class DirectorySearchBusy(RuntimeError):"""The platform's directory is being searched too often to take one more.@@ -324,7 +332,9 @@ class SupportsSharedConnection(Protocol):Structural on purpose: the lifecycle, the gateway and boot narrow to thiswith `isinstance` and stay ignorant of the concrete adapter, and an adapterwith no shared connection (Slack, Mattermost, Teams, Telegram) never matches- and is left alone.+ and is left alone. A bridge on the distributed Teams app shares the+ deployment's app too, but has nothing to wait for: it is handed the app+ before it starts, by its own bridge-starting listener, and never matches."""def attach_shared_connection(self, connection: Any) -> None: ...@@ -597,6 +607,20 @@ class PlatformAdapter(ABC):"""return None+ @classmethod+ def editable_config_keys(+ cls, connection_config: Mapping[str, object]+ ) -> frozenset[str] | None:+ """Which connection settings a workspace admin may change, or None for all.++ None — the default — leaves every setting editable, which is right for a+ bridge on the organisation's own app: its settings are theirs. A bridge+ on an app the deployment owns may hold settings that decide where the+ deployment's credential is pointed, and an adapter names here the few+ that are safe to change; an edit to any other is refused.+ """+ return None+@classmethodasync def verify_credentials(cls, connection_config: dict[str, object]) -> None:"""Prove the credentials work, before the bridge is persisted.@@ -624,11 +648,33 @@ class PlatformAdapter(ABC):@abstractmethodasync def stop(self) -> None: ...+ async def withdraw(self) -> None:+ """Let go of what this bridge holds on the platform, because it is being+ removed for good.++ Called once, while the bridge is still running, just before it is+ stopped for the last time — never on a restart, which is what `stop`+ alone is for. Most adapters hold nothing on the platform that outlives+ them and have nothing to do; one that registered something there (a+ subscription that keeps delivering, an app installed into a team) undoes+ it here, so the platform stops sending traffic nobody will read.++ Best effort: a removal is what someone asked for, and it goes ahead+ whatever this manages. Raise to say what was left behind; the caller+ logs it.+ """+ return None+async def dispatch_event(self, *, envelope_type: str, payload: dict[str, Any]- ) -> None:+ ) -> dict[str, Any] | None:"""Handle one event that arrived over the public webhook.+ Returns the body to answer with for an event the platform waits on in+ the response itself (`InboundWebhook.answers_inline`), and None for+ every other — which is every event on a platform that acknowledges+ first and handles after.+Concrete on the base and raising, rather than abstract, becausereceiving events over HTTP is a property of a platform and of which appa bridge's token came from — most adapters dial out and are handed@@ -1213,6 +1259,37 @@ class PlatformAdapter(ABC):of that platform."""return []+ @property+ def places_app_in_teams(self) -> bool:+ """Whether Switch chooses which of the platform's teams its app is in.++ True only for a bridge on an app the deployment owns and can add to,+ and remove from, the organisation's teams itself (the distributed+ Teams app). Everywhere else the app is added on the platform by+ whoever owns it, and the dashboard offers nothing to choose.+ """+ return False++ async def check_config_edit(self, connection_config: Mapping[str, object]) -> None:+ """Raise `ConfigEditRefused` for an edit only the platform can tell is wrong.++ Asked of the running bridge before an edit of its settings is stored,+ with the settings as they would be after it. For what validating the+ config cannot know by itself — whether a team it names is one the app+ is in, say. Nothing, by default.+ """+ return None++ async def attention(self) -> str | None:+ """What a workspace admin has to do for this bridge to keep working.++ Something only the platform's side can fix — an approval withdrawn, an+ app blocked by the organisation's admin — found while the bridge runs,+ in plain words fit to show on the connection. None while nothing is+ known to be wrong, which is the default.+ """+ return None+async def install_note(self) -> str | None:"""What the links do not cover, in the platform's own terms.diff --git a/core/switch_core/bridges/collaboration/discord/install.py b/core/switch_core/bridges/collaboration/discord/install.pyindex fa27b1d8a..72228e397 100644--- a/core/switch_core/bridges/collaboration/discord/install.py+++ b/core/switch_core/bridges/collaboration/discord/install.py@@ -75,6 +75,9 @@ PERMISSIONS: int = sum(_PERMISSION_BITS.values())class DiscordAppInstaller(MessagingAppInstaller):platform: ClassVar[str] = "discord"+ # Discord delivers over the Gateway, so the app posts to no webhook and+ # every `/messaging/discord/*` request is answered as if nothing were here.+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset()def __init__(self,@@ -155,6 +158,7 @@ class DiscordAppInstaller(MessagingAppInstaller):# The one that makes this a Discord grant: no per-install token.bot_token=None,scopes=payload.get("scope") or "",+ platform_data={},)def workspace_of_bridge(@@ -179,17 +183,12 @@ class DiscordAppInstaller(MessagingAppInstaller):# ── The webhook half the ABC declares and Discord does not have ───────────## Discord delivers over the Gateway (DISCORD_DISTRIBUTED_APP.md, "the one- # public URL"), so none of these carries real traffic: no- # `/messaging/discord/events` event is ours to read, and `disconnect` skips- # `revoke` for a tokenless install.- #- # `verify_webhook` is the one an unauthenticated stranger can reach — it runs- # first for any POST to `/messaging/discord/{events,interactive,commands}`.- # It raises `MessagingInstallError`, which the route turns into a 404 (the- # same answer as an unregistered platform), rather than an unhandled error- # that would be a repeatable 500 plus a traceback for anyone who found the- # URL. The rest raise loudly: they are only reachable from code that would- # have had to wire a Discord webhook up by mistake.+ # public URL"), so none of these carries real traffic. `webhook_endpoints`+ # is empty, so no request to `/messaging/discord/*` reaches them — the+ # route answers 404 before anything is read — and `disconnect` skips+ # `revoke` for a tokenless install. They raise loudly: they are only+ # reachable from code that would have had to wire a Discord webhook up by+ # mistake.async def revoke(self, *, bot_token: str) -> None:raise NotImplementedError(@@ -197,14 +196,26 @@ class DiscordAppInstaller(MessagingAppInstaller):"is deployment config shared by every install")- def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:+ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:raise MessagingInstallError("the distributed Discord app has no webhook; events arrive over the Gateway")def parse_webhook(- self, *, endpoint: WebhookEndpoint, headers: Mapping[str, str], body: bytes- ) -> InboundWebhook:+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:raise NotImplementedError("the distributed Discord app has no webhook; events arrive over the Gateway")diff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.pyindex b785c6235..47e7f04ce 100644--- a/core/switch_core/bridges/collaboration/install.py+++ b/core/switch_core/bridges/collaboration/install.py@@ -72,6 +72,10 @@ def commands_path(platform: str) -> str:return f"{PUBLIC_PATH_PREFIX}/{platform}/commands"+def notifications_path(platform: str) -> str:+ return f"{PUBLIC_PATH_PREFIX}/{platform}/notifications"++def public_url(public_origin: str, path: str) -> str:"""Absolute URL for one install path, given the deployment's public origin.@@ -105,6 +109,16 @@ class WebhookAuthenticityError(RuntimeError):"""+class WebhookVerificationUnavailable(RuntimeError):+ """An inbound webhook could not be checked at all, so it is neither+ accepted nor refused.++ The platform's signing keys could not be fetched: that is the platform's+ outage, or ours, and says nothing about the request. Answered 503, which+ platforms retry, where a 401 would turn the outage into lost events.+ """++class WebhookPayloadError(RuntimeError):"""A webhook proved genuine and then could not be read.@@ -118,13 +132,15 @@ class WebhookPayloadError(RuntimeError):#: Which of a platform's inbound endpoints a request arrived on.#:-#: Three, because that is what the platforms ask for and what the app manifests-#: declare: events, interactivity, and slash commands. They are separate URLs-#: rather than one, because a platform decides that, not us — and they carry-#: genuinely different bodies (Slack posts JSON to the first and a form to the-#: other two), which is why the endpoint is an argument to parsing rather than-#: something a handler could infer.-WebhookEndpoint = Literal["events", "interactive", "commands"]+#: Each platform declares the ones it uses (`webhook_endpoints`): Slack asks+#: for events, interactivity and slash commands; Teams for the Bot Framework's+#: events and Graph's change notifications. They are separate URLs rather than+#: one, because a platform decides that, not us — and they carry genuinely+#: different bodies (Slack posts JSON to one and a form to the others, and a+#: Bot Framework activity is signed differently from a Graph notification),+#: which is why the endpoint is an argument to verifying and parsing rather+#: than something a handler could infer.+WebhookEndpoint = Literal["events", "interactive", "commands", "notifications"]@dataclass(frozen=True)@@ -156,6 +172,13 @@ class InboundWebhook:event is handled — the receipt decides that — and is carried because it isthe only place the deployment is told its own acknowledgements are arrivingtoo late.++ `answers_inline` marks an event the platform waits on for its answer in the+ response itself — a press on a Teams card, which spins on the presser's+ screen until the response arrives and says what came of it. Every other+ event is acknowledged first and handled after. One that answers inline is+ handled before the response, under a deadline, and is never deduplicated+ by receipt: a retry has to be given the same answer, not nothing."""envelope_type: str@@ -163,6 +186,7 @@ class InboundWebhook:handshake: str | Noneexternal_event_id: str | Nonedelivery_attempt: int+ answers_inline: bool@dataclass(frozen=True)@@ -191,26 +215,40 @@ class InstallGrant:means nothing to us is still the thing to show an operator asking why acall was refused, and parsing it into a list here would be a parser to keepin step with someone else's vocabulary for no gain.++ `platform_data` is anything else the platform will need about this install+ later and that is not a secret — kept on the install row, where a+ workspace admin cannot edit it, rather than in the bridge's config, where+ they can. Empty for a platform with nothing to keep."""external_workspace_id: strworkspace_name: strbot_token: str | Nonescopes: str+ platform_data: Mapping[str, object]class MessagingAppInstaller(ABC):"""The install half of one platform, holding that platform's app credentials.One instance per platform per deployment, built at boot from config and- registered by platform name. Every method is deliberately synchronous- except the code exchange, which is the only one that talks to the network.+ registered by platform name. The methods that may need the network — the+ code exchange, and proving a webhook genuine, which for some platforms+ means fetching the keys it was signed with — are asynchronous; the rest+ are pure and synchronous."""#: The platform this installs, matching the adapter registry's key and the#: `platform` column on `messaging_installs`.platform: ClassVar[str]+ #: The inbound endpoints this platform's app posts to. A request to any+ #: other is answered as if no app were registered, before anything reads+ #: it — so a platform that delivers over a socket of its own declares none+ #: and its webhook URLs simply do not exist.+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]]+@abstractmethoddef authorize_url(self, *, state: str, redirect_uri: str) -> str:"""Where to send the browser to begin an install.@@ -257,14 +295,45 @@ class MessagingAppInstaller(ABC):access with it."""+ def unsigned_handshake(+ self, *, endpoint: WebhookEndpoint, query: Mapping[str, str]+ ) -> str | None:+ """The answer to a URL check the platform makes without signing it.++ Microsoft Graph proves a notification URL is ours by posting a+ `validationToken` in the query string with nothing to authenticate it+ by, and expects the token echoed back within seconds. That is answered+ here, before verification, because it cannot pass verification by+ design — and echoing a stranger's string back to them discloses+ nothing and does nothing.++ None — the default — for every other request. A platform whose URL+ check is signed (Slack's `url_verification`) answers it as an ordinary+ event's `handshake` instead, after it has been verified.+ """+ return None+@abstractmethod- def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:- """Prove an inbound event came from the platform, or raise.+ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:+ """Prove an inbound request came from the platform, or raise.Takes the **raw body**, not a parsed payload, because every platform'ssignature covers the bytes as sent: re-serialising a parsed dictproduces different bytes and a signature that never verifies.+ Takes the endpoint because what proves a request genuine can differ by+ endpoint — a Teams activity carries a Bot Framework token, a Graph+ notification carries tokens from the Microsoft identity platform —+ and is asynchronous because proving it can mean fetching the keys it+ was signed with.+This is the first thing any webhook handler does — before parsing,before resolving a tenant, before logging the body. Raise:class:`WebhookAuthenticityError`.@@ -272,9 +341,19 @@ class MessagingAppInstaller(ABC):@abstractmethoddef parse_webhook(- self, *, endpoint: WebhookEndpoint, headers: Mapping[str, str], body: bytes- ) -> InboundWebhook:- """Read a verified request into an event a running adapter takes.+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ """Read a verified request into the events a running adapter takes.++ A list, because one request can carry several: Graph batches change+ notifications, and the notifications in one batch can belong to+ different organisations, each of which is routed on its own. Most+ platforms send one event per request and return one.Called only after :meth:`verify_webhook` has passed, and separate fromit for exactly that reason: parsing before verifying is how an@@ -334,6 +413,28 @@ class MessagingAppInstaller(ABC):"""return None+ async def release(self, *, external_workspace_id: str) -> None:+ """Take the app out of a workspace whose install is being disconnected.++ The counterpart of `revoke` for a platform with no per-install token,+ called only when the install's bridge is not running to do it itself+ (`PlatformAdapter.withdraw`). A no-op where there is nothing on+ the platform to undo. Best effort: raise `MessagingInstallError` to+ say what was left behind, and the disconnect is refused so it can be+ tried again.+ """+ return None++ def describe_callback_error(self, *, error: str, description: str | None) -> str:+ """What to tell the person whose install the platform refused, in plain words.++ The platform's own refusal arrives on the callback as a code and, from+ some platforms, a description written for developers. The default says+ which code it was; a platform whose codes mean something a person can+ act on — "you need to be an administrator" — says that instead.+ """+ return f"{self.platform} reported: {error}."+@abstractmethoddef connection_config(self, grant: InstallGrant) -> dict[str, object]:"""Render a grant as the connection config this platform's adapter takes.diff --git a/core/switch_core/bridges/collaboration/install_confirmation.py b/core/switch_core/bridges/collaboration/install_confirmation.pyindex 89e71f95c..725bc83b7 100644--- a/core/switch_core/bridges/collaboration/install_confirmation.py+++ b/core/switch_core/bridges/collaboration/install_confirmation.py@@ -61,6 +61,7 @@ def seal(ticket: InstallTicket, *, keyring: Keyring) -> str:"name": ticket.grant.workspace_name,"tok": ticket.grant.bot_token,"scopes": ticket.grant.scopes,+ "pd": dict(ticket.grant.platform_data),},separators=(",", ":"),)@@ -91,5 +92,8 @@ def open_ticket(token: str, *, keyring: Keyring) -> InstallTicket:workspace_name=decoded["name"],bot_token=decoded["tok"],scopes=decoded["scopes"],+ # Absent from a ticket sealed before platform data existed, which+ # a confirmation page left open across that deploy still carries.+ platform_data=decoded.get("pd", {}),),)diff --git a/core/switch_core/bridges/collaboration/install_routes.py b/core/switch_core/bridges/collaboration/install_routes.pyindex f3f6278c7..0664b48fe 100644--- a/core/switch_core/bridges/collaboration/install_routes.py+++ b/core/switch_core/bridges/collaboration/install_routes.py@@ -25,12 +25,14 @@ codes and say the rest in the log.from __future__ import annotations+import asyncio+import functoolsimport htmlimport logging-from typing import Annotated, Literal+from typing import Annotated, Any, Literalfrom fastapi import APIRouter, BackgroundTasks, Form, Query, Request, Response-from starlette.responses import HTMLResponse, PlainTextResponse+from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponsefrom switch_core.bridges.collaboration.install import (PUBLIC_PATH_PREFIX,@@ -39,6 +41,7 @@ from switch_core.bridges.collaboration.install import (WebhookAuthenticityError,WebhookEndpoint,WebhookPayloadError,+ WebhookVerificationUnavailable,oauth_confirm_path,)from switch_core.bridges.collaboration.install_confirmation import (@@ -61,6 +64,36 @@ from switch_core.db.stores.messaging_install_store import (logger = logging.getLogger(__name__)+#: How long an event the platform waits on may take before it is answered as+#: failed. Under the platforms' own limits — Teams gives up on a card press+#: after about fifteen seconds — so the answer that says it failed is the one+#: the person sees, rather than the platform's own timeout.+_INLINE_ANSWER_SECONDS = 10.0++#: Inline handling that outran its deadline and is still finishing. Held so+#: the task is not collected mid-way, and dropped as each one ends.+_finishing: set[asyncio.Task[dict[str, Any] | None]] = set()+++def _finished_late(+ target: WebhookTarget,+ envelope_type: str,+ task: asyncio.Task[dict[str, Any] | None],+) -> None:+ _finishing.discard(task)+ if task.cancelled():+ return+ error = task.exception()+ if error is not None:+ logger.error(+ "A %s %s event for bridge %s failed after its answer was sent",+ target.platform,+ envelope_type,+ target.bridge_id,+ exc_info=error,+ )++_PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{title}</title>@@ -148,14 +181,21 @@ def create_messaging_install_router(code: str | None = Query(default=None),state: str | None = Query(default=None),error: str | None = Query(default=None),+ error_description: str | None = Query(default=None),) -> HTMLResponse:# The platform's own refusal, which is usually the customer deciding# not to install after all. Nothing went wrong here and nothing was# written; saying so is the whole handling.if error:+ try:+ explained = service.installer(platform).describe_callback_error(+ error=error, description=error_description+ )+ except MessagingInstallError:+ explained = f"{platform} reported: {error}."return _page(title="Install cancelled",- detail=f"{platform} reported: {error}. Nothing was connected.",+ detail=f"{explained} Nothing was connected.",status=200,)@@ -192,6 +232,12 @@ def create_messaging_install_router(detail=str(failure),status=400,)+ except MessagingInstallClaimedError as failure:+ return _page(+ title="Workspace already connected",+ detail=str(failure),+ status=409,+ )except MessagingInstallError as failure:return _page(title="Install could not be completed",@@ -316,13 +362,56 @@ def create_messaging_install_router(revocation.reason,)+ async def _answer(target: WebhookTarget, event: InboundWebhook) -> Response:+ """Handle an event the platform waits on, and answer with what came of it.++ Under a deadline, and with every failure answered rather than raised:+ until it is answered the person who pressed is looking at a spinner,+ and the platform's own timeout reports a failure in its words, not+ ours.+ """+ handling = asyncio.create_task(service.answer(target, event))+ try:+ # Shielded: the deadline is the platform's, and running out of it+ # ends the wait, not the handling — a press abandoned half way+ # could be recorded with its card never redrawn.+ body = await asyncio.wait_for(+ asyncio.shield(handling), _INLINE_ANSWER_SECONDS+ )+ except TimeoutError:+ logger.error(+ "A %s %s event for bridge %s was not handled within %ss; it is "+ "still being handled, but the platform has been told it failed",+ target.platform,+ event.envelope_type,+ target.bridge_id,+ _INLINE_ANSWER_SECONDS,+ )+ _finishing.add(handling)+ handling.add_done_callback(+ functools.partial(_finished_late, target, event.envelope_type)+ )+ return Response(status_code=504)+ except Exception:+ logger.exception(+ "Failed to handle a %s %s event for bridge %s (tenant %s)",+ target.platform,+ event.envelope_type,+ target.bridge_id,+ target.tenant_id,+ )+ return Response(status_code=500)+ if body is None:+ return Response(status_code=200)+ return JSONResponse(body)+async def _inbound(platform: str,endpoint: WebhookEndpoint,request: Request,background: BackgroundTasks,) -> Response:- """One verified event, from any of a platform's three inbound URLs.+ """One verified request, from any of a platform's inbound URLs.The status codes are read by the platform, not by a person, and theyare chosen for what it does with them. Slack retries a 5xx and gives up@@ -330,22 +419,44 @@ def create_messaging_install_router(permanent condition must not look transient, and a transient one mustnot look permanent."""+ query = dict(request.query_params)+ try:+ # Before verification, because it cannot pass it by design and+ # answering it does nothing but echo the caller's own string.+ unsigned = service.unsigned_handshake(+ platform=platform, endpoint=endpoint, query=query+ )+ except MessagingInstallError:+ # No app registered for this platform, or none that posts here, so+ # nothing here could have signed anything. Not found rather than an+ # explanation: the caller is unauthenticated and learns only that+ # there is nothing here.+ return Response(status_code=404)+ if unsigned is not None:+ logger.info("Answered a %s URL validation", platform)+ return PlainTextResponse(unsigned)+body = await request.body()try:- event = service.authenticate(+ events = await service.authenticate(platform=platform,endpoint=endpoint,headers=dict(request.headers),+ query=query,body=body,)except MessagingInstallError:- # No app registered for this platform, so nothing here could have- # signed anything. Not found rather than an explanation: the caller- # is unauthenticated and learns only that there is nothing here.return Response(status_code=404)except WebhookAuthenticityError as failure:logger.warning("Refused an unverified %s webhook: %s", platform, failure)return Response(status_code=401)+ except WebhookVerificationUnavailable as failure:+ logger.error(+ "Could not check a %s webhook, so asked for it again: %s",+ platform,+ failure,+ )+ return Response(status_code=503)except WebhookPayloadError as failure:# Verified, so this really is the platform sending something this# build cannot read. Worth an error rather than a shrug — it is how@@ -353,59 +464,106 @@ def create_messaging_install_router(logger.error("Could not read a verified %s webhook: %s", platform, failure)return Response(status_code=400)- if event.handshake is not None:+ handshake = next((e.handshake for e in events if e.handshake is not None), None)+ if handshake is not None:logger.info("Answered a %s URL verification", platform)- return PlainTextResponse(event.handshake)-- if event.delivery_attempt > 0:- # The only signal this deployment gets that its own acknowledgements- # are arriving too late. The event itself is handled normally — the- # receipt decides whether it is a duplicate — but a run of these is- # the platform saying the three-second answer is being missed, and- # nothing else in the system would say so.- logger.warning(- "%s is re-sending a %s event (attempt %s), which means an earlier "- "delivery was not acknowledged in time",- platform,- event.envelope_type,- event.delivery_attempt,- )+ return PlainTextResponse(handshake)++ unavailable = 0+ unreadable = 0+ handled = 0+ # A batch usually names a handful of workspaces among many events, and+ # each lookup is two database reads before the platform is answered.+ resolved: dict[str, WebhookTarget | Exception] = {}++ async def resolve(event: InboundWebhook) -> WebhookTarget:+ workspace_id = service.workspace_of(platform=platform, event=event)+ if workspace_id not in resolved:+ try:+ resolved[workspace_id] = await service.resolve_by_workspace(+ platform=platform, workspace_id=workspace_id+ )+ except (WebhookWorkspaceUnknown, WebhookBridgeUnavailable) as failure:+ resolved[workspace_id] = failure+ outcome = resolved[workspace_id]+ if isinstance(outcome, Exception):+ raise outcome+ return outcome++ for event in events:+ if event.delivery_attempt > 0:+ # The only signal this deployment gets that its own+ # acknowledgements are arriving too late. The event itself is+ # handled normally — the receipt decides whether it is a+ # duplicate — but a run of these is the platform saying the+ # three-second answer is being missed, and nothing else in the+ # system would say so.+ logger.warning(+ "%s is re-sending a %s event (attempt %s), which means an "+ "earlier delivery was not acknowledged in time",+ platform,+ event.envelope_type,+ event.delivery_attempt,+ )- try:- # Before resolving, because this is the one event that arrives as- # the bridge it would be resolved to is going away.- revocation = service.revocation(platform=platform, event=event)- if revocation is not None:- background.add_task(_end_install, platform, revocation)- return Response(status_code=200)-- target = await service.resolve(platform=platform, event=event)- except WebhookPayloadError as failure:- logger.error(- "A verified %s event named no workspace: %s", platform, failure- )+ try:+ # Before resolving, because this is the one event that arrives+ # as the bridge it would be resolved to is going away.+ revocation = service.revocation(platform=platform, event=event)+ if revocation is not None:+ background.add_task(_end_install, platform, revocation)+ handled += 1+ continue++ target = await resolve(event)+ except WebhookPayloadError as failure:+ # Skipped rather than answered: on an endpoint every workspace+ # shares, one unreadable item in a batch must not take the rest+ # of it down with it.+ logger.error(+ "A verified %s event named no workspace: %s", platform, failure+ )+ unreadable += 1+ continue+ except WebhookWorkspaceUnknown as failure:+ # A 200 for an event that reached nobody, which is the one place+ # this file answers something other than what happened. The app+ # left behind in a workspace whose install ended goes on+ # posting, the platform cannot act on a 404, and it counts the+ # refusals against the app as a whole — so the honest answer+ # costs every other customer's delivery. The log is where it is+ # visible.+ logger.warning("Dropped a %s event: %s", platform, failure)+ continue+ except WebhookBridgeUnavailable as failure:+ logger.error("Could not deliver a %s event: %s", platform, failure)+ unavailable += 1+ continue++ if event.answers_inline:+ # Only ever one to a request: a platform that waits on an+ # answer sends the one event it waits on.+ return await _answer(target, event)++ # Answered first, handled after. The platform's deadline is short+ # and what happens next is not bounded by it — a turn can take+ # minutes — so acknowledging on the way out is what keeps a slow+ # room from becoming a retried, duplicated one.+ background.add_task(_deliver, target, event)+ handled += 1++ # A 503 asks the platform to send the request again, which is right+ # while a bridge restarts — a 200 would drop a real message and report+ # it handled. But only when nothing in it was delivered: a batch on an+ # endpoint every workspace shares is otherwise one workspace's restart+ # failing, and the platform backing off from, everyone else's delivery.+ # What was undeliverable in a partly delivered batch is logged above.+ # A batch nothing in which could be read is the platform's payload+ # changing under this build, and says so with a 400 that is not retried.+ if events and unreadable == len(events):return Response(status_code=400)- except WebhookWorkspaceUnknown as failure:- # A 200 for an event that reached nobody, which is the one place- # this file answers something other than what happened. The app- # left behind in a workspace whose install ended goes on posting,- # the platform cannot act on a 404, and it counts the refusals- # against the app as a whole — so the honest answer costs every- # other customer's delivery. The log is where it is visible.- logger.warning("Dropped a %s event: %s", platform, failure)- return Response(status_code=200)- except WebhookBridgeUnavailable as failure:- # Deliberately a 503: the platform retrying is the right behaviour- # while a bridge restarts, and a 200 here would drop a real message- # on the floor and report that it had been handled.- logger.error("Could not deliver a %s event: %s", platform, failure)+ if unavailable and not handled:return Response(status_code=503)-- # Answered first, handled after. The platform's deadline is short and- # what happens next is not bounded by it — a turn can take minutes —- # so acknowledging on the way out is what keeps a slow room from- # becoming a retried, duplicated one.- background.add_task(_deliver, target, event)return Response(status_code=200)@router.post("/{platform}/events")@@ -435,4 +593,15 @@ def create_messaging_install_router() -> Response:return await _inbound(platform, "commands", request, background)+ @router.post("/{platform}/notifications")+ async def notifications(+ platform: str, request: Request, background: BackgroundTasks+ ) -> Response:+ """Change notifications a platform pushes for what it was asked to watch.++ Microsoft Graph's, for the distributed Teams app: every message in the+ channels Switch captures, batched, from every organisation at once.+ """+ return await _inbound(platform, "notifications", request, background)+return routerdiff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex 4d46085ae..3e967f7b4 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -59,6 +59,7 @@ from __future__ import annotationsimport loggingfrom collections.abc import Mappingfrom dataclasses import dataclass+from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -271,10 +272,17 @@ class MessagingInstallService:# Refused here rather than after the approver has chosen Connect on# a page offering a workspace that cannot be had. `confirm` checks- # again, since the workspace may be claimed in between.+ # again, since the workspace may be claimed in between. The+ # tenant's own tokenless install is no rival: approving it again+ # refreshes it (`_refresh_own_install`).+ own = await self._own_tokenless_install(+ tenant_id=state.tenant_id, platform=platform, grant=grant+ )try:await self._lifecycle.reject_claim_conflict(- platform, installer.connection_config(grant)+ platform,+ installer.connection_config(grant),+ exclude_bridge_id=own.bridge_id if own is not None else None,)except BridgeClaimConflict as exc:raise MessagingInstallClaimedError(str(exc)) from exc@@ -327,6 +335,13 @@ class MessagingInstallService:)await session.commit()+ if grant.bot_token is None:+ refreshed = await self._refresh_own_install(+ tenant_id=opened.tenant_id, platform=platform, grant=grant+ )+ if refreshed is not None:+ return refreshed+connection_config = installer.connection_config(grant)# Before the install is recorded: registering the bridge re-checks@@ -353,6 +368,7 @@ class MessagingInstallService:else None),scopes=grant.scopes,+ platform_data=grant.platform_data,user_id=decided.created_by_user_id,)install_id = install.id@@ -487,6 +503,78 @@ class MessagingInstallService:)return opened+ async def _own_tokenless_install(+ self, *, tenant_id: str, platform: str, grant: InstallGrant+ ) -> MessagingInstall | None:+ """The tenant's live install of a tokenless grant's workspace, if any.++ None for a grant with a token, which `_refresh_own_install` never+ refreshes and the claim check should therefore see as it is.+ """+ if grant.bot_token is not None:+ return None+ async with tenant_session(self._session_factory, tenant_id) as session:+ return await self._store.get_for_workspace(+ session,+ platform=platform,+ external_workspace_id=grant.external_workspace_id,+ )++ async def _refresh_own_install(+ self, *, tenant_id: str, platform: str, grant: InstallGrant+ ) -> MessagingInstall | None:+ """Take a repeated approval of the tenant's own live install as a refresh.++ For a platform with no per-install token, the same organisation+ approving again — for new permissions, a newer app, or to restore an+ approval it withdrew — must not be refused as "already connected" by+ its own install. Read under the tenant, so another tenant's install of+ the workspace is invisible here and still refused by the claim below.+ The bridge is restarted so it checks the approval afresh.++ A platform with a token is left to the claim: its bridge holds the old+ token, and swapping it is not something this does.+ """+ async with tenant_session(self._session_factory, tenant_id) as session:+ existing = await self._store.get_for_workspace(+ session,+ platform=platform,+ external_workspace_id=grant.external_workspace_id,+ )+ if existing is None:+ return None+ refreshed = await self._store.refresh(+ session,+ install_id=existing.id,+ scopes=grant.scopes,+ platform_data=grant.platform_data,+ )+ await session.commit()+ if refreshed.bridge_id is not None:+ try:+ await self._lifecycle.restart(refreshed.bridge_id)+ except Exception as error:+ logger.exception(+ "Bridge %s did not restart after %s workspace %s was approved "+ "again",+ refreshed.bridge_id,+ platform,+ grant.external_workspace_id,+ )+ raise MessagingInstallError(+ "Switch recorded the approval, but the connection could not "+ f"restart to use it ({error}). It is stopped until Switch "+ "restarts or the approval is given again."+ ) from error+ logger.info(+ "Refreshed the install of %s workspace %s for tenant %s after it was "+ "approved again",+ platform,+ grant.external_workspace_id,+ tenant_id,+ )+ return refreshed+async def refuse_uninstalled_bridge(self,*,@@ -568,10 +656,15 @@ class MessagingInstallService:return await self._store.get(session, install_id=install_id)with tenant_scope(tenant_id):+ installer = self._installers.get(platform)if token is not None:- await self._installers.get(platform).revoke(- bot_token=self._keyring.decrypt(token)- )+ await installer.revoke(bot_token=self._keyring.decrypt(token))+ elif bridge_id is None or not self._lifecycle.is_connected(bridge_id):+ # A tokenless install has nothing to revoke, and a connected+ # bridge lets go of the platform itself as it is removed. One+ # that is not running, or still starting, cannot, so the+ # installer does it.+ await installer.release(external_workspace_id=workspace_id)async with tenant_session(self._session_factory, tenant_id) as session:ended = await self._store.end(@@ -670,23 +763,59 @@ class MessagingInstallService:# messages. Everything up to and including `resolve` is fast enough to# answer inside, and `deliver` runs after the response has gone.- def authenticate(+ def _webhook_installer(+ self, platform: str, endpoint: WebhookEndpoint+ ) -> MessagingAppInstaller:+ """The installer for a webhook request, or the same refusal as no app.++ An endpoint the platform's app does not post to does not exist, and is+ answered exactly as a platform with no app registered is — before+ anything reads the request.+ """+ installer = self._installers.get(platform)+ if endpoint not in installer.webhook_endpoints:+ raise MessagingInstallError(+ f"the {platform} app does not post to {endpoint}"+ )+ return installer++ def unsigned_handshake(+ self,+ *,+ platform: str,+ endpoint: WebhookEndpoint,+ query: Mapping[str, str],+ ) -> str | None:+ """The answer to a platform's unsigned URL check, if this request is one.++ The one thing answered before verification, and only because it cannot+ be verified by design; see `MessagingAppInstaller.unsigned_handshake`.+ """+ installer = self._webhook_installer(platform, endpoint)+ return installer.unsigned_handshake(endpoint=endpoint, query=query)++ async def authenticate(self,*,platform: str,endpoint: WebhookEndpoint,headers: Mapping[str, str],+ query: Mapping[str, str],body: bytes,- ) -> InboundWebhook:+ ) -> list[InboundWebhook]:"""Prove an inbound request came from the platform, and read it.Verification is first and unconditional. Nothing above it inspects thebody, so an unsigned request cannot pick which parser runs, and nothingis logged from it either — it is a stranger's bytes until this passes."""- installer = self._installers.get(platform)- installer.verify_webhook(headers=headers, body=body)- return installer.parse_webhook(endpoint=endpoint, headers=headers, body=body)+ installer = self._webhook_installer(platform, endpoint)+ await installer.verify_webhook(+ endpoint=endpoint, headers=headers, query=query, body=body+ )+ return installer.parse_webhook(+ endpoint=endpoint, headers=headers, query=query, body=body+ )def revocation(self, *, platform: str, event: InboundWebhook) -> Revocation | None:"""Whether this event is the platform ending the install, and for whom.@@ -710,12 +839,18 @@ class MessagingInstallService:async def resolve(self, *, platform: str, event: InboundWebhook) -> WebhookTarget:"""Turn a webhook event's workspace into the bridge entitled to it."""- installer = self._installers.get(platform)- workspace_id = installer.workspace_of_event(event.payload)return await self.resolve_by_workspace(- platform=platform, workspace_id=workspace_id+ platform=platform,+ workspace_id=self.workspace_of(platform=platform, event=event),)+ def workspace_of(self, *, platform: str, event: InboundWebhook) -> str:+ """The workspace a webhook event is for, as its platform names it.++ Raises `WebhookPayloadError` for an event that names none.+ """+ return self._installers.get(platform).workspace_of_event(event.payload)+async def resolve_by_workspace(self, *, platform: str, workspace_id: str) -> WebhookTarget:@@ -759,7 +894,7 @@ class MessagingInstallService:)adapter = self._lifecycle.get_adapter(install.bridge_id)- if adapter is None:+ if adapter is None or not self._lifecycle.is_connected(install.bridge_id):raise WebhookBridgeUnavailable(f"bridge {install.bridge_id}, which serves {platform} workspace "f"{workspace_id}, is not running"@@ -833,8 +968,22 @@ class MessagingInstallService:target.tenant_id,)- async def _dispatch(self, target: WebhookTarget, event: InboundWebhook) -> None:+ async def answer(+ self, target: WebhookTarget, event: InboundWebhook+ ) -> dict[str, Any] | None:+ """Handle an event the platform waits on, and return its answer.++ No receipt, unlike `deliver`: a platform that retries one of these+ does so because it never saw the answer, and the retry has to be given+ one rather than dropped as a duplicate. Handling the same press twice+ is the adapter's to make harmless, and on Teams it already is.+ """+ return await self._dispatch(target, event)++ async def _dispatch(+ self, target: WebhookTarget, event: InboundWebhook+ ) -> dict[str, Any] | None:with no_tenant():- await target.adapter.dispatch_event(+ return await target.adapter.dispatch_event(envelope_type=event.envelope_type, payload=event.payload)diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex be9113e5a..227438ca0 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -18,6 +18,7 @@ from switch_core.bridges.collaboration.ingress import CallbackEndpoint, Callbackfrom switch_core.bridges.collaboration.models import (BridgeConnectionConfig,BridgeCredentialError,+ BridgeNotRunning,BridgeOperationError,BridgeStartRefused,)@@ -434,6 +435,17 @@ class CollaborationBridgeLifecycleService:def get_registered_types(self) -> list[str]:return list(self._adapter_registry.keys())+ def is_connected(self, bridge_id: str) -> bool:+ """Whether a bridge's adapter has finished starting and is serving.++ A bridge is registered as running the moment it is started, well+ before its adapter has loaded what it needs to handle traffic; an event+ handed to it in that window is acknowledged and lost. Whoever delivers+ platform traffic asks this, and tells the platform to try again until+ it is true.+ """+ return bridge_id in self._connected+def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:"""The live adapter for a running bridge, or None if it isn't running.@@ -508,6 +520,32 @@ class CollaborationBridgeLifecycleService:connection_config=connection_config,)+ async def check_config_edit(+ self,+ *,+ bridge_id: str,+ bridge_type: str,+ current: Mapping[str, object],+ connection_config: Mapping[str, object],+ ) -> None:+ """Ask the running bridge whether an edit of its settings is sound.++ See `PlatformAdapter.check_config_edit`. A bridge on an app the+ deployment owns (one whose adapter limits what is editable) checks+ with the platform, and cannot until it has finished starting, so the+ edit is refused with `BridgeNotRunning` rather than stored unchecked. Any other+ bridge's edit goes through on its validation alone.+ """+ adapter = self.get_adapter(bridge_id)+ if adapter is None or not self.is_connected(bridge_id):+ if self.editable_config_keys(bridge_type, current) is not None:+ raise BridgeNotRunning(+ "The connection is not running, so Switch cannot check this "+ "change with the platform; try again in a moment."+ )+ return+ await adapter.check_config_edit(connection_config)+def iter_adapters(self) -> Iterator[PlatformAdapter]:"""The live adapter of every running bridge, as a snapshot.@@ -535,6 +573,20 @@ class CollaborationBridgeLifecycleService:return Truereturn adapter_cls.supports_channel_creation+ def editable_config_keys(+ self, bridge_type: str, connection_config: Mapping[str, object]+ ) -> frozenset[str] | None:+ """Which of a bridge's connection settings may be edited, or None for all.++ The adapter class decides — see `PlatformAdapter.editable_config_keys`.+ An unknown type has no adapter to ask and leaves everything to the+ validation that rejects it by name.+ """+ adapter_cls = self._adapter_registry.get(bridge_type)+ if adapter_cls is None:+ return None+ return adapter_cls.editable_config_keys(connection_config)+def supports_directory_search(self, bridge_type: str) -> bool:"""Whether this platform has a user directory Switch can search.@@ -873,7 +925,31 @@ class CollaborationBridgeLifecycleService:},)- await self.start(bridge.id)+ try:+ await self.start(bridge.id)+ except Exception:+ # Stored and not startable is a half state: a row that fails every+ # boot, and for an install a second bridge on the next attempt. So+ # a bridge whose start is refused outright is not kept. Once its+ # adapter is connecting, in the background, a failure is the+ # bridge's own — logged and reported like any other start's — and+ # credentials were already checked before anything was stored.+ logger.exception(+ "Collaboration bridge %s (%s) could not start; removing it",+ bridge.id,+ bridge_type,+ )+ try:+ await self.remove(bridge.id)+ except Exception:+ # The start failure is what the caller needs to see; this one+ # is logged rather than raised in its place.+ logger.exception(+ "Collaboration bridge %s could not be removed after failing "+ "to start; its record remains",+ bridge.id,+ )+ raiselogger.info("Registered collaboration bridge %s (%s): %s",@@ -1425,6 +1501,23 @@ class CollaborationBridgeLifecycleService:was_connected = await milestone_claimed(self._session_factory, f"connector_added:{bridge_id}")+ running = self._bridges.get(bridge_id)+ if running is not None:+ try:+ await running.adapter.withdraw()+ except Exception:+ logger.error(+ "Collaboration bridge %s could not let go of everything it "+ "held on its platform; removing it anyway",+ bridge_id,+ exc_info=True,+ )+ else:+ logger.warning(+ "Collaboration bridge %s is not running, so it cannot let go of "+ "what it holds on its platform itself; removing it anyway",+ bridge_id,+ )await self.stop(bridge_id)async with self._session_factory() as session:bridge = await self._bridge_store.get(session, bridge_id)diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.pyindex 815e5a706..234363d01 100644--- a/core/switch_core/bridges/collaboration/models.py+++ b/core/switch_core/bridges/collaboration/models.py@@ -224,6 +224,13 @@ class BridgeStartRefused(RuntimeError):"""+class BridgeNotRunning(RuntimeError):+ """What was asked needs the bridge running, and it is not.++ Usually the moment of a restart, so worth trying again shortly.+ """++class BridgeOperationError(RuntimeError):"""A platform refused an operation the bridge asked it to perform.diff --git a/core/switch_core/bridges/collaboration/slack/install.py b/core/switch_core/bridges/collaboration/slack/install.pyindex 522ebbf9c..af28131fd 100644--- a/core/switch_core/bridges/collaboration/slack/install.py+++ b/core/switch_core/bridges/collaboration/slack/install.py@@ -140,6 +140,9 @@ BOT_SCOPES: tuple[str, ...] = (class SlackAppInstaller(MessagingAppInstaller):platform: ClassVar[str] = "slack"+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset(+ {"events", "interactive", "commands"}+ )def __init__(self, *, client_id: str, client_secret: str, signing_secret: str@@ -201,6 +204,7 @@ class SlackAppInstaller(MessagingAppInstaller):workspace_name=team.get("name") or workspace_id,bot_token=access_token,scopes=response.get("scope") or "",+ platform_data={},)async def revoke(self, *, bot_token: str) -> None:@@ -232,7 +236,16 @@ class SlackAppInstaller(MessagingAppInstaller):"was not revoked, so it is still valid.")- def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:+ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:+ # Every Slack endpoint is signed the same way, with the signing secret+ # over the timestamp and the raw body — no network, nothing to fetch.try:valid = self._verifier.is_valid_request(body, dict(headers))except ValueError as error:@@ -244,6 +257,17 @@ class SlackAppInstaller(MessagingAppInstaller):raise WebhookAuthenticityError("bad Slack signature")def parse_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ # One event per request, always: Slack does not batch.+ return [self._parse_one(endpoint=endpoint, headers=headers, body=body)]++ def _parse_one(self, *, endpoint: WebhookEndpoint, headers: Mapping[str, str], body: bytes) -> InboundWebhook:attempt = _retry_number(headers)@@ -263,6 +287,7 @@ class SlackAppInstaller(MessagingAppInstaller):# deduplicate by.external_event_id=None,delivery_attempt=attempt,+ answers_inline=False,)if endpoint == "interactive":@@ -279,6 +304,7 @@ class SlackAppInstaller(MessagingAppInstaller):handshake=None,external_event_id=None,delivery_attempt=attempt,+ answers_inline=False,)envelope = _json_object(body)@@ -298,6 +324,7 @@ class SlackAppInstaller(MessagingAppInstaller):handshake=challenge,external_event_id=None,delivery_attempt=attempt,+ answers_inline=False,)event_id = envelope.get("event_id")@@ -312,6 +339,7 @@ class SlackAppInstaller(MessagingAppInstaller):if isinstance(event_id, str) and event_idelse None,delivery_attempt=attempt,+ answers_inline=False,)def workspace_of_event(self, payload: Mapping[str, object]) -> str:diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex 03cff1ba8..4b887a286 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -1,7 +1,6 @@from __future__ import annotationsimport asyncio-import hmacimport htmlimport jsonimport logging@@ -9,21 +8,23 @@ import reimport secretsimport timefrom collections import OrderedDict-from collections.abc import AsyncIterator, Awaitable, Callable+from collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom contextlib import asynccontextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclass, replacefrom datetime import UTC, datetime, timedelta-from typing import Any, ClassVar-from urllib.parse import quote, unquote+from typing import TYPE_CHECKING, Any, ClassVar, Literal+from urllib.parse import quote, unquote, urlsplitimport httpxfrom aiohttp import web-from pydantic import Field, model_validator+from pydantic import ConfigDict, Field, model_validatorfrom pydantic.json_schema import SkipJsonSchemafrom switch_core.bridges.agent.commands import COMMANDS_BY_NAMEfrom switch_core.bridges.collaboration.adapter import (+ ChannelNotBindable,+ ConfigEditRefused,PlatformAdapter,RemovalFailed,RequestCard,@@ -35,6 +36,7 @@ from switch_core.bridges.collaboration.adapter import (from switch_core.bridges.collaboration.models import (BridgeConnectionConfig,BridgeCredentialError,+ BridgeOperationError,ChannelType,DirectoryUser,InboundAgentJoin,@@ -57,8 +59,13 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (turn_status,)from switch_core.bridges.collaboration.teams.auth import (- InboundActivityValidator,+ BOTFRAMEWORK_OPENID,+ BotFrameworkAuthenticator,+ ClientSecret,+ SigningKeys,+ SigningKeysUnavailable,TeamsTokenProvider,+ TokenRequestRefused,)from switch_core.bridges.collaboration.teams.cards import (activity_detail,@@ -76,17 +83,31 @@ from switch_core.bridges.collaboration.teams.connector import (BotConnectorThrottled,)from switch_core.bridges.collaboration.teams.crypto import (- decrypt_resource_data,+ ResourceDataError,generate_encryption_keypair,load_certificate_der_b64,+ load_private_key,+)+from switch_core.bridges.collaboration.teams.graph import GraphClient, GraphError+from switch_core.bridges.collaboration.teams.identity import (+ NotificationKey,+ NotificationKeyring,+ TeamsIdentity,+ TeamsTokens,+)+from switch_core.bridges.collaboration.teams.withdrawal import (+ delete_own_subscriptions,+ leave_every_team,)-from switch_core.bridges.collaboration.teams.graph import GraphClientfrom switch_core.room_wide_mention import (CODE_AND_URLS,defuse_mass_mention_words_in_prose,)from switch_core.sessions.contract import TURN_ENDED+if TYPE_CHECKING:+ from switch_core.bridges.collaboration.teams.shared_app import TeamsSharedApp+logger = logging.getLogger(__name__)_MENTION_TAG = re.compile(r"<at\b[^>]*>(.*?)</at>", re.IGNORECASE | re.DOTALL)@@ -234,6 +255,26 @@ def _read_publication_ref(ref: str) -> tuple[str, str, str] | None:return (service_url, conversation_id, activity_id)+@dataclass(frozen=True)+class TeamPlacement:+ """One team in the organisation, and whether Switch is in it.++ `has_switch` is None when the team's apps could not be read.+ """++ team_id: str+ name: str+ has_switch: bool | None+++@dataclass(frozen=True)+class TeamPlacements:+ teams: list[TeamPlacement]+ #: The app's id in the organisation's catalogue, as an installation in one+ #: of these teams reported it; None when Switch is in none of them.+ catalog_app_id: str | None++@dataclass(frozen=True)class _Publication:"""Where a publication is, and whether that is known or reconstructed.@@ -449,41 +490,136 @@ def _aad_failure_message(exc: Exception) -> str:return f"Microsoft rejected these credentials — {text}"-# Channel-message subscriptions with resource data live at most 60 minutes; we-# request 55 and proactively renew well before expiry.+# Channel-message subscriptions with resource data live at most 60 minutes+# without a lifecycle URL; we request 55 and renew well before expiry._SUBSCRIPTION_TTL = timedelta(minutes=55)-_RENEWAL_INTERVAL_SECONDS = 40 * 60+# How often the renewal loop wakes, and how close to running out a+# subscription must be for it to be renewed then. Four chances before a+# subscription lapses, so one failed renewal is retried rather than fatal.+_RENEWAL_CHECK_SECONDS = 5 * 60+_RENEW_WHEN_WITHIN = timedelta(minutes=20)+# How long a "the app is blocked" answer from Teams stays on the connection's+# attention note after it was last seen. Nothing tells Switch when it is lifted,+# so it fades rather than staying forever.+_BOT_DISABLED_NOTICE_SECONDS = 60 * 60+# How many teams' installed apps are read at once when listing where Switch+# is: enough to answer a large organisation in seconds, few enough that one+# request does not spend the organisation's Graph budget on its own.+_TEAM_READS_AT_ONCE = 8+_GLOBAL_SERVICE_URL = "https://smba.trafficmanager.net/teams/"# How soon, and how rarely, to re-attempt a channel that has no live# subscription. The floor is short because the common failure clears in about a# minute (a load balancer registering a newly-started pod); the ceiling keeps a# permanently broken channel from hammering Graph for the life of the process._REPAIR_MIN_INTERVAL_SECONDS = 30_REPAIR_MAX_INTERVAL_SECONDS = 5 * 60+# How long an answer to "is Switch in this team" stands before it is asked+# again: Teams says when the app joins or leaves a team, but not reliably.+_TEAM_RECHECK_SECONDS = 15 * 60+# The least time between readings of Graph's subscriptions prompted by a+# notification for one the bridge does not know.+_ADOPT_ON_DEMAND_COOLDOWN_SECONDS = 10-class TeamsConnectionConfig(BridgeConnectionConfig):- """Per-bridge Microsoft Teams credentials and endpoints.+def activity_tenant(activity: dict[str, Any]) -> str | None:+ """The organisation an activity says it is from, or None if it does not+ say one thing.++ Teams carries the directory in two places. Both are inside the signed+ activity; if they disagree there is no telling which to believe, so the+ answer is neither.+ """+ named = {+ str(value)+ for value in (+ (activity.get("conversation") or {}).get("tenantId"),+ ((activity.get("channelData") or {}).get("tenant") or {}).get("id"),+ )+ if value+ }+ return named.pop() if len(named) == 1 else None+++_CHANNEL_ID = re.compile(r"19:[^\s/?#%@]+@thread\.(?:tacv2|skype)")+++def _is_channel_id(channel_id: str) -> bool:+ """Whether an id is a Teams channel's, as opposed to a chat's.- Teams integration uses an Azure AD app registration that backs both a Bot- Framework bot (outbound messaging, proactive messages) and Microsoft Graph- access (channel-message capture, provisioning). Secrets live per-bridge in- the ``connection_config`` JSONB column, like every other collaboration- bridge — nothing here belongs in global config.+ Channels are `19:…@thread.tacv2` (or the older `@thread.skype`); group+ chats are `@thread.v2` and one-to-one chats have other shapes entirely.+ Nothing that could change the shape of a URL is allowed in between, since+ a channel id offered for binding goes into the Graph call that proves the+ channel is this organisation's."""+ return _CHANNEL_ID.fullmatch(channel_id) is not None- # Azure AD app registration (bot client id + secret + tenant).- app_id: str- app_password: str++def _parse_graph_time(value: object) -> datetime | None:+ """A Graph timestamp (`2026-10-01T12:00:00Z`, sometimes with fractional+ seconds and a numeric offset) as an aware datetime, or None if unreadable."""+ if not isinstance(value, str) or not value:+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++#: What the bring-your-own registration form must ask for. Declared rather+#: than read off the field types, because the same model also describes a+#: bridge on the distributed app, which holds none of the app's credentials —+#: so they are optional to the model and required of the person filling the+#: form, and the form is built from the schema.+_FORM_REQUIRED = ["app_id", "app_password", "tenant_id", "team_id", "public_base_url"]+++def _require_on_form(schema: dict[str, Any]) -> None:+ schema["required"] = list(_FORM_REQUIRED)+++class TeamsConnectionConfig(BridgeConnectionConfig):+ """Per-bridge Microsoft Teams settings.++ Two shapes, decided by which app the bridge belongs to (`event_delivery`):++ - **own_listener** — the bring-your-own app. An Azure AD app registration+ the operator created backs both a Bot Framework bot and Microsoft Graph+ access, and its secrets live per-bridge here, like every other+ collaboration bridge. The bridge runs its own inbound listener.+ - **shared** — the distributed app. The app and its credentials are the+ deployment's; this bridge names only the organisation (`tenant_id`) that+ approved it and, once chosen, the team new channels go in. Its traffic+ reaches it through the deployment's public messaging routes.+ """++ model_config = ConfigDict(json_schema_extra=_require_on_form)++ # Hidden from the form for the same reason Discord's is: reaching the form+ # means the bring-your-own app, and `shared` is written by the install flow.+ event_delivery: SkipJsonSchema[Literal["own_listener", "shared"]] = "own_listener"++ # Azure AD app registration (bot client id + secret). The bring-your-own+ # app's; a shared bridge carries none.+ app_id: str | None = None+ app_password: str | None = None+ # The organisation's directory. Under the bring-your-own app it is where+ # the operator's app lives; under the distributed app it is the customer+ # organisation that approved ours.tenant_id: str# AAD team (group) id that outbound-created channels are provisioned into.- team_id: str+ # Required of a bring-your-own bridge; chosen after install on a shared one,+ # and channel creation refuses until it is.+ team_id: str | None = None# Public HTTPS base URL where this adapter's inbound listener is reachable.- # Teams and Graph are HTTP-push, so the adapter hosts its own listener:- # Bot Framework activities at ``/api/messages`` and Graph change- # notifications at ``/api/teams/notifications``, both under this base.- public_base_url: str+ # Teams and Graph are HTTP-push, so the bring-your-own adapter hosts its+ # own listener: Bot Framework activities at ``/api/messages`` and Graph+ # change notifications at ``/api/teams/notifications``, both under this+ # base.+ public_base_url: str | None = None# Local bind for the inbound listener. This is a Switch-internal deployment# detail, not an admin concern, so it is hidden from the gateway config form@@ -506,18 +642,21 @@ class TeamsConnectionConfig(BridgeConnectionConfig):encryption_private_key: SkipJsonSchema[str | None] = None# Shared secret echoed back in every change notification and validated on- # receipt. The ONLY control that authenticates a notification's origin: Graph- # resource-data encryption proves integrity but NOT origin (the wrapping key- # is the public certificate, which anyone can encrypt to), so without- # clientState the notification endpoint is spoofable.+ # receipt. The ONLY control that authenticates a bring-your-own bridge's+ # notifications: Graph resource-data encryption proves integrity but NOT+ # origin (the wrapping key is the public certificate, which anyone can+ # encrypt to), so without clientState the notification endpoint is+ # spoofable.## Generated, not asked for: it is a secret with no external meaning, so# prompting an operator to invent one only invites a weak or reused value.- # Required rather than defaulted, and minted in prepare_config at- # registration — a default here would mint a fresh secret every time a stored- # config was validated, and every live subscription would start failing its- # origin check with nothing to point at.- client_state: SkipJsonSchema[str]+ # Required of a bring-your-own bridge rather than defaulted, and minted in+ # prepare_config at registration — a default here would mint a fresh secret+ # every time a stored config was validated, and every live subscription+ # would start failing its origin check with nothing to point at. A shared+ # bridge's is derived for its organisation by the deployment and never+ # stored.+ client_state: SkipJsonSchema[str | None] = None# Bot Connector serviceUrl (the per-tenant outbound endpoint). It is learned# from inbound Bot Framework activities and persisted here so outbound@@ -540,6 +679,59 @@ class TeamsConnectionConfig(BridgeConnectionConfig):# Learned at runtime, never an admin input, so it is hidden from the form.channel_teams: SkipJsonSchema[dict[str, str]] = Field(default_factory=dict)+ @model_validator(mode="after")+ def _fields_match_delivery(self) -> TeamsConnectionConfig:+ """Refuse the half-states that look configured and cannot work.++ A bring-your-own bridge missing any of its app's settings has nothing+ to authenticate with or nowhere to be reached. A shared bridge carrying+ any of them is the opposite mistake — credentials, keys or a listener+ for an app this bridge does not own, read as evidence that it does.+ """+ if self.event_delivery == "own_listener":+ missing = [+ name+ for name in (+ "app_id",+ "app_password",+ "team_id",+ "public_base_url",+ "client_state",+ )+ if not getattr(self, name)+ ]+ if missing:+ raise ValueError(+ f"{', '.join(missing)} must be set for a Teams bridge on its "+ "own app."+ )+ return self+ # Compared with each field's default rather than read off which were+ # supplied, so a config that has been dumped and read back — defaults+ # and all — is still the same config.+ foreign = sorted(+ name+ for name in (+ "app_id",+ "app_password",+ "public_base_url",+ "client_state",+ "encryption_certificate_id",+ "encryption_public_certificate",+ "encryption_private_key",+ "listen_host",+ "listen_port",+ )+ if getattr(self, name) != type(self).model_fields[name].default+ )+ if foreign:+ raise ValueError(+ f"{', '.join(foreign)} must not be set on a bridge on the "+ "distributed Teams app; its credentials, keys and listener are "+ "the deployment's, not this connection's."+ )+ return self+@model_validator(mode="after")def _encryption_material_is_all_or_nothing(self) -> TeamsConnectionConfig:"""A half-supplied encryption trio is a mistake, not a partial request.@@ -628,7 +820,11 @@ class TeamsAdapter(PlatformAdapter):restart, while Graph carried on encrypting to the old certificate andechoing the old secret. Capture would fail its origin check and itsdecryption, with nothing in the logs pointing at why.++ A bridge on the distributed app gets neither: both are the deployment's."""+ if connection_config.get("event_delivery") == "shared":+ return connection_configprepared = dict(connection_config)if not prepared.get("client_state"):prepared["client_state"] = secrets.token_urlsafe(32)@@ -651,14 +847,34 @@ class TeamsAdapter(PlatformAdapter):def exclusive_resource(cls, connection_config: dict[str, object]) -> str | None:"""The inbound listener's TCP port, which one process can hold once.- Teams is push-based, so each bridge runs an HTTP server; two on the same- port means the second never binds. Declaring it here turns that into a- refusal at registration naming the port, rather than a bind error in a- background task that leaves the bridge silently dropped.+ Teams is push-based, so each bring-your-own bridge runs an HTTP server;+ two on the same port means the second never binds. Declaring it here+ turns that into a refusal at registration naming the port, rather than+ a bind error in a background task that leaves the bridge silently+ dropped. A bridge on the distributed app listens on nothing of its own,+ so any number of them coexist."""config = TeamsConnectionConfig.model_validate(connection_config)+ if config.event_delivery == "shared":+ return Nonereturn f"tcp/{config.listen_port}"+ @classmethod+ def editable_config_keys(+ cls, connection_config: Mapping[str, object]+ ) -> frozenset[str] | None:+ """Only the default team is anyone's to edit on a shared bridge.++ Everything else in it either names the organisation — which decides+ whose Graph data the deployment's credential reads — or was learned+ from Microsoft and decides where the deployment's Bot Connector token+ is sent. Either, edited, would point one customer's connection at+ another's organisation or at somebody else's server.+ """+ if connection_config.get("event_delivery") == "shared":+ return frozenset({"team_id"})+ return None+@classmethodasync def verify_credentials(cls, connection_config: dict[str, object]) -> None:"""Ask Azure AD for both tokens the bridge will need.@@ -667,13 +883,19 @@ class TeamsAdapter(PlatformAdapter):error names the mistake precisely — including the classic case of thesecret's ID being pasted instead of its value. Getting that to theoperator at save time is the whole point.++ A bridge on the distributed app has no credentials of its own to try;+ whether its organisation approved the app is proved when it installs."""config = TeamsConnectionConfig.model_validate(connection_config)+ if config.event_delivery == "shared":+ return+ assert config.app_id is not None and config.app_password is not Noneasync with httpx.AsyncClient(timeout=30) as http:tokens = TeamsTokenProvider(tenant_id=config.tenant_id,app_id=config.app_id,- app_password=config.app_password,+ credential=ClientSecret(config.app_password),http=http,)try:@@ -690,13 +912,31 @@ class TeamsAdapter(PlatformAdapter):super().__init__()self._config = config+ # Who this bridge speaks as. A bring-your-own bridge's is in its own+ # config; a shared bridge's arrives from the deployment's app before it+ # starts (`attach_shared_app`), and start refuses without it.+ self._shared_app: TeamsSharedApp | None = None+ self._identity: TeamsIdentity | None = (+ None if config.event_delivery == "shared" else self._own_identity(config)+ )+self._http: httpx.AsyncClient | None = None- self._tokens: TeamsTokenProvider | None = None+ # A shared bridge borrows the deployment app's client and must not+ # close it when it stops.+ self._owns_http = False+ self._tokens: TeamsTokens | None = Noneself._connector: BotConnectorClient | None = Noneself._graph: GraphClient | None = None- self._validator: InboundActivityValidator | None = None+ self._authenticator: BotFrameworkAuthenticator | None = Noneself._runner: web.AppRunner | None = None+ # What an admin has to act on for this bridge to keep working, as last+ # found: the organisation's approval narrowed or withdrawn. None while+ # nothing is known to be wrong. See `attention`.+ self._approval_problem: str | None = None+ # When Teams last answered that an admin blocked the app (monotonic).+ self._bot_disabled_at: float | None = None+# Per-tenant Bot Connector endpoint, captured from inbound activities and# seeded from persisted config so outbound works right after a restart,# before the bot next receives a Bot Framework activity.@@ -740,6 +980,11 @@ class TeamsAdapter(PlatformAdapter):# channel id -> Graph subscription id, for channels we capture.self._subscriptions: dict[str, str] = {}+ # channel id -> when its subscription runs out, as Graph last said. The+ # renewal loop works from this rather than a fixed cadence, so a+ # subscription adopted after a restart with minutes left is renewed in+ # minutes rather than after a full interval it does not have.+ self._subscription_expiry: dict[str, datetime] = {}# Channels that should be captured, whether or not they currently are.# Kept apart from `_subscriptions` so a failed attempt is remembered as# work still owed rather than forgotten the moment it fails.@@ -747,6 +992,17 @@ class TeamsAdapter(PlatformAdapter):# channel id -> last failure, so the repair loop can retry quietly and# still speak up when the reason changes.self._capture_failures: dict[str, str] = {}+ # On the distributed app, whether Switch is in each team (team id ->+ # answer), and the channels not captured because it is not: Graph+ # delivers a team's messages whether or not the app is in it.+ # (answer, when it was found, monotonic)+ self._team_has_switch: dict[str, tuple[bool, float]] = {}+ # channel id -> the team whose lack of Switch is keeping it uncaptured.+ self._capture_parked: dict[str, str] = {}+ # channel id -> the team Graph accepted its subscription through,+ # which proves the channel is in that team.+ self._subscription_team: dict[str, str] = {}+ self._adopt_on_demand_at: float | None = None# channel id -> AAD team id, learned from inbound activities so a# channel-message subscription can be created for it. Seeded from the# persisted config, so a channel outside the configured team keeps its@@ -755,9 +1011,103 @@ class TeamsAdapter(PlatformAdapter):# Installed by the bridge to persist a newly-learned channel/team pair.self._persist_channel_team: Callable[[str, str], Awaitable[None]] | None = Noneself._sub_lock = asyncio.Lock()+ # Whether the subscriptions Graph already holds for this bridge have+ # been read since it started; see `_adopt_existing_subscriptions`.+ self._adopted = False+ # Set once the bridge starts letting go of the organisation for good,+ # after which nothing may make a new subscription there.+ self._withdrawing = Falseself._renewal_task: asyncio.Task[None] | None = Noneself._repair_task: asyncio.Task[None] | None = None+ @staticmethod+ def _own_identity(config: TeamsConnectionConfig) -> TeamsIdentity:+ """A bring-your-own bridge's identity, read from its own config.++ Malformed encryption material is logged and treated as absent rather+ than failing the bridge: everything but channel capture still works+ without it, and capture says why it is not running for as long as it+ is not.+ """+ assert config.app_id is not None+ assert config.client_state is not None+ assert config.public_base_url is not None+ keyring: NotificationKeyring | None = None+ if (+ config.encryption_certificate_id+ and config.encryption_public_certificate+ and config.encryption_private_key+ ):+ try:+ keyring = NotificationKeyring(+ current=NotificationKey(+ certificate_id=config.encryption_certificate_id,+ private_key=load_private_key(config.encryption_private_key),+ ),+ certificate_der_b64=load_certificate_der_b64(+ config.encryption_public_certificate+ ),+ retired=(),+ )+ except (ValueError, TypeError, ResourceDataError) as error:+ logger.error(+ "The Teams bridge's Graph encryption material cannot be read "+ "(%s); channel capture stays off until it is replaced",+ error,+ )+ return TeamsIdentity(+ app_id=config.app_id,+ org_tenant_id=config.tenant_id,+ shared=False,+ notification_url=(+ f"{config.public_base_url.rstrip('/')}/api/teams/notifications"+ ),+ client_state=config.client_state,+ keyring=keyring,+ allowed_service_hosts=None,+ required_graph_roles=frozenset(),+ )++ @property+ def serves_shared_app(self) -> bool:+ return self._config.event_delivery == "shared"++ @property+ def places_app_in_teams(self) -> bool:+ return self.serves_shared_app++ @property+ def default_team_id(self) -> str | None:+ """The team new channels are created in, if one has been chosen."""+ return self._config.team_id++ def attach_shared_app(self, app: TeamsSharedApp) -> None:+ """Be handed the deployment's Teams app, before starting.++ Only a bridge on the distributed app takes one. Its identity is built+ for the organisation its config names, which the start guard has+ already checked this tenant holds the install for — so this is the one+ place the deployment's credential is pointed at an organisation, and it+ is pointed at that one.+ """+ if not self.serves_shared_app:+ raise ValueError(+ "a bring-your-own Teams bridge carries its own app and cannot "+ "be attached to the deployment's"+ )+ self._shared_app = app+ self._identity = app.identity_for(self._config.tenant_id)++ @property+ def _me(self) -> TeamsIdentity:+ if self._identity is None:+ raise RuntimeError(+ "This Teams bridge belongs to the distributed Teams app, which "+ "is not configured on this deployment, so it has no app to "+ "speak as. Set the TEAMS_APP_* settings or remove the connection."+ )+ return self._identity+# ── Lifecycle ────────────────────────────────────────────────────────────async def start(@@ -774,17 +1124,48 @@ class TeamsAdapter(PlatformAdapter):self._on_user_joined = on_user_joinedself._on_app_joined = on_app_joined- self._http = httpx.AsyncClient(timeout=30)- self._tokens = TeamsTokenProvider(- tenant_id=self._config.tenant_id,- app_id=self._config.app_id,- app_password=self._config.app_password,+ identity = self._me+ if self._shared_app is not None:+ # The deployment's app: its client, our own directory's Bot+ # Connector tokens, and Graph tokens issued in this organisation.+ # No listener — this bridge's traffic reaches it through the+ # deployment's public messaging routes.+ self._http = self._shared_app.http+ self._owns_http = False+ self._tokens = self._shared_app.tokens_for(self._config.tenant_id)+ else:+ assert self._config.app_id is not None+ assert self._config.app_password is not None+ self._http = httpx.AsyncClient(timeout=30)+ self._owns_http = True+ self._tokens = TeamsTokenProvider(+ tenant_id=self._config.tenant_id,+ app_id=self._config.app_id,+ credential=ClientSecret(self._config.app_password),+ http=self._http,+ )+ self._authenticator = BotFrameworkAuthenticator(+ app_id=self._config.app_id,+ keys=SigningKeys(metadata_url=BOTFRAMEWORK_OPENID, http=self._http),+ )+ self._connector = BotConnectorClient(+ tokens=self._tokens,http=self._http,+ allowed_hosts=identity.allowed_service_hosts,+ on_bot_disabled=self._note_bot_disabled,)- self._connector = BotConnectorClient(tokens=self._tokens, http=self._http)self._graph = GraphClient(tokens=self._tokens, http=self._http)- self._validator = InboundActivityValidator(app_id=self._config.app_id)+ if self._shared_app is None:+ # Only once there is something to answer with: an activity taken+ # before then is acknowledged and lost, and Teams does not resend.+ await self._open_listener()+ async with self._sub_lock:+ await self._adopt_existing_subscriptions()+ self._renewal_task = asyncio.create_task(self._renewal_loop())+ self._repair_task = asyncio.create_task(self._repair_loop())+ async def _open_listener(self) -> None:+ """The bring-your-own bridge's own inbound HTTP listener."""app = web.Application()app.router.add_post("/api/messages", self._handle_http_messages)app.router.add_post("/api/teams/notifications", self._handle_http_notifications)@@ -801,14 +1182,6 @@ class TeamsAdapter(PlatformAdapter):self._config.listen_port,self._config.app_id,)- await self._adopt_existing_subscriptions()- self._renewal_task = asyncio.create_task(self._renewal_loop())- self._repair_task = asyncio.create_task(self._repair_loop())-- @property- def _notification_url(self) -> str:- base = self._config.public_base_url.rstrip("/")- return f"{base}/api/teams/notifications"async def _adopt_existing_subscriptions(self) -> None:"""Re-attach to subscriptions this bridge already owns after a restart,@@ -819,21 +1192,41 @@ class TeamsAdapter(PlatformAdapter):duplicates. Subscriptions for our channels that point at a *different*URL (e.g. a rotated tunnel) can never deliver here, so we delete them;``ensure_channel_subscriptions`` then recreates them against the current- URL."""+ URL.++ This is also why one Entra app must never serve two environments: each+ would read the other's subscriptions as stale and delete them.++ Until this has succeeded once, no subscription is made: one made for a+ channel whose live subscription could not be seen would be a second,+ delivering every message twice until the first runs out. A failure here+ leaves the channels to the repair loop, which tries this again first."""if self._graph is None:returntry:existing = await self._graph.list_subscriptions()- except Exception:- logger.warning("Could not list existing Graph subscriptions on start")+ except Exception as error:+ logger.warning(+ "Could not list this Teams bridge's Graph subscriptions (%s); "+ "capture waits until they can be read, so none is made twice",+ error,+ )return+ notification_url = self._me.notification_urlfor sub in existing:resource = str(sub.get("resource", ""))channel_id = self._channel_from_resource(resource)if not channel_id:continue- if sub.get("notificationUrl") == self._notification_url:+ if sub.get("notificationUrl") == notification_url:self._subscriptions[channel_id] = str(sub.get("id", ""))+ team_id = self._team_from_resource(resource)+ if team_id:+ self._subscription_team[channel_id] = team_id+ self._capture_wanted.add(channel_id)+ expiry = _parse_graph_time(sub.get("expirationDateTime"))+ if expiry is not None:+ self._subscription_expiry[channel_id] = expirycontinuestale_id = str(sub.get("id", ""))if not stale_id:@@ -848,6 +1241,7 @@ class TeamsAdapter(PlatformAdapter):)except Exception:logger.warning("Failed to delete stale Teams subscription %s", stale_id)+ self._adopted = Trueif self._subscriptions:logger.info("Re-attached to %d existing Teams subscriptions",@@ -870,30 +1264,233 @@ class TeamsAdapter(PlatformAdapter):await self._ensure_channel_subscription(channel_id)async def _renewal_loop(self) -> None:- """Proactively renew channel-message subscriptions before they expire.-- Complements the reactive ``reauthorizationRequired`` lifecycle handler:- even if a lifecycle notification is missed, subscriptions are refreshed- on this cadence so capture never silently lapses."""+ """Keep subscriptions alive and the organisation's approval checked.++ Wakes often and renews only what is close to running out, rather than+ renewing everything on a long fixed cadence: a renewal that fails is+ tried again minutes later instead of after a full interval, by which+ time a 55-minute subscription has already lapsed. Complements the+ reactive ``reauthorizationRequired`` lifecycle handler, so capture never+ silently lapses even if a lifecycle notification is missed.++ The first round runs at once, for subscriptions adopted at start that+ are already close to running out — here rather than in `start`, where+ renewing many of them one by one, waiting out Graph's throttling,+ would keep the bridge from connecting."""while True:- await asyncio.sleep(_RENEWAL_INTERVAL_SECONDS)- await self._renew_all_subscriptions()+ # Caught here, in the loop, because the loop is what keeps every+ # subscription alive: an error escaping it would end the task, and+ # with it renewal, silently and for good.+ try:+ await self._check_approval()+ await self._renew_due_subscriptions()+ except Exception:+ logger.exception(+ "Teams subscription renewal failed this round; trying again in %ss",+ _RENEWAL_CHECK_SECONDS,+ )+ await asyncio.sleep(_RENEWAL_CHECK_SECONDS)- async def _renew_all_subscriptions(self) -> None:+ async def _renew_due_subscriptions(self) -> None:if self._graph is None:return+ due_by = datetime.now(UTC) + _RENEW_WHEN_WITHINfor channel_id, subscription_id in list(self._subscriptions.items()):- try:- await self._graph.renew_subscription(- subscription_id=subscription_id,- expiration_iso=self._expiration_iso(),- )- except Exception:- logger.exception(- "Failed to renew subscription %s for channel %s",+ expiry = self._subscription_expiry.get(channel_id)+ if expiry is not None and expiry > due_by:+ continue+ await self._renew_subscription(channel_id, subscription_id)++ async def _renew_subscription(+ self, channel_id: str | None, subscription_id: str+ ) -> None:+ """Renew one subscription, recording when it now runs out.++ `channel_id` is None for a subscription this bridge is not tracking —+ one Graph asked to have renewed that was not adopted at start. Renewed+ all the same, since the request passed its origin check; there is just+ no channel to hand back to the repair loop if it has gone.+ """+ if self._graph is None:+ return+ requested = self._expiration_iso()+ try:+ await self._graph.renew_subscription(+ subscription_id=subscription_id, expiration_iso=requested+ )+ except GraphError as error:+ if error.status == 404 and channel_id is not None:+ # The subscription is gone — expired, or removed on Graph's+ # side. Renewing it again can never work; dropping it hands the+ # channel to the repair loop, which makes a new one.+ logger.warning(+ "Teams subscription %s for channel %s no longer exists; "+ "making a new one",subscription_id,channel_id,)+ self._forget_subscription(channel_id)+ self._capture_wanted.add(channel_id)+ return+ logger.exception(+ "Failed to renew subscription %s for channel %s; retrying shortly",+ subscription_id,+ channel_id,+ )+ return+ except Exception:+ logger.exception(+ "Failed to renew subscription %s for channel %s; retrying shortly",+ subscription_id,+ channel_id,+ )+ return+ logger.info("Renewed Teams subscription %s", subscription_id)+ parsed = _parse_graph_time(requested)+ if parsed is not None and channel_id is not None:+ self._subscription_expiry[channel_id] = parsed++ def _forget_subscription(self, channel_id: str) -> None:+ self._subscriptions.pop(channel_id, None)+ self._subscription_expiry.pop(channel_id, None)+ self._subscription_team.pop(channel_id, None)++ async def _check_approval(self) -> None:+ """Find out whether the organisation's approval of the app still stands.++ Only a bridge on the distributed app has an approval to lose, and+ Microsoft sends no word when it goes. A withdrawn approval shows up as+ a directory that no longer issues tokens to the app; a narrowed one as+ a token missing some of the permissions it was granted. Either becomes+ something the workspace is told (`attention`), and neither ends the+ install: a blip in Microsoft's directory must not disconnect a customer+ and free their organisation for anyone else to claim.++ Rides the renewal loop, which mints this organisation's token anyway,+ so it costs no extra work.+ """+ identity = self._me+ if not identity.required_graph_roles or self._tokens is None:+ return+ try:+ granted = await self._tokens.graph_roles()+ except TokenRequestRefused as error:+ if error.app_not_approved:+ self._approval_problem = (+ "Microsoft says Switch is no longer approved in this "+ "organisation. A Microsoft admin there needs to approve it "+ "again before Switch can read or post in Teams."+ )+ logger.error(+ "Teams organisation %s no longer approves the app: %s",+ identity.org_tenant_id,+ error,+ )+ else:+ logger.warning(+ "Could not check the Teams app's approval in organisation %s: %s",+ identity.org_tenant_id,+ error,+ )+ return+ except (httpx.HTTPError, OSError) as error:+ # OSError: the federated credential's token file, unreadable for a+ # moment while the kubelet rotates it.+ logger.warning(+ "Could not reach Microsoft to check the Teams app's approval in "+ "organisation %s: %s",+ identity.org_tenant_id,+ error,+ )+ return+ missing = sorted(identity.required_graph_roles - granted)+ if missing:+ self._approval_problem = (+ "Switch's approval in this organisation no longer includes "+ f"{', '.join(missing)}. A Microsoft admin there needs to approve "+ "Switch again for it to work fully."+ )+ logger.error(+ "Teams organisation %s withdrew permissions from the app: %s",+ identity.org_tenant_id,+ ", ".join(missing),+ )+ return+ if self._approval_problem is not None:+ logger.info(+ "Teams organisation %s approves the app again", identity.org_tenant_id+ )+ self._approval_problem = None++ def _note_bot_disabled(self) -> None:+ self._bot_disabled_at = time.monotonic()+ logger.error(+ "Teams says an admin in organisation %s has blocked the app",+ self._me.org_tenant_id,+ )++ async def attention(self) -> str | None:+ notes: list[str] = []+ if self._approval_problem is not None:+ notes.append(self._approval_problem)+ if (+ self._bot_disabled_at is not None+ and time.monotonic() - self._bot_disabled_at < _BOT_DISABLED_NOTICE_SECONDS+ ):+ notes.append(+ "A Teams admin in this organisation has blocked the Switch app, "+ "so Switch cannot post there until they allow it again."+ )+ return " ".join(notes) or None++ async def withdraw(self) -> None:+ """Stop listening in the organisation, because the bridge is being removed.++ Graph keeps delivering a subscription until it runs out, and a removed+ bridge would leave every channel's still running. From the start of+ this nothing may make a new one — not the repair loop, and not a+ `subscriptionRemoved` notification arriving while the bridge is still+ routable — so none is made between these being deleted and the bridge+ being stopped. Subscriptions are+ found by asking Graph rather than from memory, so one this process+ failed to adopt goes too.++ On the distributed app the bridge also takes the app out of every team+ it is in, since nothing else will: the customer asked to disconnect,+ and the bot would otherwise stay in their channels unable to answer.+ A bring-your-own bridge leaves its operator's app where they put it.+ """+ self._withdrawing = True+ await self._cancel(self._renewal_task)+ self._renewal_task = None+ await self._cancel(self._repair_task)+ self._repair_task = None+ if self._graph is None:+ return+ identity = self._me+ # Taken so a subscription being made as this starts is finished, and+ # found and deleted below, rather than made just after.+ async with self._sub_lock:+ pass+ left_behind = await delete_own_subscriptions(+ self._graph, identity=identity, known=self._subscriptions.values()+ )+ self._subscriptions.clear()+ self._subscription_expiry.clear()+ self._capture_wanted.clear()++ if identity.shared:+ left_behind += await leave_every_team(self._graph, app_id=identity.app_id)++ if self._shared_app is not None:+ self._shared_app.forget_org(identity.org_tenant_id)++ if left_behind:+ raise BridgeOperationError(+ "Removing the Teams connection left behind: "+ + "; ".join(left_behind)+ + ". Subscriptions run out on their own within the hour."+ )@staticmethodasync def _cancel(task: asyncio.Task[None] | None) -> None:@@ -913,18 +1510,21 @@ class TeamsAdapter(PlatformAdapter):if self._runner is not None:await self._runner.cleanup()self._runner = None- if self._validator is not None:- self._validator.close()- self._validator = None- if self._http is not None:+ if self._http is not None and self._owns_http:await self._http.aclose()- self._http = None+ self._http = Nonelogger.info("Teams adapter stopped")# ── Outbound helpers ─────────────────────────────────────────────────────def _service_url_for(self, channel_id: str) -> str:url = self._service_url.get(channel_id) or self._default_service_url+ if not url and self._me.shared:+ # Microsoft's documented global endpoint for a proactive message+ # sent before any activity has named a regional one — which on the+ # distributed app is a channel created from Switch straight after+ # an organisation approved it.+ url = _GLOBAL_SERVICE_URLif not url:raise RuntimeError(f"no Bot Connector serviceUrl known for channel {channel_id} — "@@ -1238,7 +1838,10 @@ class TeamsAdapter(PlatformAdapter):conversation_id = self._reply_conversation(channel_id, thread_root_id)if conversation_id is None:conversation_id, msg_id = await connector.create_channel_thread(- service_url=service_url, channel_id=channel_id, activity=activity+ service_url=service_url,+ channel_id=channel_id,+ tenant_id=self._me.org_tenant_id,+ activity=activity,)# A message that opened its own post is that post.remembered = msg_id@@ -1809,6 +2412,7 @@ class TeamsAdapter(PlatformAdapter):conversation_id, ref = await self._connector.create_channel_thread(service_url=service_url,channel_id=channel_id,+ tenant_id=self._me.org_tenant_id,activity=activity,)else:@@ -1998,9 +2602,16 @@ class TeamsAdapter(PlatformAdapter):"from the messaging platform")+ team_id = self._config.team_id+ if not team_id:+ raise BridgeOperationError(+ "No default team is set for this Teams connection, so Switch "+ "does not know which team to create the channel in. Choose one "+ "in the connection's Microsoft Teams settings."+ )membership_type = "private" if channel_type == "channel_private" else "standard"channel = await self._graph.create_channel(- team_id=self._config.team_id,+ team_id=team_id,display_name=self._sanitize_channel_name(name),description=topic,membership_type=membership_type,@@ -2010,7 +2621,7 @@ class TeamsAdapter(PlatformAdapter):raise RuntimeError(f"Teams channel creation returned no id for '{name}'")self._channel_type[channel_id] = channel_type- await self._learn_channel_team(channel_id, self._config.team_id)+ await self._learn_channel_team(channel_id, team_id)self._channel_names[channel_id] = str(channel.get("displayName") or "")self._channel_layouts[channel_id] = str(channel.get("layoutType") or "")# Capture the new channel's messages right away.@@ -2069,7 +2680,9 @@ class TeamsAdapter(PlatformAdapter):Teams client. Built from the channel id, its team, and the tenant."""if not external_channel_id:return None- team_id = self._team_of_channel.get(external_channel_id, self._config.team_id)+ team_id = self._team_of_channel.get(external_channel_id) or self._config.team_id+ if not team_id:+ return Noneencoded = quote(external_channel_id, safe="")return (f"https://teams.microsoft.com/l/channel/{encoded}/channel"@@ -2103,7 +2716,14 @@ class TeamsAdapter(PlatformAdapter):) -> list[str]:if self._graph is None:raise RuntimeError("Teams adapter not started")- team_id = self._team_of_channel.get(channel_id, self._config.team_id)+ team_id = self._team_of_channel.get(channel_id) or self._config.team_id+ if not team_id:+ logger.error(+ "Cannot add people to Teams channel %s: Switch does not know "+ "which team it is in",+ channel_id,+ )+ return list(user_external_ids)# Private channels have their own membership; standard channels inherit# the team's, so a user is added to the team instead — only ever when# the channel is known to be standard, never as a fallback.@@ -2361,23 +2981,37 @@ class TeamsAdapter(PlatformAdapter):# ── Inbound listener ─────────────────────────────────────────────────────async def _handle_http_messages(self, request: web.Request) -> web.Response:- auth_header = request.headers.get("Authorization")- if self._validator is not None:- try:- await asyncio.get_running_loop().run_in_executor(- None, self._validator.validate, auth_header- )- except Exception as e:- logger.warning("Rejected inbound Teams activity: %s", e)- return web.Response(status=401, text="unauthorized")+ """The bring-your-own listener's Bot Framework endpoint.+ Read before it is checked because the check needs the body — the token+ has to name the same `serviceUrl` and be endorsed for the same channel+ as the activity — but nothing in it is acted on until it passes.+ """try:activity = await request.json()except Exception:return web.Response(status=400, text="invalid json")+ if not isinstance(activity, dict):+ return web.Response(status=400, text="invalid activity")++ if self._authenticator is not None:+ try:+ await self._authenticator.verify(+ request.headers.get("Authorization"),+ service_url=str(activity.get("serviceUrl", "")).strip(),+ channel_id=str(activity.get("channelId", "")),+ )+ except PermissionError as e:+ logger.warning("Rejected inbound Teams activity: %s", e)+ return web.Response(status=401, text="unauthorized")+ except SigningKeysUnavailable as e:+ # Not refused as forged: Teams resends what it was told to+ # retry, and nothing about this one was found wrong.+ logger.error("Could not check an inbound Teams activity: %s", e)+ return web.Response(status=503, text="unavailable")try:- answer = await self._dispatch_activity(activity)+ answer = await self.receive_activity(activity)except Exception:logger.exception("Failed to handle inbound Teams activity")return web.Response(status=200)@@ -2386,6 +3020,59 @@ class TeamsAdapter(PlatformAdapter):return web.Response(status=200)return web.json_response(answer)+ async def dispatch_event(+ self, *, envelope_type: str, payload: dict[str, Any]+ ) -> dict[str, Any] | None:+ """An activity or a notification for the distributed app, from the+ deployment's public route — already authenticated, and routed here by+ the organisation it is for."""+ if envelope_type == "activity":+ return await self.receive_activity(payload)+ if envelope_type == "notification":+ await self.receive_notification(payload)+ return None+ raise ValueError(f"not a Teams envelope: {envelope_type!r}")++ async def receive_activity(self, activity: dict[str, Any]) -> dict[str, Any] | None:+ """Handle one authenticated Bot Framework activity; return an invoke's answer.++ The one entry point for activities, whichever way they arrived — the+ bring-your-own listener above, or the deployment's public route for the+ distributed app. Whoever calls it has already checked the activity's+ token.++ On the distributed app the token proves the activity came from the Bot+ Framework, not which organisation it is for: one app serves them all.+ So an activity from any other organisation is refused here, and a+ service URL that is not Microsoft's is refused before it is learned,+ since this bridge then sends the deployment's token to it.+ """+ identity = self._me+ tenant = activity_tenant(activity)+ if not identity.serves(tenant):+ logger.warning(+ "Refused a Teams activity from organisation %s on the bridge for %s",+ tenant,+ identity.org_tenant_id,+ )+ if activity.get("type") == "invoke":+ return _invoke_error(+ 403, "Forbidden", "This card belongs to another organisation."+ )+ return None+ service_url = str(activity.get("serviceUrl", "")).strip()+ hosts = identity.allowed_service_hosts+ if service_url and hosts is not None:+ parts = urlsplit(service_url)+ if parts.scheme != "https" or parts.hostname not in hosts:+ logger.warning(+ "Refused a Teams activity naming service URL host %r, which "+ "is not a Bot Connector host",+ parts.hostname,+ )+ return None+ return await self._dispatch_activity(activity)+async def _dispatch_activity(self, activity: dict[str, Any]) -> dict[str, Any] | None:@@ -2401,11 +3088,22 @@ class TeamsAdapter(PlatformAdapter):team = (activity.get("channelData") or {}).get("team") or {}# Graph channel subscriptions key on the team's AAD group GUID, which- # Teams sends as ``aadGroupId``. ``team.id`` is the non-GUID channel- # thread id and Graph rejects it ("TeamGroupId must be ... a valid- # GUID"). Fall back to the configured team_id, which is also that GUID.- group_id = team.get("aadGroupId") or self._config.team_id- if group_id and channel_id:+ # Teams sends as ``aadGroupId`` — on some activities only. ``team.id``+ # is the non-GUID channel thread id and Graph rejects it ("TeamGroupId+ # must be ... a valid GUID"). A bring-your-own bridge lives in its one+ # configured team, so that stands in for a channel not yet placed; a+ # bridge on the distributed app is in many teams, and guessing its+ # default would file another team's channel under it.+ group_id = team.get("aadGroupId")+ if (+ not group_id+ and not self._me.shared+ and channel_id not in self._team_of_channel+ ):+ group_id = self._config.team_id+ # A chat's type is known from the activity; a channel's is not.+ is_channel = chat_type is None+ if group_id and channel_id and is_channel:await self._learn_channel_team(channel_id, str(group_id))if activity_type == "message":@@ -2413,10 +3111,324 @@ class TeamsAdapter(PlatformAdapter):await self._dispatch_message(activity, channel_id, channel_type)elif activity_type == "conversationUpdate":await self._dispatch_conversation_update(activity, channel_id, chat_type)+ elif activity_type == "installationUpdate":+ await self._dispatch_installation_update(activity)elif activity_type == "invoke" and activity.get("name") == _INVOKE_CARD_ACTION:return await self._dispatch_card_action(activity, channel_id)return None+ async def _dispatch_installation_update(self, activity: dict[str, Any]) -> None:+ """The app was added to or removed from a team.++ Removed, Graph keeps delivering that team's channels to a bot that can+ no longer answer in them, so their subscriptions are deleted and their+ capture waits for Switch to be added back. Added, the channels that+ were waiting are captured again; the bot's own join arrives as a+ `conversationUpdate` and is handled there. An upgrade arrives as+ `remove-upgrade` followed by `add-upgrade` and is neither.+ """+ action = activity.get("action")+ if action not in ("add", "remove"):+ return+ team = (activity.get("channelData") or {}).get("team") or {}+ team_id = str(team.get("aadGroupId") or "")+ if not team_id:+ logger.warning(+ "The Teams app was %s a team that the activity does not name",+ "added to" if action == "add" else "removed from",+ )+ return+ if action == "add":+ await self._switch_joined_team(team_id)+ return+ logger.info(+ "The Teams app was removed from team %s; stopping capture in its "+ "known channels",+ team_id,+ )+ await self._switch_left_team(team_id)++ async def _switch_in_team(self, team_id: str) -> bool | None:+ """On the distributed app, whether Switch is in a team; None if unknown.++ Asked before capturing any of the team's channels, because Graph+ delivers them whether or not the app is in the team: a room in a team+ Switch was taken out of would otherwise go on receiving everything+ said there, across restarts, to a bot that cannot answer. Remembered+ per team, changed by Switch joining or leaving it, and asked again by+ the repair loop once it is old (`_recheck_teams`).+ """+ cached = self._team_has_switch.get(team_id)+ if cached is not None:+ return cached[0]+ assert self._graph is not None+ try:+ installations = await self._graph.find_app_installations(+ team_id=team_id, external_id=self._me.app_id+ )+ except Exception as error:+ logger.warning(+ "Could not check whether Switch is in Teams team %s: %s",+ team_id,+ error,+ )+ return None+ known = bool(installations)+ self._team_has_switch[team_id] = (known, time.monotonic())+ return known++ def _capture_team(self, channel_id: str) -> str | None:+ """The team a channel's messages would be captured through: the one it+ is known to be in, or failing that the default team."""+ return self._known_team(channel_id) or self._config.team_id++ def _known_team(self, channel_id: str) -> str | None:+ """The team a channel is known to be in: as Teams said, or as proved+ by Graph accepting a subscription through it. Not the default team+ merely because nothing else is known."""+ return self._team_of_channel.get(channel_id) or self._subscription_team.get(+ channel_id+ )++ async def _park_capture(self, channel_id: str, team_id: str) -> None:+ """Stop capturing a channel whose team Switch is not in, until it is."""+ await self._stop_capture(channel_id)+ if self._capture_parked.get(channel_id) != team_id:+ self._capture_parked[channel_id] = team_id+ logger.info(+ "Not capturing Teams channel %s: Switch is not in its team %s",+ channel_id,+ team_id,+ )++ async def _switch_joined_team(self, team_id: str) -> None:+ """Switch is in a team now: capture the channels waiting on that."""+ self._team_has_switch[team_id] = (True, time.monotonic())+ waiting = [c for c, t in self._capture_parked.items() if t == team_id]+ for channel_id in waiting:+ del self._capture_parked[channel_id]+ await self._ensure_channel_subscription(channel_id)++ async def _switch_left_team(self, team_id: str) -> None:+ """Switch is out of a team: stop capturing it, ready to resume on return."""+ self._team_has_switch[team_id] = (False, time.monotonic())+ known = (+ self._capture_wanted | set(self._subscriptions) | set(self._team_of_channel)+ )+ for channel_id in [c for c in known if self._known_team(c) == team_id]:+ captured = (+ channel_id in self._capture_wanted or channel_id in self._subscriptions+ )+ await self._stop_capture(channel_id)+ if captured:+ self._capture_parked[channel_id] = team_id++ async def _recheck_teams(self) -> None:+ """Ask again whether Switch is in each team whose answer is old.++ Teams tells the bot when the app joins or leaves a team, but an admin+ can do either where the bot hears nothing of it, and an answer kept+ for ever would keep a team uncaptured, or captured, for ever.+ """+ if not self._me.shared or self._graph is None:+ return+ now = time.monotonic()+ stale = [+ (team_id, answer)+ for team_id, (answer, found_at) in self._team_has_switch.items()+ if now - found_at >= _TEAM_RECHECK_SECONDS+ ]+ for team_id, previous in stale:+ del self._team_has_switch[team_id]+ current = await self._switch_in_team(team_id)+ if current is None:+ # Asked again next round, rather than taken as changed.+ self._team_has_switch[team_id] = (previous, 0.0)+ elif current and not previous:+ await self._switch_joined_team(team_id)+ elif previous and not current:+ await self._switch_left_team(team_id)++ async def _stop_capture(self, channel_id: str) -> None:+ self._capture_wanted.discard(channel_id)+ self._capture_failures.pop(channel_id, None)+ subscription_id = self._subscriptions.get(channel_id)+ self._forget_subscription(channel_id)+ if subscription_id is None or self._graph is None:+ return+ try:+ await self._graph.delete_subscription(subscription_id=subscription_id)+ except Exception:+ logger.warning(+ "Failed to delete the Teams subscription for channel %s; it runs "+ "out on its own within the hour",+ channel_id,+ exc_info=True,+ )++ # ── Which teams Switch is in (the distributed app) ──────────────────────++ def _require_shared(self) -> GraphClient:+ if not self._me.shared:+ raise BridgeOperationError(+ "Only a connection on the distributed Teams app places itself "+ "in teams from Switch; a bring-your-own app is added in Teams."+ )+ if self._graph is None:+ raise RuntimeError("Teams adapter not started")+ return self._graph++ async def list_team_placements(self) -> TeamPlacements:+ """Every team in the organisation, and whether Switch is in each.++ One read per team for the second half, a handful at a time: Graph has+ no call that answers it for the whole organisation at once. A team+ whose apps cannot be read — archived, being deleted, restricted, or+ the read timing out — is listed as unknown rather than failing the+ rest.++ Each installation found also says the app's id in the organisation's+ catalogue, so this is how Switch learns that id when a Teams admin+ uploaded the app by hand rather than Switch publishing it.+ """+ graph = self._require_shared()+ app_id = self._me.app_id+ teams = await graph.list_teams()+ gate = asyncio.Semaphore(_TEAM_READS_AT_ONCE)+ seen_catalog_ids: set[str] = set()++ async def placed(team: dict[str, Any]) -> TeamPlacement:+ team_id = str(team.get("id") or "")+ name = str(team.get("displayName") or team_id)+ try:+ async with gate:+ installations = await graph.find_app_installations(+ team_id=team_id, external_id=app_id+ )+ except (GraphError, httpx.HTTPError) as error:+ logger.warning(+ "Could not read which apps are in Teams team %s: %s", team_id, error+ )+ return TeamPlacement(team_id=team_id, name=name, has_switch=None)+ seen_catalog_ids.update(+ i.catalog_app_id for i in installations if i.catalog_app_id+ )+ return TeamPlacement(+ team_id=team_id, name=name, has_switch=bool(installations)+ )++ # Anything else — the organisation's token refused — fails every read+ # alike, so the listing fails, and the reads still queued are+ # cancelled rather than left spending the organisation's Graph budget.+ reads = [asyncio.create_task(placed(team)) for team in teams if team.get("id")]+ try:+ placements = await asyncio.gather(*reads)+ except BaseException:+ for read in reads:+ read.cancel()+ await asyncio.gather(*reads, return_exceptions=True)+ raise+ if len(seen_catalog_ids) > 1:+ # A copy uploaded to one team on its own (sideloaded) carries an id+ # of its own; which one the catalogue holds cannot be told from here.+ logger.warning(+ "The Switch app is in Microsoft organisation %s's teams under "+ "more than one catalogue id (%s); using the first",+ self._config.tenant_id,+ ", ".join(sorted(seen_catalog_ids)),+ )+ return TeamPlacements(+ teams=sorted(placements, key=lambda p: p.name.casefold()),+ catalog_app_id=next(iter(sorted(seen_catalog_ids)), None),+ )++ async def add_to_team(self, team_id: str, *, catalog_app_id: str) -> None:+ """Add Switch to a team; its own join then makes the rooms, as today."""+ await self._require_shared().install_app(+ team_id=team_id, catalog_app_id=catalog_app_id+ )+ await self._switch_joined_team(team_id)++ async def remove_from_team(self, team_id: str) -> None:+ graph = self._require_shared()+ for installation in await graph.find_app_installations(+ team_id=team_id, external_id=self._me.app_id+ ):+ await graph.uninstall_app(+ team_id=team_id, installation_id=installation.installation_id+ )+ await self._switch_left_team(team_id)++ async def check_config_edit(self, connection_config: Mapping[str, object]) -> None:+ """On the distributed app, a default team must be one Switch is in.++ New channels are made in it, which fails in a team the app is not in —+ and fails at the first room, long after the edit that caused it.+ """+ if not self._me.shared:+ return+ team_id = connection_config.get("team_id")+ if not team_id or team_id == self._config.team_id:+ return+ try:+ installations = await self._require_shared().find_app_installations(+ team_id=str(team_id), external_id=self._me.app_id+ )+ except GraphError as error:+ if error.status in (400, 404):+ raise ConfigEditRefused(+ f"There is no team {team_id} in this organisation."+ ) from error+ raise+ except (TokenRequestRefused, httpx.HTTPError) as error:+ raise BridgeOperationError(+ f"Microsoft could not be asked whether Switch is in team {team_id}: "+ f"{error}"+ ) from error+ if not installations:+ raise ConfigEditRefused(+ "Switch is not in that team. Add it to the team first, then "+ "make it the default."+ )++ async def require_bindable_channel(self, channel_id: str) -> None:+ """On the distributed app, bind only a channel in this organisation.++ The deployment's Bot Connector token posts into every approving+ organisation's channels, so a room bound to another organisation's+ channel id would post there. Reading the channel with a Graph token+ issued in this organisation is what proves it is this organisation's:+ Graph answers only for its own directory. Chats cannot be checked that+ way, and become rooms only from activity Microsoft delivered to this+ bridge, so they cannot be bound by id at all.++ A bring-your-own bridge's own credential reaches only its own+ organisation, so there is nothing to refuse.+ """+ if not self._me.shared:+ return+ if not _is_channel_id(channel_id):+ raise ChannelNotBindable(+ f"{channel_id!r} is not a Teams channel id. Only a channel can be "+ "bound by id; a chat becomes a room when someone messages Switch "+ "in it."+ )+ team_id = self._team_of_channel.get(channel_id) or self._config.team_id+ if not team_id:+ raise ChannelNotBindable(+ "Switch does not know which team this channel is in. Add the "+ "Switch app to its team first."+ )+ if self._graph is None:+ raise RuntimeError("Teams adapter not started")+ try:+ await self._graph.get_channel(team_id=team_id, channel_id=channel_id)+ except GraphError as error:+ raise ChannelNotBindable(+ f"Teams channel {channel_id} is not one Switch can reach in this "+ f"organisation ({error})."+ ) from error+@staticmethoddef _channel_from_activity(activity: dict[str, Any],@@ -2785,6 +3797,9 @@ class TeamsAdapter(PlatformAdapter):# The bot was added to a channel/team → start capturing all of# its messages via a Graph subscription (channels only; chats are# captured through the Bot Framework path).+ team_id = self._team_of_channel.get(channel_id)+ if self._me.shared and team_id:+ await self._switch_joined_team(team_id)if channel_type in ("channel_public", "channel_private"):await self._ensure_channel_subscription(channel_id)if self._on_app_joined is not None:@@ -2885,7 +3900,11 @@ class TeamsAdapter(PlatformAdapter):raise RuntimeError("Teams adapter not started")team_id = self._team_of_channel.get(channel_id) or self._config.team_idif not team_id:- raise RuntimeError(f"No team is known for Teams channel {channel_id}")+ raise BridgeOperationError(+ f"Switch does not know which team Teams channel {channel_id} is "+ "in. Add the Switch app to that team, or message the channel, so "+ "Switch can learn it."+ )channel = await self._graph.get_channel(team_id=team_id, channel_id=channel_id)channel_type = _channel_type_of(channel)self._channel_read_failed_at.pop(channel_id, None)@@ -2994,6 +4013,12 @@ class TeamsAdapter(PlatformAdapter):match = re.search(r"channels/([^/]+)/messages", resource)return match.group(1) if match else ""+ @staticmethod+ def _team_from_resource(resource: str) -> str:+ """The team id in a subscription's ``resource`` string."""+ match = re.match(r"teams/([^/]+)/channels/", resource)+ return match.group(1) if match else ""+async def _ensure_channel_subscription(self, channel_id: str) -> None:"""Create a Graph change-notification subscription for a channel'smessages, so the bridge captures every post — not just @mentions.@@ -3001,44 +4026,67 @@ class TeamsAdapter(PlatformAdapter):Requires the encryption certificate + private key (Graph encrypts themessage body) and the channel's team id. A missing prerequisite is aloud log, not a crash: the bot still joins, capture is simply degraded.++ Wanted before it is checked for, so a channel whose subscription was+ adopted at start, and later lost, is still one the repair loop owes."""- if channel_id in self._subscriptions or self._graph is None:- returnself._capture_wanted.add(channel_id)- if not (- self._config.encryption_public_certificate- and self._config.encryption_certificate_id- ):+ if self._graph is None or self._withdrawing:+ return+ identity = self._me+ team_id = self._capture_team(channel_id)+ if identity.shared and team_id:+ in_team = await self._switch_in_team(team_id)+ if in_team is False:+ await self._park_capture(channel_id, team_id)+ return+ if in_team is None and channel_id not in self._subscriptions:+ self._note_capture_failure(+ channel_id, f"could not check that Switch is in team {team_id}"+ )+ return+ if channel_id in self._subscriptions:+ return+ keyring = identity.keyring+ if keyring is None:self._note_capture_failure(channel_id,"encryption certificate not configured on the Teams bridge",)return- team_id = self._team_of_channel.get(channel_id) or self._config.team_idif not team_id:self._note_capture_failure(channel_id, "team id unknown")returnasync with self._sub_lock:- if channel_id in self._subscriptions:+ if not self._adopted:+ await self._adopt_existing_subscriptions()+ if not self._adopted:+ self._note_capture_failure(+ channel_id,+ "the subscriptions Graph already holds could not be read",+ )+ return+ if channel_id in self._subscriptions or self._withdrawing:returntry:- cert_der = load_certificate_der_b64(- self._config.encryption_public_certificate- )sub = await self._graph.create_subscription(resource=f"teams/{team_id}/channels/{channel_id}/messages",- notification_url=self._notification_url,- lifecycle_notification_url=self._notification_url,- client_state=self._config.client_state,+ notification_url=identity.notification_url,+ lifecycle_notification_url=identity.notification_url,+ client_state=identity.client_state,expiration_iso=self._expiration_iso(),- encryption_certificate=cert_der,- encryption_certificate_id=self._config.encryption_certificate_id,+ encryption_certificate=keyring.certificate_der_b64,+ encryption_certificate_id=keyring.certificate_id,)except Exception as exc:self._note_capture_failure(channel_id, f"{type(exc).__name__}: {exc}")returnself._subscriptions[channel_id] = str(sub.get("id", ""))+ self._subscription_team[channel_id] = team_id+ expiry = _parse_graph_time(sub.get("expirationDateTime"))+ if expiry is not None:+ self._subscription_expiry[channel_id] = expiryrecovered = self._capture_failures.pop(channel_id, None) is not Nonelogger.info("%s Teams channel %s messages (subscription %s)",@@ -3098,12 +4146,19 @@ class TeamsAdapter(PlatformAdapter):delay = _REPAIR_MIN_INTERVAL_SECONDSwhile True:await asyncio.sleep(delay)+ try:+ await self._recheck_teams()+ except Exception:+ logger.exception("Teams team membership recheck failed this round")missing = [c for c in self._capture_wanted if c not in self._subscriptions]if not missing:delay = _REPAIR_MIN_INTERVAL_SECONDScontinue- for channel_id in missing:- await self._ensure_channel_subscription(channel_id)+ try:+ for channel_id in missing:+ await self._ensure_channel_subscription(channel_id)+ except Exception:+ logger.exception("Teams capture repair failed this round")if any(c not in self._subscriptions for c in missing):delay = min(delay * 2, _REPAIR_MAX_INTERVAL_SECONDS)else:@@ -3125,26 +4180,48 @@ class TeamsAdapter(PlatformAdapter):for item in payload.get("value", []):try:- await self._dispatch_graph_notification(item)+ await self.receive_notification(item)except Exception:logger.exception("Failed to handle Graph change notification")return web.Response(status=202)- async def _dispatch_graph_notification(self, item: dict[str, Any]) -> None:+ async def receive_notification(self, item: dict[str, Any]) -> None:+ """Handle one Graph change notification addressed to this bridge.++ The one entry point for notifications, whichever way they arrived. On+ the distributed app the deployment's route has already checked Graph's+ validation tokens and routed the item by the organisation they vouch+ for; what is checked here holds either way — the organisation's own+ `clientState`, and that the subscription is one this bridge made.+ """# Authenticate origin BEFORE acting on anything — data notifications and- # lifecycle events alike. clientState is the only origin control (the- # encryption proves integrity, not origin), so an unverified lifecycle- # event (e.g. a forged reauthorizationRequired) must not be honoured.- # Compared in constant time: this is an authentication check, and a- # `!=` on a secret leaks its prefix through timing. 256 bits makes that- # impractical to exploit rather than impossible to attempt, and the- # cheap version is the same one line.- if not hmac.compare_digest(- str(item.get("clientState") or ""), self._config.client_state- ):+ # lifecycle events alike. clientState is the bring-your-own bridge's only+ # origin control (the encryption proves integrity, not origin), so an+ # unverified lifecycle event (e.g. a forged reauthorizationRequired)+ # must not be honoured.+ identity = self._me+ # Load-bearing on the distributed app: a batch of lifecycle+ # notifications carries no validation tokens, so the deployment's+ # route lets it through on the organisation it names, and these two+ # checks are all that stand between a forged one and a renewal or a+ # recreated subscription.+ if not identity.accepts_client_state(item.get("clientState")):logger.warning("Rejected Graph notification: clientState mismatch")return+ subscription_id = str(item.get("subscriptionId", ""))+ if identity.shared and not await self._knows_subscription(subscription_id):+ logger.warning(+ "Rejected a Graph notification for subscription %s, which the "+ "bridge for organisation %s did not make%s",+ subscription_id,+ identity.org_tenant_id,+ ""+ if self._adopted+ else " — as far as it can tell: the subscriptions Graph holds "+ "could not be read",+ )+ returnif item.get("lifecycleEvent"):await self._handle_lifecycle_event(item)@@ -3153,32 +4230,50 @@ class TeamsAdapter(PlatformAdapter):encrypted = item.get("encryptedContent")if not encrypted:return- if not self._config.encryption_private_key:+ if identity.keyring is None:logger.error("Received encrypted Graph notification but no private key is ""configured to decrypt it")return- chat_message = decrypt_resource_data(- encrypted, self._config.encryption_private_key- )+ chat_message = identity.keyring.decrypt(encrypted)await self._deliver_graph_message(chat_message)+ def _owns_subscription(self, subscription_id: str) -> bool:+ return bool(subscription_id) and subscription_id in self._subscriptions.values()++ async def _knows_subscription(self, subscription_id: str) -> bool:+ """Whether a notification's subscription is one this bridge made.++ Until the subscriptions Graph holds have been read once, every one of+ them is unknown — and the notifications they deliver have already been+ answered, so they would be lost until the repair loop next reads them.+ An unknown one is a reason to read them now.+ """+ if self._owns_subscription(subscription_id) or self._adopted:+ return self._owns_subscription(subscription_id)+ async with self._sub_lock:+ now = time.monotonic()+ due = (+ self._adopt_on_demand_at is None+ or now - self._adopt_on_demand_at >= _ADOPT_ON_DEMAND_COOLDOWN_SECONDS+ )+ if not self._adopted and due:+ # Spaced out, so a run of unknown ones — Graph failing, or+ # someone holding the organisation's clientState — is not one+ # listing each.+ self._adopt_on_demand_at = now+ await self._adopt_existing_subscriptions()+ return self._owns_subscription(subscription_id)+async def _handle_lifecycle_event(self, item: dict[str, Any]) -> None:event = item.get("lifecycleEvent")subscription_id = str(item.get("subscriptionId", ""))- if event == "reauthorizationRequired" and self._graph is not None:- try:- await self._graph.renew_subscription(- subscription_id=subscription_id,- expiration_iso=self._expiration_iso(),- )- logger.info("Renewed Teams subscription %s", subscription_id)- except Exception:- logger.exception(- "Failed to renew Teams subscription %s", subscription_id- )+ if event == "reauthorizationRequired":+ await self._renew_subscription(+ self._channel_of_subscription(subscription_id), subscription_id+ )elif event == "subscriptionRemoved":# Graph dropped the subscription (e.g. a transient permission/quota# issue). Recreate it rather than only logging — otherwise channel@@ -3191,11 +4286,14 @@ class TeamsAdapter(PlatformAdapter):event,)- async def _recreate_removed_subscription(self, subscription_id: str) -> None:- channel_id = next(+ def _channel_of_subscription(self, subscription_id: str) -> str | None:+ return next((c for c, s in self._subscriptions.items() if s == subscription_id),None,)++ async def _recreate_removed_subscription(self, subscription_id: str) -> None:+ channel_id = self._channel_of_subscription(subscription_id)if channel_id is None:logger.info("Teams subscriptionRemoved for unknown subscription %s; ignoring",@@ -3208,7 +4306,7 @@ class TeamsAdapter(PlatformAdapter):channel_id,)# Drop the dead mapping so _ensure_channel_subscription rebuilds it.- self._subscriptions.pop(channel_id, None)+ self._forget_subscription(channel_id)await self._ensure_channel_subscription(channel_id)async def _deliver_graph_message(self, chat_message: dict[str, Any]) -> None:@@ -3223,7 +4321,7 @@ class TeamsAdapter(PlatformAdapter):application = sender.get("application") or {}if application:# Drop our own bot's posts (they are captured too) to avoid a loop.- if str(application.get("id", "")) == self._config.app_id:+ if str(application.get("id", "")) == self._me.app_id:returnsender_id = str(application.get("id", ""))sender_name = str(application.get("displayName") or sender_id)@@ -3277,11 +4375,12 @@ class TeamsAdapter(PlatformAdapter):one whose ``mentioned.application.id`` matches our app id. Mirrors theBot Framework path's ``_self_mention_token`` so both capture paths flag abot mention identically."""+ app_id = self._me.app_idfor mention in chat_message.get("mentions") or []:mentioned = mention.get("mentioned") or {}application = mentioned.get("application") or {}- if str(application.get("id", "")) == self._config.app_id:- return self._config.app_id+ if str(application.get("id", "")) == app_id:+ return app_idreturn None@staticmethoddiff --git a/core/switch_core/bridges/collaboration/teams/app_package.py b/core/switch_core/bridges/collaboration/teams/app_package.pynew file mode 100644index 000000000..c67a46fc1--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/app_package.py@@ -0,0 +1,90 @@+"""The distributed Teams app's package, built for this deployment.++A Teams app reaches an organisation as a zip: its manifest and two icons.+For the distributed app Switch puts that zip into the organisation's own app+catalogue itself, with the approving admin's sign-in, so it is built here+rather than by an operator with a script. What differs per deployment — the+app id, its name, the host the bot is reached on, the privacy and terms pages+— is filled into the template in `distributed_app/`.++The template carries no resource-specific permissions: the organisation's+admin grants the app's permissions once, organisation-wide, and asking for+the same access again per team would only add a consent prompt and a broader+install permission. It does carry `webApplicationInfo`, naming the Entra app:+that is how Microsoft knows this Teams app is the one the app's token belongs+to, which installing it into a team under the app's own "itself" permission+(`TeamsAppInstallation.ReadWriteSelfForTeam.All`) requires. It names no+`resource`, which only single sign-on uses.++`version` is the template's. Raise it whenever the template changes, so an+organisation holding the old one can be offered the new.+"""++from __future__ import annotations++import io+import json+import zipfile+from dataclasses import dataclass+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit++_TEMPLATE_DIR = Path(__file__).parent / "distributed_app"+_ICONS = ("color.png", "outline.png")+#: Where the template's short and full names take this deployment's app name.+_NAME_PLACEHOLDER = "{{APP_NAME}}"+++@dataclass(frozen=True)+class DistributedAppPackage:+ #: The manifest id, which is also the bot's: the Entra app id. It is the+ #: same in every organisation, and is how the app is found again in an+ #: organisation's catalogue, where it is given an id of its own.+ manifest_id: str+ version: str+ archive: bytes+++def build_distributed_app_package(+ *,+ app_id: str,+ app_name: str,+ messaging_public_url: str,+ privacy_url: str,+ terms_url: str,+) -> DistributedAppPackage:+ manifest: dict[str, Any] = json.loads(+ (_TEMPLATE_DIR / "manifest.json").read_text(encoding="utf-8")+ )+ # Set on the parsed manifest rather than substituted into its text, so a+ # value is always a JSON string whatever characters it holds.+ manifest["id"] = app_id+ manifest["bots"][0]["botId"] = app_id+ manifest["webApplicationInfo"]["id"] = app_id+ manifest["validDomains"] = [str(urlsplit(messaging_public_url).hostname)]+ manifest["developer"]["privacyUrl"] = privacy_url+ manifest["developer"]["termsOfUseUrl"] = terms_url+ # Checked before the name goes in, the one value set into the template's+ # own text, so a name that happens to contain braces is not mistaken for+ # a placeholder left unfilled.+ if "{{" in json.dumps(manifest).replace(_NAME_PLACEHOLDER, ""):+ raise ValueError(+ "the distributed Teams app manifest names a value this build does "+ "not fill in"+ )+ for form in ("short", "full"):+ manifest["name"][form] = manifest["name"][form].replace(+ _NAME_PLACEHOLDER, app_name+ )++ buffer = io.BytesIO()+ # Flat, with the three files at the root: Teams rejects a package whose+ # contents sit inside a folder.+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ archive.writestr("manifest.json", json.dumps(manifest, indent=4))+ for icon in _ICONS:+ archive.writestr(icon, (_TEMPLATE_DIR / icon).read_bytes())+ return DistributedAppPackage(+ manifest_id=app_id, version=str(manifest["version"]), archive=buffer.getvalue()+ )diff --git a/core/switch_core/bridges/collaboration/teams/auth.py b/core/switch_core/bridges/collaboration/teams/auth.pyindex 5f94e323a..2672695f9 100644--- a/core/switch_core/bridges/collaboration/teams/auth.py+++ b/core/switch_core/bridges/collaboration/teams/auth.py@@ -1,12 +1,20 @@from __future__ import annotations+import asyncio+import base64+import hashlibimport loggingimport time-from typing import Any+import uuid+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Protocolimport httpximport jwt-from jwt import PyJWKClient+from cryptography import x509+from cryptography.hazmat.primitives import serializationlogger = logging.getLogger(__name__)@@ -16,20 +24,165 @@ BOT_CONNECTOR_SCOPE = "https://api.botframework.com/.default"GRAPH_SCOPE = "https://graph.microsoft.com/.default"# OpenID metadata for tokens the Bot Connector attaches to inbound activities.-_BOTFRAMEWORK_OPENID = (+BOTFRAMEWORK_OPENID = ("https://login.botframework.com/v1/.well-known/openidconfiguration")# Expected issuer of Bot Connector tokens (public Azure cloud).-_BOTFRAMEWORK_ISSUER = "https://api.botframework.com"+BOTFRAMEWORK_ISSUER = "https://api.botframework.com"++# OpenID metadata for the Microsoft identity platform, whose keys sign the+# `validationTokens` Graph attaches to a change notification carrying data.+MICROSOFT_IDENTITY_OPENID = (+ "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"+)+# The application Graph sends change notifications as. A validation token not+# issued to it was not issued for a notification.+GRAPH_CHANGE_TRACKING_APP_ID = "0bf30f3b-4a52-48df-9a82-234910c4a086"++_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"++# Microsoft's own guidance for Bot Framework tokens: allow five minutes either+# way, since the two clocks are not ours to keep in step.+_CLOCK_SKEW_SECONDS = 300++# How long a provider's keys are trusted before being fetched again, and how+# soon an unrecognised key id may trigger a fetch of its own. The second is a+# floor so that a stream of tokens naming made-up key ids cannot turn into a+# stream of requests to Microsoft.+_KEYS_REFRESH_SECONDS = 24 * 60 * 60+_KEYS_REFETCH_FLOOR_SECONDS = 5 * 60++# Directory errors that mean the app is not approved in the directory asked.+# AADSTS700016: no such application there (never approved, or approval+# withdrawn by deleting it). AADSTS7000112: the application is disabled.+APP_NOT_APPROVED_CODES = frozenset({700016, 7000112})+++def token_endpoint(tenant_id: str) -> str:+ return f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"+++class TokenRequestRefused(RuntimeError):+ """The Microsoft identity platform refused to issue a token.++ `error_codes` carries the platform's own numeric codes, which are the only+ reliable way to tell a mistyped secret from an app nobody approved. Empty+ when the body did not say.+ """++ def __init__(self, message: str, *, error_codes: frozenset[int]) -> None:+ super().__init__(message)+ self.error_codes = error_codes++ @property+ def app_not_approved(self) -> bool:+ return bool(self.error_codes & APP_NOT_APPROVED_CODES)+++class ClientCredential(Protocol):+ """How an app proves who it is when asking for a token.++ The form fields differ by credential, and a certificate's depend on where+ the request is going: its signed assertion names the token endpoint as its+ audience, so it is built per request.+ """++ async def form(self, *, app_id: str, token_url: str) -> dict[str, str]: ...+++@dataclass(frozen=True)+class ClientSecret:+ secret: str++ async def form(self, *, app_id: str, token_url: str) -> dict[str, str]:+ return {"client_secret": self.secret}+++def _b64url(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).decode().rstrip("=")+++class ClientCertificate:+ """A certificate credential: a short-lived assertion signed with its key.++ Nothing secret leaves the process. Microsoft identifies the certificate by+ the thumbprints in the assertion's header and checks the signature against+ the public key uploaded to the app registration.+ """++ _ASSERTION_LIFETIME_SECONDS = 600++ def __init__(self, *, certificate_pem: str, private_key_pem: str) -> None:+ certificate = x509.load_pem_x509_certificate(certificate_pem.encode())+ der = certificate.public_bytes(serialization.Encoding.DER)+ self._headers = {+ "x5t#S256": _b64url(hashlib.sha256(der).digest()),+ # Older Entra endpoints read only the SHA-1 thumbprint; it names+ # the certificate and secures nothing, so carrying both is safe.+ "x5t": _b64url(hashlib.sha1(der, usedforsecurity=False).digest()),+ }+ self._key = serialization.load_pem_private_key(+ private_key_pem.encode(), password=None+ )++ async def form(self, *, app_id: str, token_url: str) -> dict[str, str]:+ now = int(time.time())+ assertion = jwt.encode(+ {+ "aud": token_url,+ "iss": app_id,+ "sub": app_id,+ "jti": str(uuid.uuid4()),+ "iat": now,+ "nbf": now,+ "exp": now + self._ASSERTION_LIFETIME_SECONDS,+ },+ self._key, # type: ignore[arg-type]+ algorithm="PS256",+ headers=self._headers,+ )+ return {"client_assertion_type": _JWT_BEARER, "client_assertion": assertion}+++@dataclass(frozen=True)+class FederatedTokenFile:+ """A workload-identity credential: a token another issuer wrote to a file.++ The file is projected into the pod and rotated by the platform, so it is+ read on every request rather than once.+ """++ path: str++ async def form(self, *, app_id: str, token_url: str) -> dict[str, str]:+ token = (await asyncio.to_thread(Path(self.path).read_text)).strip()+ if not token:+ raise TokenRequestRefused(+ f"The federated token file {self.path!r} is empty, so there is "+ "nothing to present to Microsoft in place of a secret.",+ error_codes=frozenset(),+ )+ return {"client_assertion_type": _JWT_BEARER, "client_assertion": token}+++def _error_codes(resp: httpx.Response) -> frozenset[int]:+ try:+ codes = resp.json().get("error_codes") or []+ return frozenset(int(code) for code in codes)+ except (ValueError, TypeError, AttributeError):+ return frozenset()class TeamsTokenProvider:- """Acquires and caches AAD app-only (client-credentials) access tokens.+ """Acquires and caches app-only (client-credentials) tokens in one directory.- One provider per bridge, shared by the Bot Connector (outbound) and Graph- (capture/provisioning) call paths — each scope is cached independently with- its own expiry. Tokens are refreshed a minute before expiry so an in-flight- request never carries a just-expired token.+ One provider per directory: a bring-your-own bridge has one for its own+ directory, shared by the Bot Connector (outbound) and Graph+ (capture/provisioning) call paths; the distributed app has one for its own+ directory's Bot Connector tokens and one per customer directory for Graph.+ Each scope is cached independently with its own expiry. Tokens are refreshed+ a minute before expiry so an in-flight request never carries a just-expired+ token."""def __init__(@@ -37,14 +190,12 @@ class TeamsTokenProvider:*,tenant_id: str,app_id: str,- app_password: str,+ credential: ClientCredential,http: httpx.AsyncClient,) -> None:- self._token_url = (- f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"- )+ self._token_url = token_endpoint(tenant_id)self._app_id = app_id- self._app_password = app_password+ self._credential = credentialself._http = http# scope -> (access_token, expires_at_epoch, issued_at_epoch)self._cache: dict[str, tuple[str, float, float]] = {}@@ -80,14 +231,17 @@ class TeamsTokenProvider:data={"grant_type": "client_credentials","client_id": self._app_id,- "client_secret": self._app_password,"scope": scope,+ **await self._credential.form(+ app_id=self._app_id, token_url=self._token_url+ ),},)if resp.status_code != 200:- raise RuntimeError(+ raise TokenRequestRefused(f"AAD token request for scope {scope} failed "- f"({resp.status_code}): {resp.text}"+ f"({resp.status_code}): {resp.text}",+ error_codes=_error_codes(resp),)# A 200 whose body is not the token response we expect — an HTML error# page from a proxy in front of AAD, or a shape change — must fail the@@ -98,9 +252,10 @@ class TeamsTokenProvider:payload = resp.json()access_token = str(payload["access_token"])except (ValueError, KeyError, TypeError) as exc:- raise RuntimeError(+ raise TokenRequestRefused(f"AAD token request for scope {scope} returned "- f"{resp.status_code} with an unusable body: {resp.text[:500]}"+ f"{resp.status_code} with an unusable body: {resp.text[:500]}",+ error_codes=frozenset(),) from excexpires_in = float(payload.get("expires_in", 3600))self._cache[scope] = (access_token, now + expires_in, now)@@ -112,44 +267,198 @@ class TeamsTokenProvider:async def graph_token(self) -> str:return await self.token(GRAPH_SCOPE)+ async def graph_roles(self) -> frozenset[str]:+ """The Graph application permissions this directory has granted the app.++ Read from the token Microsoft just issued us, over TLS, so its claims+ are Microsoft's answer rather than anyone's assertion; the signature is+ not checked because a Graph token is not meant to be verified by its+ holder. A directory that withdrew a permission but kept the app still+ issues a token — one without that role — so this, not whether a token+ was issued, is what says the approval is intact.+ """+ # Graph access tokens are Microsoft's to verify, not their holder's:+ # Graph signs them with a nonce in the header that makes any other+ # party's signature check fail by design. This one is read only for+ # the claims Microsoft just issued to us, never to admit a caller.+ claims = jwt.decode( # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode+ await self.graph_token(), options={"verify_signature": False}+ )+ roles = claims.get("roles") or []+ return frozenset(str(role) for role in roles)+++@dataclass(frozen=True)+class SigningKey:+ key: Any+ #: The channels the key is endorsed for. The Bot Framework publishes this+ #: per key; the Microsoft identity platform does not, and leaves it empty.+ endorsements: frozenset[str]-class InboundActivityValidator:- """Validates the JWT the Bot Connector attaches to inbound activities.- Bot Framework signs each inbound call with a token issued by- ``https://api.botframework.com``; the bot must verify the signature against- the published JWKS and confirm the audience is its own app id before- trusting the activity. This rejects forged POSTs to the messaging endpoint.+class SigningKeysUnavailable(RuntimeError):+ """No signing keys are held, and none could be fetched.++ Not a `PermissionError`: nothing about the token was found wrong, and+ refusing it as forged would turn an outage into lost traffic.+ """+++class SigningKeys:+ """An OpenID provider's signing keys, fetched without blocking and cached.++ Asynchronous because the request that needs a key is being served on the+ event loop every tenant's traffic shares; a synchronous fetch there stalls+ all of it for as long as the provider takes to answer.+ """++ def __init__(self, *, metadata_url: str, http: httpx.AsyncClient) -> None:+ self._metadata_url = metadata_url+ self._http = http+ self._keys: dict[str, SigningKey] = {}+ # When the keys last arrived, which decides when they are stale, and+ # when a fetch was last tried at all, which decides when another may+ # be. Kept apart so a provider that is down is not asked again on+ # every request while the keys already held carry on working.+ self._fetched_at: float | None = None+ self._attempted_at: float | None = None+ self._lock = asyncio.Lock()++ def _may_attempt(self, now: float) -> bool:+ if self._attempted_at is None:+ return True+ # Holding nothing, a request cannot be answered at all, so a failed+ # first fetch is retried sooner than a refresh is.+ floor = _KEYS_REFETCH_FLOOR_SECONDS if self._keys else 30+ return now - self._attempted_at > floor++ def _holds_fresh(self, kid: str) -> bool:+ return (+ kid in self._keys+ and self._fetched_at is not None+ and time.monotonic() - self._fetched_at <= _KEYS_REFRESH_SECONDS+ )++ async def get(self, kid: str) -> SigningKey:+ if self._holds_fresh(kid):+ return self._keys[kid]+ # Waited on even when no fetch may start, so a request arriving while+ # another's fetch is in flight — a burst at a cold start, or the first+ # tokens signed with a new key — uses what that fetch brings back+ # instead of being refused for a key it is about to have.+ async with self._lock:+ if not self._holds_fresh(kid) and self._may_attempt(time.monotonic()):+ await self._fetch()+ found = self._keys.get(kid)+ if found is None:+ if not self._keys:+ raise SigningKeysUnavailable(+ f"no signing keys could be fetched from {self._metadata_url}"+ )+ raise PermissionError(f"token is signed with an unknown key ({kid!r})")+ return found++ async def _fetch(self) -> None:+ self._attempted_at = time.monotonic()+ try:+ metadata = await self._http.get(self._metadata_url)+ metadata.raise_for_status()+ jwks_uri = str(metadata.json()["jwks_uri"])+ published = await self._http.get(jwks_uri)+ published.raise_for_status()+ entries = published.json()["keys"]+ except (httpx.HTTPError, ValueError, KeyError, TypeError) as error:+ if self._keys:+ logger.warning(+ "Could not refresh signing keys from %s (%s); keeping the "+ "%d already held",+ self._metadata_url,+ error,+ len(self._keys),+ )+ return+ raise SigningKeysUnavailable(+ f"could not fetch signing keys from {self._metadata_url}: {error}"+ ) from error+ keys: dict[str, SigningKey] = {}+ for entry in entries:+ kid = entry.get("kid")+ if not kid:+ continue+ try:+ key = jwt.PyJWK(entry).key+ except jwt.PyJWTError:+ continue+ keys[str(kid)] = SigningKey(+ key=key,+ endorsements=frozenset(str(e) for e in entry.get("endorsements") or []),+ )+ if not keys:+ if self._keys:+ logger.warning(+ "%s published no usable signing keys; keeping the %d already held",+ self._metadata_url,+ len(self._keys),+ )+ return+ raise SigningKeysUnavailable(+ f"{self._metadata_url} published no usable signing keys"+ )+ self._keys = keys+ self._fetched_at = time.monotonic()+++def _bearer(authorization: str | None) -> str:+ if not authorization or not authorization.lower().startswith("bearer "):+ raise PermissionError("missing bearer token on inbound Teams activity")+ return authorization.split(" ", 1)[1].strip()+++def _kid(token: str) -> str:+ try:+ kid = jwt.get_unverified_header(token).get("kid")+ except jwt.PyJWTError as error:+ raise PermissionError(f"token is not a JWT: {error}") from error+ if not kid:+ raise PermissionError("token names no signing key")+ return str(kid)+++class BotFrameworkAuthenticator:+ """Checks the JWT the Bot Connector attaches to an inbound activity.++ Everything Microsoft's Bot Connector authentication spec requires of a+ bot: the token is signed by a key the Bot Framework publishes, issued by+ the Bot Framework, addressed to this app, current, endorsed for the channel+ the activity claims to come from, and naming the same `serviceUrl` the+ activity does. The last two are what stop a token minted for one channel+ or one region being replayed with an activity pointing elsewhere — and in+ the distributed app the `serviceUrl` is where this app's own token is then+ sent, so it is checked before anything is learned from it."""- def __init__(self, *, app_id: str) -> None:+ def __init__(self, *, app_id: str, keys: SigningKeys) -> None:self._app_id = app_id- self._jwks: PyJWKClient | None = None- self._jwks_uri: str | None = None- self._http = httpx.Client(timeout=10)-- def _ensure_jwks(self) -> PyJWKClient:- if self._jwks is not None:- return self._jwks- meta = self._http.get(_BOTFRAMEWORK_OPENID)- meta.raise_for_status()- self._jwks_uri = meta.json()["jwks_uri"]- self._jwks = PyJWKClient(self._jwks_uri)- return self._jwks-- def validate(self, auth_header: str | None) -> None:- """Raise if the Authorization header is missing or the token is invalid."""- if not auth_header or not auth_header.lower().startswith("bearer "):- raise PermissionError("missing bearer token on inbound Teams activity")- token = auth_header.split(" ", 1)[1].strip()- signing_key = self._ensure_jwks().get_signing_key_from_jwt(token)+ self._keys = keys++ async def verify(+ self,+ authorization: str | None,+ *,+ service_url: str,+ channel_id: str,+ ) -> None:+ """Raise `PermissionError` unless the activity's token is genuine."""+ token = _bearer(authorization)+ signing_key = await self._keys.get(_kid(token))try:- jwt.decode(+ claims = jwt.decode(token,signing_key.key,algorithms=["RS256"],audience=self._app_id,- issuer=_BOTFRAMEWORK_ISSUER,+ issuer=BOTFRAMEWORK_ISSUER,+ leeway=_CLOCK_SKEW_SECONDS,options={"require": ["exp", "iss", "aud"]},)except jwt.InvalidAudienceError as exc:@@ -160,6 +469,22 @@ class InboundActivityValidator:"The Azure Bot resource's Microsoft App ID must be the app id ""registered on the bridge.") from exc+ except jwt.PyJWTError as exc:+ raise PermissionError(+ f"inbound Teams activity token rejected: {exc}"+ ) from exc++ if channel_id not in signing_key.endorsements:+ raise PermissionError(+ f"the key that signed this activity is not endorsed for channel "+ f"{channel_id!r}"+ )+ claimed = claims.get("serviceurl")+ if claimed is None or str(claimed) != service_url:+ raise PermissionError(+ "the activity's serviceUrl does not match the one its token was "+ "issued for"+ )@staticmethoddef _describe_audience(token: str, signing_key: Any) -> str:@@ -179,7 +504,8 @@ class InboundActivityValidator:token,signing_key,algorithms=["RS256"],- issuer=_BOTFRAMEWORK_ISSUER,+ issuer=BOTFRAMEWORK_ISSUER,+ leeway=_CLOCK_SKEW_SECONDS,options={"verify_aud": False},)except jwt.PyJWTError:@@ -187,5 +513,88 @@ class InboundActivityValidator:aud = claims.get("aud")return f"app id {aud!r}" if aud else "no audience"- def close(self) -> None:- self._http.close()++class GraphNotificationAuthenticator:+ """Checks the `validationTokens` Graph attaches to notifications with data.++ One token per app and directory pair whose notifications share the POST.+ Each must be signed by the Microsoft identity platform, addressed to this+ app, issued to Graph's change-tracking application, and current. The+ directories they were issued in are the only ones the POST may carry+ notifications for: a `tenantId` in the body is otherwise just a claim.+ """++ def __init__(self, *, app_id: str, keys: SigningKeys) -> None:+ self._app_id = app_id+ self._keys = keys++ async def vouched_tenants(+ self, validation_tokens: Sequence[object]+ ) -> frozenset[str]:+ """The directories the tokens vouch for; raise if any token is not genuine."""+ tenants: set[str] = set()+ for raw in validation_tokens:+ token = str(raw)+ signing_key = await self._keys.get(_kid(token))+ try:+ claims = jwt.decode(+ token,+ signing_key.key,+ algorithms=["RS256"],+ audience=self._app_id,+ leeway=_CLOCK_SKEW_SECONDS,+ options={"require": ["exp", "aud", "iss"]},+ )+ except jwt.PyJWTError as exc:+ raise PermissionError(+ f"Graph validation token rejected: {exc}"+ ) from exc+ caller = claims.get("azp") or claims.get("appid")+ if caller != GRAPH_CHANGE_TRACKING_APP_ID:+ raise PermissionError(+ "Graph validation token was not issued to Graph's "+ f"change-tracking application (got {caller!r})"+ )+ tenant = str(claims.get("tid") or "")+ if not tenant or not _issued_in(claims, tenant):+ raise PermissionError(+ "Graph validation token names no directory, or one its "+ "issuer does not"+ )+ tenants.add(tenant)+ return frozenset(tenants)+++def _issued_in(claims: Mapping[str, object], tenant: str) -> bool:+ issuer = str(claims.get("iss") or "")+ return issuer in (+ f"https://sts.windows.net/{tenant}/",+ f"https://login.microsoftonline.com/{tenant}/v2.0",+ )+++async def verify_microsoft_id_token(+ id_token: str, *, app_id: str, keys: SigningKeys+) -> dict[str, Any]:+ """Verify an id token the Microsoft identity platform issued to `app_id`.++ Raises `PermissionError` unless it is signed by one of the platform's keys,+ addressed to the app, current, and issued by the very organisation its+ `tid` names (`https://login.microsoftonline.com/{tid}/v2.0`).+ """+ signing_key = await keys.get(_kid(id_token))+ try:+ claims: dict[str, Any] = jwt.decode(+ id_token,+ signing_key.key,+ algorithms=["RS256"],+ audience=app_id,+ leeway=_CLOCK_SKEW_SECONDS,+ options={"require": ["exp", "aud", "iss", "tid"]},+ )+ except jwt.PyJWTError as exc:+ raise PermissionError(f"id token rejected: {exc}") from exc+ tenant = str(claims.get("tid") or "")+ if claims.get("iss") != f"https://login.microsoftonline.com/{tenant}/v2.0":+ raise PermissionError("id token was not issued by the organisation it names")+ return claimsdiff --git a/core/switch_core/bridges/collaboration/teams/connector.py b/core/switch_core/bridges/collaboration/teams/connector.pyindex a0bd8c339..25b212c8f 100644--- a/core/switch_core/bridges/collaboration/teams/connector.py+++ b/core/switch_core/bridges/collaboration/teams/connector.py@@ -2,11 +2,13 @@ from __future__ import annotationsimport jsonimport logging+from collections.abc import Callablefrom typing import Any+from urllib.parse import urlsplitimport httpx-from switch_core.bridges.collaboration.teams.auth import TeamsTokenProvider+from switch_core.bridges.collaboration.teams.identity import TeamsTokenslogger = logging.getLogger(__name__)@@ -139,14 +141,48 @@ class BotConnectorClient:call is authorised with an app-only Bot Connector token from the sharedtoken provider.+ `allowed_hosts` bounds where that token may go. Under the distributed app+ the token posts into every approving organisation's Teams, and a service+ URL is learned from traffic and kept in config, so an address that is not+ Microsoft's is refused here, on every call, before the token is attached.+ None leaves a bring-your-own bridge's own token, which reaches only its+ own organisation, unrestricted.++ `on_bot_disabled` is told when Teams answers that an admin has blocked the+ app, which no individual call can do anything about and which somebody has+ to be told.+Every failure leaves here as a `BotConnectorError` saying which kind it was,including a transport failure: an `httpx` exception escaping raw would reachcallers that have no way to tell it from a refusal."""- def __init__(self, *, tokens: TeamsTokenProvider, http: httpx.AsyncClient) -> None:+ def __init__(+ self,+ *,+ tokens: TeamsTokens,+ http: httpx.AsyncClient,+ allowed_hosts: frozenset[str] | None,+ on_bot_disabled: Callable[[], None],+ ) -> None:self._tokens = tokensself._http = http+ self._allowed_hosts = allowed_hosts+ self._on_bot_disabled = on_bot_disabled++ def _refuse_foreign_host(self, operation: str, url: str) -> None:+ if self._allowed_hosts is None:+ return+ parts = urlsplit(url)+ if parts.scheme == "https" and parts.hostname in self._allowed_hosts:+ return+ raise BotConnectorRefused(+ f"{operation} was not attempted: {parts.hostname!r} is not a Bot "+ "Connector host, and this app's token is only ever sent to "+ "Microsoft.",+ status=None,+ retry_after=None,+ )async def _headers(self) -> dict[str, str]:token = await self._tokens.bot_token()@@ -164,6 +200,7 @@ class BotConnectorClient:url: str,body: dict[str, Any] | None,) -> httpx.Response:+ self._refuse_foreign_host(operation, url)headers = await self._headers()content: bytes | None = Noneif body is not None:@@ -182,6 +219,8 @@ class BotConnectorClient:retry_after=None,) from errorif resp.status_code >= 300:+ if resp.status_code == 403 and "BotDisabledByAdmin" in resp.text:+ self._on_bot_disabled()raise _failure(operation, resp)return resp@@ -212,10 +251,19 @@ class BotConnectorClient:return valueasync def create_channel_thread(- self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ self,+ *,+ service_url: str,+ channel_id: str,+ tenant_id: str,+ activity: dict[str, Any],) -> tuple[str, str]:"""Start a new thread in a Teams channel with ``activity``.+ Names the organisation the channel belongs to, as Microsoft asks of a+ proactive message: with one app serving many organisations, the+ channel id alone is not what decides where the thread is opened.+Returns ``(conversation_id, activity_id)`` — the new thread'sconversation id and the posted message's id (its thread root)."""@@ -226,7 +274,10 @@ class BotConnectorClient:url=f"{self._base(service_url)}v3/conversations",body={"isGroup": True,- "channelData": {"channel": {"id": channel_id}},+ "channelData": {+ "channel": {"id": channel_id},+ "tenant": {"id": tenant_id},+ },"activity": activity,},)diff --git a/core/switch_core/bridges/collaboration/teams/crypto.py b/core/switch_core/bridges/collaboration/teams/crypto.pyindex 943d5bded..ec71bee19 100644--- a/core/switch_core/bridges/collaboration/teams/crypto.py+++ b/core/switch_core/bridges/collaboration/teams/crypto.py@@ -22,13 +22,23 @@ class ResourceDataError(RuntimeError):"""A Graph change-notification resource payload failed to decrypt/verify."""-def _load_private_key(pem: str) -> Any:+def load_private_key(pem: str) -> rsa.RSAPrivateKey:+ """Parse the PEM private key Graph's notifications are wrapped to.++ Parsed once by whoever holds the key, not once per notification: a busy+ deployment decrypts every captured message, and re-reading the PEM each+ time is pure overhead on the loop every tenant shares.+ """key = load_pem_private_key(pem.encode("utf-8"), password=None)+ if not isinstance(key, rsa.RSAPrivateKey):+ raise ResourceDataError(+ f"the notification private key must be RSA, got {type(key).__name__}"+ )return keydef decrypt_resource_data(- encrypted_content: dict[str, Any], private_key_pem: str+ encrypted_content: dict[str, Any], private_key: rsa.RSAPrivateKey) -> dict[str, Any]:"""Decrypt and verify the ``encryptedContent`` of a Graph change notification.@@ -52,7 +62,6 @@ def decrypt_resource_data(except (KeyError, ValueError, TypeError) as e:raise ResourceDataError(f"malformed encryptedContent: {e}") from e- private_key = _load_private_key(private_key_pem)symmetric_key = private_key.decrypt(data_key,asym_padding.OAEP(diff --git a/core/switch_core/bridges/collaboration/teams/distributed_app/color.png b/core/switch_core/bridges/collaboration/teams/distributed_app/color.pngnew file mode 100644index 000000000..6495f519dBinary files /dev/null and b/core/switch_core/bridges/collaboration/teams/distributed_app/color.png differdiff --git a/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.json b/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.jsonnew file mode 100644index 000000000..bd2666f05--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.json@@ -0,0 +1,171 @@+{+ "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.29/MicrosoftTeams.schema.json",+ "manifestVersion": "1.29",+ "version": "1.0.0",+ "id": "{{APP_ID}}",+ "developer": {+ "name": "Agent Switch",+ "websiteUrl": "https://github.com/sandbox-quantum/switch",+ "privacyUrl": "{{PRIVACY_URL}}",+ "termsOfUseUrl": "{{TERMS_URL}}"+ },+ "name": {+ "short": "{{APP_NAME}}",+ "full": "{{APP_NAME}} — your AI agents, in your channels"+ },+ "description": {+ "short": "Work with your AI agents in Teams channels and chats.",+ "full": "Agent Switch puts your AI agents into Microsoft Teams. Mention an agent by name in a channel and it answers there, in the same conversation, with its progress shown on the message while it works. Each Switch room is a Teams channel, so the people and the agents share one thread of context rather than one per tool.\n\nThis app connects your organisation's Teams to your Switch workspace. Messages in the channels Switch is added to are delivered to that workspace and nowhere else; your Microsoft admin approves the app for your organisation from Switch, and can remove it at any time.\n\nIn a chat, type /help. In a channel, mention the app first: @Agent Switch /help."+ },+ "icons": {+ "color": "color.png",+ "outline": "outline.png"+ },+ "accentColor": "#3F3C3B",+ "supportsChannelFeatures": "tier1",+ "bots": [+ {+ "botId": "{{APP_ID}}",+ "scopes": [+ "team",+ "personal",+ "groupChat"+ ],+ "supportsTargetedMessages": true,+ "isNotificationOnly": false,+ "supportsFiles": false,+ "commandLists": [+ {+ "scopes": [+ "team",+ "groupChat",+ "personal"+ ],+ "triggers": [+ "mention"+ ],+ "commands": [+ {+ "title": "/help",+ "description": "Show every in-room command"+ },+ {+ "title": "/list-agents",+ "description": "List the agents in this room"+ },+ {+ "title": "/agents-status",+ "description": "Show each agent's presence and capabilities"+ },+ {+ "title": "/invite-agent",+ "description": "Add an existing agent: /invite-agent @agent-name"+ },+ {+ "title": "/agents-greet",+ "description": "Have the agents here introduce themselves"+ },+ {+ "title": "/roles",+ "description": "List this room's roles and who holds each"+ },+ {+ "title": "/list-aliases",+ "description": "List this room's agent aliases"+ },+ {+ "title": "/set-alias",+ "description": "Give an agent a room alias: /set-alias @agent-name @alias"+ },+ {+ "title": "/reset",+ "description": "Reset an agent's session: /reset @agent-name"+ },+ {+ "title": "/interrupt",+ "description": "Interrupt an agent's current turn: /interrupt @agent-name"+ },+ {+ "title": "/list-switch-agents",+ "description": "List every agent on this Switch, to find one to invite"+ },+ {+ "title": "/room-url",+ "description": "Show this room's address in Switch"+ }+ ]+ },+ {+ "scopes": [+ "team",+ "groupChat",+ "personal"+ ],+ "triggers": [+ "slash"+ ],+ "commands": [+ {+ "title": "help",+ "description": "Show every in-room command"+ },+ {+ "title": "list-agents",+ "description": "List the agents in this room"+ },+ {+ "title": "agents-status",+ "description": "Show each agent's presence and capabilities"+ },+ {+ "title": "invite-agent",+ "description": "Add an existing agent: /invite-agent @agent-name"+ },+ {+ "title": "agents-greet",+ "description": "Have the agents here introduce themselves"+ },+ {+ "title": "roles",+ "description": "List this room's roles and who holds each"+ },+ {+ "title": "list-aliases",+ "description": "List this room's agent aliases"+ },+ {+ "title": "set-alias",+ "description": "Give an agent a room alias: /set-alias @agent-name @alias"+ },+ {+ "title": "reset",+ "description": "Reset an agent's session: /reset @agent-name"+ },+ {+ "title": "interrupt",+ "description": "Interrupt an agent's current turn: /interrupt @agent-name"+ },+ {+ "title": "list-switch-agents",+ "description": "List every agent on this Switch, to find one to invite"+ },+ {+ "title": "room-url",+ "description": "Show this room's address in Switch"+ }+ ]+ }+ ]+ }+ ],+ "permissions": [+ "identity",+ "messageTeamMembers"+ ],+ "webApplicationInfo": {+ "id": "{{APP_ID}}"+ },+ "validDomains": [+ "{{MESSAGING_HOST}}"+ ]+}diff --git a/core/switch_core/bridges/collaboration/teams/distributed_app/outline.png b/core/switch_core/bridges/collaboration/teams/distributed_app/outline.pngnew file mode 100644index 000000000..bf01bddcdBinary files /dev/null and b/core/switch_core/bridges/collaboration/teams/distributed_app/outline.png differdiff --git a/core/switch_core/bridges/collaboration/teams/graph.py b/core/switch_core/bridges/collaboration/teams/graph.pyindex 698828c2c..37e95f231 100644--- a/core/switch_core/bridges/collaboration/teams/graph.py+++ b/core/switch_core/bridges/collaboration/teams/graph.py@@ -1,24 +1,41 @@from __future__ import annotations+import asyncioimport logging+from dataclasses import dataclassfrom typing import Any-from urllib.parse import quote+from urllib.parse import quote, urlsplitimport httpxfrom switch_core.bridges.collaboration.models import BridgeOperationError-from switch_core.bridges.collaboration.teams.auth import GRAPH_SCOPE, TeamsTokenProvider+from switch_core.bridges.collaboration.teams.auth import GRAPH_SCOPE+from switch_core.bridges.collaboration.teams.identity import TeamsTokenslogger = logging.getLogger(__name__)GRAPH_BASE = "https://graph.microsoft.com/v1.0"+_GRAPH_HOST = urlsplit(GRAPH_BASE).hostname# How old our token must be before an authorization refusal is worth re-minting# it for. A token issued seconds ago cannot have missed a grant._TOKEN_RETRY_AGE = 30.0+# How often a throttled call is asked again, and the longest wait between+# attempts this will sit through rather than fail the call.+_THROTTLE_RETRIES = 2+_THROTTLE_MAX_WAIT_SECONDS = 30.0class GraphError(BridgeOperationError):- """A Microsoft Graph REST call returned a non-success status."""+ """A Microsoft Graph REST call returned a non-success status.++ `status` is kept because some refusals mean something specific to the+ caller — a 404 on a subscription is a subscription that no longer exists,+ which is answered by making a new one rather than by retrying.+ """++ def __init__(self, message: str, *, status: int) -> None:+ super().__init__(message)+ self.status = statusdef _graph_error(operation: str, resp: httpx.Response) -> GraphError:@@ -41,7 +58,35 @@ def _graph_error(operation: str, resp: httpx.Response) -> GraphError:detail = f"{code}: {message}" if code else messageexcept (ValueError, KeyError, TypeError):pass- return GraphError(f"{operation} failed ({resp.status_code}): {detail}")+ return GraphError(+ f"{operation} failed ({resp.status_code}): {detail}", status=resp.status_code+ )+++def _retry_after(resp: httpx.Response, *, default: float) -> float:+ """The wait Graph asked for, in seconds; `default` when it named none."""+ try:+ return max(0.0, float(resp.headers["Retry-After"]))+ except (KeyError, ValueError):+ return default+++def _segment(value: str) -> str:+ """One identifier as a single URL path segment.++ A team id can arrive from a request, and an unescaped `?`, `#` or `/` in+ it would move the rest of the URL somewhere else. `:` and `@` are left as+ they are: they are legal in a path segment, and every channel id has both.+ """+ return quote(value, safe=":@")+++@dataclass(frozen=True)+class AppInstallation:+ installation_id: str+ #: The app's id in the organisation's own catalogue, as the installation+ #: reports it.+ catalog_app_id: str | Noneclass GraphClient:@@ -49,7 +94,7 @@ class GraphClient:change-notification subscriptions, channel and membership provisioning, anddirectory lookups. Every call carries an app-only Graph token."""- def __init__(self, *, tokens: TeamsTokenProvider, http: httpx.AsyncClient) -> None:+ def __init__(self, *, tokens: TeamsTokens, http: httpx.AsyncClient) -> None:self._tokens = tokensself._http = http@@ -81,9 +126,7 @@ class GraphClient:grant, so a genuine denial costs one extra round trip rather thanlooping."""- resp = await self._http.request(- method, url, headers=await self._headers(extra_headers), **kwargs- )+ resp = await self._request(method, url, extra_headers, kwargs)if resp.status_code not in (401, 403):return respif not self._tokens.invalidate(GRAPH_SCOPE, min_age_seconds=_TOKEN_RETRY_AGE):@@ -95,9 +138,40 @@ class GraphClient:url,resp.status_code,)- return await self._http.request(- method, url, headers=await self._headers(extra_headers), **kwargs- )+ return await self._request(method, url, extra_headers, kwargs)++ async def _request(+ self,+ method: str,+ url: str,+ extra_headers: dict[str, str] | None,+ kwargs: dict[str, Any],+ ) -> httpx.Response:+ """One Graph call, waited out and asked again while Graph is throttling.++ Graph throttles per app and per organisation, and says how long to+ wait in `Retry-After`; asking again sooner only extends it. The+ distributed app shares one budget across everything it does in an+ organisation, so a burst — listing every team's apps, say — is the+ likely way to meet it. A wait longer than this will sit through, or+ throttling that outlasts the retries, is answered with Graph's own+ response, which the caller raises as an error naming it.+ """+ attempt = 0+ while True:+ resp = await self._http.request(+ method, url, headers=await self._headers(extra_headers), **kwargs+ )+ if resp.status_code != 429 or attempt == _THROTTLE_RETRIES:+ return resp+ wait = _retry_after(resp, default=float(2**attempt))+ if wait > _THROTTLE_MAX_WAIT_SECONDS:+ return resp+ logger.warning(+ "Graph is throttling %s %s; asking again in %.0fs", method, url, wait+ )+ await asyncio.sleep(wait)+ attempt += 1async def create_subscription(self,@@ -138,7 +212,7 @@ class GraphClient:) -> None:resp = await self._send("PATCH",- f"{GRAPH_BASE}/subscriptions/{subscription_id}",+ f"{GRAPH_BASE}/subscriptions/{_segment(subscription_id)}",json={"expirationDateTime": expiration_iso},)if resp.status_code >= 300:@@ -146,17 +220,37 @@ class GraphClient:async def delete_subscription(self, *, subscription_id: str) -> None:resp = await self._send(- "DELETE", f"{GRAPH_BASE}/subscriptions/{subscription_id}"+ "DELETE", f"{GRAPH_BASE}/subscriptions/{_segment(subscription_id)}")if resp.status_code >= 300 and resp.status_code != 404:raise _graph_error(f"delete subscription {subscription_id}", resp)async def list_subscriptions(self) -> list[dict[str, Any]]:- resp = await self._send("GET", f"{GRAPH_BASE}/subscriptions")- if resp.status_code >= 300:- raise _graph_error("list subscriptions", resp)- value: list[dict[str, Any]] = resp.json().get("value", [])- return value+ """Every subscription this app holds in the directory, across Graph's pages."""+ return await self._all_pages(+ f"{GRAPH_BASE}/subscriptions", params=None, what="list subscriptions"+ )++ async def _all_pages(+ self, url: str, *, params: dict[str, str] | None, what: str+ ) -> list[dict[str, Any]]:+ items: list[dict[str, Any]] = []+ next_url: str | None = url+ while next_url is not None:+ resp = await self._send("GET", next_url, params=params)+ if resp.status_code >= 300:+ raise _graph_error(what, resp)+ page = resp.json()+ items.extend(page.get("value", []) or [])+ # The next link already carries the query.+ next_url = page.get("@odata.nextLink")+ params = None+ if next_url is not None and urlsplit(next_url).hostname != _GRAPH_HOST:+ raise BridgeOperationError(+ f"Graph's next page for {what} is not on {_GRAPH_HOST}, so "+ "Switch did not send its token there"+ )+ return items# ── Provisioning ─────────────────────────────────────────────────────────@@ -176,7 +270,7 @@ class GraphClient:"membershipType": membership_type,}resp = await self._send(- "POST", f"{GRAPH_BASE}/teams/{team_id}/channels", json=body+ "POST", f"{GRAPH_BASE}/teams/{_segment(team_id)}/channels", json=body)if resp.status_code >= 300:raise _graph_error(@@ -196,7 +290,7 @@ class GraphClient:"""resp = await self._send("GET",- f"{GRAPH_BASE}/teams/{team_id}/channels/{channel_id}",+ f"{GRAPH_BASE}/teams/{_segment(team_id)}/channels/{_segment(channel_id)}",params={"$select": "id,displayName,description,membershipType,layoutType"},)if resp.status_code >= 300:@@ -244,7 +338,7 @@ class GraphClient:"""resp = await self._send("GET",- f"{GRAPH_BASE}/users/{quote(user_id, safe='')}",+ f"{GRAPH_BASE}/users/{_segment(user_id)}",params={"$select": "id,displayName,userPrincipalName,mail"},)if resp.status_code >= 300:@@ -263,7 +357,7 @@ class GraphClient:}resp = await self._send("POST",- f"{GRAPH_BASE}/teams/{team_id}/channels/{channel_id}/members",+ f"{GRAPH_BASE}/teams/{_segment(team_id)}/channels/{_segment(channel_id)}/members",json=body,)if resp.status_code >= 300 and resp.status_code != 409:@@ -279,7 +373,72 @@ class GraphClient:"[email protected]": (f"{GRAPH_BASE}/users('{user_aad_id}')"),}resp = await self._send(- "POST", f"{GRAPH_BASE}/teams/{team_id}/members", json=body+ "POST", f"{GRAPH_BASE}/teams/{_segment(team_id)}/members", json=body)if resp.status_code >= 300 and resp.status_code != 409:raise _graph_error(f"add member {user_aad_id} to team {team_id}", resp)++ # ── The app's own installation in a team ─────────────────────────────────++ async def list_teams(self) -> list[dict[str, Any]]:+ """Every team in the organisation, by id and name, across Graph's pages."""+ return await self._all_pages(+ f"{GRAPH_BASE}/teams",+ params={"$select": "id,displayName"},+ what="list the organisation's teams",+ )++ async def install_app(self, *, team_id: str, catalog_app_id: str) -> None:+ """Add the app, by its id in the organisation's catalogue, to a team."""+ resp = await self._send(+ "POST",+ f"{GRAPH_BASE}/teams/{_segment(team_id)}/installedApps",+ json={+ "[email protected]": (+ f"{GRAPH_BASE}/appCatalogs/teamsApps/{_segment(catalog_app_id)}"+ )+ },+ )+ # 409: it is there already, which is what was asked for.+ if resp.status_code >= 300 and resp.status_code != 409:+ raise _graph_error(f"add the app to team {team_id}", resp)++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ """This app's installations in a team, if it is installed.++ Matched on the app's manifest id (`externalId`), which is the same in+ every organisation's catalogue, rather than the id the catalogue+ assigned, which differs per organisation — and which each installation+ also reports, so finding one is how that id is learned without a+ catalogue permission.+ """+ resp = await self._send(+ "GET",+ f"{GRAPH_BASE}/teams/{_segment(team_id)}/installedApps",+ params={+ "$expand": "teamsApp",+ "$filter": f"teamsApp/externalId eq '{external_id}'",+ },+ )+ if resp.status_code >= 300:+ raise _graph_error(f"list app installations in team {team_id}", resp)+ installations: list[dict[str, Any]] = resp.json().get("value", []) or []+ return [+ AppInstallation(+ installation_id=str(item["id"]),+ catalog_app_id=str((item.get("teamsApp") or {}).get("id") or "")+ or None,+ )+ for item in installations+ if item.get("id")+ ]++ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ resp = await self._send(+ "DELETE",+ f"{GRAPH_BASE}/teams/{_segment(team_id)}/installedApps/{_segment(installation_id)}",+ )+ if resp.status_code >= 300 and resp.status_code != 404:+ raise _graph_error(f"remove the app from team {team_id}", resp)diff --git a/core/switch_core/bridges/collaboration/teams/identity.py b/core/switch_core/bridges/collaboration/teams/identity.pynew file mode 100644index 000000000..f5a3daa9d--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/identity.py@@ -0,0 +1,195 @@+"""Who a Teams bridge speaks as, and how it reads what Graph sends it.++A bring-your-own bridge carries its own app: its credentials, the secret Graph+echoes back, and the keypair Graph encrypts to all live in its connection+config. A bridge serving the distributed app carries none of that — the app is+the deployment's, shared by every organisation that approved it — and is told+which organisation it serves.++Everything the adapter needs from either is behind `TeamsIdentity` and+`TeamsTokens`, so the rest of the adapter is one code path whichever app a+bridge belongs to.+"""++from __future__ import annotations++import hmac+from dataclasses import dataclass+from typing import Any, Protocol+from urllib.parse import urlsplit++from cryptography.hazmat.primitives.asymmetric import rsa++from switch_core.bridges.collaboration.teams.auth import (+ BOT_CONNECTOR_SCOPE,+ TeamsTokenProvider,+)+from switch_core.bridges.collaboration.teams.crypto import (+ ResourceDataError,+ decrypt_resource_data,+)++#: The Graph application permissions an organisation's admin grants the+#: distributed app, and that every token issued in their directory must carry.+#: A token missing any of them means the approval was narrowed or withdrawn,+#: and the bridge says so rather than failing call by call.+REQUIRED_GRAPH_ROLES = frozenset(+ {+ "ChannelMessage.Read.All",+ "Channel.Create",+ "Channel.ReadBasic.All",+ "TeamMember.ReadWriteNonOwnerRole.All",+ "ChannelMember.ReadWrite.All",+ "User.ReadBasic.All",+ "Team.ReadBasic.All",+ "TeamsAppInstallation.ReadWriteSelfForTeam.All",+ }+)++#: Where Microsoft's public-cloud Bot Connector lives. The distributed app's+#: Bot Connector token is good in every approving organisation, so it is sent+#: here and nowhere else, whatever address a stored reference or a learned+#: setting names. Government clouds have hosts of their own and are out of+#: scope.+BOT_CONNECTOR_HOSTS = frozenset({"smba.trafficmanager.net"})+++class TeamsTokens(Protocol):+ """The tokens the Bot Connector and Graph clients authorise calls with."""++ def invalidate(self, scope: str, *, min_age_seconds: float = 0.0) -> bool: ...++ async def bot_token(self) -> str: ...++ async def graph_token(self) -> str: ...++ async def graph_roles(self) -> frozenset[str]: ...+++class OrgTokens:+ """Tokens for one customer organisation under the distributed app.++ The two halves come from different directories, which is the whole of+ Microsoft's arrangement for a SingleTenant bot serving other+ organisations: every Bot Connector token is issued in our own directory,+ and every Graph token in the organisation whose data it reads.+ """++ def __init__(self, *, home: TeamsTokenProvider, org: TeamsTokenProvider) -> None:+ self._home = home+ self._org = org++ def invalidate(self, scope: str, *, min_age_seconds: float = 0.0) -> bool:+ provider = self._home if scope == BOT_CONNECTOR_SCOPE else self._org+ return provider.invalidate(scope, min_age_seconds=min_age_seconds)++ async def bot_token(self) -> str:+ return await self._home.bot_token()++ async def graph_token(self) -> str:+ return await self._org.graph_token()++ async def graph_roles(self) -> frozenset[str]:+ return await self._org.graph_roles()+++@dataclass(frozen=True)+class NotificationKey:+ certificate_id: str+ private_key: rsa.RSAPrivateKey+++class NotificationKeyring:+ """The keypair Graph encrypts notifications to, and any it still might.++ New subscriptions are made against the current certificate. A notification+ names the certificate it was encrypted to, so one made against a key being+ retired is still read until its subscription runs out — which is the whole+ of what rotating the key needs.+ """++ def __init__(+ self,+ *,+ current: NotificationKey,+ certificate_der_b64: str,+ retired: tuple[NotificationKey, ...],+ ) -> None:+ self._current = current+ self._certificate_der_b64 = certificate_der_b64+ self._keys = {key.certificate_id: key for key in (current, *retired)}++ @property+ def certificate_id(self) -> str:+ return self._current.certificate_id++ @property+ def certificate_der_b64(self) -> str:+ return self._certificate_der_b64++ def decrypt(self, encrypted_content: dict[str, Any]) -> dict[str, Any]:+ named = encrypted_content.get("encryptionCertificateId")+ key = self._keys.get(str(named)) if named else self._current+ if key is None:+ raise ResourceDataError(+ f"notification is encrypted to certificate {named!r}, which this "+ "deployment does not hold"+ )+ return decrypt_resource_data(encrypted_content, key.private_key)+++@dataclass(frozen=True)+class TeamsIdentity:+ """The app a bridge speaks as, and the organisation it serves.++ `shared` is the one fact the adapter branches on outside its start-up:+ under the distributed app one credential reaches every organisation, so a+ bridge must refuse whatever belongs to an organisation other than its own,+ and must only ever send that credential to Microsoft.+ """++ app_id: str+ org_tenant_id: str+ shared: bool+ notification_url: str+ client_state: str+ #: None when a bring-your-own bridge has no encryption material, in which+ #: case channel capture is degraded and says so.+ keyring: NotificationKeyring | None+ #: Hosts the Bot Connector token may be sent to, or None for no restriction.+ allowed_service_hosts: frozenset[str] | None+ #: The Graph application permissions the organisation must have granted,+ #: checked against every token. Empty for a bring-your-own bridge, whose+ #: operator decides what their own app is granted.+ required_graph_roles: frozenset[str]++ def delivers_here(self, notification_url: str) -> bool:+ """Whether a subscription's notification URL is this deployment's own.++ Compared without the query, which carries the clientState key's+ fingerprint: a subscription made under an earlier key still delivers+ here, and is this deployment's to clean up.+ """+ theirs = urlsplit(notification_url)+ ours = urlsplit(self.notification_url)+ return (theirs.scheme, theirs.netloc, theirs.path) == (+ ours.scheme,+ ours.netloc,+ ours.path,+ )++ def accepts_client_state(self, value: object) -> bool:+ # Constant time: this is an authentication check, and a `!=` on a+ # secret leaks its prefix through timing.+ return hmac.compare_digest(str(value or ""), self.client_state)++ def serves(self, tenant_id: str | None) -> bool:+ """Whether something from directory `tenant_id` is this bridge's.++ A bring-your-own bridge's credential reaches only its own directory,+ so whatever it receives is its own. A shared bridge's reaches every+ approving organisation's, so only its own is.+ """+ if not self.shared:+ return True+ return tenant_id == self.org_tenant_iddiff --git a/core/switch_core/bridges/collaboration/teams/install.py b/core/switch_core/bridges/collaboration/teams/install.pynew file mode 100644index 000000000..8ef420573--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/install.py@@ -0,0 +1,647 @@+"""Approving the distributed Teams app for a customer's Microsoft organisation.++The counterpart to `TEAMS_SETUP.md`'s bring-your-own app (see+`TEAMS_DISTRIBUTED_APP.md`). An install here is a Microsoft admin signing in+from Switch and approving the app for their whole organisation; Switch then+puts the app into the organisation's Teams app catalogue itself.++Three things differ from Slack's installer, and all three are Microsoft's:++- **No token per install.** Approval grants the deployment's one app access+ to the organisation; Switch mints that organisation's tokens with its own+ credential when it needs them. The grant is tokenless, as Discord's is.+- **The redirect proves nothing by itself.** Microsoft's own docs warn that+ the organisation named on the redirect can be forged, and that `admin_consent`+ appears on error replies too. So nothing is recorded until three things are+ proved: the id token (from the code exchange, signed by Microsoft) names+ the organisation; the person who signed in holds an admin role there; and a+ token issued in that organisation carries every permission the app needs.+ Without the second, any employee of an organisation that had approved the+ app before — after a disconnect, say, since Switch cannot remove the+ approval on their side — could connect it to a workspace of their own.+- **Approval does not put the app anywhere.** Microsoft keeps consent, the+ Teams catalogue and each team's installed apps apart, so after approval+ Switch publishes the app to the organisation's catalogue with the admin's+ delegated token, which is then thrown away. If the admin may approve but+ not publish, the install still succeeds and says so (`platform_data`); the+ connection's Teams panel offers the package to upload instead.+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+from collections import OrderedDict+from collections.abc import Mapping+from typing import Any, ClassVar+from urllib.parse import quote, urlencode++import httpx++from switch_core.bridges.collaboration.install import (+ InboundWebhook,+ InstallGrant,+ MessagingAppInstaller,+ MessagingInstallError,+ WebhookAuthenticityError,+ WebhookEndpoint,+ WebhookPayloadError,+ WebhookVerificationUnavailable,+)+from switch_core.bridges.collaboration.teams.adapter import activity_tenant+from switch_core.bridges.collaboration.teams.app_package import DistributedAppPackage+from switch_core.bridges.collaboration.teams.auth import (+ GRAPH_SCOPE,+ SigningKeysUnavailable,+ TokenRequestRefused,+ token_endpoint,+)+from switch_core.bridges.collaboration.teams.identity import REQUIRED_GRAPH_ROLES+from switch_core.bridges.collaboration.teams.shared_app import PLATFORM, TeamsSharedApp++logger = logging.getLogger(__name__)++_AUTHORITY = "organizations"+_AUTHORIZE_URL = f"https://login.microsoftonline.com/{_AUTHORITY}/oauth2/v2.0/authorize"+#: Sign-in and every permission configured on the app registration, delegated+#: and application alike: `.default` is what lets one consent screen cover the+#: lot when the admin approves for the whole organisation.+_SCOPES = f"openid profile {GRAPH_SCOPE}"+_GRAPH = "https://graph.microsoft.com/v1.0"++#: Directory roles that may grant an app Microsoft Graph application+#: permissions: Global Administrator and Privileged Role Administrator. The+#: ids are Microsoft's role template ids, the same in every organisation.+_APPROVING_ROLES = frozenset(+ {+ "62e90394-69f5-4237-9190-012177145e10",+ "e8611ab8-c189-46e8-94e1-60213ab1f814",+ }+)++#: The directory personal Microsoft accounts sign in from. Not an organisation,+#: so nothing in it can approve an app for one.+_PERSONAL_ACCOUNTS_TENANT = "9188040d-6c67-4c5b-b112-36a304b66dad"++#: Government clouds, which the distributed app does not serve: their Teams+#: is reached at hosts of its own, which this deployment's token never goes to.+_GOVERNMENT_SUB_SCOPES = frozenset({"GCC", "DOD", "DODCON"})++#: A just-approved organisation can take a few seconds to issue the app its+#: first token. Long enough to ride that out, short enough that a person+#: watching a browser is not left wondering.+_APPROVAL_PROPAGATION_ATTEMPTS = 5+_APPROVAL_PROPAGATION_DELAY_SECONDS = 2.0++#: How many batches' vouched organisations are held between their check and+#: their parse. Both happen within one request, so this only bounds what a+#: request that failed between the two could leave behind.+_VOUCHED_KEPT = 256+++class TeamsAppInstaller(MessagingAppInstaller):+ platform: ClassVar[str] = PLATFORM+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset(+ {"events", "notifications"}+ )++ def __init__(self, *, app: TeamsSharedApp, package: DistributedAppPackage) -> None:+ self._app = app+ self._package = package+ self._vouched: OrderedDict[bytes, frozenset[str]] = OrderedDict()++ @property+ def package(self) -> DistributedAppPackage:+ """The app package, for an admin to upload by hand where Switch could+ not put it in the organisation's catalogue itself."""+ return self._package++ # ── Installing ───────────────────────────────────────────────────────────++ def authorize_url(self, *, state: str, redirect_uri: str) -> str:+ return f"{_AUTHORIZE_URL}?" + urlencode(+ {+ "client_id": self._app.app_id,+ "response_type": "code",+ "response_mode": "query",+ "redirect_uri": redirect_uri,+ "scope": _SCOPES,+ # Always ask, so the admin is shown the box that approves the+ # app for their whole organisation rather than for themselves.+ "prompt": "consent",+ "state": state,+ }+ )++ async def redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:+ try:+ return await self._redeem(code=code, redirect_uri=redirect_uri)+ except (httpx.HTTPError, OSError) as error:+ # The install link is spent by now, so the person is told plainly+ # rather than shown a server error, and starts again.+ raise MessagingInstallError(+ f"Switch could not reach Microsoft to finish connecting ({error}). "+ "Nothing was saved; start again from Switch."+ ) from error++ async def _redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:+ tokens = await self._exchange(code=code, redirect_uri=redirect_uri)+ claims = await self._verified_identity(tokens.get("id_token"))+ tenant_id = str(claims["tid"])+ if tenant_id == _PERSONAL_ACCOUNTS_TENANT:+ raise MessagingInstallError(+ "That is a personal Microsoft account. Sign in with a work account "+ "from the organisation whose Teams you are connecting."+ )+ sub_scope = str(claims.get("tenant_region_sub_scope") or "")+ if sub_scope.upper() in _GOVERNMENT_SUB_SCOPES:+ raise MessagingInstallError(+ f"This organisation is in a Microsoft government cloud ({sub_scope}), "+ "which the Switch Teams app does not serve."+ )+ self._require_approving_admin(claims)+ roles = await self._granted_roles(tenant_id)++ delegated = str(tokens.get("access_token") or "")+ name = await self._organisation_name(self._app.http, delegated, tenant_id)+ platform_data = await self._publish(self._app.http, delegated, tenant_id)+ return InstallGrant(+ external_workspace_id=tenant_id,+ workspace_name=name,+ bot_token=None,+ scopes=" ".join(sorted(roles)),+ platform_data=platform_data,+ )++ async def _exchange(self, *, code: str, redirect_uri: str) -> dict[str, Any]:+ token_url = token_endpoint(_AUTHORITY)+ form = {+ "grant_type": "authorization_code",+ "client_id": self._app.app_id,+ "code": code,+ "redirect_uri": redirect_uri,+ "scope": _SCOPES,+ **await self._app.credential.form(+ app_id=self._app.app_id, token_url=token_url+ ),+ }+ response = await self._app.http.post(token_url, data=form)+ try:+ payload: dict[str, Any] = response.json()+ except ValueError as error:+ raise MessagingInstallError(+ f"Microsoft answered the sign-in with something that is not JSON "+ f"({response.status_code}). Nothing was saved."+ ) from error+ if response.status_code != 200:+ raise MessagingInstallError(+ "Microsoft refused the sign-in: "+ f"{payload.get('error_description') or payload.get('error')}. "+ "Nothing was saved."+ )+ return payload++ async def _verified_identity(self, id_token: object) -> dict[str, Any]:+ """The signed-in person's claims, from an id token Microsoft signed.++ It came straight from Microsoft over TLS, but it is verified anyway:+ its `tid` is what decides which organisation is claimed, and a value+ that decides that is not one to take on trust.+ """+ if not isinstance(id_token, str) or not id_token:+ raise MessagingInstallError(+ "Microsoft returned no id token, so the organisation cannot be "+ "told. Nothing was saved."+ )+ try:+ return await self._app.verify_id_token(id_token)+ except PermissionError as error:+ raise MessagingInstallError(+ f"Microsoft's id token could not be verified ({error}). Nothing "+ "was saved."+ ) from error+ except SigningKeysUnavailable as error:+ raise MessagingInstallError(+ "Switch could not fetch Microsoft's signing keys to check the "+ f"sign-in ({error}). Nothing was saved; start again from Switch."+ ) from error++ def _require_approving_admin(self, claims: Mapping[str, Any]) -> None:+ roles = claims.get("wids")+ if roles is None:+ raise MessagingInstallError(+ "Microsoft did not say which roles the person signing in holds, so "+ "Switch cannot check they may approve it. The Switch app "+ "registration must emit directory roles in its tokens (its "+ "groupMembershipClaims setting); this is for the deployment's "+ "operator to fix."+ )+ if not _APPROVING_ROLES & {str(role) for role in roles}:+ raise MessagingInstallError(+ "Approving Switch for an organisation needs a Microsoft Global "+ "Administrator or Privileged Role Administrator. Ask one of them "+ "to connect Teams from Switch."+ )++ async def _granted_roles(self, tenant_id: str) -> frozenset[str]:+ """Prove the organisation approved the app, by what its tokens carry.++ A token issued in the organisation lists the application permissions+ it was granted. Every one the app needs has to be there; a sign-in on+ which the admin did not approve for the organisation leaves them out.+ """+ tokens = self._app.org_tokens(tenant_id)+ for attempt in range(_APPROVAL_PROPAGATION_ATTEMPTS):+ try:+ granted = await tokens.graph_roles()+ except TokenRequestRefused as error:+ if not error.app_not_approved:+ raise MessagingInstallError(+ f"Microsoft would not issue Switch a token in this "+ f"organisation ({error}). Nothing was saved."+ ) from error+ granted = frozenset()+ missing = REQUIRED_GRAPH_ROLES - granted+ if not missing:+ return granted+ if attempt + 1 < _APPROVAL_PROPAGATION_ATTEMPTS:+ tokens.invalidate(GRAPH_SCOPE)+ await asyncio.sleep(_APPROVAL_PROPAGATION_DELAY_SECONDS)+ raise MessagingInstallError(+ "Switch was not approved for the whole organisation: "+ f"{', '.join(sorted(missing))} were not granted. Start again from "+ "Switch, and tick “Consent on behalf of your organization” on "+ "Microsoft's screen."+ )++ async def _organisation_name(+ self, http: httpx.AsyncClient, delegated: str, tenant_id: str+ ) -> str:+ try:+ response = await http.get(+ f"{_GRAPH}/organization",+ params={"$select": "displayName"},+ headers={"Authorization": f"Bearer {delegated}"},+ )+ response.raise_for_status()+ organisations = response.json().get("value") or []+ name = organisations[0].get("displayName") if organisations else None+ except (httpx.HTTPError, ValueError, AttributeError) as error:+ logger.warning(+ "Could not read the name of Microsoft organisation %s: %s",+ tenant_id,+ error,+ )+ return tenant_id+ return str(name) if name else tenant_id++ async def _publish(+ self, http: httpx.AsyncClient, delegated: str, tenant_id: str+ ) -> dict[str, object]:+ """Put the app into the organisation's catalogue, or say why not.++ Idempotent: an organisation that approved before, disconnected and is+ approving again already has the app, and is given the newer version if+ this one is. Publishing needs a Teams administrator as well as the+ approver's role, so a refusal does not fail the install — the approval+ is done — and is recorded for the connection to show.+ """+ headers = {"Authorization": f"Bearer {delegated}"}+ catalog_app_id: str | None = None+ try:+ existing = await http.get(+ f"{_GRAPH}/appCatalogs/teamsApps",+ params={+ "$filter": f"externalId eq '{self._package.manifest_id}'",+ "$expand": "appDefinitions($select=id,version,authorization)",+ },+ headers=headers,+ )+ existing.raise_for_status()+ found = existing.json().get("value") or []+ if found:+ definitions = found[0].get("appDefinitions") or []+ versions = [str(d.get("version")) for d in definitions]+ same_version = [+ d+ for d in definitions+ if str(d.get("version")) == self._package.version+ ]+ if any(_asks_per_team(d) for d in same_version):+ # Not Switch's package, which asks for nothing per team:+ # most likely one uploaded by hand under the same id. It+ # cannot be replaced at this version, and Switch cannot+ # add an app that asks per team to a team itself.+ return {+ "publish_problem": (+ "your organisation's Teams app list already has an "+ "app under Switch's id that asks for per-team "+ "permissions — probably a package uploaded by hand — "+ "and Switch cannot add that one to teams. A Teams "+ "admin should delete it (Teams admin center, Teams "+ "apps, Manage apps), then approve Switch again so it "+ "adds its own"+ )+ }+ catalog_app_id = str(found[0]["id"])+ if self._package.version not in versions:+ updated = await http.post(+ f"{_GRAPH}/appCatalogs/teamsApps/{quote(catalog_app_id, safe='')}/appDefinitions",+ content=self._package.archive,+ headers={**headers, "Content-Type": "application/zip"},+ )+ updated.raise_for_status()+ else:+ published = await http.post(+ f"{_GRAPH}/appCatalogs/teamsApps",+ content=self._package.archive,+ headers={**headers, "Content-Type": "application/zip"},+ )+ published.raise_for_status()+ catalog_app_id = str(published.json()["id"])+ except (httpx.HTTPError, ValueError, KeyError, TypeError) as error:+ reason = _graph_refusal(error)+ logger.warning(+ "Could not publish the Teams app to organisation %s's catalogue: %s",+ tenant_id,+ reason,+ )+ # What was found is kept even when giving it the newer version+ # failed: the organisation still has the app, and an id that works+ # must not be lost to an update that did not.+ if catalog_app_id is not None:+ return {"catalog_app_id": catalog_app_id, "publish_problem": reason}+ return {"publish_problem": reason}+ return {+ "catalog_app_id": catalog_app_id,+ "manifest_version": self._package.version,+ "publish_problem": None,+ }++ def connection_config(self, grant: InstallGrant) -> dict[str, object]:+ return {"event_delivery": "shared", "tenant_id": grant.external_workspace_id}++ def workspace_of_bridge(+ self, connection_config: Mapping[str, object]+ ) -> str | None:+ if connection_config.get("event_delivery") != "shared":+ return None+ tenant_id = connection_config.get("tenant_id")+ return str(tenant_id) if tenant_id is not None else None++ async def release(self, *, external_workspace_id: str) -> None:+ """Leave an organisation whose bridge is not running to leave it itself.++ The same as the bridge's own `withdraw`, from outside it: delete the+ subscriptions this app holds there and take the app out of every team+ it is in.++ Best effort, and never a refusal, unlike what the base class allows:+ Graph refuses these calls exactly when the organisation has blocked+ the app or withdrawn its approval, and a customer who has done that+ must still be able to disconnect. What is left behind is logged as an+ error. A subscription left behind runs out within the hour, since+ nothing renews it.+ """+ await self._app.withdraw_from_org(external_workspace_id)++ async def revoke(self, *, bot_token: str) -> None:+ raise NotImplementedError(+ "a Teams install has no per-install token to revoke; the app's "+ "credential is deployment config shared by every install"+ )++ def describe_callback_error(self, *, error: str, description: str | None) -> str:+ text = description or ""+ if "AADSTS65004" in text or error == "access_denied":+ return "Switch was not approved on Microsoft's screen."+ if "AADSTS90094" in text:+ return (+ "Approving Switch needs a Microsoft Global Administrator or "+ "Privileged Role Administrator. Ask one of them to connect Teams "+ "from Switch."+ )+ return f"Microsoft reported: {description or error}."++ # ── Inbound ──────────────────────────────────────────────────────────────++ def unsigned_handshake(+ self, *, endpoint: WebhookEndpoint, query: Mapping[str, str]+ ) -> str | None:+ if endpoint == "notifications":+ return query.get("validationToken")+ return None++ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:+ payload = _json(body, WebhookAuthenticityError)+ if endpoint == "events":+ try:+ await self._app.bot_authenticator.verify(+ _header(headers, "authorization"),+ service_url=str(payload.get("serviceUrl", "")).strip(),+ channel_id=str(payload.get("channelId", "")),+ )+ except PermissionError as error:+ raise WebhookAuthenticityError(str(error)) from error+ except SigningKeysUnavailable as error:+ raise WebhookVerificationUnavailable(str(error)) from error+ return+ await self._verify_notifications(payload)++ async def _verify_notifications(self, payload: Mapping[str, Any]) -> None:+ """Check every validation token the batch carries.++ A forged token refuses the whole request. The tokens vouch for the+ organisations their notifications belong to; parsing then drops any+ notification carrying data for an organisation they did not vouch for,+ rather than refusing the batch — one organisation's missing token (it+ set "assignment required" on the Switch enterprise app, and Microsoft+ stops sending one) must not cost every other organisation in the same+ batch its messages. Lifecycle notifications carry no data and usually+ no tokens; they reach the bridge they name, which checks that+ organisation's own `clientState` and that the subscription is its own+ before acting.+ """+ items = payload.get("value")+ if not isinstance(items, list):+ raise WebhookAuthenticityError("not a Graph notification collection")+ carrying_data = [+ item+ for item in items+ if isinstance(item, dict) and not item.get("lifecycleEvent")+ ]+ if not carrying_data:+ return+ tokens = payload.get("validationTokens") or []+ try:+ vouched = await self._app.notification_authenticator.vouched_tenants(+ list(tokens)+ )+ except PermissionError as error:+ raise WebhookAuthenticityError(str(error)) from error+ except SigningKeysUnavailable as error:+ raise WebhookVerificationUnavailable(str(error)) from error+ self._remember_vouched(_digest(payload), vouched)++ def parse_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ payload = _json(body, WebhookPayloadError)+ if endpoint == "events":+ return [_activity_event(payload)]+ items = payload.get("value")+ if not isinstance(items, list):+ raise WebhookPayloadError("a Graph notification collection had no value")+ vouched = self._vouched.get(_digest(payload), frozenset())+ events: list[InboundWebhook] = []+ for item in items:+ if not isinstance(item, dict):+ continue+ tenant = str(item.get("tenantId") or "")+ if not item.get("lifecycleEvent") and tenant not in vouched:+ logger.error(+ "Dropped a Graph notification for organisation %s: no "+ "validation token vouched for it. Microsoft sends none when "+ "the organisation has set “assignment required” on the Switch "+ "enterprise app.",+ tenant,+ )+ continue+ events.append(_notification_event(item))+ return events++ def _remember_vouched(self, digest: bytes, vouched: frozenset[str]) -> None:+ """Hand the organisations a batch's tokens vouched for to its parse.++ Keyed by the body, so the parse of these bytes reads what the check of+ the same bytes found, and bounded, so a parse that never comes leaves+ nothing behind for long. Read rather than removed: Graph resends a+ batch it thinks was not answered, and a copy checked while the first+ is still being parsed must find the same answer — the same bytes carry+ the same tokens, so they vouch for the same organisations.+ """+ self._vouched[digest] = vouched+ self._vouched.move_to_end(digest)+ while len(self._vouched) > _VOUCHED_KEPT:+ self._vouched.popitem(last=False)++ def workspace_of_event(self, payload: Mapping[str, object]) -> str:+ if "subscriptionId" in payload:+ tenant = payload.get("tenantId")+ else:+ tenant = activity_tenant(dict(payload))+ if not tenant:+ raise WebhookPayloadError(+ "a Teams event names no organisation, or names two"+ )+ return str(tenant)++ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:+ # Microsoft announces no organisation-wide uninstall: removal from a+ # team is per team, and goes to the bridge like any other activity.+ return None+++def _digest(payload: Mapping[str, Any]) -> bytes:+ return hashlib.sha256(+ json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()+ ).digest()+++def _json(body: bytes, error: type[Exception]) -> dict[str, Any]:+ try:+ payload = json.loads(body)+ except ValueError as failure:+ raise error(f"the body is not JSON: {failure}") from failure+ if not isinstance(payload, dict):+ raise error("the body is not a JSON object")+ return payload+++def _header(headers: Mapping[str, str], name: str) -> str | None:+ for key, value in headers.items():+ if key.lower() == name:+ return value+ return None+++def _activity_event(activity: dict[str, Any]) -> InboundWebhook:+ is_invoke = activity.get("type") == "invoke"+ tenant = activity_tenant(activity)+ conversation = str((activity.get("conversation") or {}).get("id") or "")+ activity_id = str(activity.get("id") or "")+ return InboundWebhook(+ envelope_type="activity",+ payload=activity,+ handshake=None,+ # Teams message ids are only unique within one conversation, and a+ # workspace can hold several organisations, so the key carries both.+ # A press is never keyed: it is answered inline, and a retry of one+ # has to be answered again.+ external_event_id=(+ f"{tenant}|{conversation}|{activity_id}"+ if not is_invoke and tenant and conversation and activity_id+ else None+ ),+ delivery_attempt=0,+ answers_inline=is_invoke,+ )+++def _notification_event(item: dict[str, Any]) -> InboundWebhook:+ resource = str(item.get("resource") or "")+ tenant = str(item.get("tenantId") or "")+ is_data = not item.get("lifecycleEvent")+ return InboundWebhook(+ envelope_type="notification",+ payload=item,+ handshake=None,+ # The resource names the team, the channel and the message, so the+ # same message captured twice is one key whichever subscription or+ # batch it came in.+ external_event_id=(+ f"{tenant}|{resource}|{item.get('changeType') or ''}"+ if is_data and tenant and resource+ else None+ ),+ delivery_attempt=0,+ answers_inline=False,+ )+++def _asks_per_team(definition: Mapping[str, Any]) -> bool:+ """Whether a catalogue app definition requires resource-specific consent."""+ authorization = definition.get("authorization") or {}+ permission_set = authorization.get("requiredPermissionSet") or {}+ return bool(permission_set.get("resourceSpecificPermissions"))+++def _graph_refusal(error: Exception) -> str:+ if isinstance(error, httpx.HTTPStatusError):+ response = error.response+ try:+ detail = response.json()["error"]["message"]+ except (ValueError, KeyError, TypeError):+ detail = response.text[:300]+ if response.status_code == 403:+ return (+ "the person who approved Switch is not a Teams administrator, so "+ f"Microsoft would not let Switch add the app to the organisation's "+ f"app list ({detail})"+ )+ return f"Microsoft refused ({response.status_code}): {detail}"+ return str(error)diff --git a/core/switch_core/bridges/collaboration/teams/shared_app.py b/core/switch_core/bridges/collaboration/teams/shared_app.pynew file mode 100644index 000000000..54030ecbc--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/shared_app.py@@ -0,0 +1,304 @@+"""The one deployment-level Microsoft Teams app.++The distributed Teams app is a single multi-tenant Entra app registration+backing a SingleTenant Azure Bot in our own directory (see+`TEAMS_DISTRIBUTED_APP.md`). One credential reaches every organisation that+approved it, so — like Discord's Gateway client — this object holds it, binds no+organisation, and is not a bridge. Each approving organisation gets an ordinary+bridge, and this hands that bridge what it needs to serve that organisation and+no other:++- Bot Connector tokens, issued in our own directory for every organisation,+ because that is the only directory a SingleTenant bot's tokens come from.+- Graph tokens issued in the organisation's directory, one provider each.+- The organisation's own `clientState`, derived rather than stored, so a secret+ leaked for one organisation forges nothing for another.+- The notification keyring and the authenticators for inbound activities and+ change notifications, which run before anything says which organisation a+ request is for.++It lives in the one switch-core process (a forced singleton), started at boot,+so there is never a second holder of the credential.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import logging+from typing import Any++import httpx+from cryptography.hazmat.primitives import serialization++from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.install import notifications_path, public_url+from switch_core.bridges.collaboration.teams.adapter import TeamsAdapter+from switch_core.bridges.collaboration.teams.auth import (+ BOTFRAMEWORK_OPENID,+ MICROSOFT_IDENTITY_OPENID,+ BotFrameworkAuthenticator,+ ClientCertificate,+ ClientCredential,+ ClientSecret,+ FederatedTokenFile,+ GraphNotificationAuthenticator,+ SigningKeys,+ TeamsTokenProvider,+ verify_microsoft_id_token,+)+from switch_core.bridges.collaboration.teams.crypto import (+ load_certificate_der_b64,+ load_private_key,+)+from switch_core.bridges.collaboration.teams.graph import GraphClient+from switch_core.bridges.collaboration.teams.identity import (+ BOT_CONNECTOR_HOSTS,+ REQUIRED_GRAPH_ROLES,+ NotificationKey,+ NotificationKeyring,+ OrgTokens,+ TeamsIdentity,+)+from switch_core.bridges.collaboration.teams.withdrawal import (+ delete_own_subscriptions,+ leave_every_team,+)+from switch_core.config import SwitchConfig+from switch_core.keys import Purpose++logger = logging.getLogger(__name__)++PLATFORM = "teams"++#: Distinguishes this use of the clientState secret from every other.+#: Changing it changes every organisation's clientState, which fails every+#: live subscription's origin check until it is recreated.+_CLIENT_STATE_KEY_INFO = b"switch/teams-client-state/v1"+++def _client_state_key(secret: str) -> bytes:+ return hmac.new(secret.encode(), _CLIENT_STATE_KEY_INFO, hashlib.sha256).digest()+++def client_state_for(secret: str, org_tenant_id: str) -> str:+ """The `clientState` Graph echoes on an organisation's notifications.++ Derived from the deployment secret and the organisation, so nothing is+ stored and a value learned for one organisation is useless for any other.+ Graph caps it at 128 characters; this is 43.+ """+ key = _client_state_key(secret)+ digest = hmac.new(key, org_tenant_id.encode(), hashlib.sha256).digest()+ return base64.urlsafe_b64encode(digest).decode().rstrip("=")+++def _notification_certificate_id(private_key_pem: str) -> str:+ """A label for the notification keypair, derived from the key itself.++ Graph echoes it back on every notification so the right key can be picked,+ and deriving it means a retired key needs no label of its own to be found.+ """+ public = load_private_key(private_key_pem).public_key()+ der = public.public_bytes(+ encoding=serialization.Encoding.DER,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ return "switch-" + hashlib.sha256(der).hexdigest()[:16]+++def _credential(config: SwitchConfig) -> ClientCredential:+ if config.teams_app_client_secret:+ return ClientSecret(config.teams_app_client_secret)+ if config.teams_app_certificate:+ assert config.teams_app_certificate_private_key is not None+ return ClientCertificate(+ certificate_pem=config.teams_app_certificate,+ private_key_pem=config.teams_app_certificate_private_key,+ )+ assert config.teams_app_federated_token_file is not None+ return FederatedTokenFile(config.teams_app_federated_token_file)+++class TeamsSharedApp:+ def __init__(+ self,+ *,+ app_id: str,+ home_tenant_id: str,+ credential: ClientCredential,+ keyring: NotificationKeyring,+ messaging_public_url: str,+ client_state_secret: str,+ http: httpx.AsyncClient,+ ) -> None:+ self._app_id = app_id+ self._credential = credential+ self._keyring = keyring+ # The clientState key's fingerprint rides on the notification URL, so+ # rotating SECRET_KEYS changes the URL too: every subscription made+ # under the old key then reads as stale at the next start and is+ # remade, instead of being kept, renewed and failing every origin check+ # with nothing to point at why.+ fingerprint = hashlib.sha256(_client_state_key(client_state_secret)).hexdigest()+ self._notification_url = (+ public_url(messaging_public_url, notifications_path(PLATFORM))+ + f"?v={fingerprint[:12]}"+ )+ self._client_state_secret = client_state_secret+ self._http = http+ self._home_tokens = TeamsTokenProvider(+ tenant_id=home_tenant_id, app_id=app_id, credential=credential, http=http+ )+ self._org_tokens: dict[str, TeamsTokenProvider] = {}+ self.bot_authenticator = BotFrameworkAuthenticator(+ app_id=app_id,+ keys=SigningKeys(metadata_url=BOTFRAMEWORK_OPENID, http=http),+ )+ # One set of Microsoft identity platform keys signs both Graph's+ # validation tokens and the id token an approving admin signs in with.+ self._identity_keys = SigningKeys(+ metadata_url=MICROSOFT_IDENTITY_OPENID, http=http+ )+ self.notification_authenticator = GraphNotificationAuthenticator(+ app_id=app_id, keys=self._identity_keys+ )++ @classmethod+ def from_config(cls, config: SwitchConfig) -> TeamsSharedApp:+ assert config.teams_app_client_id is not None+ assert config.teams_app_tenant_id is not None+ assert config.teams_app_notification_certificate is not None+ assert config.teams_app_notification_private_key is not None+ assert config.messaging_public_url is not None+ current = NotificationKey(+ certificate_id=_notification_certificate_id(+ config.teams_app_notification_private_key+ ),+ private_key=load_private_key(config.teams_app_notification_private_key),+ )+ retired: tuple[NotificationKey, ...] = ()+ if config.teams_app_notification_previous_private_key:+ retired = (+ NotificationKey(+ certificate_id=_notification_certificate_id(+ config.teams_app_notification_previous_private_key+ ),+ private_key=load_private_key(+ config.teams_app_notification_previous_private_key+ ),+ ),+ )+ return cls(+ app_id=config.teams_app_client_id,+ home_tenant_id=config.teams_app_tenant_id,+ credential=_credential(config),+ keyring=NotificationKeyring(+ current=current,+ certificate_der_b64=load_certificate_der_b64(+ config.teams_app_notification_certificate+ ),+ retired=retired,+ ),+ messaging_public_url=config.messaging_public_url,+ client_state_secret=config.keyring.derive(Purpose.TEAMS_CLIENT_STATE).hex(),+ http=httpx.AsyncClient(timeout=30),+ )++ @property+ def app_id(self) -> str:+ return self._app_id++ @property+ def http(self) -> httpx.AsyncClient:+ return self._http++ @property+ def credential(self) -> ClientCredential:+ return self._credential++ async def verify_id_token(self, id_token: str) -> dict[str, Any]:+ """The claims of an id token Microsoft issued to this app, verified.++ Checked as Microsoft asks of a multi-tenant app: signed by a Microsoft+ identity platform key, addressed to this app, current, and issued by+ the organisation it names — the issuer carries the organisation's id,+ so a token from one organisation cannot claim to be another's.+ """+ return await verify_microsoft_id_token(+ id_token, app_id=self._app_id, keys=self._identity_keys+ )++ def client_state_for(self, org_tenant_id: str) -> str:+ return client_state_for(self._client_state_secret, org_tenant_id)++ def org_tokens(self, org_tenant_id: str) -> TeamsTokenProvider:+ """The provider of Graph tokens issued in one organisation's directory."""+ provider = self._org_tokens.get(org_tenant_id)+ if provider is None:+ provider = TeamsTokenProvider(+ tenant_id=org_tenant_id,+ app_id=self._app_id,+ credential=self._credential,+ http=self._http,+ )+ self._org_tokens[org_tenant_id] = provider+ return provider++ def forget_org(self, org_tenant_id: str) -> None:+ """Drop an organisation's token provider, its bridge having been removed.++ Built again on demand if the organisation approves the app once more.+ """+ self._org_tokens.pop(org_tenant_id, None)++ def tokens_for(self, org_tenant_id: str) -> OrgTokens:+ return OrgTokens(home=self._home_tokens, org=self.org_tokens(org_tenant_id))++ def identity_for(self, org_tenant_id: str) -> TeamsIdentity:+ return TeamsIdentity(+ app_id=self._app_id,+ org_tenant_id=org_tenant_id,+ shared=True,+ notification_url=self._notification_url,+ client_state=self.client_state_for(org_tenant_id),+ keyring=self._keyring,+ allowed_service_hosts=BOT_CONNECTOR_HOSTS,+ required_graph_roles=REQUIRED_GRAPH_ROLES,+ )++ async def withdraw_from_org(self, org_tenant_id: str) -> None:+ """Delete this app's subscriptions in an organisation and leave its teams.++ For an organisation whose bridge is not running to do it itself+ (`TeamsAdapter.withdraw`). Every subscription the app holds there that+ delivers to this deployment goes — whichever clientState key it was+ made under — and the app is taken out of every team it is in. Best+ effort, item by item: what could not be undone is logged.+ """+ graph = GraphClient(tokens=self.tokens_for(org_tenant_id), http=self._http)+ left_behind = await delete_own_subscriptions(+ graph, identity=self.identity_for(org_tenant_id), known=()+ )+ left_behind += await leave_every_team(graph, app_id=self._app_id)+ self.forget_org(org_tenant_id)+ if left_behind:+ logger.error(+ "Leaving Microsoft organisation %s left behind: %s",+ org_tenant_id,+ "; ".join(left_behind),+ )++ def attach_if_teams(self, adapter: PlatformAdapter) -> None:+ """Hand a starting Teams bridge on the distributed app this app.++ Registered as a bridge-starting listener, so it runs before the bridge+ does anything. Unconditional, unlike Discord's: there is no socket to+ wait for, so a bridge never starts without what it needs.+ """+ if isinstance(adapter, TeamsAdapter) and adapter.serves_shared_app:+ adapter.attach_shared_app(self)++ async def aclose(self) -> None:+ await self._http.aclose()diff --git a/core/switch_core/bridges/collaboration/teams/withdrawal.py b/core/switch_core/bridges/collaboration/teams/withdrawal.pynew file mode 100644index 000000000..0e6640c2f--- /dev/null+++ b/core/switch_core/bridges/collaboration/teams/withdrawal.py@@ -0,0 +1,71 @@+"""Letting go of an organisation: what a removed Teams bridge leaves behind.++Shared by a bridge removing itself (`TeamsAdapter.withdraw`) and the+deployment's app doing it for a bridge that is not running+(`TeamsSharedApp.withdraw_from_org`), so the two leave the same nothing behind.++Best effort, item by item: a removal is what someone asked for and goes ahead+whatever these manage, so one subscription or team that cannot be undone is+reported and the rest are still tried. Each returns what it could not do, in+words fit for a log line.+"""++from __future__ import annotations++from collections.abc import Iterable++from switch_core.bridges.collaboration.teams.graph import GraphClient+from switch_core.bridges.collaboration.teams.identity import TeamsIdentity+++async def delete_own_subscriptions(+ graph: GraphClient, *, identity: TeamsIdentity, known: Iterable[str]+) -> list[str]:+ """Delete every subscription that delivers to this deployment.++ `known` are the ones the bridge holds; Graph is asked as well, so one the+ bridge failed to adopt goes too, whichever clientState key it was made+ under.+ """+ subscription_ids = set(known)+ left_behind: list[str] = []+ try:+ for sub in await graph.list_subscriptions():+ if identity.delivers_here(str(sub.get("notificationUrl") or "")):+ subscription_ids.add(str(sub.get("id") or ""))+ except Exception as error:+ left_behind.append(f"listing subscriptions failed ({error})")+ for subscription_id in sorted(s for s in subscription_ids if s):+ try:+ await graph.delete_subscription(subscription_id=subscription_id)+ except Exception as error:+ left_behind.append(f"subscription {subscription_id} ({error})")+ return left_behind+++async def leave_every_team(graph: GraphClient, *, app_id: str) -> list[str]:+ """Take the app out of every team in the organisation it is in.++ Every team, not only those the bridge learned of: an install whose join+ was never seen would otherwise stay, unable to answer. Each team is asked+ on its own, since nothing answers this for the organisation at once.+ """+ left_behind: list[str] = []+ try:+ teams = await graph.list_teams()+ except Exception as error:+ return [f"listing the organisation's teams failed ({error})"]+ for team in teams:+ team_id = str(team.get("id") or "")+ if not team_id:+ continue+ try:+ for installation in await graph.find_app_installations(+ team_id=team_id, external_id=app_id+ ):+ await graph.uninstall_app(+ team_id=team_id, installation_id=installation.installation_id+ )+ except Exception as error:+ left_behind.append(f"the app in team {team_id} ({error})")+ return left_behinddiff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex c45238276..0262071ce 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -7,6 +7,9 @@ from pathlib import Pathfrom typing import Literalfrom urllib.parse import urlsplit+from cryptography import x509+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsafrom pydantic import AliasChoices, Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -21,6 +24,52 @@ _PG_INTERVAL_RE = re.compile(r"^\d+\s*(us|ms|s|min|h|d)?$")# worth catching at startup rather than at the first `GRANT`. The 63-character# cap matches Postgres's own `NAMEDATALEN` limit._DB_ROLE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")+# The longest short name a Teams app manifest takes.+_TEAMS_APP_SHORT_NAME_LIMIT = 30+++def _require_rsa_private_key(name: str, pem: str) -> rsa.RSAPrivateKey:+ """Parse an RSA private key from a setting, or say which setting is wrong.++ RSA because both of the Teams app's keypairs are used where Microsoft only+ takes RSA: Graph wraps a notification's key with RSA-OAEP, and the+ certificate credential is checked against an RSA signature.+ """+ try:+ key = serialization.load_pem_private_key(pem.encode(), password=None)+ except (ValueError, TypeError) as error:+ raise ValueError(+ f"{name} is not an unencrypted PEM private key: {error}"+ ) from error+ if not isinstance(key, rsa.RSAPrivateKey):+ raise ValueError(f"{name} must be an RSA key, got {type(key).__name__}.")+ return key+++def _require_matching_keypair(+ certificate_name: str, certificate_pem: str, key_name: str, key_pem: str+) -> None:+ """Refuse a certificate paired with a key that is not its own.++ The mismatch is otherwise silent until it matters: Microsoft rejects every+ token request signed with the wrong key, or Graph encrypts every captured+ message to a key Switch does not hold.+ """+ try:+ certificate = x509.load_pem_x509_certificate(certificate_pem.encode())+ except ValueError as error:+ raise ValueError(+ f"{certificate_name} is not a PEM certificate: {error}"+ ) from error+ key = _require_rsa_private_key(key_name, key_pem)+ public = serialization.PublicFormat.SubjectPublicKeyInfo+ if certificate.public_key().public_bytes(+ serialization.Encoding.DER, public+ ) != key.public_key().public_bytes(serialization.Encoding.DER, public):+ raise ValueError(+ f"{certificate_name} and {key_name} are not a pair: the key does "+ "not match the certificate's public key."+ )class SwitchConfig(BaseSettings):@@ -431,6 +480,49 @@ class SwitchConfig(BaseSettings):# riding message content's, because the two are approved independently.discord_app_members: bool = False+ # The distributed Microsoft Teams app (`TEAMS_DISTRIBUTED_APP.md`): one+ # multi-tenant Entra app registration, backing a SingleTenant Azure Bot in+ # *our* directory, that a customer's Microsoft admin approves for their+ # organisation. Distinct from the bring-your-own Teams app, whose+ # credentials an operator pastes into a bridge.+ #+ # Like Discord, Microsoft grants no per-install credential: the app's one+ # credential reaches every organisation that approved it, so it lives here+ # and never in a bridge row. Setting the app id enables installs; setting+ # some of what it needs and not the rest is a startup error.+ teams_app_client_id: str | None = None+ # Our own directory, where the bot is registered. Bot Connector tokens for+ # a SingleTenant bot can only come from here, so it is a directory id —+ # never `common` or `organizations`.+ teams_app_tenant_id: str | None = None++ # How the app proves who it is to Microsoft: exactly one of a client+ # secret, a certificate with its private key, or a workload-identity token+ # file (a federated credential, so no secret exists at all). A secret is+ # the simplest and expires; the other two are what a deployment should run.+ teams_app_client_secret: str | None = None+ teams_app_certificate: str | None = None+ teams_app_certificate_private_key: str | None = None+ teams_app_federated_token_file: str | None = None++ # The keypair Graph encrypts captured channel messages to. One per+ # deployment rather than per bridge: a notification has to be decrypted+ # before anything says which organisation it belongs to. The previous key+ # is kept only while subscriptions made against it run out after a+ # rotation, and is otherwise unset.+ teams_app_notification_certificate: str | None = None+ teams_app_notification_private_key: str | None = None+ teams_app_notification_previous_private_key: str | None = None+ # Where the app's privacy statement and terms of use live. Every Teams app+ # package has to name both, and they are shown to the admin approving it,+ # so they are the deployment's to state rather than a placeholder of ours.+ teams_app_privacy_url: str | None = None+ teams_app_terms_url: str | None = None+ # The name the app goes by in Teams. Every environment registers an app of+ # its own, and an organisation approving more than one — ours, testing+ # them — would otherwise see several apps of the same name.+ teams_app_name: str = "Agent Switch"+# Public origin (scheme + host, no path) that a messaging platform reaches# Switch on: the base of the OAuth redirect and of the three event URLs# under `/messaging`, and the one registered with the app.@@ -1138,6 +1230,149 @@ class SwitchConfig(BaseSettings):def trust_enabled(self) -> bool:return bool(self.switch_trust_api_key and self.switch_trust_policy_id)+ @model_validator(mode="after")+ def _validate_teams_app(self) -> "SwitchConfig":+ settings = {+ "TEAMS_APP_CLIENT_ID": self.teams_app_client_id,+ "TEAMS_APP_TENANT_ID": self.teams_app_tenant_id,+ "TEAMS_APP_CLIENT_SECRET": self.teams_app_client_secret,+ "TEAMS_APP_CERTIFICATE": self.teams_app_certificate,+ "TEAMS_APP_CERTIFICATE_PRIVATE_KEY": self.teams_app_certificate_private_key,+ "TEAMS_APP_FEDERATED_TOKEN_FILE": self.teams_app_federated_token_file,+ "TEAMS_APP_NOTIFICATION_CERTIFICATE": (+ self.teams_app_notification_certificate+ ),+ "TEAMS_APP_NOTIFICATION_PRIVATE_KEY": (+ self.teams_app_notification_private_key+ ),+ "TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY": (+ self.teams_app_notification_previous_private_key+ ),+ "TEAMS_APP_PRIVACY_URL": self.teams_app_privacy_url,+ "TEAMS_APP_TERMS_URL": self.teams_app_terms_url,+ }+ if not any(settings.values()):+ return self++ missing = [+ name+ for name in (+ "TEAMS_APP_CLIENT_ID",+ "TEAMS_APP_TENANT_ID",+ "TEAMS_APP_NOTIFICATION_CERTIFICATE",+ "TEAMS_APP_NOTIFICATION_PRIVATE_KEY",+ "TEAMS_APP_PRIVACY_URL",+ "TEAMS_APP_TERMS_URL",+ )+ if not settings[name]+ ]+ if missing:+ raise ValueError(+ "Partial distributed Teams app config: "+ f"{' / '.join(missing)} must be set as well. The app needs its "+ "id, the directory its bot is registered in, the keypair Graph "+ "encrypts captured messages to, and the privacy and terms pages "+ "its package names."+ )+ app_name = self.teams_app_name+ if (+ not app_name+ or app_name != app_name.strip()+ or len(app_name) > _TEAMS_APP_SHORT_NAME_LIMIT+ ):+ raise ValueError(+ f"TEAMS_APP_NAME must be 1 to {_TEAMS_APP_SHORT_NAME_LIMIT} "+ "characters with no spaces around it; Teams refuses an app "+ f"package whose short name is longer, got {app_name!r}."+ )+ for name in ("TEAMS_APP_PRIVACY_URL", "TEAMS_APP_TERMS_URL"):+ parts = urlsplit(str(settings[name]))+ if parts.scheme != "https" or not parts.netloc:+ raise ValueError(+ f"{name} must be an https URL; Teams refuses an app package "+ f"naming anything else, got {settings[name]!r}."+ )++ try:+ uuid.UUID(str(self.teams_app_tenant_id))+ except ValueError as error:+ raise ValueError(+ "TEAMS_APP_TENANT_ID must be the id of the directory the bot is "+ "registered in (a GUID). A SingleTenant bot can only be issued "+ "tokens there, so `common` or `organizations` cannot work, got "+ f"{self.teams_app_tenant_id!r}."+ ) from error++ if bool(self.teams_app_certificate) != bool(+ self.teams_app_certificate_private_key+ ):+ raise ValueError(+ "TEAMS_APP_CERTIFICATE and TEAMS_APP_CERTIFICATE_PRIVATE_KEY must "+ "be set together: the certificate names the credential to "+ "Microsoft and the key signs with it."+ )+ kinds = [+ name+ for name, chosen in (+ ("TEAMS_APP_CLIENT_SECRET", self.teams_app_client_secret),+ ("TEAMS_APP_CERTIFICATE", self.teams_app_certificate),+ ("TEAMS_APP_FEDERATED_TOKEN_FILE", self.teams_app_federated_token_file),+ )+ if chosen+ ]+ if len(kinds) != 1:+ raise ValueError(+ "The distributed Teams app needs exactly one credential: "+ "TEAMS_APP_CLIENT_SECRET, TEAMS_APP_CERTIFICATE (with its private "+ "key), or TEAMS_APP_FEDERATED_TOKEN_FILE. "+ + (f"Got {', '.join(kinds)}." if kinds else "Got none.")+ )++ if self.teams_app_certificate:+ assert self.teams_app_certificate_private_key is not None+ _require_matching_keypair(+ "TEAMS_APP_CERTIFICATE",+ self.teams_app_certificate,+ "TEAMS_APP_CERTIFICATE_PRIVATE_KEY",+ self.teams_app_certificate_private_key,+ )+ assert self.teams_app_notification_certificate is not None+ assert self.teams_app_notification_private_key is not None+ _require_matching_keypair(+ "TEAMS_APP_NOTIFICATION_CERTIFICATE",+ self.teams_app_notification_certificate,+ "TEAMS_APP_NOTIFICATION_PRIVATE_KEY",+ self.teams_app_notification_private_key,+ )+ if self.teams_app_notification_previous_private_key:+ _require_rsa_private_key(+ "TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY",+ self.teams_app_notification_previous_private_key,+ )+ if (+ self.teams_app_federated_token_file+ and not Path(self.teams_app_federated_token_file).is_file()+ ):+ raise ValueError(+ "TEAMS_APP_FEDERATED_TOKEN_FILE names "+ f"{self.teams_app_federated_token_file!r}, which is not a file. "+ "It is the projected service-account token the app presents to "+ "Microsoft in place of a secret, and is mounted before Switch "+ "starts."+ )++ # The bot's messaging endpoint and Graph's notification URL are both+ # built from the public origin, and Microsoft calls them from the+ # internet. Without it there is nothing to register with the bot.+ if not self.messaging_public_url:+ raise ValueError(+ "A distributed Teams app is configured but MESSAGING_PUBLIC_URL "+ "is not. The bot's messaging endpoint, the notification URL Graph "+ "delivers captured messages to, and the approval redirect are "+ "all built from it."+ )+ return self+@propertydef gateway_oidc_enabled(self) -> bool:return bool(diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 483927269..47084f516 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -1,6 +1,7 @@import uuidfrom datetime import datetimefrom enum import StrEnum+from typing import Anyfrom sqlalchemy import (DDL,@@ -1812,6 +1813,13 @@ class MessagingInstall(TenantScoped, Base):verbatim rather than parsed into a list — a scope string that meansnothing to us is still the thing to show an operator asking why a call wasrefused.++ `platform_data` is what one platform needs to remember about an install+ and no other platform has: Teams' id for the app in the customer's own+ catalogue, say, which differs per organisation and is needed to act on it+ later. Never a secret — those have a column, and an encryption — and never+ in the bridge's connection config, which a workspace admin can edit. Empty+ for a platform that has nothing to keep."""__tablename__ = "messaging_installs"@@ -1848,6 +1856,9 @@ class MessagingInstall(TenantScoped, Base):ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ platform_data: Mapped[dict[str, Any]] = mapped_column(+ JSONB, nullable=False, server_default=text("'{}'::jsonb")+ )class MessagingInstallState(TenantScoped, Base):diff --git a/core/switch_core/db/stores/collaboration_bridge_store.py b/core/switch_core/db/stores/collaboration_bridge_store.pyindex 90dd8593c..420703eea 100644--- a/core/switch_core/db/stores/collaboration_bridge_store.py+++ b/core/switch_core/db/stores/collaboration_bridge_store.py@@ -135,10 +135,10 @@ class CollaborationBridgeStore:Merging rather than replacing means an operator can flip one settingwithout re-sending the platform's tokens. Reassigns the dict so- SQLAlchemy tracks the change."""- bridge = await session.get(CollaborationBridge, bridge_id)- if bridge is None:- raise ValueError(f"Bridge not found: {bridge_id}")+ SQLAlchemy tracks the change. Merged into the row as it is now, under+ its lock, not as this session first read it: a bridge may have learned+ and persisted something since."""+ bridge = await self._locked_for_config_update(session, bridge_id)bridge.connection_config = {**(bridge.connection_config or {}), **changes}await session.flush()return bridge@@ -160,10 +160,13 @@ class CollaborationBridgeStore:state that makes Graph refuse that channel's subscription after thenext restart, which is the failure the entry exists to prevent."""+ # `populate_existing`, because a row this session already holds would+ # otherwise come back as it was first read, lock or no lock.row = await session.execute(select(CollaborationBridge).where(CollaborationBridge.id == bridge_id).with_for_update()+ .execution_options(populate_existing=True))bridge = row.scalar_one_or_none()if bridge is None:diff --git a/core/switch_core/db/stores/messaging_install_store.py b/core/switch_core/db/stores/messaging_install_store.pyindex feb1b50a5..19c5091a4 100644--- a/core/switch_core/db/stores/messaging_install_store.py+++ b/core/switch_core/db/stores/messaging_install_store.py@@ -1,5 +1,6 @@from __future__ import annotations+from collections.abc import Mappingfrom datetime import UTC, datetime, timedeltafrom sqlalchemy import select, update@@ -156,6 +157,7 @@ class MessagingInstallStore:external_workspace_id: str,encrypted_bot_token: str | None,scopes: str,+ platform_data: Mapping[str, object],user_id: str,) -> MessagingInstall:"""Claim a workspace for the bound tenant.@@ -180,6 +182,7 @@ class MessagingInstallStore:external_workspace_id=external_workspace_id,encrypted_bot_token=encrypted_bot_token,scopes=scopes,+ platform_data=dict(platform_data),status=INSTALL_ACTIVE,installed_by_user_id=user_id,)@@ -191,9 +194,9 @@ class MessagingInstallStore:raiseraise MessagingInstallClaimedError(f"the {platform} workspace {external_workspace_id} is already "- "connected to Switch. Disconnect the existing install — from "- "the organisation that holds it, which may not be yours — "- "before connecting it again."+ "connected to a Switch workspace, possibly another one, and "+ "possibly one you do not belong to. Disconnect it from that "+ "Switch workspace before connecting it again.") from excreturn install@@ -268,6 +271,53 @@ class MessagingInstallStore:)return list(result.scalars())+ async def refresh(+ self,+ session: AsyncSession,+ *,+ install_id: str,+ scopes: str,+ platform_data: Mapping[str, object],+ ) -> MessagingInstall:+ """Record what a repeated approval of a live install granted.++ For a platform with no per-install token, approving again is how an+ organisation grants new permissions, takes a newer version of the app,+ or restores an approval it withdrew — and the install it refreshes is+ the same one, still serving, so nothing about who holds the workspace+ changes.+ """+ install = await self.get(session, install_id=install_id)+ if install.status != INSTALL_ACTIVE:+ raise MessagingInstallStateError(+ "this install has ended, so it cannot be approved again; install "+ "it afresh instead"+ )+ install.scopes = scopes+ # Merged over what is kept rather than replacing it: a repeated+ # approval that could not re-learn something (an id it failed to read+ # this time) must not erase what an earlier one learned.+ install.platform_data = {**install.platform_data, **platform_data}+ await session.flush()+ return install++ async def remember(+ self,+ session: AsyncSession,+ *,+ install_id: str,+ platform_data: Mapping[str, object],+ ) -> MessagingInstall:+ """Add to what a live install keeps about its platform.++ For a fact learned after the install, from the platform itself —+ never from a person's input.+ """+ install = await self.get(session, install_id=install_id)+ install.platform_data = {**install.platform_data, **platform_data}+ await session.flush()+ return install+async def end(self, session: AsyncSession, *, install_id: str, status: str) -> MessagingInstall:diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 63f76e311..44e79d9b4 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -64,6 +64,7 @@ from switch_core.gateway.references import router as references_routerfrom switch_core.gateway.room_groups import router as room_groups_routerfrom switch_core.gateway.room_links import router as room_links_routerfrom switch_core.gateway.rooms import router as rooms_router+from switch_core.gateway.teams_placements import router as teams_placements_routerfrom switch_core.gateway.template_runs import router as template_runs_routerfrom switch_core.gateway.templates import router as templates_routerfrom switch_core.gateway.tenants import router as tenants_router@@ -206,6 +207,9 @@ def create_gateway_app(app.include_router(collaborations_router, prefix="/collaborations", tags=["collaborations"])+ app.include_router(+ teams_placements_router, prefix="/collaborations", tags=["collaborations"]+ )app.include_router(connectors_router, prefix="/connectors", tags=["connectors"])app.include_router(api_keys_router, prefix="/api-keys", tags=["api-keys"])app.include_router(references_router, tags=["references"])diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 842f0406e..d9576df80 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -9,7 +9,10 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import ValidationErrorfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.bridges.collaboration.adapter import DirectorySearchBusy+from switch_core.bridges.collaboration.adapter import (+ ConfigEditRefused,+ DirectorySearchBusy,+)from switch_core.bridges.collaboration.lifecycle_service import (BridgeClaimConflict,CollaborationBridgeLifecycleService,@@ -17,6 +20,8 @@ from switch_core.bridges.collaboration.lifecycle_service import (from switch_core.bridges.collaboration.models import (BridgeCredentialError,BridgeInstallLink,+ BridgeNotRunning,+ BridgeOperationError,BridgeStartRefused,DirectoryUser,)@@ -119,6 +124,30 @@ async def _install_note(return None+async def _attention(+ bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService+) -> str | None:+ """What a workspace admin must do for the bridge to keep working, from the+ live adapter. None when the bridge is not running or nothing is wrong."""+ adapter = collab_lifecycle.get_adapter(bridge_id)+ if adapter is None:+ return None+ try:+ return await adapter.attention()+ except Exception:+ logger.warning(+ "Failed to read the attention note for bridge %s", bridge_id, exc_info=True+ )+ return None+++def _places_app_in_teams(+ bridge_id: str, collab_lifecycle: CollaborationBridgeLifecycleService+) -> bool:+ adapter = collab_lifecycle.get_adapter(bridge_id)+ return adapter is not None and adapter.places_app_in_teams++async def _detail(bridge: CollaborationBridge,*,@@ -149,6 +178,8 @@ async def _detail(directory_search_supported=collab_lifecycle.supports_directory_search(bridge.type),+ attention=await _attention(bridge.id, collab_lifecycle),+ team_placement_supported=_places_app_in_teams(bridge.id, collab_lifecycle),)@@ -335,6 +366,24 @@ async def update_bridge(status_code=422,detail="event_delivery cannot be changed on an existing connection.",)+ # A connection on an app the deployment owns may hold settings that+ # decide where the deployment's credential is pointed; only the ones+ # its adapter names are anyone's to change.+ editable = collab_lifecycle.editable_config_keys(bridge.type, current)+ if editable is not None:+ locked = sorted(+ key+ for key, value in payload.connection_config.items()+ if key not in editable and current.get(key) != value+ )+ if locked:+ raise HTTPException(+ status_code=422,+ detail=(+ f"{', '.join(locked)} cannot be changed on this "+ "connection: Switch manages it for the installed app."+ ),+ )# Not held across the platform's credential check; nothing is written# until it passes, so a refused edit still changes nothing.await session.commit()@@ -357,6 +406,19 @@ async def update_bridge(raise HTTPException(status_code=422, detail=str(exc)) from excexcept (BridgeClaimConflict, BridgeCredentialError) as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ try:+ await collab_lifecycle.check_config_edit(+ bridge_id=bridge_id,+ bridge_type=bridge.type,+ current=current,+ connection_config=merged,+ )+ except ConfigEditRefused as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ except BridgeNotRunning as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ except BridgeOperationError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from excif payload.agent_greetings_enabled is not None:bridge = await bridge_store.set_agent_greetings_enabled(diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 9a1c92e1c..671cc7ad1 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -517,6 +517,15 @@ class BridgeDetail(BaseModel):# What those links do not cover, in the platform's own terms — the kinds of# chat that have to be joined by hand. None when there is nothing to add.install_note: str | None = None+ # Something only the platform's side can fix, found while the bridge runs+ # — an approval withdrawn, the app blocked by the organisation's admin — in+ # plain words for a banner on the connection. None while nothing is known+ # to be wrong, or the bridge is not running.+ attention: str | None = None+ # Whether the workspace chooses, here, which of the platform's teams the+ # connection's app is in (the distributed Teams app); see+ # `/collaborations/{id}/teams`. False while the bridge is not running.+ team_placement_supported: bool = False# Whether the platform can create a channel from Switch at all, and whether# an operator permits this connection to. The two are separate so a UI can# tell "your organisation turned this off" (changeable here) from "Telegramdiff --git a/core/switch_core/gateway/teams_placements.py b/core/switch_core/gateway/teams_placements.pynew file mode 100644index 000000000..a5b40baf4--- /dev/null+++ b/core/switch_core/gateway/teams_placements.py@@ -0,0 +1,301 @@+"""Which teams the distributed Teams app is in, from Switch.++A Microsoft admin approves the app for the whole organisation, and Switch adds+it to the organisation's app catalogue; which teams it then joins is chosen+here, on the connection, by the workspace's own admins. The team new channels+go in — the connection's default team — is an ordinary edit of the connection+(`PATCH /collaborations/{id}`), the one setting of a shared Teams bridge that+is anyone's to change.++Everything here is refused for a connection that is not on the distributed+app: a bring-your-own app is added to teams in Teams, by whoever owns it.+"""++from __future__ import annotations++import logging+from typing import Annotated++import httpx+from fastapi import APIRouter, Depends, HTTPException, Response+from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.bridges.collaboration.install import MessagingInstallError+from switch_core.bridges.collaboration.install_service import MessagingInstallService+from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.bridges.collaboration.models import BridgeOperationError+from switch_core.bridges.collaboration.teams.adapter import TeamsAdapter+from switch_core.bridges.collaboration.teams.auth import TokenRequestRefused+from switch_core.bridges.collaboration.teams.install import TeamsAppInstaller+from switch_core.db.models import MessagingInstall, User+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.gateway.auth import require_tenant_admin+from switch_core.gateway.dependencies import (+ get_bridge_store,+ get_collab_lifecycle,+ get_install_service,+ get_install_store,+ get_session,+)++logger = logging.getLogger(__name__)++router = APIRouter()+++class TeamPlacementOut(BaseModel):+ team_id: str+ name: str+ # None when the team's apps could not be read (archived, being deleted,+ # restricted); the rest of the list is still answered.+ has_switch: bool | None+ is_default: bool+++class TeamPlacements(BaseModel):+ teams: list[TeamPlacementOut]+ default_team_id: str | None+ # Whether the app is in the organisation's catalogue, which adding it to a+ # team needs. When it is not, `catalog_problem` says why, and the package+ # can be downloaded for a Teams admin to upload.+ in_catalog: bool+ catalog_problem: str | None+++async def _connection(+ bridge_id: str,+ session: AsyncSession,+ bridge_store: CollaborationBridgeStore,+ install_store: MessagingInstallStore,+ collab_lifecycle: CollaborationBridgeLifecycleService,+) -> tuple[TeamsAdapter, MessagingInstall]:+ """The running shared Teams bridge and its install, if both are the caller's.++ The bridge is read on the caller's own scoped session, so another tenant's+ is simply not found.+ """+ bridge = await bridge_store.get(session, bridge_id)+ install = await install_store.get_for_bridge(session, bridge_id=bridge_id)+ if bridge is None or install is None or bridge.type != "teams":+ raise HTTPException(+ status_code=404,+ detail="No connection on the distributed Teams app has that id.",+ )+ # Connected, not merely registered: a bridge restarting — as it does after+ # its default team changes — is registered before it has a Graph client.+ adapter = collab_lifecycle.get_adapter(bridge_id)+ if not isinstance(adapter, TeamsAdapter) or not collab_lifecycle.is_connected(+ bridge_id+ ):+ raise HTTPException(+ status_code=503,+ detail="The Teams connection is not running; try again in a moment.",+ )+ return adapter, install+++def _catalog_app_id(install: MessagingInstall) -> str | None:+ value = install.platform_data.get("catalog_app_id")+ return str(value) if value else None+++#: What Microsoft can answer a placement request with that is its refusal or+#: its absence rather than a fault here: shown to the admin, never a 500.+_MICROSOFT_FAILURES = (BridgeOperationError, TokenRequestRefused, httpx.HTTPError)+++def _microsoft_failed(error: Exception) -> HTTPException:+ return HTTPException(status_code=502, detail=f"Microsoft refused: {error}")+++async def _learn_catalog_app_id(+ session: AsyncSession,+ install_store: MessagingInstallStore,+ install: MessagingInstall,+ seen: str | None,+) -> str | None:+ """The app's catalogue id, recording it if an installation just revealed it.++ Switch learns the id when it publishes the app itself. When a Teams admin+ uploaded the package by hand instead, the first team the app is added to+ — from Teams — reports it, and from then on Switch can add the app to the+ rest.+ """+ known = _catalog_app_id(install)+ if known is not None or seen is None:+ return known+ await install_store.remember(+ session,+ install_id=install.id,+ platform_data={"catalog_app_id": seen, "publish_problem": None},+ )+ await session.commit()+ return seen++[email protected]("/{bridge_id}/teams")+async def list_team_placements(+ bridge_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],+ install_store: Annotated[MessagingInstallStore, Depends(get_install_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> TeamPlacements:+ adapter, install = await _connection(+ bridge_id, session, bridge_store, install_store, collab_lifecycle+ )+ try:+ placements = await adapter.list_team_placements()+ except _MICROSOFT_FAILURES as error:+ raise _microsoft_failed(error) from error+ catalog_app_id = await _learn_catalog_app_id(+ session, install_store, install, placements.catalog_app_id+ )+ default = adapter.default_team_id+ problem = install.platform_data.get("publish_problem")+ return TeamPlacements(+ teams=[+ TeamPlacementOut(+ team_id=p.team_id,+ name=p.name,+ has_switch=p.has_switch,+ is_default=p.team_id == default,+ )+ for p in placements.teams+ ],+ default_team_id=default,+ in_catalog=catalog_app_id is not None,+ catalog_problem=str(problem) if problem and catalog_app_id is None else None,+ )++[email protected]("/{bridge_id}/teams/{team_id}", status_code=204)+async def add_to_team(+ bridge_id: str,+ team_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],+ install_store: Annotated[MessagingInstallStore, Depends(get_install_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> Response:+ adapter, install = await _connection(+ bridge_id, session, bridge_store, install_store, collab_lifecycle+ )+ catalog_app_id = _catalog_app_id(install)+ try:+ if catalog_app_id is None:+ placements = await adapter.list_team_placements()+ catalog_app_id = await _learn_catalog_app_id(+ session, install_store, install, placements.catalog_app_id+ )+ if catalog_app_id is None:+ raise HTTPException(+ status_code=409,+ detail=(+ "Switch cannot add itself to a team until it knows where the "+ "app is in your organisation's Teams app list. Once a Teams "+ "admin has uploaded it, add it to any one team from Teams "+ "(Apps, Built for your org, Agent Switch) and Switch can add "+ "it to the rest; or have a Global Administrator approve "+ "Switch again, so Switch puts it in the list itself."+ ),+ )+ await adapter.add_to_team(team_id, catalog_app_id=catalog_app_id)+ except _MICROSOFT_FAILURES as error:+ raise _microsoft_failed(error) from error+ return Response(status_code=204)++[email protected]("/{bridge_id}/teams/{team_id}", status_code=204)+async def remove_from_team(+ bridge_id: str,+ team_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],+ install_store: Annotated[MessagingInstallStore, Depends(get_install_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> Response:+ adapter, _install = await _connection(+ bridge_id, session, bridge_store, install_store, collab_lifecycle+ )+ try:+ await adapter.remove_from_team(team_id)+ except _MICROSOFT_FAILURES as error:+ raise _microsoft_failed(error) from error+ if adapter.default_team_id == team_id:+ # New channels are made in the default team, and cannot be in one the+ # app has left: channel creation goes off with the default, until+ # another team is chosen, rather than failing at the next room.+ await bridge_store.merge_connection_config(+ session, bridge_id, {"team_id": None}+ )+ await bridge_store.set_channel_creation_enabled(session, bridge_id, False)+ await session.commit()+ try:+ await collab_lifecycle.restart(bridge_id)+ except Exception as error:+ logger.exception(+ "Teams connection %s did not restart after leaving its default team",+ bridge_id,+ )+ raise HTTPException(+ status_code=503,+ detail=(+ "Switch left the team, and channel creation is off until "+ "another default team is chosen, but the connection did "+ f"not restart ({error}). It is stopped until it is "+ "restarted."+ ),+ ) from error+ return Response(status_code=204)++[email protected]("/{bridge_id}/teams-package")+async def download_app_package(+ bridge_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],+ install_store: Annotated[MessagingInstallStore, Depends(get_install_store)],+ collab_lifecycle: Annotated[+ CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)+ ],+ install_service: Annotated[+ MessagingInstallService | None, Depends(get_install_service)+ ],+ _user: Annotated[User, Depends(require_tenant_admin)],+) -> Response:+ """The app package, for a Teams admin to upload where Switch could not."""+ await _connection(bridge_id, session, bridge_store, install_store, collab_lifecycle)+ try:+ installer = (+ install_service.installer("teams") if install_service is not None else None+ )+ except MessagingInstallError:+ installer = None+ if not isinstance(installer, TeamsAppInstaller):+ raise HTTPException(+ status_code=404,+ detail="This deployment has no distributed Teams app.",+ )+ return Response(+ content=installer.package.archive,+ media_type="application/zip",+ headers={+ "Content-Disposition": (+ f'attachment; filename="switch-teams-{installer.package.version}.zip"'+ )+ },+ )diff --git a/core/switch_core/keys.py b/core/switch_core/keys.pyindex c525b367b..4e9d91357 100644--- a/core/switch_core/keys.py+++ b/core/switch_core/keys.py@@ -48,6 +48,7 @@ class Purpose(StrEnum):INSTALL_STATE = "messaging-install-state"INSTALL_CONFIRM = "messaging-install-confirm"BRIDGE_CALLBACK = "collaboration-callback"+ TEAMS_CLIENT_STATE = "teams-graph-client-state"class KeyringError(ValueError):diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex f9c1e731d..53f39ef78 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -79,6 +79,11 @@ from switch_core.bridges.collaboration.teams.adapter import (TeamsAdapter,TeamsConnectionConfig,)+from switch_core.bridges.collaboration.teams.app_package import (+ build_distributed_app_package,+)+from switch_core.bridges.collaboration.teams.install import TeamsAppInstaller+from switch_core.bridges.collaboration.teams.shared_app import TeamsSharedAppfrom switch_core.bridges.collaboration.telegram.adapter import (TelegramAdapter,TelegramConnectionConfig,@@ -785,6 +790,8 @@ async def run(config: SwitchConfig) -> None:))+ teams_app = _distributed_teams_app(config, installers, collab_lifecycle)+install_service: MessagingInstallService | None = Noneif installers.platforms():assert config.messaging_public_url is not None@@ -1061,6 +1068,7 @@ async def run(config: SwitchConfig) -> None:provisioning,discord_gateway,discord_gateway_task,+ teams_app,)),)@@ -1500,6 +1508,40 @@ async def _bootstrap_key_tenant(return TENANT_ZERO_ID+def _distributed_teams_app(+ config: SwitchConfig,+ installers: MessagingInstallerRegistry,+ collab_lifecycle: CollaborationBridgeLifecycleService,+) -> TeamsSharedApp | None:+ """The one distributed Teams app, when this deployment is configured with it.++ Its installer is registered, and every bridge on the app is handed it as+ the bridge starts, before it runs — so this must happen before any bridge+ does. Unlike Discord's Gateway client there is nothing to connect. Config+ validation has already required every `TEAMS_APP_*` value together.+ """+ if not config.teams_app_client_id:+ return None+ assert config.messaging_public_url is not None+ assert config.teams_app_privacy_url is not None+ assert config.teams_app_terms_url is not None+ teams_app = TeamsSharedApp.from_config(config)+ installers.register(+ TeamsAppInstaller(+ app=teams_app,+ package=build_distributed_app_package(+ app_id=config.teams_app_client_id,+ app_name=config.teams_app_name,+ messaging_public_url=config.messaging_public_url,+ privacy_url=config.teams_app_privacy_url,+ terms_url=config.teams_app_terms_url,+ ),+ )+ )+ collab_lifecycle.add_bridge_starting_listener(teams_app.attach_if_teams)+ return teams_app++async def _shutdown(server: uvicorn.Server,controllers: ControllerPresence,@@ -1509,6 +1551,7 @@ async def _shutdown(provisioning: Provisioning,discord_gateway: DiscordGatewayClient | None,discord_gateway_task: asyncio.Task[None] | None,+ teams_app: TeamsSharedApp | None,) -> None:logger.info("Shutting down...")# Before uvicorn closes the sockets, so the controllers' are recorded as@@ -1527,6 +1570,9 @@ async def _shutdown(passif discord_gateway is not None:await discord_gateway.stop()+ # After the bridges, which borrow its HTTP client until they stop.+ if teams_app is not None:+ await teams_app.aclose()await client_lifecycle.stop_all()await provisioning.close()diff --git a/core/switch_core/migrations/versions/e4b7d2a91c06_messaging_installs_platform_data.py b/core/switch_core/migrations/versions/e4b7d2a91c06_messaging_installs_platform_data.pynew file mode 100644index 000000000..1b70c4b16--- /dev/null+++ b/core/switch_core/migrations/versions/e4b7d2a91c06_messaging_installs_platform_data.py@@ -0,0 +1,45 @@+"""what one platform has to remember about an install++`messaging_installs` recorded the same few things for every platform: the+workspace, the credential, the scopes. The distributed Teams app needs to keep+something only Teams has — the id Microsoft gave our app in the customer+organisation's own catalogue, which differs per organisation and is needed to+add the app to a team or push it a new version — and there was nowhere to put+it that a workspace admin could not edit.++So the table gains `platform_data`, a JSONB object each platform reads and+writes for itself. Not a secret store: secrets keep their encrypted column.+Empty for every existing row, and for a platform with nothing to keep.++Revision ID: e4b7d2a91c06+Revises: 2f6919dcdead+Create Date: 2026-10-01 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "e4b7d2a91c06"+down_revision: str | None = "2f6919dcdead"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "messaging_installs",+ sa.Column(+ "platform_data",+ postgresql.JSONB(astext_type=sa.Text()),+ nullable=False,+ server_default=sa.text("'{}'::jsonb"),+ ),+ )+++def downgrade() -> None:+ op.drop_column("messaging_installs", "platform_data")diff --git a/core/tests/switch_core/bridges/collaboration/test_collaboration_adapter_defaults.py b/core/tests/switch_core/bridges/collaboration/test_collaboration_adapter_defaults.pynew file mode 100644index 000000000..25e51de41--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_collaboration_adapter_defaults.py@@ -0,0 +1,44 @@+"""The base `PlatformAdapter` behaviour every platform inherits unless it+overrides it.++Exercised through `MattermostAdapter`, which overrides none of these: it holds+nothing on the platform that outlives a bridge, offers no choice of which+teams it is in, and has nothing a platform-side check or an admin's attention+would ever need to say.+"""++from __future__ import annotations++from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+++def _adapter() -> MattermostAdapter:+ return MattermostAdapter(+ config=MattermostConnectionConfig(+ url="http://mm",+ admin_user="admin",+ admin_password="pw",+ team_name="team",+ )+ )+++async def test_withdrawing_is_a_no_op_for_a_bridge_that_holds_nothing_on_the_platform() -> (+ None+):+ assert await _adapter().withdraw() is None+++def test_an_adapter_does_not_place_its_app_in_teams_by_default() -> None:+ assert _adapter().places_app_in_teams is False+++async def test_a_config_edit_is_not_checked_against_the_platform_by_default() -> None:+ assert await _adapter().check_config_edit({"url": "http://mm2"}) is None+++async def test_nothing_needs_a_workspace_admins_attention_by_default() -> None:+ assert await _adapter().attention() is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_discord_installer.py b/core/tests/switch_core/bridges/collaboration/test_discord_installer.pyindex d1cc44b31..63efc8b1a 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_installer.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_installer.py@@ -129,6 +129,7 @@ class TestConnectionConfig:workspace_name="Acme",bot_token=None,scopes="bot applications.commands",+ platform_data={},))assert config == {"guild_id": "42", "event_delivery": "shared"}@@ -170,15 +171,22 @@ class TestTheWebhookHalfIsStubbed:with pytest.raises(NotImplementedError):await installer.revoke(bot_token="whatever")- def test_verify_webhook_raises_not_found(+ def test_the_app_posts_to_no_webhook(self, installer: DiscordAppInstaller) -> None:+ """So every `/messaging/discord/*` request is answered as if nothing+ were there, before anything reads it."""+ assert installer.webhook_endpoints == frozenset()++ async def test_verify_webhook_raises_not_found(self, installer: DiscordAppInstaller) -> None:with pytest.raises(MessagingInstallError):- installer.verify_webhook(headers={}, body=b"")+ await installer.verify_webhook(+ endpoint="events", headers={}, query={}, body=b""+ )def test_parse_webhook_raises(self, installer: DiscordAppInstaller) -> None:with pytest.raises(NotImplementedError):- installer.parse_webhook(endpoint="events", headers={}, body=b"")+ installer.parse_webhook(endpoint="events", headers={}, query={}, body=b"")def test_workspace_of_event_raises(self, installer: DiscordAppInstaller) -> None:with pytest.raises(NotImplementedError):diff --git a/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.py b/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.pyindex c27e60992..fbc8e75d6 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_confirmation_page.py@@ -59,6 +59,27 @@ async def test_the_callback_renders_a_confirmation_and_connects_nothing(assert fixture.lifecycle.registered == []+async def test_a_workspace_another_holds_is_explained_at_the_callback(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)+ state = await _begin(rls_harness.restricted, fixture, fixture.tenant_a)+ fixture.lifecycle.claim_conflict = (+ f"Slack workspace {fixture.workspace} is already claimed"+ )++ async with _client(fixture.service) as client:+ response = await client.get(+ "/messaging/slack/oauth/callback",+ params={"code": "the-code", "state": state},+ )++ assert response.status_code == 409+ assert "Workspace already connected" in response.text+ assert "already claimed" in response.text+ assert fixture.lifecycle.registered == []++async def test_connect_on_the_page_finishes_the_install(rls_harness: RLSHarness,) -> None:diff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.pyindex ad49287ff..a15a0d4b6 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py@@ -77,13 +77,18 @@ class _FakeInstaller(MessagingAppInstaller):"""A platform that always says yes, and counts how often it was asked."""platform: ClassVar[str] = "slack"+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset(+ {"events", "interactive", "commands"}+ )def __init__(self, workspace_id: str, *, tokenless: bool = False) -> None:self.workspace_id = workspace_idself.tokenless = tokenlessself.redeem_calls: list[str] = []+ self.platform_data: dict[str, object] = {"kept": "for later"}self.revoked_tokens: list[str] = []self.revoke_error: Exception | None = None+ self.released: list[str] = []def authorize_url(self, *, state: str, redirect_uri: str) -> str:return f"https://platform.example/authorize?state={state}"@@ -98,6 +103,7 @@ class _FakeInstaller(MessagingAppInstaller):# store no token for it and revoke nothing on disconnect.bot_token=None if self.tokenless else "xoxb-granted",scopes="chat:write",+ platform_data=self.platform_data,)async def revoke(self, *, bot_token: str) -> None:@@ -105,6 +111,9 @@ class _FakeInstaller(MessagingAppInstaller):raise self.revoke_errorself.revoked_tokens.append(bot_token)+ async def release(self, *, external_workspace_id: str) -> None:+ self.released.append(external_workspace_id)+def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:event = payload.get("event")if not isinstance(event, dict):@@ -113,19 +122,34 @@ class _FakeInstaller(MessagingAppInstaller):return "the app was removed"return None- def verify_webhook(self, *, headers: Mapping[str, str], body: bytes) -> None:+ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:return Nonedef parse_webhook(- self, *, endpoint: WebhookEndpoint, headers: Mapping[str, str], body: bytes- ) -> InboundWebhook:- return InboundWebhook(- envelope_type=endpoint,- payload={},- handshake=None,- external_event_id=None,- delivery_attempt=0,- )+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ return [+ InboundWebhook(+ envelope_type=endpoint,+ payload={},+ handshake=None,+ external_event_id=None,+ delivery_attempt=0,+ answers_inline=False,+ )+ ]def workspace_of_event(self, payload: Mapping[str, object]) -> str:return self.workspace_id@@ -157,13 +181,33 @@ class _FakeLifecycle:# the real one does when the platform rejects or cannot check the# credential. Cleared once raised, so a retry succeeds.self.register_failure: Exception | None = None+ self.restarted: list[str] = []+ self.running: dict[str, object] = {}+ # Registered but still starting: running, and not yet connected.+ self.starting: set[str] = set()+ self.restart_failure: Exception | None = Noneasync def reject_claim_conflict(- self, bridge_type: str, connection_config: dict[str, object]+ self,+ bridge_type: str,+ connection_config: dict[str, object],+ *,+ exclude_bridge_id: str | None = None,) -> None:if self.claim_conflict is not None:raise BridgeClaimConflict(self.claim_conflict)+ async def restart(self, bridge_id: str) -> None:+ self.restarted.append(bridge_id)+ if self.restart_failure is not None:+ raise self.restart_failure++ def get_adapter(self, bridge_id: str) -> object | None:+ return self.running.get(bridge_id)++ def is_connected(self, bridge_id: str) -> bool:+ return bridge_id in self.running and bridge_id not in self.starting+async def register(self, **kwargs: object) -> CollaborationBridge:if self.register_failure is not None:failure, self.register_failure = self.register_failure, None@@ -941,3 +985,132 @@ class TestATokenlessGrant:assert ended.ended_at is not Noneassert ended.bridge_id is Noneassert fixture.lifecycle.removed == [bridge_id]+++class TestWhatAnInstallRemembers:+ async def test_what_the_platform_keeps_is_recorded_with_the_install(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness)++ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ reread = await _reread(rls_harness.restricted, fixture.tenant_a, install.id)+ assert reread.platform_data == {"kept": "for later"}+++class TestApprovingAgain:+ async def test_the_same_organisation_approving_again_refreshes_its_install(+ self, rls_harness: RLSHarness+ ) -> None:+ """For a platform with no token, approving again is how new permissions+ or a newer app are granted — not a second claim on the workspace."""+ fixture = await _fixture(rls_harness, tokenless=True)+ first = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ fixture.installer.platform_data = {"kept": "something newer"}++ again = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ assert again.id == first.id+ assert again.platform_data == {"kept": "something newer"}+ assert fixture.lifecycle.restarted == [first.bridge_id]+ assert len(fixture.lifecycle.registered) == 1++ async def test_a_connection_that_cannot_restart_says_so_on_the_page(+ self, rls_harness: RLSHarness+ ) -> None:+ """The approval is recorded either way; the admin is told the+ connection is stopped, not shown a raw server error."""+ fixture = await _fixture(rls_harness, tokenless=True)+ first = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ fixture.lifecycle.restart_failure = RuntimeError("database went away")++ with pytest.raises(MessagingInstallError, match="could not restart"):+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ assert fixture.lifecycle.restarted == [first.bridge_id]++ async def test_another_tenant_approving_the_same_workspace_is_still_refused(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness, tokenless=True)+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ with pytest.raises(MessagingInstallClaimedError):+ await _installed(rls_harness.restricted, fixture, fixture.tenant_b)++ async def test_a_platform_with_a_token_is_not_refreshed_this_way(+ self, rls_harness: RLSHarness+ ) -> None:+ """Its bridge holds the old token; swapping it is not what this does."""+ fixture = await _fixture(rls_harness)+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ with pytest.raises(MessagingInstallClaimedError):+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+++class TestLettingGoOfATokenlessWorkspace:+ async def test_a_bridge_that_is_not_running_is_released_by_the_installer(+ self, rls_harness: RLSHarness+ ) -> None:+ """A running bridge lets go of the platform as it is removed; one that+ is not running cannot, so the installer does it instead."""+ fixture = await _fixture(rls_harness, tokenless=True)+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=install.id+ )++ assert fixture.installer.released == [fixture.workspace]++ async def test_a_running_bridge_is_left_to_let_go_itself(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _fixture(rls_harness, tokenless=True)+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ assert install.bridge_id is not None+ fixture.lifecycle.running[install.bridge_id] = object()++ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=install.id+ )++ assert fixture.installer.released == []++ async def test_a_bridge_still_starting_is_released_by_the_installer(+ self, rls_harness: RLSHarness+ ) -> None:+ """Registered is not connected: a bridge just restarted has no Graph+ client yet, and letting go itself would quietly do nothing."""+ fixture = await _fixture(rls_harness, tokenless=True)+ install = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ assert install.bridge_id is not None+ fixture.lifecycle.running[install.bridge_id] = object()+ fixture.lifecycle.starting.add(install.bridge_id)++ await fixture.service.disconnect(+ tenant_id=fixture.tenant_a, install_id=install.id+ )++ assert fixture.installer.released == [fixture.workspace]+++class TestApprovingAgainKeepsWhatItLearned:+ async def test_a_repeated_approval_that_learned_less_erases_nothing(+ self, rls_harness: RLSHarness+ ) -> None:+ """An id an earlier approval learned is still good when this one could+ not read it again."""+ fixture = await _fixture(rls_harness, tokenless=True)+ fixture.installer.platform_data = {"catalog_app_id": "c-1"}+ await _installed(rls_harness.restricted, fixture, fixture.tenant_a)+ fixture.installer.platform_data = {"publish_problem": "update refused"}++ again = await _installed(rls_harness.restricted, fixture, fixture.tenant_a)++ assert again.platform_data == {+ "catalog_app_id": "c-1",+ "publish_problem": "update refused",+ }diff --git a/core/tests/switch_core/bridges/collaboration/test_install_ticket.py b/core/tests/switch_core/bridges/collaboration/test_install_ticket.pynew file mode 100644index 000000000..67c2f7f3c--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_install_ticket.py@@ -0,0 +1,61 @@+"""The confirmation ticket, sealed at the callback and opened at the decision."""++from __future__ import annotations++import base64+import json++from cryptography.fernet import Fernet++from switch_core.bridges.collaboration.install import InstallGrant+from switch_core.bridges.collaboration.install_confirmation import (+ InstallTicket,+ open_ticket,+ seal,+)+from switch_core.keys import Purpose+from tests.conftest import TEST_KEYRING+++def test_a_ticket_opens_to_what_was_sealed() -> None:+ ticket = InstallTicket(+ tenant_id="tenant-a",+ state_id="state-1",+ platform="teams",+ grant=InstallGrant(+ external_workspace_id="org-1",+ workspace_name="Contoso",+ bot_token=None,+ scopes=["ChannelMessage.Read.All"],+ platform_data={"catalog_app_id": "app-1"},+ ),+ )++ assert (+ open_ticket(seal(ticket, keyring=TEST_KEYRING), keyring=TEST_KEYRING) == ticket+ )+++def test_a_ticket_sealed_before_platform_data_existed_still_opens() -> None:+ """A confirmation page left open across the deploy that added platform+ data carries a ticket without it; Connect must still finish the install."""+ payload = {+ "tid": "tenant-a",+ "sid": "state-1",+ "plat": "slack",+ "ws": "T123",+ "name": "Acme",+ "tok": "bot-token-placeholder",+ "scopes": ["chat:write"],+ }+ key = TEST_KEYRING.derive(Purpose.INSTALL_CONFIRM)+ token = (+ Fernet(base64.urlsafe_b64encode(key))+ .encrypt(json.dumps(payload).encode())+ .decode()+ )++ opened = open_ticket(token, keyring=TEST_KEYRING)++ assert opened.grant.platform_data == {}+ assert opened.grant.bot_token == "bot-token-placeholder"diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex 248798a48..31fc399a8 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -166,6 +166,9 @@ class _FakeLifecycle:def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:return self.adapters.get(bridge_id)+ def is_connected(self, bridge_id: str) -> bool:+ return bridge_id in self.adapters+async def remove(self, bridge_id: str) -> None:"""Delete the row, on an unscoped session like the real one.@@ -613,10 +616,11 @@ class TestABridgeThatCannotTakeEvents:adapter = _SocketOnlyAdapter()fixture.lifecycle.adapters[fixture.a.bridge_id] = adapter- event = fixture.service.authenticate(+ [event] = await fixture.service.authenticate(platform="slack",endpoint="events",headers=_signed(_event(fixture.a.workspace_id, "x")),+ query={},body=_event(fixture.a.workspace_id, "x"),)target = await fixture.service.resolve(platform="slack", event=event)@@ -661,8 +665,12 @@ class TestAnEventIsHandledOnce:gated = _GatedAdapter()fixture.lifecycle.adapters[fixture.a.bridge_id] = gatedbody = _numbered_event(fixture.a.workspace_id, "hello", "Ev1")- event = fixture.service.authenticate(- platform="slack", endpoint="events", headers=_signed(body), body=body+ [event] = await fixture.service.authenticate(+ platform="slack",+ endpoint="events",+ headers=_signed(body),+ query={},+ body=body,)target = await fixture.service.resolve(platform="slack", event=event)diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook_shapes.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook_shapes.pynew file mode 100644index 000000000..dbc26a47c--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook_shapes.py@@ -0,0 +1,738 @@+"""The shapes of webhook a platform other than Slack posts.++Slack posts one signed event per request and wants an empty acknowledgement.+Microsoft's platforms do not: Graph checks a notification URL with a request+nobody signed, batches notifications from several organisations into one+post, and the Bot Framework waits on a card press for its answer in the+response itself. A fake platform here posts each shape, against real Postgres+and the real routing, so the generic route is tested apart from any one+platform's installer.+"""++from __future__ import annotations++import asyncio+import json+import uuid+from collections.abc import Mapping+from typing import Any, ClassVar++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy import select+from sqlalchemy.ext.asyncio import async_sessionmaker++from switch_core.bridges.collaboration import install_routes+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.install import (+ InboundWebhook,+ InstallGrant,+ MessagingAppInstaller,+ MessagingInstallerRegistry,+ WebhookAuthenticityError,+ WebhookEndpoint,+ WebhookPayloadError,+ WebhookVerificationUnavailable,+)+from switch_core.bridges.collaboration.install_routes import (+ create_messaging_install_router,+)+from switch_core.bridges.collaboration.install_service import (+ MessagingInstallService,+ WebhookTarget,+)+from switch_core.db.models import (+ Client,+ CollaborationBridge,+ MessagingEventReceipt,+ MessagingInstall,+ Tenant,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.messaging_event_store import MessagingEventReceiptStore+from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.keys import Keyring+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant++_PLATFORM = "relay"+_ORIGIN = "https://switch.example"+_KEYRING = Keyring.parse("test:" + "x" * 40, legacy_secret=None)+_SIGNED = {"X-Test-Signature": "ok"}+++class _RelayInstaller(MessagingAppInstaller):+ """A platform that posts events and batched notifications, and checks its+ notification URL without signing the check."""++ platform: ClassVar[str] = _PLATFORM+ webhook_endpoints: ClassVar[frozenset[WebhookEndpoint]] = frozenset(+ {"events", "notifications"}+ )++ def __init__(self) -> None:+ self.verified = 0++ def authorize_url(self, *, state: str, redirect_uri: str) -> str:+ return "https://relay.example/authorize"++ async def redeem(self, *, code: str, redirect_uri: str) -> InstallGrant:+ raise NotImplementedError++ async def revoke(self, *, bot_token: str) -> None:+ raise NotImplementedError++ def unsigned_handshake(+ self, *, endpoint: WebhookEndpoint, query: Mapping[str, str]+ ) -> str | None:+ if endpoint == "notifications":+ return query.get("validationToken")+ return None++ async def verify_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> None:+ self.verified += 1+ if headers.get("x-test-signature") == "keys-unavailable":+ raise WebhookVerificationUnavailable("the platform's keys are out of reach")+ if headers.get("x-test-signature") != "ok":+ raise WebhookAuthenticityError("unsigned")++ def parse_webhook(+ self,+ *,+ endpoint: WebhookEndpoint,+ headers: Mapping[str, str],+ query: Mapping[str, str],+ body: bytes,+ ) -> list[InboundWebhook]:+ return [+ InboundWebhook(+ envelope_type=endpoint,+ payload=item,+ handshake=None,+ external_event_id=item.get("id"),+ delivery_attempt=item.get("delivery_attempt", 0),+ answers_inline=bool(item.get("inline")),+ )+ for item in json.loads(body)["items"]+ ]++ def workspace_of_event(self, payload: Mapping[str, object]) -> str:+ if "workspace" not in payload:+ raise WebhookPayloadError("an event named no workspace")+ return str(payload["workspace"])++ def revocation_of_event(self, payload: Mapping[str, object]) -> str | None:+ return None++ def connection_config(self, grant: InstallGrant) -> dict[str, object]:+ return {}+++class _Adapter(PlatformAdapter):+ """Records what it is handed and answers with what it was asked to."""++ def __init__(+ self, *, delay: float = 0.0, fail: bool = False, no_body: bool = False+ ) -> None:+ self.dispatched: list[dict[str, Any]] = []+ self.finished: list[dict[str, Any]] = []+ self._delay = delay+ self._fail = fail+ self._no_body = no_body++ async def dispatch_event(+ self, *, envelope_type: str, payload: dict[str, Any]+ ) -> dict[str, Any] | None:+ self.dispatched.append(payload)+ if self._delay:+ await asyncio.sleep(self._delay)+ self.finished.append(payload)+ if self._fail:+ raise RuntimeError("the press could not be handled")+ if self._no_body:+ return None+ return {"answer": payload["id"]} if payload.get("inline") else None++ async def start(self, *a: Any, **k: Any) -> Any: ...+ async def stop(self, *a: Any, **k: Any) -> Any: ...+ async def send_message(self, *a: Any, **k: Any) -> Any: ...+ async def send_typing(self, *a: Any, **k: Any) -> Any: ...+ async def update_message(self, *a: Any, **k: Any) -> Any: ...+ async def delete_message(self, *a: Any, **k: Any) -> Any: ...+ async def create_channel(self, *a: Any, **k: Any) -> Any: ...+ async def get_channel_type(self, *a: Any, **k: Any) -> Any: ...+ async def get_channel_agent_names(self, *a: Any, **k: Any) -> Any: ...+ async def add_agents_to_channel(self, *a: Any, **k: Any) -> Any: ...+ async def add_users_to_channel(self, *a: Any, **k: Any) -> Any: ...+ async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...+ async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...+ def translate_inbound(self, *a: Any, **k: Any) -> Any: ...+ def translate_outbound(self, *a: Any, **k: Any) -> Any: ...+ def _render_outbound(self, *a: Any, **k: Any) -> Any: ...+++class _Lifecycle:+ def __init__(self) -> None:+ self.adapters: dict[str, PlatformAdapter] = {}+ self.starting: set[str] = set()++ def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:+ return self.adapters.get(bridge_id)++ def is_connected(self, bridge_id: str) -> bool:+ return bridge_id in self.adapters and bridge_id not in self.starting+++class _Fixture:+ installer: _RelayInstaller+ lifecycle: _Lifecycle+ client: httpx.AsyncClient+ tenants: dict[str, str]+ bridges: dict[str, str]+++async def _fixture(harness: RLSHarness) -> _Fixture:+ fixture = _Fixture()+ suffix = uuid.uuid4().hex[:8]+ fixture.tenants = {label: f"tenant-{label}-{suffix}" for label in ("a", "b")}+ fixture.bridges = {}+ fixture.lifecycle = _Lifecycle()++ async with harness.owner() as session:+ for tenant_id in fixture.tenants.values():+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ user = User(name="installer", email=f"{suffix}@example.test", role="user")+ session.add(user)+ await session.flush()+ user_id = user.id+ await session.commit()++ for label, tenant_id in fixture.tenants.items():+ async with tenant_session(harness.restricted, tenant_id) as session:+ client = Client(+ transport_user_id=f"@bridge-{label}:{suffix}",+ display_name="bridge",+ type="collaboration_bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ type=_PLATFORM,+ display_name=label,+ connection_config={},+ client_id=client.id,+ status="active",+ )+ session.add(bridge)+ await session.flush()+ session.add(+ MessagingInstall(+ tenant_id=tenant_id,+ platform=_PLATFORM,+ external_workspace_id=f"org-{label}",+ encrypted_bot_token=None,+ scopes="",+ status="active",+ installed_by_user_id=user_id,+ bridge_id=bridge.id,+ )+ )+ fixture.bridges[label] = bridge.id+ await session.commit()+ fixture.lifecycle.adapters[fixture.bridges[label]] = _Adapter()++ fixture.installer = _RelayInstaller()+ installers = MessagingInstallerRegistry()+ installers.register(fixture.installer)+ service = MessagingInstallService(+ session_factory=harness.restricted,+ store=MessagingInstallStore(),+ receipts=MessagingEventReceiptStore(),+ installers=installers,+ lifecycle=fixture.lifecycle, # type: ignore[arg-type]+ public_origin=_ORIGIN,+ keyring=_KEYRING,+ )+ app = FastAPI()+ app.include_router(create_messaging_install_router(service))+ fixture.client = httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=_ORIGIN+ )+ return fixture+++def _adapter(fixture: _Fixture, label: str) -> _Adapter:+ adapter = fixture.lifecycle.adapters[fixture.bridges[label]]+ assert isinstance(adapter, _Adapter)+ return adapter+++def _batch(*items: dict[str, Any]) -> bytes:+ return json.dumps({"items": list(items)}).encode()+++async def _receipts(factory: async_sessionmaker, tenant_id: str) -> list[Any]:+ async with tenant_session(factory, tenant_id) as session:+ return list((await session.execute(select(MessagingEventReceipt))).scalars())+++async def test_an_endpoint_the_app_does_not_post_to_does_not_exist(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/commands", content=b"{}", headers=_SIGNED+ )++ assert response.status_code == 404+ assert fixture.installer.verified == 0+++async def test_an_unsigned_url_check_is_answered_before_anything_is_verified(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications?validationToken=prove-it"+ )++ assert response.status_code == 200+ assert response.text == "prove-it"+ assert fixture.installer.verified == 0+++async def test_anything_else_unsigned_is_refused(rls_harness: RLSHarness) -> None:+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"workspace": "org-a", "id": "n1"}),+ )++ assert response.status_code == 401+ assert _adapter(fixture, "a").dispatched == []+++async def test_a_request_that_cannot_be_checked_is_asked_for_again(+ rls_harness: RLSHarness,+) -> None:+ """The platform's keys out of reach says nothing about the request: a+ 401 would lose it, where a 503 is retried."""+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"workspace": "org-a", "id": "n1"}),+ headers={"x-test-signature": "keys-unavailable"},+ )++ assert response.status_code == 503+ assert _adapter(fixture, "a").dispatched == []+++async def test_a_batch_reaches_each_organisations_own_bridge(+ rls_harness: RLSHarness,+) -> None:+ """One post, two organisations: each item goes to the bridge its own+ organisation resolves to, and none of it to the other's."""+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch(+ {"workspace": "org-a", "id": "n-a"}, {"workspace": "org-b", "id": "n-b"}+ ),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert [p["id"] for p in _adapter(fixture, "a").dispatched] == ["n-a"]+ assert [p["id"] for p in _adapter(fixture, "b").dispatched] == ["n-b"]+++async def test_an_unknown_organisation_does_not_hold_back_the_rest(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch(+ {"workspace": "org-nobody", "id": "n-x"},+ {"workspace": "org-a", "id": "n-a"},+ ),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert [p["id"] for p in _adapter(fixture, "a").dispatched] == ["n-a"]+++async def test_an_unreadable_item_does_not_hold_back_the_rest(+ rls_harness: RLSHarness,+) -> None:+ """One item naming no workspace, in a batch every workspace shares, is+ skipped; answering the whole batch with a 400 would drop everyone else's+ events in it for good."""+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"id": "n-x"}, {"workspace": "org-a", "id": "n-a"}),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert [p["id"] for p in _adapter(fixture, "a").dispatched] == ["n-a"]+++async def test_a_batch_nothing_in_which_can_be_read_is_refused(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"id": "n-x"}, {"id": "n-y"}),+ headers=_SIGNED,+ )++ assert response.status_code == 400+ assert _adapter(fixture, "a").dispatched == []+++async def test_undeliverable_and_unreadable_alone_is_asked_for_again(+ rls_harness: RLSHarness,+) -> None:+ """Nothing in it was delivered, and some of it can be once the bridge is+ back; the unreadable item is skipped again on the retry."""+ fixture = await _fixture(rls_harness)+ del fixture.lifecycle.adapters[fixture.bridges["b"]]++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"id": "n-x"}, {"workspace": "org-b", "id": "n-b"}),+ headers=_SIGNED,+ )++ assert response.status_code == 503+++async def test_nothing_delivered_is_asked_for_again_even_beside_an_unknown_workspace(+ rls_harness: RLSHarness,+) -> None:+ """A dropped event for a workspace nobody holds is not a delivery; with the+ rest of the batch undeliverable, the platform is asked to send it again."""+ fixture = await _fixture(rls_harness)+ del fixture.lifecycle.adapters[fixture.bridges["b"]]++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch(+ {"workspace": "org-b", "id": "n-b"},+ {"workspace": "org-nobody", "id": "n-x"},+ ),+ headers=_SIGNED,+ )++ assert response.status_code == 503+++async def test_a_workspace_is_looked_up_once_per_batch(+ rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+) -> None:+ fixture = await _fixture(rls_harness)+ lookups: list[str] = []+ original = MessagingInstallService.resolve_by_workspace++ async def counting(+ self: MessagingInstallService, *, platform: str, workspace_id: str+ ) -> Any:+ lookups.append(workspace_id)+ return await original(self, platform=platform, workspace_id=workspace_id)++ monkeypatch.setattr(MessagingInstallService, "resolve_by_workspace", counting)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch(+ {"workspace": "org-a", "id": "n-1"},+ {"workspace": "org-a", "id": "n-2"},+ {"workspace": "org-nobody", "id": "n-3"},+ {"workspace": "org-nobody", "id": "n-4"},+ {"workspace": "org-a", "id": "n-5"},+ ),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert sorted(lookups) == ["org-a", "org-nobody"]+ assert [p["id"] for p in _adapter(fixture, "a").dispatched] == ["n-1", "n-2", "n-5"]+++async def test_a_bridge_that_is_down_asks_for_its_events_again(+ rls_harness: RLSHarness,+) -> None:+ """A request whose every event was undeliverable is retried; receipts make+ the retry harmless once the bridge is back."""+ fixture = await _fixture(rls_harness)+ del fixture.lifecycle.adapters[fixture.bridges["b"]]+ body = _batch({"workspace": "org-b", "id": "n-b"})++ first = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications", content=body, headers=_SIGNED+ )+ fixture.lifecycle.adapters[fixture.bridges["b"]] = _Adapter()+ retry = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications", content=body, headers=_SIGNED+ )++ assert first.status_code == 503+ assert retry.status_code == 200+ assert [p["id"] for p in _adapter(fixture, "b").dispatched] == ["n-b"]+++async def test_a_bridge_still_starting_is_not_handed_events(+ rls_harness: RLSHarness,+) -> None:+ """Running is not serving: an event handed over before the adapter has+ finished starting is acknowledged and lost, so it is asked for again."""+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.starting.add(fixture.bridges["a"])++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"workspace": "org-a", "id": "n-a"}),+ headers=_SIGNED,+ )++ assert response.status_code == 503+ assert _adapter(fixture, "a").dispatched == []+++async def test_one_workspace_down_does_not_fail_another_workspaces_delivery(+ rls_harness: RLSHarness,+) -> None:+ """On an endpoint every workspace shares, a 503 for a mixed batch would+ have the platform back off from everyone's delivery for one restart."""+ fixture = await _fixture(rls_harness)+ del fixture.lifecycle.adapters[fixture.bridges["b"]]++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch(+ {"workspace": "org-a", "id": "n-a"}, {"workspace": "org-b", "id": "n-b"}+ ),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert [p["id"] for p in _adapter(fixture, "a").dispatched] == ["n-a"]+++async def test_an_event_the_platform_waits_on_is_answered_in_the_response(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/events",+ content=_batch({"workspace": "org-a", "id": "press-1", "inline": True}),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert response.json() == {"answer": "press-1"}+++async def test_a_retried_press_is_answered_again_rather_than_dropped(+ rls_harness: RLSHarness,+) -> None:+ """The platform retries because it never saw the answer; a receipt would+ give the retry nothing."""+ fixture = await _fixture(rls_harness)+ body = _batch({"workspace": "org-a", "id": "press-1", "inline": True})++ await fixture.client.post(+ f"/messaging/{_PLATFORM}/events", content=body, headers=_SIGNED+ )+ retry = await fixture.client.post(+ f"/messaging/{_PLATFORM}/events", content=body, headers=_SIGNED+ )++ assert retry.json() == {"answer": "press-1"}+ assert await _receipts(rls_harness.restricted, fixture.tenants["a"]) == []+++async def test_a_press_that_takes_too_long_is_answered_as_failed(+ rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch+) -> None:+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.adapters[fixture.bridges["a"]] = _Adapter(delay=1.0)+ monkeypatch.setattr(install_routes, "_INLINE_ANSWER_SECONDS", 0.05)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/events",+ content=_batch({"workspace": "org-a", "id": "press-1", "inline": True}),+ headers=_SIGNED,+ )++ assert response.status_code == 504+ # The deadline ends the wait, not the handling: a press abandoned half+ # way could be recorded with its card never redrawn.+ adapter = _adapter(fixture, "a")+ for _ in range(50):+ if adapter.finished:+ break+ await asyncio.sleep(0.05)+ assert [p["id"] for p in adapter.finished] == ["press-1"]+++async def test_a_press_whose_handling_fails_is_answered_as_failed(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.adapters[fixture.bridges["a"]] = _Adapter(fail=True)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/events",+ content=_batch({"workspace": "org-a", "id": "press-1", "inline": True}),+ headers=_SIGNED,+ )++ assert response.status_code == 500+++async def test_an_inline_answered_event_with_nothing_to_say_back_is_a_bare_200(+ rls_harness: RLSHarness,+) -> None:+ """Most events the platform waits on carry an answer, but one that does+ not is still a plain success rather than an empty JSON body."""+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.adapters[fixture.bridges["a"]] = _Adapter(no_body=True)++ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/events",+ content=_batch({"workspace": "org-a", "id": "press-1", "inline": True}),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert response.content == b""+++async def test_a_redelivered_event_is_warned_about_and_still_handled(+ rls_harness: RLSHarness, caplog: pytest.LogCaptureFixture+) -> None:+ """A positive `delivery_attempt` is the platform saying an earlier+ acknowledgement arrived too late — worth a log, but the event is handled+ exactly as any other, not dropped as a duplicate."""+ fixture = await _fixture(rls_harness)++ with caplog.at_level("WARNING"):+ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/notifications",+ content=_batch({"workspace": "org-a", "id": "n-a", "delivery_attempt": 2}),+ headers=_SIGNED,+ )++ assert response.status_code == 200+ assert [p["id"] for p in _adapter(fixture, "a").dispatched] == ["n-a"]+ assert any(+ "re-sending" in record.message and "attempt 2" in record.message+ for record in caplog.records+ )+++async def test_a_callback_error_for_an_unregistered_platform_is_reported_plainly(+ rls_harness: RLSHarness,+) -> None:+ """No installer is registered to translate the code into words a person+ acts on, so the fallback explanation is used instead of a 500."""+ fixture = await _fixture(rls_harness)++ response = await fixture.client.get(+ "/messaging/no-such-platform/oauth/callback?error=access_denied"+ )++ assert response.status_code == 200+ assert "no-such-platform reported: access_denied." in response.text+++async def test_a_refused_install_is_explained_in_the_platforms_terms(+ rls_harness: RLSHarness,+) -> None:+ fixture = await _fixture(rls_harness)++ def explain(*, error: str, description: str | None) -> str:+ return f"You need to be an administrator ({error}: {description})."++ fixture.installer.describe_callback_error = explain # type: ignore[method-assign]++ response = await fixture.client.get(+ f"/messaging/{_PLATFORM}/oauth/callback"+ "?error=access_denied&error_description=not+an+admin"+ )++ assert response.status_code == 200+ assert "You need to be an administrator (access_denied: not an admin)." in (+ response.text+ )+++async def test_a_press_that_fails_after_its_deadline_is_logged(+ rls_harness: RLSHarness,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ fixture = await _fixture(rls_harness)+ fixture.lifecycle.adapters[fixture.bridges["a"]] = _Adapter(delay=0.2, fail=True)+ monkeypatch.setattr(install_routes, "_INLINE_ANSWER_SECONDS", 0.05)++ with caplog.at_level("ERROR"):+ response = await fixture.client.post(+ f"/messaging/{_PLATFORM}/events",+ content=_batch({"workspace": "org-a", "id": "press-1", "inline": True}),+ headers=_SIGNED,+ )+ for _ in range(50):+ if not install_routes._finishing:+ break+ await asyncio.sleep(0.05)++ assert response.status_code == 504+ assert "failed after its answer was sent" in caplog.text+++async def test_a_late_press_cancelled_at_shutdown_is_let_go_quietly() -> None:+ async def forever() -> dict[str, Any] | None:+ await asyncio.sleep(3600)+ return None++ task = asyncio.create_task(forever())+ install_routes._finishing.add(task)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ install_routes._finished_late(+ WebhookTarget(+ tenant_id="t", platform=_PLATFORM, bridge_id="b", adapter=_Adapter()+ ),+ "events",+ task,+ )++ assert task not in install_routes._finishingdiff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_config_edit.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_config_edit.pynew file mode 100644index 000000000..388959439--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_config_edit.py@@ -0,0 +1,126 @@+"""Asking a running bridge whether an edit of its settings is sound."""++from __future__ import annotations++from collections.abc import Mapping+from types import SimpleNamespace+from typing import Any+from unittest.mock import MagicMock++import pytest++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 BridgeNotRunning+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)++_SHARED = {"event_delivery": "shared", "tenant_id": "org-1"}+++def _service() -> CollaborationBridgeLifecycleService:+ service = CollaborationBridgeLifecycleService(+ bridge_store=MagicMock(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=MagicMock(),+ agent_store=MagicMock(),+ client_store=MagicMock(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ provisioning=MagicMock(),+ session_factory=MagicMock(),+ config=MagicMock(),+ client_factory=MagicMock(),+ session_activity_listener=MagicMock(),+ session_activity_service=MagicMock(),+ connections=MagicMock(),+ )+ service.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)+ service.register_adapter(+ "mattermost", MattermostAdapter, MattermostConnectionConfig+ )+ return service+++class _Adapter:+ def __init__(self) -> None:+ self.asked: list[Mapping[str, object]] = []++ async def check_config_edit(self, connection_config: Mapping[str, object]) -> None:+ self.asked.append(connection_config)+++def _running(service: CollaborationBridgeLifecycleService, adapter: Any) -> None:+ service._bridges["b-1"] = SimpleNamespace(adapter=adapter) # type: ignore[assignment]+ service._connected.add("b-1")+++async def test_the_running_bridge_is_asked() -> None:+ service = _service()+ adapter = _Adapter()+ _running(service, adapter)+ edited = {**_SHARED, "team_id": "team-2"}++ await service.check_config_edit(+ bridge_id="b-1",+ bridge_type="teams",+ current=_SHARED,+ connection_config=edited,+ )++ assert adapter.asked == [edited]+++async def test_a_stopped_bridge_on_the_deployments_app_cannot_be_checked() -> None:+ """Its edits need the platform to check, so one made while it is stopped+ is refused rather than stored unchecked."""+ with pytest.raises(BridgeNotRunning):+ await _service().check_config_edit(+ bridge_id="b-1",+ bridge_type="teams",+ current=_SHARED,+ connection_config={**_SHARED, "team_id": "team-2"},+ )+++async def test_a_stopped_bridge_on_its_own_app_is_edited_on_validation_alone() -> None:+ await _service().check_config_edit(+ bridge_id="b-1",+ bridge_type="mattermost",+ current={"url": "https://mm.example"},+ connection_config={"url": "https://mm2.example"},+ )+++def test_an_unknown_type_leaves_editing_to_validation() -> None:+ assert _service().editable_config_keys("no-such-platform", {}) is None+++def test_the_adapter_names_what_is_editable() -> None:+ assert _service().editable_config_keys("teams", _SHARED) == frozenset({"team_id"})+++async def test_a_bridge_still_starting_cannot_be_checked() -> None:+ """A restart registers the bridge before its adapter has a Graph client;+ asked then, the edit is refused as not running, not failed as a fault."""+ service = _service()+ adapter = _Adapter()+ service._bridges["b-1"] = SimpleNamespace(adapter=adapter) # type: ignore[assignment]++ with pytest.raises(BridgeNotRunning):+ await service.check_config_edit(+ bridge_id="b-1",+ bridge_type="teams",+ current=_SHARED,+ connection_config={**_SHARED, "team_id": "team-2"},+ )++ assert adapter.asked == []diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.pyindex 42169336c..cbad03d23 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py@@ -11,6 +11,10 @@ from switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,_workspace_consumer_localpart,)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)from switch_core.db.models import (TENANT_ZERO_ID,Client,@@ -381,3 +385,179 @@ async def test_removing_a_bridge_forgets_that_it_was_preconfigured(await service.remove(bridge_id)assert bridge_id not in service._preconfigured+++class _WithdrawingAdapter:+ def __init__(self, events: list[str], *, fail: bool = False) -> None:+ self._events = events+ self._fail = fail++ async def withdraw(self) -> None:+ self._events.append("withdraw")+ if self._fail:+ raise RuntimeError("the platform would not let go")+++class _RunningBridge:+ def __init__(self, adapter: _WithdrawingAdapter, events: list[str]) -> None:+ self.adapter = adapter+ self._events = events++ async def stop(self) -> None:+ self._events.append("stop")+++async def test_a_removed_bridge_withdraws_from_its_platform_before_it_stops(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Withdrawing needs the bridge still running — its clients and its+ platform credential — and only a removal does it, never a restart."""+ service = _service(session_factory, _ClientLifecycle())+ async with session_factory() as session:+ bridge_id, _ = await _make_bridge(session)+ await session.commit()+ events: list[str] = []+ service._bridges[bridge_id] = _RunningBridge( # type: ignore[assignment]+ _WithdrawingAdapter(events), events+ )++ await service.remove(bridge_id)++ assert events == ["withdraw", "stop"]+++async def test_a_bridge_that_cannot_withdraw_is_still_removed(+ session_factory: async_sessionmaker[AsyncSession],+ caplog: pytest.LogCaptureFixture,+) -> None:+ """The removal is what someone asked for; what was left behind is logged."""+ service = _service(session_factory, _ClientLifecycle())+ async with session_factory() as session:+ bridge_id, _ = await _make_bridge(session)+ await session.commit()+ events: list[str] = []+ service._bridges[bridge_id] = _RunningBridge( # type: ignore[assignment]+ _WithdrawingAdapter(events, fail=True), events+ )++ await service.remove(bridge_id)++ async with session_factory() as session:+ assert await CollaborationBridgeStore().get(session, bridge_id) is None+ assert "could not let go" in caplog.text+++class _RegisteringClientLifecycle(_ClientLifecycle):+ """Also creates the bridge's client row, as registration needs."""++ def __init__(self, factory: async_sessionmaker[AsyncSession]) -> None:+ super().__init__()+ self._factory = factory++ async def create_client(+ self, *, client_type: str, display_name: str, localpart: str+ ) -> Client:+ async with self._factory() as session:+ client = Client(+ transport_user_id=f"@{localpart}-{uuid.uuid4().hex[:8]}:test",+ display_name=display_name,+ type=client_type,+ tenant_id=TENANT_ZERO_ID,+ )+ session.add(client)+ await session.commit()+ return client+++async def test_a_bridge_that_cannot_start_is_not_left_registered(+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Stored and not startable would be a row that fails every boot — and,+ for an install, a second bridge on the customer's next attempt."""+ service = _service(session_factory, _RegisteringClientLifecycle(session_factory))+ service.register_adapter(+ "mattermost", MattermostAdapter, MattermostConnectionConfig+ )++ async def refuse(bridge_id: str) -> None:+ raise RuntimeError("the bridge could not start")++ async def accept(connection_config: dict[str, object]) -> None:+ return None++ async def reachable(bridge_type: str, connection_config: object) -> None:+ return None++ monkeypatch.setattr(service, "check_outbound_urls", reachable)+ monkeypatch.setattr(service, "start", refuse)+ monkeypatch.setattr(+ MattermostAdapter, "verify_credentials", classmethod(lambda cls, c: accept(c))+ )++ with pytest.raises(RuntimeError, match="could not start"):+ await service.register(+ bridge_type="mattermost",+ display_name="MM",+ connection_config={+ "url": "https://mm.example",+ "admin_user": "admin",+ "admin_password": "pw",+ "team_name": "team",+ },+ channel_creation_enabled=False,+ preconfigured=False,+ )++ async with session_factory() as session:+ assert await CollaborationBridgeStore().get_all(session) == []+++async def test_a_failed_cleanup_does_not_hide_why_the_bridge_could_not_start(+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ service = _service(session_factory, _RegisteringClientLifecycle(session_factory))+ service.register_adapter(+ "mattermost", MattermostAdapter, MattermostConnectionConfig+ )++ async def refuse(bridge_id: str) -> None:+ raise RuntimeError("the bridge could not start")++ async def remove_fails(bridge_id: str) -> None:+ raise RuntimeError("the database went away")++ async def accept(connection_config: dict[str, object]) -> None:+ return None++ async def reachable(bridge_type: str, connection_config: object) -> None:+ return None++ monkeypatch.setattr(service, "check_outbound_urls", reachable)+ monkeypatch.setattr(service, "start", refuse)+ monkeypatch.setattr(service, "remove", remove_fails)+ monkeypatch.setattr(+ MattermostAdapter, "verify_credentials", classmethod(lambda cls, c: accept(c))+ )++ with pytest.raises(RuntimeError, match="could not start"):+ await service.register(+ bridge_type="mattermost",+ display_name="MM",+ connection_config={+ "url": "https://mm.example",+ "admin_user": "admin",+ "admin_password": "pw",+ "team_name": "team",+ },+ channel_creation_enabled=False,+ preconfigured=False,+ )++ assert "could not be removed after failing to start" in caplog.textdiff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.pyindex d1722d7f1..761633a6f 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py@@ -8,6 +8,7 @@ starting listeners.from __future__ import annotations+import asyncioimport uuidfrom collections.abc import Mapping@@ -106,3 +107,29 @@ async def test_an_edit_can_be_checked_before_it_is_stored()assert seen == [{"guild_id": "2"}]+++async def test_is_connected_is_false_until_the_bridge_finishes_starting(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """`_run_bridge` marks a bridge connected only once its adapter's `start`+ has returned and its own client loop is live, the moment traffic can+ safely reach it. Before that — and for a bridge nobody ever started — it+ is not."""+ _, bridge_id = await _bridge(session_factory)+ service = _service(session_factory)+ service.register_adapter("mattermost", _StubAdapter, _StubConfig)++ assert service.is_connected(bridge_id) is False++ async def _run(started_id: str, *_: object) -> None:+ service._connected.add(started_id)++ service._run_bridge = _run # type: ignore[method-assign]++ await service.start(bridge_id)+ # `start` schedules the task and returns; let it run.+ await asyncio.sleep(0)++ assert service.is_connected(bridge_id) is True+ await service.stop_all()diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py b/core/tests/switch_core/bridges/collaboration/test_slack_installer.pyindex b15e9c65f..0c4dcb7ed 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_installer.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_installer.py@@ -18,6 +18,7 @@ import pytestfrom slack_sdk.web.async_client import AsyncWebClientfrom switch_core.bridges.collaboration.install import (+ PUBLIC_PATH_PREFIX,InstallGrant,MessagingInstallerRegistry,MessagingInstallError,@@ -25,6 +26,7 @@ from switch_core.bridges.collaboration.install import (WebhookEndpoint,WebhookPayloadError,events_path,+ notifications_path,oauth_callback_path,public_url,)@@ -86,31 +88,46 @@ class TestAuthorizeUrl:class TestWebhookVerification:- def test_a_correctly_signed_body_passes(self, installer: SlackAppInstaller) -> None:+ async def test_a_correctly_signed_body_passes(+ self, installer: SlackAppInstaller+ ) -> None:body = b'{"type":"event_callback","team_id":"T1"}'- installer.verify_webhook(headers=_signed_headers(body), body=body)+ await installer.verify_webhook(+ endpoint="events", query={}, headers=_signed_headers(body), body=body+ )- def test_a_tampered_body_is_refused(self, installer: SlackAppInstaller) -> None:+ async def test_a_tampered_body_is_refused(+ self, installer: SlackAppInstaller+ ) -> None:body = b'{"type":"event_callback","team_id":"T1"}'headers = _signed_headers(body)with pytest.raises(WebhookAuthenticityError):- installer.verify_webhook(headers=headers, body=body + b" ")+ await installer.verify_webhook(+ endpoint="events", query={}, headers=headers, body=body + b" "+ )- def test_an_old_signature_is_refused(self, installer: SlackAppInstaller) -> None:+ async def test_an_old_signature_is_refused(+ self, installer: SlackAppInstaller+ ) -> None:"""Replay window. A capture stays valid forever without it."""body = b'{"team_id":"T1"}'with pytest.raises(WebhookAuthenticityError):- installer.verify_webhook(- headers=_signed_headers(body, age_seconds=60 * 10), body=body+ await installer.verify_webhook(+ endpoint="events",+ query={},+ headers=_signed_headers(body, age_seconds=60 * 10),+ body=body,)- def test_missing_headers_are_refused_rather_than_skipped(+ async def test_missing_headers_are_refused_rather_than_skipped(self, installer: SlackAppInstaller) -> None:with pytest.raises(WebhookAuthenticityError):- installer.verify_webhook(headers={}, body=b"{}")+ await installer.verify_webhook(+ endpoint="events", query={}, headers={}, body=b"{}"+ )- def test_a_nonnumeric_timestamp_is_a_bad_signature_not_a_crash(+ async def test_a_nonnumeric_timestamp_is_a_bad_signature_not_a_crash(self, installer: SlackAppInstaller) -> None:"""Reachable by anyone who finds the URL.@@ -121,7 +138,9 @@ class TestWebhookVerification:"""body = b"{}"with pytest.raises(WebhookAuthenticityError):- installer.verify_webhook(+ await installer.verify_webhook(+ endpoint="events",+ query={},headers={"X-Slack-Request-Timestamp": "not-a-number","X-Slack-Signature": "v0=deadbeef",@@ -129,10 +148,14 @@ class TestWebhookVerification:body=body,)- def test_header_case_does_not_matter(self, installer: SlackAppInstaller) -> None:+ async def test_header_case_does_not_matter(+ self, installer: SlackAppInstaller+ ) -> None:body = b'{"team_id":"T1"}'headers = {k.lower(): v for k, v in _signed_headers(body).items()}- installer.verify_webhook(headers=headers, body=body)+ await installer.verify_webhook(+ endpoint="events", query={}, headers=headers, body=body+ )class TestRedeem:@@ -163,6 +186,7 @@ class TestRedeem:workspace_name="Acme",bot_token="xoxb-granted",scopes="chat:write,commands",+ platform_data={},)async def test_a_workspace_with_no_name_falls_back_to_its_id(@@ -257,7 +281,9 @@ class TestParsingAWebhook:}).encode()- parsed = installer.parse_webhook(endpoint="events", headers={}, body=body)+ parsed = installer.parse_webhook(+ endpoint="events", headers={}, body=body, query={}+ )[0]assert parsed.envelope_type == "events_api"assert parsed.handshake is None@@ -277,7 +303,9 @@ class TestParsingAWebhook:"""body = json.dumps({"type": "url_verification", "challenge": "abc123"}).encode()- parsed = installer.parse_webhook(endpoint="events", headers={}, body=body)+ parsed = installer.parse_webhook(+ endpoint="events", headers={}, body=body, query={}+ )[0]assert parsed.handshake == "abc123"@@ -286,7 +314,10 @@ class TestParsingAWebhook:) -> None:with pytest.raises(WebhookPayloadError, match="challenge"):installer.parse_webhook(- endpoint="events", headers={}, body=b'{"type":"url_verification"}'+ endpoint="events",+ headers={},+ body=b'{"type":"url_verification"}',+ query={},)def test_a_slash_command_is_its_form_fields(@@ -296,7 +327,9 @@ class TestParsingAWebhook:{"command": "/agents-status", "text": "", "team_id": "T1", "user_id": "U1"}).encode()- parsed = installer.parse_webhook(endpoint="commands", headers={}, body=body)+ parsed = installer.parse_webhook(+ endpoint="commands", headers={}, body=body, query={}+ )[0]assert parsed.envelope_type == "slash_commands"assert parsed.payload["command"] == "/agents-status"@@ -310,7 +343,9 @@ class TestParsingAWebhook:inner = {"type": "block_actions", "team": {"id": "T1"}}body = urlencode({"payload": json.dumps(inner)}).encode()- parsed = installer.parse_webhook(endpoint="interactive", headers={}, body=body)+ parsed = installer.parse_webhook(+ endpoint="interactive", headers={}, body=body, query={}+ )[0]assert parsed.envelope_type == "interactive"assert parsed.payload == inner@@ -319,7 +354,9 @@ class TestParsingAWebhook:self, installer: SlackAppInstaller) -> None:with pytest.raises(WebhookPayloadError, match="payload"):- installer.parse_webhook(endpoint="interactive", headers={}, body=b"other=1")+ installer.parse_webhook(+ endpoint="interactive", headers={}, body=b"other=1", query={}+ )def test_an_event_callback_carries_slacks_own_event_id(self, installer: SlackAppInstaller@@ -334,7 +371,9 @@ class TestParsingAWebhook:{"type": "event_callback", "team_id": "T1", "event_id": "Ev123"}).encode()- parsed = installer.parse_webhook(endpoint="events", headers={}, body=body)+ parsed = installer.parse_webhook(+ endpoint="events", headers={}, body=body, query={}+ )[0]assert parsed.external_event_id == "Ev123"@@ -362,8 +401,11 @@ class TestParsingAWebhook:receipt on, so the event is handled the way an unnumbered one is."""parsed = installer.parse_webhook(- endpoint="events", headers={}, body=json.dumps(envelope).encode()- )+ endpoint="events",+ headers={},+ query={},+ body=json.dumps(envelope).encode(),+ )[0]assert parsed.external_event_id is None@@ -388,7 +430,9 @@ class TestParsingAWebhook:A command and an interaction are a person waiting on a dialog. Slacksends each exactly once and puts no id on it."""- parsed = installer.parse_webhook(endpoint=endpoint, headers={}, body=body)+ parsed = installer.parse_webhook(+ endpoint=endpoint, headers={}, body=body, query={}+ )[0]assert parsed.external_event_id is None@@ -416,7 +460,9 @@ class TestParsingAWebhook:{"type": "event_callback", "team_id": "T1", "event_id": "Ev1"}).encode()- parsed = installer.parse_webhook(endpoint="events", headers=headers, body=body)+ parsed = installer.parse_webhook(+ endpoint="events", headers=headers, body=body, query={}+ )[0]assert parsed.delivery_attempt == expected@@ -438,7 +484,7 @@ class TestParsingAWebhook:rather than a shrug."""with pytest.raises(WebhookPayloadError):- installer.parse_webhook(endpoint="events", headers={}, body=body)+ installer.parse_webhook(endpoint="events", headers={}, body=body, query={})class TestWhichWorkspaceSentIt:@@ -483,6 +529,7 @@ class TestConnectionConfig:workspace_name="Acme",bot_token="xoxb-granted",scopes="chat:write",+ platform_data={},))config = SlackConnectionConfig.model_validate(rendered)@@ -558,3 +605,27 @@ class TestPaths:assert public_url("https://switch.example/", oauth_callback_path("slack")) == public_url("https://switch.example", oauth_callback_path("slack"))++ def test_the_notifications_path_is_scoped_to_its_own_platform(self) -> None:+ assert (+ notifications_path("slack") == f"{PUBLIC_PATH_PREFIX}/slack/notifications"+ )+++class TestInstallerDefaults:+ """Behaviour `MessagingAppInstaller` gives every platform that has no+ per-install token to revoke and no refusal code worth translating —+ Slack's installer overrides neither."""++ async def test_releasing_a_workspace_is_a_no_op_with_no_per_install_token(+ self, installer: SlackAppInstaller+ ) -> None:+ assert await installer.release(external_workspace_id="T1") is None++ def test_a_refusal_is_reported_in_the_platforms_own_words_by_default(+ self, installer: SlackAppInstaller+ ) -> None:+ message = installer.describe_callback_error(+ error="access_denied", description=None+ )+ assert message == "slack reported: access_denied."diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.pyindex 3cda7e06c..66f79b1c7 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py@@ -3,6 +3,9 @@ from __future__ import annotationsimport asynciofrom typing import Any+import httpx+import pytest+from switch_core.agent_icon import generated_icon_urlfrom switch_core.bridges.collaboration.adapter import AgentPresentation, AgentRenderingfrom switch_core.bridges.collaboration.models import InboundCommand, InboundMessage@@ -10,6 +13,7 @@ from switch_core.bridges.collaboration.teams.adapter import (TeamsAdapter,TeamsConnectionConfig,)+from switch_core.bridges.collaboration.teams.auth import SigningKeysUnavailablefrom switch_core.bridges.collaboration.teams.cards import (ADAPTIVE_CARD_CONTENT_TYPE,agent_message_card,@@ -50,7 +54,12 @@ class _FakeConnector:self._raise_on_send = raise_on_sendasync def create_channel_thread(- self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ self,+ *,+ service_url: str,+ channel_id: str,+ tenant_id: str,+ activity: dict[str, Any],) -> tuple[str, str]:self.threads.append({"service_url": service_url, "channel_id": channel_id, "activity": activity}@@ -255,19 +264,30 @@ class _FakeHttpRequest:return self._body-class _RaisingValidator:- def validate(self, auth_header: str | None) -> None:+class _RaisingAuthenticator:+ async def verify(+ self, authorization: str | None, *, service_url: str, channel_id: str+ ) -> None:raise PermissionError("forged")-class _PassValidator:- def validate(self, auth_header: str | None) -> None:+class _KeysOutOfReachAuthenticator:+ async def verify(+ self, authorization: str | None, *, service_url: str, channel_id: str+ ) -> None:+ raise SigningKeysUnavailable("could not fetch signing keys")+++class _PassAuthenticator:+ async def verify(+ self, authorization: str | None, *, service_url: str, channel_id: str+ ) -> None:return Nonedef test_http_messages_rejects_unauthenticated_activity() -> None:adapter = _adapter()- adapter._validator = _RaisingValidator() # type: ignore[assignment]+ adapter._authenticator = _RaisingAuthenticator() # type: ignore[assignment]resp = _run(adapter._handle_http_messages(@@ -281,9 +301,28 @@ def test_http_messages_rejects_unauthenticated_activity() -> None:assert resp.status == 401+def test_http_messages_asks_again_when_microsofts_keys_are_out_of_reach() -> None:+ """Not refused as forged: Teams resends what it is told to retry."""+ adapter = _adapter()+ adapter._authenticator = _KeysOutOfReachAuthenticator() # type: ignore[assignment]+ captured = _capture_messages(adapter)++ resp = _run(+ adapter._handle_http_messages(+ _FakeHttpRequest( # type: ignore[arg-type]+ headers={"Authorization": "Bearer t"},+ body={"type": "message"},+ )+ )+ )++ assert resp.status == 503+ assert captured == []++def test_http_messages_rejects_invalid_json() -> None:adapter = _adapter()- adapter._validator = _PassValidator() # type: ignore[assignment]+ adapter._authenticator = _PassAuthenticator() # type: ignore[assignment]resp = _run(adapter._handle_http_messages(@@ -296,9 +335,24 @@ def test_http_messages_rejects_invalid_json() -> None:assert resp.status == 400+def test_http_messages_rejects_a_json_body_that_is_not_an_activity() -> None:+ """A Bot Framework activity is always a JSON object; a list or a bare+ scalar parses as valid JSON but is not one."""+ adapter = _adapter()+ adapter._authenticator = _PassAuthenticator() # type: ignore[assignment]++ resp = _run(+ adapter._handle_http_messages(+ _FakeHttpRequest(headers={}, body=["not", "an", "activity"]) # type: ignore[arg-type]+ )+ )++ assert resp.status == 400++def test_http_messages_dispatches_authenticated_activity() -> None:adapter = _adapter()- adapter._validator = _PassValidator() # type: ignore[assignment]+ adapter._authenticator = _PassAuthenticator() # type: ignore[assignment]captured = _capture_messages(adapter)activity = {@@ -900,3 +954,61 @@ def _card_text(activity: dict[str, Any]) -> str:"""The body an agent card carries, whatever its shape."""card = activity["attachments"][0]["content"]return "\n".join(str(block.get("text", "")) for block in card["body"])+++def test_a_bring_your_own_bridge_starts_its_own_listener_and_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The bring-your-own path of `start`, unchanged by the distributed app:+ its own HTTP client and credential, its own listener, and on `stop` both+ are closed, since nothing else shares them. The listener opens last: an+ activity it took before the clients existed would be acknowledged and+ lost."""+ real_client = httpx.AsyncClient+ made: list[httpx.AsyncClient] = []++ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return httpx.Response(200, json={"access_token": "t", "expires_in": 3600})+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ def client(**kwargs: Any) -> httpx.AsyncClient:+ made.append(real_client(transport=httpx.MockTransport(handler), **kwargs))+ return made[-1]++ monkeypatch.setattr(httpx, "AsyncClient", client)+ adapter = TeamsAdapter(+ config=_config().model_copy(+ update={"listen_host": "127.0.0.1", "listen_port": 0}+ )+ )++ open_listener = adapter._open_listener+ ready_when_listening: list[bool] = []++ async def open_listener_once_ready() -> None:+ ready_when_listening.append(+ adapter._connector is not None and adapter._graph is not None+ )+ await open_listener()++ adapter._open_listener = open_listener_once_ready # type: ignore[method-assign]++ async def scenario() -> None:+ async def _noop(*args: Any) -> None:+ return None++ await adapter.start(_noop, _noop, _noop, _noop, _noop)+ assert ready_when_listening == [True]+ assert adapter._runner is not None+ assert adapter._owns_http is True+ assert adapter._authenticator is not None+ assert adapter._adopted is True+ await adapter.stop()++ _run(scenario())++ assert adapter._runner is None+ assert [c.is_closed for c in made] == [True]diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_auth.py b/core/tests/switch_core/bridges/collaboration/test_teams_auth.pyindex 6411f4b23..ec6028f31 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_auth.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_auth.py@@ -1,21 +1,40 @@from __future__ import annotationsimport asyncio+import jsonfrom datetime import UTC, datetime, timedelta+from pathlib import Pathfrom typing import Any+import httpximport jwtimport pytest-from cryptography.hazmat.primitives import serialization+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serializationfrom cryptography.hazmat.primitives.asymmetric import rsa+from cryptography.x509.oid import NameOID+from jwt.algorithms import RSAAlgorithmfrom switch_core.bridges.collaboration.teams.auth import (BOT_CONNECTOR_SCOPE,- InboundActivityValidator,+ BOTFRAMEWORK_ISSUER,+ GRAPH_CHANGE_TRACKING_APP_ID,+ BotFrameworkAuthenticator,+ ClientCertificate,+ ClientSecret,+ FederatedTokenFile,+ GraphNotificationAuthenticator,+ SigningKeys,+ SigningKeysUnavailable,TeamsTokenProvider,+ TokenRequestRefused,+ token_endpoint,+ verify_microsoft_id_token,)-_ISSUER = "https://api.botframework.com"+_SERVICE_URL = "https://smba.trafficmanager.net/amer/"+_METADATA = "https://login.example/.well-known/openid"+_JWKS = "https://login.example/keys"def _run(coro: Any) -> Any:@@ -30,7 +49,7 @@ class _FakeResp:def __init__(self, status_code: int, payload: dict[str, Any]) -> None:self.status_code = status_codeself._payload = payload- self.text = str(payload)+ self.text = json.dumps(payload)def json(self) -> dict[str, Any]:return self._payload@@ -46,11 +65,11 @@ class _FakeHttp:return self._resp-def _provider(http: _FakeHttp) -> TeamsTokenProvider:+def _provider(http: _FakeHttp, credential: Any = None) -> TeamsTokenProvider:return TeamsTokenProvider(tenant_id="tenant-1",app_id="app-1",- app_password="secret",+ credential=credential or ClientSecret("secret"),http=http, # type: ignore[arg-type])@@ -63,8 +82,10 @@ def test_token_is_fetched_and_returned() -> None:assert token == "tok-1"assert len(http.calls) == 1+ assert http.calls[0]["url"] == token_endpoint("tenant-1")assert http.calls[0]["data"]["scope"] == BOT_CONNECTOR_SCOPEassert http.calls[0]["data"]["grant_type"] == "client_credentials"+ assert http.calls[0]["data"]["client_secret"] == "secret"def test_token_is_cached_until_expiry() -> None:@@ -79,138 +100,228 @@ def test_token_is_cached_until_expiry() -> None:assert len(http.calls) == 1-def test_token_error_raises() -> None:- http = _FakeHttp(_FakeResp(401, {"error": "invalid_client"}))+def test_token_error_raises_with_microsofts_codes() -> None:+ """The numeric codes are what tell an unapproved app from a bad secret."""+ http = _FakeHttp(+ _FakeResp(400, {"error": "unauthorized_client", "error_codes": [700016]})+ )provider = _provider(http)- try:+ with pytest.raises(TokenRequestRefused) as excinfo:_run(provider.token(BOT_CONNECTOR_SCOPE))- raised = False- except RuntimeError:- raised = True- assert raised+ assert excinfo.value.app_not_approved+ assert excinfo.value.error_codes == frozenset({700016})+++def test_a_wrong_secret_is_not_read_as_an_unapproved_app() -> None:+ http = _FakeHttp(+ _FakeResp(401, {"error": "invalid_client", "error_codes": [7000215]})+ )++ with pytest.raises(TokenRequestRefused) as excinfo:+ _run(_provider(http).token(BOT_CONNECTOR_SCOPE))++ assert not excinfo.value.app_not_approved+++def test_graph_roles_are_read_from_the_issued_token() -> None:+ token = jwt.encode({"roles": ["Channel.Create", "User.ReadBasic.All"]}, "k" * 32)+ http = _FakeHttp(_FakeResp(200, {"access_token": token, "expires_in": 3600}))++ roles = _run(_provider(http).graph_roles())-# ── InboundActivityValidator (Bot Framework JWT verification) ─────────────────+ assert roles == frozenset({"Channel.Create", "User.ReadBasic.All"})-def _keypair() -> tuple[str, str]:- key = rsa.generate_private_key(public_exponent=65537, key_size=2048)- priv_pem = key.private_bytes(+def test_a_token_with_no_roles_has_none() -> None:+ """A directory that withdrew every permission but kept the app still+ issues a token; it carries no roles, and that is the signal."""+ token = jwt.encode({"aud": "https://graph.microsoft.com"}, "k" * 32)+ http = _FakeHttp(_FakeResp(200, {"access_token": token, "expires_in": 3600}))++ assert _run(_provider(http).graph_roles()) == frozenset()+++# ── Credentials ──────────────────────────────────────────────────────────────+++def _rsa_key() -> rsa.RSAPrivateKey:+ return rsa.generate_private_key(public_exponent=65537, key_size=2048)+++def _certificate(key: rsa.RSAPrivateKey) -> x509.Certificate:+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-test")])+ now = datetime.now(UTC)+ return (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now - timedelta(days=1))+ .not_valid_after(now + timedelta(days=1))+ .sign(key, hashes.SHA256())+ )+++def _pem(key: rsa.RSAPrivateKey) -> str:+ return key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption(),).decode()- pub_pem = (- key.public_key()- .public_bytes(- serialization.Encoding.PEM,- serialization.PublicFormat.SubjectPublicKeyInfo,- )- .decode()+++def test_a_certificate_assertion_is_signed_for_the_endpoint_it_goes_to() -> None:+ key = _rsa_key()+ certificate = _certificate(key)+ credential = ClientCertificate(+ certificate_pem=certificate.public_bytes(serialization.Encoding.PEM).decode(),+ private_key_pem=_pem(key),)- return priv_pem, pub_pem+ url = token_endpoint("tenant-9")++ form = _run(credential.form(app_id="app-1", token_url=url))++ assert form["client_assertion_type"].endswith(":jwt-bearer")+ assertion = form["client_assertion"]+ header = jwt.get_unverified_header(assertion)+ assert header["alg"] == "PS256"+ assert "x5t#S256" in header and "x5t" in header+ claims = jwt.decode(assertion, key.public_key(), algorithms=["PS256"], audience=url)+ assert claims["iss"] == claims["sub"] == "app-1"+ assert "client_secret" not in form+++def test_each_assertion_is_fresh() -> None:+ """Microsoft refuses a replayed assertion, so each request gets its own."""+ key = _rsa_key()+ credential = ClientCertificate(+ certificate_pem=_certificate(key)+ .public_bytes(serialization.Encoding.PEM)+ .decode(),+ private_key_pem=_pem(key),+ )+ url = token_endpoint("tenant-9")+ first = _run(credential.form(app_id="app-1", token_url=url))+ second = _run(credential.form(app_id="app-1", token_url=url))-class _FakeSigningKey:- def __init__(self, public_pem: str) -> None:- self.key = public_pem+ assert first["client_assertion"] != second["client_assertion"]-class _FakeJwks:- """Stands in for the network-backed PyJWKClient so decode uses our key."""+def test_a_federated_token_is_read_from_its_file_each_time(tmp_path: Path) -> None:+ path = tmp_path / "token"+ path.write_text("first\n")+ credential = FederatedTokenFile(str(path))+ url = token_endpoint("t")- def __init__(self, public_pem: str) -> None:- self._public_pem = public_pem+ assert _run(credential.form(app_id="a", token_url=url))["client_assertion"] == (+ "first"+ )+ path.write_text("rotated")+ assert _run(credential.form(app_id="a", token_url=url))["client_assertion"] == (+ "rotated"+ )- def get_signing_key_from_jwt(self, token: str) -> _FakeSigningKey:- return _FakeSigningKey(self._public_pem)+def test_an_empty_federated_token_file_refuses(tmp_path: Path) -> None:+ path = tmp_path / "token"+ path.write_text("")-def _validator(public_pem: str, *, app_id: str = "app-1") -> InboundActivityValidator:- validator = InboundActivityValidator(app_id=app_id)- # Bypass the network JWKS fetch by pre-seeding the signing-key source.- validator._jwks = _FakeJwks(public_pem) # type: ignore[assignment]- return validator+ with pytest.raises(TokenRequestRefused, match="empty"):+ _run(FederatedTokenFile(str(path)).form(app_id="a", token_url="u"))-def _token(- priv_pem: str,- *,- aud: str = "app-1",- iss: str = _ISSUER,- expired: bool = False,-) -> str:- now = datetime.now(UTC)- exp = now - timedelta(minutes=5) if expired else now + timedelta(hours=1)- return jwt.encode(- {"aud": aud, "iss": iss, "exp": exp},- priv_pem,- algorithm="RS256",- )+# ── Signing keys and the Bot Framework authenticator ─────────────────────────-def test_validator_accepts_valid_token() -> None:- priv, pub = _keypair()- validator = _validator(pub)+def _jwk(key: rsa.RSAPrivateKey, kid: str, endorsements: list[str]) -> dict[str, Any]:+ entry: dict[str, Any] = RSAAlgorithm.to_jwk(key.public_key(), as_dict=True)+ entry["kid"] = kid+ if endorsements:+ entry["endorsements"] = endorsements+ return entry- # No raise = accepted.- validator.validate(f"Bearer {_token(priv)}")+class _KeyServer:+ """Serves OpenID metadata and a JWKS, counting how often it is asked."""-def test_validator_rejects_missing_header() -> None:- _, pub = _keypair()- validator = _validator(pub)+ def __init__(self, keys: list[dict[str, Any]]) -> None:+ self.keys = keys+ self.fetches = 0+ self.fail = False- with pytest.raises(PermissionError):- validator.validate(None)+ def handler(self, request: httpx.Request) -> httpx.Response:+ if self.fail:+ return httpx.Response(503)+ if str(request.url) == _METADATA:+ return httpx.Response(200, json={"jwks_uri": _JWKS})+ self.fetches += 1+ return httpx.Response(200, json={"keys": self.keys})-def test_validator_rejects_non_bearer_header() -> None:- _, pub = _keypair()- validator = _validator(pub)+def _signing_keys(server: _KeyServer) -> SigningKeys:+ http = httpx.AsyncClient(transport=httpx.MockTransport(server.handler))+ return SigningKeys(metadata_url=_METADATA, http=http)- with pytest.raises(PermissionError):- validator.validate("Basic Zm9vOmJhcg==")++def _bot_token(+ key: rsa.RSAPrivateKey,+ *,+ kid: str = "k1",+ aud: str = "app-1",+ iss: str = BOTFRAMEWORK_ISSUER,+ service_url: str | None = _SERVICE_URL,+ expired: bool = False,+) -> str:+ now = datetime.now(UTC)+ exp = now - timedelta(minutes=30) if expired else now + timedelta(hours=1)+ claims: dict[str, Any] = {"aud": aud, "iss": iss, "exp": exp}+ if service_url is not None:+ claims["serviceurl"] = service_url+ return jwt.encode(claims, key, algorithm="RS256", headers={"kid": kid})+++def _authenticator(+ key: rsa.RSAPrivateKey, *, endorsements: list[str] | None = None+) -> BotFrameworkAuthenticator:+ server = _KeyServer(+ [_jwk(key, "k1", ["msteams"] if endorsements is None else endorsements)]+ )+ return BotFrameworkAuthenticator(app_id="app-1", keys=_signing_keys(server))-def test_validator_rejects_wrong_audience() -> None:- priv, pub = _keypair()- validator = _validator(pub, app_id="app-1")+def _verify(authenticator: BotFrameworkAuthenticator, header: str | None) -> None:+ _run(authenticator.verify(header, service_url=_SERVICE_URL, channel_id="msteams"))- with pytest.raises(PermissionError) as excinfo:- validator.validate(f"Bearer {_token(priv, aud='someone-else')}")- # A mismatch is a misconfiguration, and the operator cannot fix it without- # both halves: the app id Azure addressed the activity to, and the one this- # bridge was registered with.- message = str(excinfo.value)- assert "someone-else" in message- assert "app-1" in message+def test_a_genuine_activity_token_is_accepted() -> None:+ key = _rsa_key()+ _verify(_authenticator(key), f"Bearer {_bot_token(key)}")-def test_audience_mismatch_message_survives_an_unreadable_token(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """The mismatch message reads the audience back out of the token. A token- that decodes for verification but not for inspection must still produce the- rejection, not a second error on top of it."""- priv, pub = _keypair()- validator = _validator(pub, app_id="app-1")- token = _token(priv, aud="someone-else")+def test_a_missing_header_is_refused() -> None:+ with pytest.raises(PermissionError):+ _verify(_authenticator(_rsa_key()), None)- original = jwt.decode- def _decode(*args: Any, **kwargs: Any) -> Any:- if kwargs.get("options", {}).get("verify_aud") is False:- raise jwt.DecodeError("unreadable")- return original(*args, **kwargs)+def test_a_non_bearer_header_is_refused() -> None:+ with pytest.raises(PermissionError):+ _verify(_authenticator(_rsa_key()), "Basic Zm9vOmJhcg==")- monkeypatch.setattr(jwt, "decode", _decode)++def test_a_wrong_audience_names_both_app_ids() -> None:+ """A mismatch is a misconfiguration, and the operator cannot fix it without+ both halves: the app id Azure addressed the activity to, and the one this+ bridge was registered with."""+ key = _rsa_key()with pytest.raises(PermissionError) as excinfo:- validator.validate(f"Bearer {token}")+ _verify(_authenticator(key), f"Bearer {_bot_token(key, aud='someone-else')}")+ assert "someone-else" in str(excinfo.value)assert "app-1" in str(excinfo.value)@@ -219,15 +330,10 @@ def test_the_audience_quoted_back_is_a_signature_verified_one() -> None:"""The rejection message names the audience the token carries, so thatvalue must not come from an unverified parse — otherwise the text- explaining why an attacker was rejected is written by the attacker.-- Every decode in the validator carries a key and checks the signature; only- the audience claim, the one already known to mismatch, is relaxed.- """- priv, pub = _keypair()- validator = _validator(pub, app_id="app-1")+ explaining why an attacker was rejected is written by the attacker."""+ key = _rsa_key()+ authenticator = _authenticator(key)seen: list[dict[str, Any]] = []-original = jwt.decodedef _decode(*args: Any, **kwargs: Any) -> Any:@@ -238,33 +344,352 @@ def test_the_audience_quoted_back_is_a_signature_verified_one(monkeypatch.setattr(jwt, "decode", _decode)with pytest.raises(PermissionError):- validator.validate(f"Bearer {_token(priv, aud='someone-else')}")+ _verify(authenticator, f"Bearer {_bot_token(key, aud='someone-else')}")- assert seen, "the validator did not decode at all"+ assert seenassert not any(o.get("verify_signature") is False for o in seen)-def test_validator_rejects_expired_token() -> None:- priv, pub = _keypair()- validator = _validator(pub)+def test_an_expired_token_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError, match="expired"):+ _verify(_authenticator(key), f"Bearer {_bot_token(key, expired=True)}")+++def test_a_token_from_another_issuer_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError):+ _verify(_authenticator(key), f"Bearer {_bot_token(key, iss='https://evil')}")+++def test_a_bad_signature_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError):+ _verify(_authenticator(key), f"Bearer {_bot_token(_rsa_key())}")+++def test_a_token_for_another_service_url_is_refused() -> None:+ """A token minted for one region replayed with an activity pointing+ elsewhere is the attack the claim exists to stop."""+ key = _rsa_key()+ token = _bot_token(key, service_url="https://smba.trafficmanager.net/emea/")+ with pytest.raises(PermissionError, match="serviceUrl"):+ _verify(_authenticator(key), f"Bearer {token}")+++def test_a_token_with_no_service_url_claim_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError, match="serviceUrl"):+ _verify(_authenticator(key), f"Bearer {_bot_token(key, service_url=None)}")+++def test_a_key_not_endorsed_for_the_channel_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError, match="endorsed"):+ _verify(+ _authenticator(key, endorsements=["skype"]), f"Bearer {_bot_token(key)}"+ )+++def test_an_unknown_key_id_is_refused_without_hammering_the_provider() -> None:+ """A stream of tokens naming made-up key ids must not become a stream of+ requests to Microsoft."""+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "k1", ["msteams"])])+ authenticator = BotFrameworkAuthenticator(+ app_id="app-1", keys=_signing_keys(server)+ )+ _verify(authenticator, f"Bearer {_bot_token(key)}")++ for _ in range(5):+ with pytest.raises(PermissionError, match="unknown key"):+ _verify(authenticator, f"Bearer {_bot_token(key, kid='made-up')}")++ assert server.fetches == 1+- with pytest.raises(jwt.ExpiredSignatureError):- validator.validate(f"Bearer {_token(priv, expired=True)}")+def test_keys_already_held_survive_a_provider_outage() -> None:+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "k1", ["msteams"])])+ keys = _signing_keys(server)+ authenticator = BotFrameworkAuthenticator(app_id="app-1", keys=keys)+ _verify(authenticator, f"Bearer {_bot_token(key)}")+ server.fail = True+ keys._fetched_at = 0.0 # stale, so the next request tries to refresh+ keys._attempted_at = 0.0+ _verify(authenticator, f"Bearer {_bot_token(key)}")-def test_validator_rejects_wrong_issuer() -> None:- priv, pub = _keypair()- validator = _validator(pub)- with pytest.raises(jwt.InvalidIssuerError):- validator.validate(f"Bearer {_token(priv, iss='https://evil.example')}")+# ── Graph validation tokens ──────────────────────────────────────────────────-def test_validator_rejects_bad_signature() -> None:- priv_signing, _ = _keypair()- _, pub_other = _keypair()- # Verify with a public key that does NOT match the signing key.- validator = _validator(pub_other)+def _validation_token(+ key: rsa.RSAPrivateKey,+ *,+ tenant: str = "org-1",+ aud: str = "app-1",+ caller: str = GRAPH_CHANGE_TRACKING_APP_ID,+ version: str = "v2",+ iss: str | None = None,+) -> str:+ issuer = iss or (+ f"https://login.microsoftonline.com/{tenant}/v2.0"+ if version == "v2"+ else f"https://sts.windows.net/{tenant}/"+ )+ claims = {+ "aud": aud,+ "iss": issuer,+ "tid": tenant,+ "exp": datetime.now(UTC) + timedelta(hours=1),+ ("azp" if version == "v2" else "appid"): caller,+ }+ return jwt.encode(claims, key, algorithm="RS256", headers={"kid": "g1"})+++def _notification_authenticator(+ key: rsa.RSAPrivateKey,+) -> GraphNotificationAuthenticator:+ server = _KeyServer([_jwk(key, "g1", [])])+ return GraphNotificationAuthenticator(app_id="app-1", keys=_signing_keys(server))++[email protected]("version", ["v1", "v2"])+def test_validation_tokens_vouch_for_their_directories(version: str) -> None:+ key = _rsa_key()+ tokens = [+ _validation_token(key, tenant="org-1", version=version),+ _validation_token(key, tenant="org-2", version=version),+ ]++ vouched = _run(_notification_authenticator(key).vouched_tenants(tokens))++ assert vouched == frozenset({"org-1", "org-2"})+++def test_a_validation_token_for_another_app_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError):+ _run(+ _notification_authenticator(key).vouched_tenants(+ [_validation_token(key, aud="someone-else")]+ )+ )+++def test_a_validation_token_not_issued_to_graph_is_refused() -> None:+ key = _rsa_key()+ with pytest.raises(PermissionError, match="change-tracking"):+ _run(+ _notification_authenticator(key).vouched_tenants(+ [_validation_token(key, caller="some-other-app")]+ )+ )+++def test_a_validation_token_whose_directory_its_issuer_does_not_name_is_refused() -> (+ None+):+ key = _rsa_key()+ token = _validation_token(+ key, tenant="org-1", iss="https://login.microsoftonline.com/org-2/v2.0"+ )+ with pytest.raises(PermissionError, match="directory"):+ _run(_notification_authenticator(key).vouched_tenants([token]))+++# ── Signing keys: what a key set can go wrong with ───────────────────────────+++def test_no_keys_to_verify_with_is_neither_accepted_nor_called_forged() -> None:+ """Microsoft's key endpoint down at the first request leaves nothing to+ check a signature against. The activity is not accepted, and not refused+ as forged either: that would lose it, where an outage is retried."""+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "k1", ["msteams"])])+ server.fail = True+ authenticator = BotFrameworkAuthenticator(+ app_id="app-1", keys=_signing_keys(server)+ )++ with pytest.raises(SigningKeysUnavailable, match="could not fetch signing keys"):+ _verify(authenticator, f"Bearer {_bot_token(key)}")+ # Too soon to fetch again, and still nothing held to check with.+ with pytest.raises(+ SigningKeysUnavailable, match="no signing keys could be fetched"+ ):+ _verify(authenticator, f"Bearer {_bot_token(key)}")+++def test_entries_that_are_not_usable_keys_are_skipped() -> None:+ key = _rsa_key()+ server = _KeyServer(+ [+ {"kty": "RSA", "n": "AQAB", "e": "AQAB"}, # no kid+ {"kid": "broken", "kty": "RSA", "n": "not base64!", "e": "x"},+ _jwk(key, "k1", ["msteams"]),+ ]+ )+ authenticator = BotFrameworkAuthenticator(+ app_id="app-1", keys=_signing_keys(server)+ )++ _verify(authenticator, f"Bearer {_bot_token(key)}")+++def test_a_key_set_with_nothing_usable_leaves_nothing_to_check_with() -> None:+ key = _rsa_key()+ server = _KeyServer([{"kid": "broken", "kty": "RSA", "n": "!", "e": "!"}])+ authenticator = BotFrameworkAuthenticator(+ app_id="app-1", keys=_signing_keys(server)+ )++ with pytest.raises(SigningKeysUnavailable, match="no usable signing keys"):+ _verify(authenticator, f"Bearer {_bot_token(key)}")+++def test_keys_already_held_survive_a_key_set_with_nothing_usable() -> None:+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "k1", ["msteams"])])+ keys = _signing_keys(server)+ authenticator = BotFrameworkAuthenticator(app_id="app-1", keys=keys)+ _verify(authenticator, f"Bearer {_bot_token(key)}")++ server.keys = [{"kid": "broken", "kty": "RSA", "n": "!", "e": "!"}]+ keys._fetched_at = 0.0+ keys._attempted_at = 0.0+ _verify(authenticator, f"Bearer {_bot_token(key)}")+++def test_a_bearer_that_is_not_a_jwt_is_refused() -> None:+ with pytest.raises(PermissionError, match="not a JWT"):+ _verify(_authenticator(_rsa_key()), "Bearer not-a-jwt")+++def test_a_token_naming_no_signing_key_is_refused() -> None:+ key = _rsa_key()+ unnamed = jwt.encode(+ {"aud": "app-1", "iss": BOTFRAMEWORK_ISSUER}, key, algorithm="RS256"+ )++ with pytest.raises(PermissionError, match="names no signing key"):+ _verify(_authenticator(key), f"Bearer {unnamed}")+++# ── Verifying an id token an admin signed in with ─────────────────────────────+++def _id_token(+ key: rsa.RSAPrivateKey,+ *,+ kid: str = "id1",+ app_id: str = "app-1",+ tenant: str = "tenant-1",+ expired: bool = False,+ claims: dict[str, Any] | None = None,+) -> str:+ now = datetime.now(UTC)+ exp = now - timedelta(minutes=5) if expired else now + timedelta(hours=1)+ body: dict[str, Any] = {+ "aud": app_id,+ "iss": f"https://login.microsoftonline.com/{tenant}/v2.0",+ "tid": tenant,+ "exp": exp,+ }+ if claims:+ body.update(claims)+ return jwt.encode(body, key, algorithm="RS256", headers={"kid": kid})+++def test_a_genuine_id_token_is_accepted() -> None:+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "id1", [])])++ verified = _run(+ verify_microsoft_id_token(+ _id_token(key), app_id="app-1", keys=_signing_keys(server)+ )+ )++ assert verified["tid"] == "tenant-1"+++def test_an_expired_id_token_is_rejected() -> None:+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "id1", [])])++ with pytest.raises(PermissionError, match="id token rejected"):+ _run(+ verify_microsoft_id_token(+ _id_token(key, expired=True),+ app_id="app-1",+ keys=_signing_keys(server),+ )+ )+++def test_an_id_token_addressed_to_a_different_app_is_rejected() -> None:+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "id1", [])])++ with pytest.raises(PermissionError, match="id token rejected"):+ _run(+ verify_microsoft_id_token(+ _id_token(key, app_id="some-other-app"),+ app_id="app-1",+ keys=_signing_keys(server),+ )+ )+++def test_an_id_token_issued_by_a_directory_other_than_the_one_it_names_is_rejected() -> (+ None+):+ key = _rsa_key()+ server = _KeyServer([_jwk(key, "id1", [])])+ forged = _id_token(+ key, claims={"iss": "https://login.microsoftonline.com/someone-else/v2.0"}+ )++ with pytest.raises(+ PermissionError, match="not issued by the organisation it names"+ ):+ _run(+ verify_microsoft_id_token(+ forged, app_id="app-1", keys=_signing_keys(server)+ )+ )+++def test_requests_arriving_during_the_first_fetch_wait_for_its_keys() -> None:+ """A burst at a cold start: every request after the first used to find no+ key and no fetch allowed, and was refused."""+ key = _rsa_key()++ class _SlowKeyServer(_KeyServer):+ async def handle(self, request: httpx.Request) -> httpx.Response:+ if str(request.url) != _METADATA:+ await asyncio.sleep(0.2)+ return self.handler(request)++ server = _SlowKeyServer([_jwk(key, "k1", ["msteams"])])+ http = httpx.AsyncClient(transport=httpx.MockTransport(server.handle))+ authenticator = BotFrameworkAuthenticator(+ app_id="app-1", keys=SigningKeys(metadata_url=_METADATA, http=http)+ )+ header = f"Bearer {_bot_token(key)}"++ async def burst() -> None:+ await asyncio.gather(+ *(+ authenticator.verify(+ header, service_url=_SERVICE_URL, channel_id="msteams"+ )+ for _ in range(5)+ )+ )++ _run(burst())- with pytest.raises(jwt.InvalidSignatureError):- validator.validate(f"Bearer {_token(priv_signing)}")+ assert server.fetches == 1diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_capture.py b/core/tests/switch_core/bridges/collaboration/test_teams_capture.pyindex 394ac9567..77ed355f4 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_capture.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_capture.py@@ -9,6 +9,7 @@ import jsonimport osfrom typing import Any+import pytestfrom cryptography import x509from cryptography.hazmat.primitives import hashes, serializationfrom cryptography.hazmat.primitives.asymmetric import padding as asym_padding@@ -22,11 +23,13 @@ from switch_core.bridges.collaboration.models import InboundMessagefrom switch_core.bridges.collaboration.teams.adapter import (TeamsAdapter,TeamsConnectionConfig,+ _parse_graph_time,)from switch_core.bridges.collaboration.teams.crypto import (ResourceDataError,decrypt_resource_data,load_certificate_der_b64,+ load_private_key,)@@ -111,7 +114,7 @@ def test_decrypt_resource_data_round_trip() -> None:payload = {"id": "m1", "body": {"content": "hello world"}}encrypted = _encrypt_like_graph(payload, cert)- decrypted = decrypt_resource_data(encrypted, key_pem)+ decrypted = decrypt_resource_data(encrypted, load_private_key(key_pem))assert decrypted == payload@@ -122,7 +125,7 @@ def test_decrypt_rejects_tampered_signature() -> None:encrypted["dataSignature"] = base64.b64encode(b"not-the-signature").decode()try:- decrypt_resource_data(encrypted, key_pem)+ decrypt_resource_data(encrypted, load_private_key(key_pem))raised = Falseexcept ResourceDataError:raised = True@@ -180,6 +183,26 @@ def test_validation_handshake_echoes_token() -> None:assert resp.text == "tok-xyz"+def test_a_notification_that_fails_to_handle_does_not_fail_the_whole_batch() -> None:+ """Graph gets a 202 either way: raising here would have it retry a batch+ where only one item was bad, instead of the one that failed."""+ key_pem, cert_pem, _ = _make_key_and_cert()+ adapter = _adapter(key_pem, cert_pem)++ async def _raise(item: dict[str, Any]) -> None:+ raise RuntimeError("boom")++ adapter.receive_notification = _raise # type: ignore[method-assign]++ resp = _run(+ adapter._handle_http_notifications(+ _FakeRequest(body={"value": [{"anything": "goes"}]}) # type: ignore[arg-type]+ )+ )++ assert resp.status == 202++def test_notification_decrypts_and_delivers_message() -> None:key_pem, cert_pem, cert = _make_key_and_cert()adapter = _adapter(key_pem, cert_pem)@@ -198,7 +221,7 @@ def test_notification_decrypts_and_delivers_message() -> None:"encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert len(captured) == 1msg = captured[0]@@ -235,7 +258,7 @@ def test_notification_sets_self_mention_token_for_bot_mention() -> None:"clientState": "s3cr3t","encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert len(captured) == 1assert captured[0].content == "@Bot hi"@@ -266,7 +289,7 @@ def test_notification_no_self_mention_token_for_human_mention() -> None:"clientState": "s3cr3t","encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert len(captured) == 1assert captured[0].content == "@Bob hi"@@ -295,7 +318,7 @@ def test_graph_message_attachment_is_disclosed() -> None:"encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert len(captured) == 1content = captured[0].content@@ -313,7 +336,7 @@ def test_notification_rejects_bad_client_state() -> None:"clientState": "WRONG","encryptedContent": _encrypt_like_graph({"id": "m1"}, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert captured == []@@ -335,7 +358,7 @@ def test_own_bot_message_is_not_delivered() -> None:"clientState": "s3cr3t","encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert captured == []@@ -357,13 +380,96 @@ def test_graph_capture_dedupes_with_bot_framework_path() -> None:"clientState": "s3cr3t","encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))# The same message id already seen via one path is ignored on the other.- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert len(captured) == 1+def _mention_activity(message_id: str) -> dict[str, Any]:+ return {+ "type": "message",+ "id": message_id,+ "serviceUrl": "https://smba.trafficmanager.net/amer/",+ "text": "<at>Switch</at> hi",+ "from": {"aadObjectId": "aad-u", "name": "Alice"},+ "conversation": {+ "id": f"19:[email protected];messageid={message_id}",+ "conversationType": "channel",+ },+ "channelData": {"channel": {"id": "19:[email protected]"}},+ }+++def _graph_message(message_id: str) -> dict[str, Any]:+ return {+ "id": message_id,+ "messageType": "message",+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},+ "body": {"contentType": "text", "content": "hi"},+ }+++def test_a_mention_heard_both_ways_reaches_the_room_once() -> None:+ """A message mentioning the bot arrives as a Bot Framework activity and+ as a Graph notification, under the same id; the second is the same+ message, whichever comes first."""+ key_pem, cert_pem, cert = _make_key_and_cert()+ for activity_first in (True, False):+ adapter = _adapter(key_pem, cert_pem)+ captured = _capture(adapter)+ adapter._channel_type["19:[email protected]"] = "channel_public"+ notification = {+ "clientState": "s3cr3t",+ "encryptedContent": _encrypt_like_graph(_graph_message("m-1"), cert),+ }+ steps = [+ adapter._dispatch_activity(_mention_activity("m-1")),+ adapter.receive_notification(notification),+ ]+ if not activity_first:+ steps.reverse()+ for step in steps:+ _run(step)++ assert len(captured) == 1+++def test_an_encrypted_notification_with_no_key_to_open_it_is_dropped_loudly(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """A subscription can outlive the key it was made with; what it then+ delivers cannot be read, and says so."""+ _, _, cert = _make_key_and_cert()+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="app-123",+ app_password="secret",+ tenant_id="tenant-1",+ team_id="team-1",+ public_base_url="https://switch.example",+ client_state="s3cr3t",+ )+ )+ assert adapter._me.keyring is None+ captured = _capture(adapter)+ caplog.set_level("ERROR")++ _run(+ adapter.receive_notification(+ {+ "clientState": "s3cr3t",+ "encryptedContent": _encrypt_like_graph(_graph_message("m-2"), cert),+ }+ )+ )++ assert captured == []+ assert any("no private key" in r.getMessage() for r in caplog.records)++def test_reply_sets_root_id_from_reply_to_id() -> None:key_pem, cert_pem, cert = _make_key_and_cert()adapter = _adapter(key_pem, cert_pem)@@ -382,7 +488,7 @@ def test_reply_sets_root_id_from_reply_to_id() -> None:"clientState": "s3cr3t","encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert captured[0].root_id == "root-1"@@ -402,7 +508,7 @@ def test_system_event_message_is_ignored() -> None:"clientState": "s3cr3t","encryptedContent": _encrypt_like_graph(chat_message, cert),}- _run(adapter._dispatch_graph_notification(item))+ _run(adapter.receive_notification(item))assert captured == []@@ -449,6 +555,34 @@ def test_ensure_channel_subscription_creates_with_expected_resource() -> None:assert adapter._subscriptions["19:[email protected]"] == "SUB-1"+class _ExpiringGraph(_FakeGraph):+ async def create_subscription(self, **kwargs: Any) -> dict[str, Any]:+ self.created.append(kwargs)+ return {"id": "SUB-1", "expirationDateTime": "2026-01-01T00:00:00Z"}+++def test_an_unparseable_graph_timestamp_is_read_as_unknown_rather_than_raised() -> None:+ assert _parse_graph_time("not-a-timestamp") is None+ assert _parse_graph_time(None) is None+ assert _parse_graph_time(12345) is None+++def test_ensure_channel_subscription_records_when_the_new_one_runs_out() -> None:+ """The renewal loop reads this back to decide whether a subscription is+ close enough to running out to renew; a new one has to record it the same+ as one adopted on restart does."""+ key_pem, cert_pem, _ = _make_key_and_cert()+ adapter = _adapter(key_pem, cert_pem)+ adapter._graph = _ExpiringGraph() # type: ignore[assignment]+ adapter._team_of_channel["19:[email protected]"] = "team-9"++ _run(adapter._ensure_channel_subscription("19:[email protected]"))++ assert adapter._subscription_expiry["19:[email protected]"] == datetime.datetime(+ 2026, 1, 1, tzinfo=datetime.UTC+ )++def test_ensure_channel_subscription_skips_without_certificate() -> None:adapter = TeamsAdapter(config=TeamsConnectionConfig(@@ -504,7 +638,7 @@ def test_adopt_existing_subscriptions_deletes_stale_and_keeps_current() -> None:# recreated cleanly.key_pem, cert_pem, _ = _make_key_and_cert()adapter = _adapter(key_pem, cert_pem)- current = adapter._notification_url+ current = adapter._me.notification_urlfake = _FakeGraph(existing=[{@@ -532,6 +666,43 @@ def test_adopt_existing_subscriptions_deletes_stale_and_keeps_current() -> None:assert fake.deleted == ["OLD"]+def test_adopt_existing_subscriptions_records_a_readable_expiry() -> None:+ """A subscription adopted on restart is handed to the renewal loop the+ same as one this process made itself, so it has to carry when the+ adopted one actually runs out."""+ key_pem, cert_pem, _ = _make_key_and_cert()+ adapter = _adapter(key_pem, cert_pem)+ current = adapter._me.notification_url+ fake = _FakeGraph(+ existing=[+ {+ "id": "CUR",+ "resource": "teams/t/channels/19:[email protected]/messages",+ "notificationUrl": current,+ "expirationDateTime": "2026-01-01T00:00:00Z",+ }+ ]+ )+ adapter._graph = fake # type: ignore[assignment]++ _run(adapter._adopt_existing_subscriptions())++ assert adapter._subscription_expiry["19:[email protected]"] == datetime.datetime(+ 2026, 1, 1, tzinfo=datetime.UTC+ )+++def test_renewing_a_subscription_with_no_graph_client_yet_is_a_no_op() -> None:+ """Reached only if a renewal round somehow outlives `stop()` clearing the+ graph client; nothing to renew against, so this is a no-op rather than an+ attribute error on a bridge mid-shutdown."""+ key_pem, cert_pem, _ = _make_key_and_cert()+ adapter = _adapter(key_pem, cert_pem)+ assert adapter._graph is None++ _run(adapter._renew_subscription("19:[email protected]", "SUB-1"))++def test_channel_from_resource_parses_channel_id() -> None:assert (TeamsAdapter._channel_from_resource(@@ -548,7 +719,7 @@ def test_lifecycle_reauthorization_renews_subscription() -> None:adapter._graph = fake # type: ignore[assignment]_run(- adapter._dispatch_graph_notification(+ adapter.receive_notification({"lifecycleEvent": "reauthorizationRequired","subscriptionId": "SUB-42",@@ -571,7 +742,7 @@ def test_lifecycle_event_with_bad_client_state_is_rejected() -> None:adapter._graph = fake # type: ignore[assignment]_run(- adapter._dispatch_graph_notification(+ adapter.receive_notification({"lifecycleEvent": "reauthorizationRequired","subscriptionId": "SUB-42",@@ -594,7 +765,7 @@ def test_lifecycle_subscription_removed_recreates() -> None:adapter._subscriptions["19:[email protected]"] = "SUB-OLD"_run(- adapter._dispatch_graph_notification(+ adapter.receive_notification({"lifecycleEvent": "subscriptionRemoved","subscriptionId": "SUB-OLD",@@ -608,7 +779,7 @@ def test_lifecycle_subscription_removed_recreates() -> None:assert adapter._subscriptions["19:[email protected]"] == "SUB-1"-def test_renew_all_subscriptions_renews_each() -> None:+def test_renew_due_subscriptions_renews_each_with_no_known_expiry() -> None:key_pem, cert_pem, _ = _make_key_and_cert()adapter = _adapter(key_pem, cert_pem)fake = _FakeGraph()@@ -618,6 +789,6 @@ def test_renew_all_subscriptions_renews_each() -> None:"19:[email protected]": "S2",}- _run(adapter._renew_all_subscriptions())+ _run(adapter._renew_due_subscriptions())assert {r["subscription_id"] for r in fake.renewed} == {"S1", "S2"}diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.py b/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.pyindex e85affe44..767e0fe66 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_capture_repair.py@@ -36,10 +36,10 @@ _CHANNEL = "19:[email protected]"@functools.lru_cache(maxsize=1)-def _cert_pem() -> str:- """A real self-signed certificate — the subscription path loads it before- it calls Graph, so a placeholder would fail these tests for the wrong- reason. Generated once for the module."""+def _keypair() -> tuple[str, str]:+ """A real self-signed certificate and its key — the bridge reads both when+ it is built, so a placeholder would fail these tests for the wrong reason.+ Generated once for the module."""key = rsa.generate_private_key(public_exponent=65537, key_size=2048)name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-teams-test")])now = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)@@ -53,7 +53,12 @@ def _cert_pem() -> str:.not_valid_after(now + datetime.timedelta(days=365)).sign(key, hashes.SHA256()))- return cert.public_bytes(serialization.Encoding.PEM).decode()+ key_pem = key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode()+ return cert.public_bytes(serialization.Encoding.PEM).decode(), key_pemdef _config() -> TeamsConnectionConfig:@@ -64,8 +69,8 @@ def _config() -> TeamsConnectionConfig:team_id="team-1",public_base_url="https://switch.example",encryption_certificate_id="cert-1",- encryption_public_certificate=_cert_pem(),- encryption_private_key="unused — nothing here decrypts a notification",+ encryption_public_certificate=_keypair()[0],+ encryption_private_key=_keypair()[1],client_state="s3cr3t",)@@ -87,6 +92,10 @@ class _Graph:raise self._errorreturn {"id": "sub-1"}+ async def list_subscriptions(self) -> list[dict[str, Any]]:+ # None yet: what the bridge reads before making its first.+ return []+def _adapter(graph: _Graph) -> TeamsAdapter:adapter = TeamsAdapter(config=_config())@@ -237,3 +246,31 @@ async def test_a_channel_that_never_recovers_is_still_being_tried(assert graph.attempts >= 4assert _CHANNEL in adapter._capture_wanted+++async def test_a_round_that_raises_outright_is_logged_and_the_loop_keeps_going(+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ """`_ensure_channel_subscription` catches its own failures, so this is the+ loop's own belt-and-braces: whatever still escapes one round must not end+ the task, with the next round running all the same."""+ monkeypatch.setattr(adapter_module, "_REPAIR_MIN_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(adapter_module, "_REPAIR_MAX_INTERVAL_SECONDS", 0.02)+ adapter = _adapter(_Graph(failures=0))+ adapter._capture_wanted.add(_CHANNEL)+ rounds = 0++ async def _raise(channel_id: str) -> None:+ nonlocal rounds+ rounds += 1+ raise RuntimeError("unexpected")++ adapter._ensure_channel_subscription = _raise # type: ignore[method-assign]++ with caplog.at_level("ERROR"):+ await _drive(adapter, until=lambda: rounds >= 2)++ assert rounds >= 2+ assert any(+ "Teams capture repair failed this round" in r.message for r in caplog.records+ )diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_card_buttons.py b/core/tests/switch_core/bridges/collaboration/test_teams_card_buttons.pyindex ded7c34fa..698803207 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_card_buttons.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_card_buttons.py@@ -462,7 +462,7 @@ async def test_the_answer_to_a_press_reaches_teams_as_the_invoke_response() -> N"""A bare 200 with no body is what every other activity gets, and it saysnothing to the presser. The response is the only channel a refusal has."""adapter, _connector = _teams()- adapter._validator = None+ adapter._authenticator = Noneasync def refuse(interaction: InboundInteraction) -> None:await adapter.tell_actor(@@ -483,7 +483,7 @@ async def test_an_ordinary_message_still_answers_with_a_bare_acknowledgement() -"""Only an invoke has a body to return, and a message carrying one would bea change in what every Teams activity has always been answered with."""adapter, _connector = _teams()- adapter._validator = None+ adapter._authenticator = Noneresponse = await adapter._handle_http_messages(_FakeHttpRequest( # type: ignore[arg-type]diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.py b/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.pyindex 81ac913d7..204980675 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_channel_layout.py@@ -37,7 +37,12 @@ class _Connector:self.replies: list[str] = []async def create_channel_thread(- self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ self,+ *,+ service_url: str,+ channel_id: str,+ tenant_id: str,+ activity: dict[str, Any],) -> tuple[str, str]:self.new_posts.append(channel_id)return f"{channel_id};messageid=new", "msg-new"diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_clients.py b/core/tests/switch_core/bridges/collaboration/test_teams_clients.pyindex 741cbc67b..5b1e59abc 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_clients.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_clients.py@@ -16,6 +16,8 @@ from typing import Anyimport httpximport pytest+from switch_core.bridges.collaboration.models import BridgeOperationError+from switch_core.bridges.collaboration.teams import graph as graph_modulefrom switch_core.bridges.collaboration.teams.connector import (ACTIVITY_SIZE_LIMIT,BotConnectorClient,@@ -99,8 +101,18 @@ def _graph(recorder: _Recorder, tokens: _FakeTokens | None = None) -> GraphClienreturn GraphClient(tokens=tokens or _FakeTokens(), http=_client(recorder)) # type: ignore[arg-type]-def _connector(recorder: _Recorder) -> BotConnectorClient:- return BotConnectorClient(tokens=_FakeTokens(), http=_client(recorder)) # type: ignore[arg-type]+def _connector(+ recorder: _Recorder,+ *,+ allowed_hosts: frozenset[str] | None = None,+ on_bot_disabled: Any = None,+) -> BotConnectorClient:+ return BotConnectorClient(+ tokens=_FakeTokens(), # type: ignore[arg-type]+ http=_client(recorder),+ allowed_hosts=allowed_hosts,+ on_bot_disabled=on_bot_disabled or (lambda: None),+ )# ── GraphClient ───────────────────────────────────────────────────────────────@@ -237,6 +249,7 @@ def test_create_channel_thread_builds_body_and_parses_ids() -> None:connector.create_channel_thread(service_url="https://smba.example/amer/",channel_id="19:[email protected]",+ tenant_id="tenant-1",activity={"type": "message", "text": "hi"},))@@ -248,6 +261,9 @@ def test_create_channel_thread_builds_body_and_parses_ids() -> None:body = rec.last_json()assert body["isGroup"] is Trueassert body["channelData"]["channel"]["id"] == "19:[email protected]"+ # Microsoft asks a proactive message to name the organisation, and with one+ # app serving many the channel id alone does not.+ assert body["channelData"]["tenant"]["id"] == "tenant-1"def test_create_channel_thread_refuses_to_invent_an_activity_id() -> None:@@ -263,6 +279,7 @@ def test_create_channel_thread_refuses_to_invent_an_activity_id() -> None:connector.create_channel_thread(service_url="https://smba.example/amer/",channel_id="19:[email protected]",+ tenant_id="tenant-1",activity={"type": "message"},))@@ -279,6 +296,7 @@ def test_create_channel_thread_error_raises() -> None:connector.create_channel_thread(service_url="https://smba.example/amer/",channel_id="19:[email protected]",+ tenant_id="tenant-1",activity={"type": "message"},))@@ -468,6 +486,8 @@ def test_a_429_is_throttling_and_carries_the_wait_teams_asked_for() -> None:connector = BotConnectorClient(tokens=_FakeTokens(), # type: ignore[arg-type]http=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ allowed_hosts=None,+ on_bot_disabled=lambda: None,)with pytest.raises(BotConnectorThrottled) as raised:@@ -489,6 +509,8 @@ def test_an_unreadable_retry_after_leaves_the_wait_unstated() -> None:connector = BotConnectorClient(tokens=_FakeTokens(), # type: ignore[arg-type]http=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ allowed_hosts=None,+ on_bot_disabled=lambda: None,)with pytest.raises(BotConnectorThrottled) as raised:@@ -543,6 +565,8 @@ def test_a_transport_failure_never_escapes_as_httpx() -> None:connector = BotConnectorClient(tokens=_FakeTokens(), # type: ignore[arg-type]http=httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ allowed_hosts=None,+ on_bot_disabled=lambda: None,)with pytest.raises(BotConnectorUnavailable) as raised:@@ -625,3 +649,356 @@ def test_what_the_guard_measured_is_what_goes_on_the_wire() -> None:assert rec.last_json()["text"] == "héllo 😀"assert rec.last.headers["Content-Type"] == "application/json"+++def test_the_token_is_never_sent_to_a_host_outside_the_allowlist() -> None:+ """Under the distributed app the token posts into every organisation's+ Teams, so a learned or stored address that is not Microsoft's is refused+ before the token is attached."""+ rec = _Recorder(201, {"id": "msg-1"})+ connector = _connector(rec, allowed_hosts=frozenset({"smba.trafficmanager.net"}))++ with pytest.raises(BotConnectorRefused, match="not a Bot Connector host"):+ _run(+ connector.send_to_conversation(+ service_url="https://attacker.example/amer/",+ conversation_id="19:[email protected]",+ activity={"type": "message"},+ )+ )++ assert rec.requests == []+++def test_an_allowed_host_over_plain_http_is_still_refused() -> None:+ rec = _Recorder(201, {"id": "msg-1"})+ connector = _connector(rec, allowed_hosts=frozenset({"smba.trafficmanager.net"}))++ with pytest.raises(BotConnectorRefused):+ _run(+ connector.send_to_conversation(+ service_url="http://smba.trafficmanager.net/amer/",+ conversation_id="19:[email protected]",+ activity={"type": "message"},+ )+ )+++def test_an_allowed_host_is_called() -> None:+ rec = _Recorder(201, {"id": "msg-1"})+ connector = _connector(rec, allowed_hosts=frozenset({"smba.trafficmanager.net"}))++ _run(+ connector.send_to_conversation(+ service_url="https://smba.trafficmanager.net/amer/",+ conversation_id="19:[email protected]",+ activity={"type": "message"},+ )+ )++ assert len(rec.requests) == 1+++def test_a_blocked_app_is_reported() -> None:+ told: list[bool] = []+ rec = _Recorder(403, {"error": {"code": "BotDisabledByAdmin"}})+ connector = _connector(rec, on_bot_disabled=lambda: told.append(True))++ with pytest.raises(BotConnectorRefused):+ _run(+ connector.send_to_conversation(+ service_url="https://smba.example/amer/",+ conversation_id="19:[email protected]",+ activity={"type": "message"},+ )+ )++ assert told == [True]+++# ── Paging, and the app's own installation in a team ─────────────────────────+++class _PagedRecorder(_Recorder):+ """Answers each request with the next of a list of pages."""++ def __init__(self, pages: list[dict[str, Any]]) -> None:+ super().__init__()+ self._pages = list(pages)++ def handler(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ return httpx.Response(200, json=self._pages.pop(0))+++def test_every_page_of_subscriptions_is_read() -> None:+ """An organisation with many captured channels has more subscriptions than+ one page holds; one left unread at start would be made a second time."""+ recorder = _PagedRecorder(+ [+ {+ "value": [{"id": "S1"}],+ "@odata.nextLink": "https://graph.microsoft.com/v1.0/subscriptions?$skiptoken=2",+ },+ {"value": [{"id": "S2"}]},+ ]+ )++ subs = _run(_graph(recorder).list_subscriptions())++ assert [s["id"] for s in subs] == ["S1", "S2"]+ assert str(recorder.requests[1].url).endswith("$skiptoken=2")+++def test_every_page_of_teams_is_read_and_the_query_is_sent_once() -> None:+ recorder = _PagedRecorder(+ [+ {+ "value": [{"id": "T1", "displayName": "One"}],+ "@odata.nextLink": "https://graph.microsoft.com/v1.0/teams?$skiptoken=2",+ },+ {"value": [{"id": "T2", "displayName": "Two"}]},+ ]+ )++ teams = _run(_graph(recorder).list_teams())++ assert [t["id"] for t in teams] == ["T1", "T2"]+ assert recorder.requests[0].url.params["$select"] == "id,displayName"+ assert "$select" not in recorder.requests[1].url.params+++def test_a_next_page_off_graph_is_not_sent_the_token() -> None:+ recorder = _PagedRecorder(+ [+ {+ "value": [{"id": "S1"}],+ "@odata.nextLink": "https://elsewhere.example/v1.0/subscriptions?$skiptoken=2",+ },+ {"value": [{"id": "S2"}]},+ ]+ )++ with pytest.raises(BridgeOperationError, match="not on graph.microsoft.com"):+ _run(_graph(recorder).list_subscriptions())++ assert len(recorder.requests) == 1+++def test_channel_and_installation_ids_stay_one_path_segment() -> None:+ recorder = _Recorder(200, {"id": "x"})+ graph = _graph(recorder)++ _run(graph.get_channel(team_id="t1", channel_id="19:a/[email protected]"))+ assert recorder.last.url.raw_path.split(b"?")[0] == (+ b"/v1.0/teams/t1/channels/19:a%2Fb%[email protected]"+ )++ _run(graph.uninstall_app(team_id="t1", installation_id="NmRi/Mw=="))+ assert recorder.last.url.raw_path == b"/v1.0/teams/t1/installedApps/NmRi%2FMw%3D%3D"+++def test_a_real_channel_id_is_sent_as_it_is() -> None:+ recorder = _Recorder(200, {"id": "x"})++ _run(+ _graph(recorder).get_channel(team_id="t1", channel_id="19:[email protected]")+ )++ assert (+ recorder.last.url.raw_path.split(b"?")[0]+ == b"/v1.0/teams/t1/channels/19:[email protected]"+ )+++def test_a_failed_page_raises() -> None:+ with pytest.raises(GraphError) as failed:+ _run(_graph(_Recorder(503, {"error": {"message": "busy"}})).list_teams())+ assert failed.value.status == 503+++def test_the_app_is_added_to_a_team_by_its_catalogue_id() -> None:+ recorder = _Recorder(201)++ _run(_graph(recorder).install_app(team_id="team-1", catalog_app_id="cat-1"))++ assert recorder.last.method == "POST"+ assert recorder.last.url.path == "/v1.0/teams/team-1/installedApps"+ assert recorder.last_json() == {+ "[email protected]": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/cat-1"+ }+++def test_adding_the_app_where_it_already_is_is_not_an_error() -> None:+ _run(_graph(_Recorder(409)).install_app(team_id="team-1", catalog_app_id="cat-1"))+++def test_a_refused_addition_raises() -> None:+ with pytest.raises(GraphError):+ _run(_graph(_Recorder(403)).install_app(team_id="team-1", catalog_app_id="c"))+++def test_the_apps_installations_are_found_by_its_manifest_id() -> None:+ recorder = _Recorder(+ 200,+ {+ "value": [+ {"id": "INST-1", "teamsApp": {"id": "cat-1"}},+ {"id": "INST-2", "teamsApp": None},+ {"teamsApp": {"id": "no-installation-id"}},+ ]+ },+ )++ found = _run(+ _graph(recorder).find_app_installations(team_id="team-1", external_id="app-1")+ )++ assert [(i.installation_id, i.catalog_app_id) for i in found] == [+ ("INST-1", "cat-1"),+ ("INST-2", None),+ ]+ assert recorder.last.url.params["$filter"] == "teamsApp/externalId eq 'app-1'"+ assert recorder.last.url.params["$expand"] == "teamsApp"+++def test_a_team_whose_apps_cannot_be_read_raises() -> None:+ with pytest.raises(GraphError) as failed:+ _run(+ _graph(_Recorder(404)).find_app_installations(+ team_id="team-1", external_id="app-1"+ )+ )+ assert failed.value.status == 404+++def test_removing_the_app_from_a_team_it_has_left_is_not_an_error() -> None:+ recorder = _Recorder(404)++ _run(_graph(recorder).uninstall_app(team_id="team-1", installation_id="INST-1"))++ assert recorder.last.method == "DELETE"+ assert recorder.last.url.path == "/v1.0/teams/team-1/installedApps/INST-1"+++def test_a_refused_removal_raises() -> None:+ with pytest.raises(GraphError):+ _run(+ _graph(_Recorder(500)).uninstall_app(+ team_id="team-1", installation_id="INST-1"+ )+ )+++def test_a_team_id_cannot_move_the_rest_of_the_url() -> None:+ """A team id comes from a request; a `?` or `/` in it must not turn the+ path after it into a query, or into somewhere else."""+ recorder = _Recorder(201)++ _run(_graph(recorder).install_app(team_id="x?y=1/../../users", catalog_app_id="c"))++ assert recorder.last.url.raw_path.startswith(+ b"/v1.0/teams/x%3Fy%3D1%2F..%2F..%2Fusers/installedApps"+ )+ assert recorder.last.url.query == b""+++# ── Throttling ───────────────────────────────────────────────────────────────+++class _ThrottlingRecorder(_Recorder):+ """Throttles the first `times` requests, naming `retry_after` if given."""++ def __init__(self, *, times: int, retry_after: str | None) -> None:+ super().__init__(200, {"value": []})+ self._times = times+ self._retry_after = retry_after++ def handler(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ if self._times > 0:+ self._times -= 1+ headers = {"Retry-After": self._retry_after} if self._retry_after else {}+ return httpx.Response(+ 429, json={"error": {"message": "slow down"}}, headers=headers+ )+ return httpx.Response(200, json=self.body)+++def waits(monkeypatch: pytest.MonkeyPatch) -> list[float]:+ slept: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ slept.append(seconds)++ monkeypatch.setattr(graph_module.asyncio, "sleep", fake_sleep)+ return slept+++def test_a_throttled_call_waits_as_long_as_graph_asks_and_tries_again(+ waits: list[float],+) -> None:+ recorder = _ThrottlingRecorder(times=2, retry_after="3")++ teams = _run(_graph(recorder).list_teams())++ assert teams == []+ assert len(recorder.requests) == 3+ assert waits == [3.0, 3.0]+++def test_without_a_named_wait_the_wait_grows(waits: list[float]) -> None:+ recorder = _ThrottlingRecorder(times=2, retry_after=None)++ _run(_graph(recorder).list_teams())++ assert waits == [1.0, 2.0]+++def test_throttling_that_outlasts_the_retries_is_raised(waits: list[float]) -> None:+ recorder = _ThrottlingRecorder(times=5, retry_after="1")++ with pytest.raises(GraphError) as failed:+ _run(_graph(recorder).list_teams())++ assert failed.value.status == 429+ assert len(recorder.requests) == 3+++def test_a_wait_longer_than_is_worth_sitting_through_is_raised_at_once(+ waits: list[float],+) -> None:+ recorder = _ThrottlingRecorder(times=1, retry_after="120")++ with pytest.raises(GraphError) as failed:+ _run(_graph(recorder).list_teams())++ assert failed.value.status == 429+ assert waits == []+ assert len(recorder.requests) == 1+++def test_a_user_is_read_by_their_escaped_id() -> None:+ recorder = _Recorder(200, {"id": "u/1", "displayName": "Alice"})++ user = _run(_graph(recorder).get_user(user_id="u/1"))++ assert user["displayName"] == "Alice"+ assert recorder.last.url.raw_path.startswith(b"/v1.0/users/u%2F1?")+++def test_a_user_graph_cannot_find_raises() -> None:+ with pytest.raises(GraphError) as failed:+ _run(_graph(_Recorder(404)).get_user(user_id="u-1"))+ assert failed.value.status == 404+++def test_a_channel_graph_will_not_show_raises() -> None:+ with pytest.raises(GraphError) as failed:+ _run(+ _graph(_Recorder(403)).get_channel(+ team_id="team-1", channel_id="19:[email protected]"+ )+ )+ assert failed.value.status == 403diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_distributed_app_package.py b/core/tests/switch_core/bridges/collaboration/test_teams_distributed_app_package.pynew file mode 100644index 000000000..c558dc23c--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_distributed_app_package.py@@ -0,0 +1,167 @@+"""The distributed Teams app's package, as Switch builds it for an organisation."""++from __future__ import annotations++import io+import json+import zipfile+from pathlib import Path+from typing import Any++import pytest++from switch_core.bridges.collaboration.teams import app_package as app_package_module+from switch_core.bridges.collaboration.teams.app_package import (+ build_distributed_app_package,+)++APP_ID = "aaaaaaaa-1111-1111-1111-111111111111"+_BYO_MANIFEST = (+ Path(__file__).resolve().parents[5] / "docs/old/bridges/teams-app/manifest.json"+)+++def _package() -> tuple[dict[str, Any], zipfile.ZipFile]:+ package = build_distributed_app_package(+ app_id=APP_ID,+ app_name="Agent Switch",+ messaging_public_url="https://switch.example",+ privacy_url="https://switch.example/privacy",+ terms_url="https://switch.example/terms",+ )+ archive = zipfile.ZipFile(io.BytesIO(package.archive))+ return json.loads(archive.read("manifest.json")), archive+++def test_the_package_is_flat_with_its_manifest_and_icons() -> None:+ """Teams rejects a package whose files sit inside a folder."""+ _, archive = _package()+ assert sorted(archive.namelist()) == ["color.png", "manifest.json", "outline.png"]+++def test_this_deployments_values_are_filled_in() -> None:+ manifest, _ = _package()+ assert manifest["id"] == APP_ID+ assert manifest["bots"][0]["botId"] == APP_ID+ assert manifest["validDomains"] == ["switch.example"]+ assert manifest["developer"]["privacyUrl"] == "https://switch.example/privacy"+ assert manifest["developer"]["termsOfUseUrl"] == "https://switch.example/terms"+++def test_the_default_name_is_agent_switch() -> None:+ manifest, _ = _package()+ assert manifest["name"] == {+ "short": "Agent Switch",+ "full": "Agent Switch — your AI agents, in your channels",+ }+++def test_an_environment_names_its_own_app() -> None:+ """Each environment registers its own app; an organisation approving more+ than one — ours, testing them — tells them apart by name."""+ package = build_distributed_app_package(+ app_id=APP_ID,+ app_name="Agent Switch (dev)",+ messaging_public_url="https://switch.example",+ privacy_url="https://switch.example/privacy",+ terms_url="https://switch.example/terms",+ )+ manifest = json.loads(+ zipfile.ZipFile(io.BytesIO(package.archive)).read("manifest.json")+ )+ assert manifest["name"] == {+ "short": "Agent Switch (dev)",+ "full": "Agent Switch (dev) — your AI agents, in your channels",+ }+++def test_a_name_with_json_characters_stays_a_string() -> None:+ package = build_distributed_app_package(+ app_id=APP_ID,+ app_name='Switch "QA" {{x}}',+ messaging_public_url="https://switch.example",+ privacy_url="https://switch.example/privacy",+ terms_url="https://switch.example/terms",+ )+ manifest = json.loads(+ zipfile.ZipFile(io.BytesIO(package.archive)).read("manifest.json")+ )+ assert manifest["name"]["short"] == 'Switch "QA" {{x}}'+++def test_it_asks_for_nothing_per_team() -> None:+ """The organisation's admin grants the app's permissions once, so asking+ again per team would only add a consent prompt and a broader install+ permission."""+ manifest, _ = _package()+ assert "authorization" not in manifest+++def test_it_names_its_entra_app_so_it_can_install_itself() -> None:+ """Graph installs a Teams app into a team under the app's "itself"+ permission only when the package's webApplicationInfo names the app whose+ token asks; without it the install is refused as one of another app.+ No resource: that is for single sign-on, which the app does not use."""+ manifest, _ = _package()+ assert manifest["webApplicationInfo"] == {"id": APP_ID}+++def test_it_works_in_private_and_shared_channels() -> None:+ manifest, _ = _package()+ assert manifest["supportsChannelFeatures"] == "tier1"+ assert tuple(int(p) for p in manifest["manifestVersion"].split(".")) >= (1, 25)+++def test_it_does_not_claim_to_be_the_self_hosted_app() -> None:+ manifest, _ = _package()+ assert "talks only to your own Switch server" not in manifest["description"]["full"]+ assert len(manifest["description"]["full"]) <= 4000+++def test_its_commands_match_the_bring_your_own_apps() -> None:+ """Both apps offer the same in-room commands; this keeps the two lists+ from drifting apart."""+ manifest, _ = _package()+ byo = json.loads(_BYO_MANIFEST.read_text())+ assert manifest["bots"][0]["commandLists"] == byo["bots"][0]["commandLists"]+ assert manifest["bots"][0]["scopes"] == byo["bots"][0]["scopes"]+++def test_a_value_with_json_syntax_in_it_stays_a_string() -> None:+ package = build_distributed_app_package(+ app_id=APP_ID,+ app_name="Agent Switch",+ messaging_public_url="https://switch.example",+ privacy_url='https://switch.example/privacy?a="b"',+ terms_url="https://switch.example/terms\\x",+ )+ manifest = json.loads(+ zipfile.ZipFile(io.BytesIO(package.archive)).read("manifest.json")+ )+ assert manifest["developer"]["privacyUrl"] == 'https://switch.example/privacy?a="b"'+ assert manifest["developer"]["termsOfUseUrl"] == "https://switch.example/terms\\x"+++def test_an_unfilled_placeholder_in_the_template_is_a_loud_failure(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A deployment value that never got substituted must not ship silently —+ Teams would treat the literal ``{{...}}`` as the value itself."""+ manifest = {+ "id": "placeholder",+ "bots": [{"botId": "placeholder"}],+ "webApplicationInfo": {"id": "placeholder"},+ "developer": {},+ "unfilled": "{{SOMETHING}}",+ }+ (tmp_path / "manifest.json").write_text(json.dumps(manifest))+ monkeypatch.setattr(app_package_module, "_TEMPLATE_DIR", tmp_path)++ with pytest.raises(ValueError, match="does not fill in"):+ build_distributed_app_package(+ app_id=APP_ID,+ app_name="Agent Switch",+ messaging_public_url="https://switch.example",+ privacy_url="https://switch.example/privacy",+ terms_url="https://switch.example/terms",+ )diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_identity.py b/core/tests/switch_core/bridges/collaboration/test_teams_identity.pynew file mode 100644index 000000000..855c8562f--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_identity.py@@ -0,0 +1,85 @@+"""Who a Teams bridge on the distributed app speaks as.++`OrgTokens` is the one place a SingleTenant bot's two directories meet: every+Bot Connector token comes from Switch's own directory, and every Graph token+from the customer's. Get the delegation backwards and either the bridge posts+with a token the customer's directory never issued, or it reads Graph with a+token the organisation approving the app never granted.+"""++from __future__ import annotations++import pytest++from switch_core.bridges.collaboration.teams.auth import BOT_CONNECTOR_SCOPE+from switch_core.bridges.collaboration.teams.crypto import ResourceDataError+from switch_core.bridges.collaboration.teams.identity import (+ NotificationKey,+ NotificationKeyring,+ OrgTokens,+)+++class _FakeProvider:+ def __init__(self, name: str) -> None:+ self.name = name+ self.invalidated: list[str] = []++ async def bot_token(self) -> str:+ return f"{self.name}-bot-token"++ async def graph_token(self) -> str:+ return f"{self.name}-graph-token"++ async def graph_roles(self) -> frozenset[str]:+ return frozenset({f"{self.name}-role"})++ def invalidate(self, scope: str, *, min_age_seconds: float = 0.0) -> bool:+ self.invalidated.append(scope)+ return True+++def _tokens() -> tuple[OrgTokens, _FakeProvider, _FakeProvider]:+ home, org = _FakeProvider("home"), _FakeProvider("org")+ return OrgTokens(home=home, org=org), home, org # type: ignore[arg-type]+++async def test_bot_connector_tokens_come_from_switchs_own_directory() -> None:+ tokens, home, _ = _tokens()++ assert await tokens.bot_token() == "home-bot-token"+++async def test_graph_tokens_come_from_the_organisations_own_directory() -> None:+ tokens, _, org = _tokens()++ assert await tokens.graph_token() == "org-graph-token"+ assert await tokens.graph_roles() == frozenset({"org-role"})+++def test_invalidating_the_bot_connector_scope_drops_the_home_tenants_token() -> None:+ tokens, home, org = _tokens()++ assert tokens.invalidate(BOT_CONNECTOR_SCOPE) is True++ assert home.invalidated == [BOT_CONNECTOR_SCOPE]+ assert org.invalidated == []+++def test_invalidating_any_other_scope_drops_the_organisations_own_token() -> None:+ tokens, home, org = _tokens()++ assert tokens.invalidate("https://graph.microsoft.com/.default") is True++ assert org.invalidated == ["https://graph.microsoft.com/.default"]+ assert home.invalidated == []+++def test_a_notification_encrypted_to_a_certificate_held_nowhere_is_refused() -> None:+ current = NotificationKey(certificate_id="switch-current", private_key=None) # type: ignore[arg-type]+ keyring = NotificationKeyring(+ current=current, certificate_der_b64="ignored", retired=()+ )++ with pytest.raises(ResourceDataError, match="which this deployment does not hold"):+ keyring.decrypt({"encryptionCertificateId": "some-other-cert"})diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_installer.py b/core/tests/switch_core/bridges/collaboration/test_teams_installer.pynew file mode 100644index 000000000..0087ae186--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_installer.py@@ -0,0 +1,974 @@+"""Approving the distributed Teams app for a Microsoft organisation, and the+webhooks that follow.++Microsoft's redirect proves nothing on its own, so the install records nothing+until the id token names the organisation, the person signing in holds an+approving role there, and a token issued there carries every permission the+app needs. Microsoft is faked at the HTTP layer; the checks are real.+"""++from __future__ import annotations++import datetime+import functools+import json+from typing import Any+from urllib.parse import parse_qs, urlsplit++import httpx+import jwt+import pytest+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import rsa+from cryptography.x509.oid import NameOID+from jwt.algorithms import RSAAlgorithm++from switch_core.bridges.collaboration.install import (+ InstallGrant,+ MessagingInstallError,+ WebhookAuthenticityError,+ WebhookPayloadError,+ WebhookVerificationUnavailable,+)+from switch_core.bridges.collaboration.teams import install as teams_install+from switch_core.bridges.collaboration.teams.app_package import (+ build_distributed_app_package,+)+from switch_core.bridges.collaboration.teams.auth import (+ ClientSecret,+ SigningKeysUnavailable,+)+from switch_core.bridges.collaboration.teams.crypto import load_certificate_der_b64+from switch_core.bridges.collaboration.teams.identity import (+ REQUIRED_GRAPH_ROLES,+ NotificationKey,+ NotificationKeyring,+)+from switch_core.bridges.collaboration.teams.install import (+ TeamsAppInstaller,+ _graph_refusal,+)+from switch_core.bridges.collaboration.teams.shared_app import TeamsSharedApp++APP_ID = "aaaaaaaa-1111-1111-1111-111111111111"+ORG = "bbbbbbbb-2222-2222-2222-222222222222"+GLOBAL_ADMIN = "62e90394-69f5-4237-9190-012177145e10"+_IDENTITY_METADATA = (+ "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"+)+_IDENTITY_KEYS = "https://login.microsoftonline.com/common/discovery/v2.0/keys"++[email protected]_cache(maxsize=1)+def _signing_key() -> rsa.RSAPrivateKey:+ return rsa.generate_private_key(public_exponent=65537, key_size=2048)++[email protected]_cache(maxsize=1)+def _notification_keypair() -> tuple[str, rsa.RSAPrivateKey]:+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-test")])+ now = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)+ certificate = (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now)+ .not_valid_after(now + datetime.timedelta(days=365))+ .sign(key, hashes.SHA256())+ )+ return certificate.public_bytes(serialization.Encoding.PEM).decode(), key+++def _id_token(**overrides: Any) -> str:+ claims: dict[str, Any] = {+ "aud": APP_ID,+ "iss": f"https://login.microsoftonline.com/{ORG}/v2.0",+ "tid": ORG,+ "exp": datetime.datetime.now(datetime.UTC) + datetime.timedelta(hours=1),+ "name": "Ada Admin",+ "wids": [GLOBAL_ADMIN],+ }+ claims.update(overrides)+ for key in [k for k, v in claims.items() if v is None]:+ del claims[key]+ return jwt.encode(claims, _signing_key(), algorithm="RS256", headers={"kid": "id1"})+++class _Microsoft:+ """Microsoft's sign-in, token and Graph endpoints, as far as an install+ touches them. Scripted per test; records what it was asked."""++ def __init__(self) -> None:+ self.id_token = _id_token()+ self.roles: list[str] = sorted(REQUIRED_GRAPH_ROLES)+ self.org_token_error: dict[str, Any] | None = None+ self.catalog: list[dict[str, Any]] = []+ self.publish_status = 201+ self.requests: list[httpx.Request] = []++ def handler(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ url = str(request.url)+ if url == _IDENTITY_METADATA:+ return httpx.Response(200, json={"jwks_uri": _IDENTITY_KEYS})+ if url == _IDENTITY_KEYS:+ jwk = RSAAlgorithm.to_jwk(_signing_key().public_key(), as_dict=True)+ return httpx.Response(200, json={"keys": [{**jwk, "kid": "id1"}]})+ if url.endswith("/organizations/oauth2/v2.0/token"):+ return httpx.Response(+ 200, json={"access_token": "delegated", "id_token": self.id_token}+ )+ if url.endswith(f"/{ORG}/oauth2/v2.0/token"):+ if self.org_token_error is not None:+ return httpx.Response(400, json=self.org_token_error)+ token = jwt.encode({"roles": self.roles}, "k" * 32)+ return httpx.Response(200, json={"access_token": token, "expires_in": 3600})+ if "/v1.0/organization" in url:+ return httpx.Response(200, json={"value": [{"displayName": "Contoso"}]})+ if "/appDefinitions" in url:+ return httpx.Response(201, json={"id": "definition"})+ if "/appCatalogs/teamsApps" in url and request.method == "GET":+ return httpx.Response(200, json={"value": self.catalog})+ if "/appCatalogs/teamsApps" in url and request.method == "POST":+ if self.publish_status >= 300:+ return httpx.Response(+ self.publish_status,+ json={"error": {"code": "Forbidden", "message": "not allowed"}},+ )+ return httpx.Response(201, json={"id": "catalog-app-1"})+ raise AssertionError(f"unexpected request to {request.method} {url}")++ def posted(self, fragment: str) -> list[httpx.Request]:+ return [+ r for r in self.requests if r.method == "POST" and fragment in str(r.url)+ ]+++def _installer(microsoft: _Microsoft) -> TeamsAppInstaller:+ certificate, key = _notification_keypair()+ app = TeamsSharedApp(+ app_id=APP_ID,+ home_tenant_id="cccccccc-3333-3333-3333-333333333333",+ credential=ClientSecret("secret"),+ keyring=NotificationKeyring(+ current=NotificationKey(certificate_id="cert", private_key=key),+ certificate_der_b64=load_certificate_der_b64(certificate),+ retired=(),+ ),+ messaging_public_url="https://switch.example",+ client_state_secret="jwt-secret",+ http=httpx.AsyncClient(transport=httpx.MockTransport(microsoft.handler)),+ )+ package = build_distributed_app_package(+ app_id=APP_ID,+ app_name="Agent Switch",+ messaging_public_url="https://switch.example",+ privacy_url="https://switch.example/privacy",+ terms_url="https://switch.example/terms",+ )+ return TeamsAppInstaller(app=app, package=package)++[email protected](autouse=True)+def _no_propagation_wait(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(teams_install, "_APPROVAL_PROPAGATION_ATTEMPTS", 2)+ monkeypatch.setattr(teams_install, "_APPROVAL_PROPAGATION_DELAY_SECONDS", 0.0)+++async def _redeem(microsoft: _Microsoft) -> Any:+ return await _installer(microsoft).redeem(+ code="the-code", redirect_uri="https://switch.example/messaging/teams/cb"+ )+++# ── Starting ─────────────────────────────────────────────────────────────────+++def test_the_sign_in_asks_for_everything_on_one_consent_screen() -> None:+ url = _installer(_Microsoft()).authorize_url(+ state="the-state", redirect_uri="https://switch.example/cb"+ )+ query = parse_qs(urlsplit(url).query)+ assert urlsplit(url).path == "/organizations/oauth2/v2.0/authorize"+ assert query["client_id"] == [APP_ID]+ assert query["state"] == ["the-state"]+ assert query["prompt"] == ["consent"]+ assert "https://graph.microsoft.com/.default" in query["scope"][0].split()+ assert "openid" in query["scope"][0].split()+++# ── Finishing ────────────────────────────────────────────────────────────────+++async def test_an_approved_organisation_is_installed_and_given_the_app() -> None:+ microsoft = _Microsoft()++ grant = await _redeem(microsoft)++ assert grant.external_workspace_id == ORG+ assert grant.workspace_name == "Contoso"+ assert grant.bot_token is None+ assert grant.scopes.split() == sorted(REQUIRED_GRAPH_ROLES)+ assert grant.platform_data == {+ "catalog_app_id": "catalog-app-1",+ "manifest_version": "1.0.0",+ "publish_problem": None,+ }+ [published] = microsoft.posted("/appCatalogs/teamsApps")+ assert published.headers["Authorization"] == "Bearer delegated"+ assert published.headers["Content-Type"] == "application/zip"+++async def test_a_person_who_cannot_approve_apps_is_refused() -> None:+ """The id token proves which organisation; only the role proves the+ person may give an app that organisation's data."""+ microsoft = _Microsoft()+ microsoft.id_token = _id_token(wids=["some-other-role"])++ with pytest.raises(MessagingInstallError, match="Global Administrator"):+ await _redeem(microsoft)++ assert microsoft.posted("/appCatalogs") == []+++async def test_a_token_that_does_not_say_the_roles_is_the_operators_to_fix() -> None:+ microsoft = _Microsoft()+ microsoft.id_token = _id_token(wids=None)++ with pytest.raises(MessagingInstallError, match="groupMembershipClaims"):+ await _redeem(microsoft)+++async def test_an_approval_for_one_person_rather_than_the_organisation_is_refused() -> (+ None+):+ """Approving only for themselves leaves the app's permissions out of the+ organisation's tokens."""+ microsoft = _Microsoft()+ microsoft.roles = ["User.ReadBasic.All"]++ with pytest.raises(MessagingInstallError, match="Consent on behalf"):+ await _redeem(microsoft)+++async def test_an_organisation_that_never_approved_is_refused() -> None:+ microsoft = _Microsoft()+ microsoft.org_token_error = {+ "error": "unauthorized_client",+ "error_codes": [700016],+ }++ with pytest.raises(MessagingInstallError, match="not approved for the whole"):+ await _redeem(microsoft)+++async def test_an_organisation_token_refused_for_an_unrelated_reason_is_not_swallowed() -> (+ None+):+ """Only "not approved" is treated as something approving again might fix;+ anything else Microsoft's identity platform says about the request is a+ Switch-side problem worth its own message, not a silent retry."""+ microsoft = _Microsoft()+ microsoft.org_token_error = {"error": "invalid_client", "error_codes": [7000215]}++ with pytest.raises(MessagingInstallError, match="would not issue Switch a token"):+ await _redeem(microsoft)+++async def test_a_token_naming_one_organisation_and_issued_by_another_is_refused() -> (+ None+):+ microsoft = _Microsoft()+ microsoft.id_token = _id_token(+ iss="https://login.microsoftonline.com/someone-else/v2.0"+ )++ with pytest.raises(MessagingInstallError, match="could not be verified"):+ await _redeem(microsoft)+++async def test_a_personal_account_is_refused() -> None:+ microsoft = _Microsoft()+ personal = "9188040d-6c67-4c5b-b112-36a304b66dad"+ microsoft.id_token = _id_token(+ tid=personal, iss=f"https://login.microsoftonline.com/{personal}/v2.0"+ )++ with pytest.raises(MessagingInstallError, match="personal Microsoft account"):+ await _redeem(microsoft)+++async def test_a_government_cloud_organisation_is_refused() -> None:+ microsoft = _Microsoft()+ microsoft.id_token = _id_token(tenant_region_sub_scope="GCC")++ with pytest.raises(MessagingInstallError, match="government cloud"):+ await _redeem(microsoft)+++async def test_an_approver_who_is_not_a_teams_admin_still_installs_and_is_told() -> (+ None+):+ """The approval is done; only putting the app in the catalogue failed,+ and the connection says so."""+ microsoft = _Microsoft()+ microsoft.publish_status = 403++ grant = await _redeem(microsoft)++ assert grant.external_workspace_id == ORG+ assert "catalog_app_id" not in grant.platform_data+ assert "not a Teams administrator" in str(grant.platform_data["publish_problem"])+++async def test_an_update_that_fails_keeps_the_catalogue_id_it_found() -> None:+ """An organisation that already has the app keeps an id that works, even+ when giving it the newer version is refused."""+ microsoft = _Microsoft()+ microsoft.catalog = [{"id": "existing", "appDefinitions": [{"version": "0.9.0"}]}]++ def refuse_update(request: httpx.Request) -> httpx.Response:+ if "/appDefinitions" in str(request.url):+ return httpx.Response(403, json={"error": {"message": "not allowed"}})+ return microsoft.handler(request)++ installer = _installer(microsoft)+ installer._app._http = httpx.AsyncClient(+ transport=httpx.MockTransport(refuse_update)+ )++ grant = await installer.redeem(code="c", redirect_uri="https://switch.example/cb")++ assert grant.platform_data["catalog_app_id"] == "existing"+ assert grant.platform_data["publish_problem"]+++async def test_microsoft_unreachable_is_explained_not_a_server_error() -> None:+ def unreachable(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("no route to host")++ installer = _installer(_Microsoft())+ installer._app._http = httpx.AsyncClient(transport=httpx.MockTransport(unreachable))++ with pytest.raises(MessagingInstallError, match="could not reach Microsoft"):+ await installer.redeem(code="c", redirect_uri="https://switch.example/cb")+++async def test_an_organisation_that_has_the_app_already_is_not_given_it_twice() -> None:+ microsoft = _Microsoft()+ microsoft.catalog = [{"id": "existing", "appDefinitions": [{"version": "1.0.0"}]}]++ grant = await _redeem(microsoft)++ assert grant.platform_data["catalog_app_id"] == "existing"+ assert microsoft.posted("/appCatalogs") == []+++async def test_a_hand_uploaded_package_under_switchs_id_is_not_adopted() -> None:+ """Seen in a real organisation: a package uploaded by hand from the+ bring-your-own template, under the same id and version, which asks for+ per-team permissions. Graph refuses to let Switch add such an app to a+ team, so adopting it only moves the failure to the Teams panel."""+ microsoft = _Microsoft()+ microsoft.catalog = [+ {+ "id": "hand-uploaded",+ "appDefinitions": [+ {+ "version": "1.0.0",+ "authorization": {+ "requiredPermissionSet": {+ "resourceSpecificPermissions": [+ {+ "permissionValue": "ChannelMessage.Read.Group",+ "permissionType": "application",+ }+ ]+ }+ },+ }+ ],+ }+ ]++ grant = await _redeem(microsoft)++ assert "catalog_app_id" not in grant.platform_data+ assert "per-team permissions" in str(grant.platform_data["publish_problem"])+ assert microsoft.posted("/appCatalogs") == []+++async def test_an_older_hand_uploaded_package_is_replaced_by_this_one() -> None:+ microsoft = _Microsoft()+ microsoft.catalog = [+ {+ "id": "hand-uploaded",+ "appDefinitions": [+ {+ "version": "0.9.0",+ "authorization": {+ "requiredPermissionSet": {+ "resourceSpecificPermissions": [+ {"permissionValue": "ChannelMessage.Read.Group"}+ ]+ }+ },+ }+ ],+ }+ ]++ grant = await _redeem(microsoft)++ assert grant.platform_data["catalog_app_id"] == "hand-uploaded"+ assert (+ len(microsoft.posted("/appCatalogs/teamsApps/hand-uploaded/appDefinitions"))+ == 1+ )+++async def test_the_catalogue_is_asked_for_each_versions_permissions() -> None:+ microsoft = _Microsoft()++ await _redeem(microsoft)++ [lookup] = [+ r+ for r in microsoft.requests+ if r.method == "GET" and "/appCatalogs/teamsApps" in str(r.url)+ ]+ assert "authorization" in lookup.url.params["$expand"]+++async def test_an_organisation_with_an_older_version_is_given_this_one() -> None:+ microsoft = _Microsoft()+ microsoft.catalog = [{"id": "existing", "appDefinitions": [{"version": "0.9.0"}]}]++ await _redeem(microsoft)++ assert len(microsoft.posted("/appCatalogs/teamsApps/existing/appDefinitions")) == 1+++def test_an_install_becomes_a_shared_bridge_for_the_organisation() -> None:+ installer = _installer(_Microsoft())+ config = {"event_delivery": "shared", "tenant_id": ORG}+ assert installer.workspace_of_bridge(config) == ORG+ assert installer.workspace_of_bridge({"tenant_id": ORG}) is None+++def test_a_refused_approval_is_explained_plainly() -> None:+ installer = _installer(_Microsoft())+ assert "not approved" in installer.describe_callback_error(+ error="access_denied", description="AADSTS65004: User declined"+ )+ assert "Global Administrator" in installer.describe_callback_error(+ error="consent_required", description="AADSTS90094: admin consent needed"+ )+++# ── Webhooks ─────────────────────────────────────────────────────────────────+++def test_graphs_url_check_is_echoed() -> None:+ installer = _installer(_Microsoft())+ assert (+ installer.unsigned_handshake(+ endpoint="notifications", query={"validationToken": "abc"}+ )+ == "abc"+ )+ assert installer.unsigned_handshake(endpoint="events", query={}) is None+++class _Authenticator:+ def __init__(self, *, refuse: bool = False, vouched: frozenset[str] = frozenset()):+ self.refuse = refuse+ self.keys_unavailable = False+ self.vouched = vouched+ self.seen: list[dict[str, Any]] = []++ async def verify(+ self, authorization: str | None, *, service_url: str, channel_id: str+ ) -> None:+ self.seen.append(+ {+ "authorization": authorization,+ "service_url": service_url,+ "channel": channel_id,+ }+ )+ if self.keys_unavailable:+ raise SigningKeysUnavailable("keys out of reach")+ if self.refuse:+ raise PermissionError("forged")++ async def vouched_tenants(self, tokens: list[object]) -> frozenset[str]:+ if self.keys_unavailable:+ raise SigningKeysUnavailable("keys out of reach")+ if self.refuse:+ raise PermissionError("forged")+ return self.vouched+++def _activity(**overrides: Any) -> dict[str, Any]:+ return {+ "type": "message",+ "id": "m1",+ "channelId": "msteams",+ "serviceUrl": "https://smba.trafficmanager.net/amer/",+ "conversation": {"id": "19:[email protected];messageid=m1", "tenantId": ORG},+ "channelData": {"tenant": {"id": ORG}},+ **overrides,+ }+++async def test_an_activity_is_checked_against_its_own_service_url_and_channel() -> None:+ installer = _installer(_Microsoft())+ authenticator = _Authenticator()+ installer._app.bot_authenticator = authenticator # type: ignore[assignment]++ await installer.verify_webhook(+ endpoint="events",+ headers={"Authorization": "Bearer t"},+ query={},+ body=json.dumps(_activity()).encode(),+ )++ assert authenticator.seen == [+ {+ "authorization": "Bearer t",+ "service_url": "https://smba.trafficmanager.net/amer/",+ "channel": "msteams",+ }+ ]+++async def test_a_forged_activity_is_refused() -> None:+ installer = _installer(_Microsoft())+ installer._app.bot_authenticator = _Authenticator(refuse=True) # type: ignore[assignment]++ with pytest.raises(WebhookAuthenticityError):+ await installer.verify_webhook(+ endpoint="events",+ headers={},+ query={},+ body=json.dumps(_activity()).encode(),+ )+++async def test_a_body_that_is_not_json_is_not_genuine() -> None:+ installer = _installer(_Microsoft())+ with pytest.raises(WebhookAuthenticityError):+ await installer.verify_webhook(+ endpoint="events", headers={}, query={}, body=b"not json"+ )+++def _notifications(*items: dict[str, Any], tokens: list[str] | None) -> bytes:+ body: dict[str, Any] = {"value": list(items)}+ if tokens is not None:+ body["validationTokens"] = tokens+ return json.dumps(body).encode()+++_DATA = {+ "subscriptionId": "s1",+ "tenantId": ORG,+ "resource": "teams('t')/channels('c')/messages('m')",+ "changeType": "created",+ "encryptedContent": {},+ "clientState": "x",+}+++async def _parsed(installer: TeamsAppInstaller, body: bytes) -> list[Any]:+ await installer.verify_webhook(+ endpoint="notifications", headers={}, query={}, body=body+ )+ return installer.parse_webhook(+ endpoint="notifications", headers={}, query={}, body=body+ )+++async def test_a_notification_no_token_vouches_for_is_dropped() -> None:+ """Microsoft sends no token for an organisation that set "assignment+ required"; its notifications cannot be trusted and are not delivered."""+ installer = _installer(_Microsoft())+ installer._app.notification_authenticator = _Authenticator(vouched=frozenset()) # type: ignore[assignment]++ assert await _parsed(installer, _notifications(_DATA, tokens=None)) == []+++async def test_one_organisations_missing_token_does_not_cost_another_its_messages() -> (+ None+):+ installer = _installer(_Microsoft())+ installer._app.notification_authenticator = _Authenticator( # type: ignore[assignment]+ vouched=frozenset({ORG})+ )+ other = {**_DATA, "tenantId": "org-without-a-token"}++ events = await _parsed(installer, _notifications(_DATA, other, tokens=["t"]))++ assert [e.payload["tenantId"] for e in events] == [ORG]+++async def test_a_resent_batch_checked_while_the_first_is_parsed_is_kept() -> None:+ """Graph resends a batch it thinks went unanswered; both copies are the+ same bytes, carrying the same tokens."""+ installer = _installer(_Microsoft())+ installer._app.notification_authenticator = _Authenticator( # type: ignore[assignment]+ vouched=frozenset({ORG})+ )+ body = _notifications(_DATA, tokens=["t"])++ for _ in range(2):+ await installer.verify_webhook(+ endpoint="notifications", headers={}, query={}, body=body+ )+ first = installer.parse_webhook(+ endpoint="notifications", headers={}, query={}, body=body+ )+ second = installer.parse_webhook(+ endpoint="notifications", headers={}, query={}, body=body+ )++ assert [e.payload["tenantId"] for e in first] == [ORG]+ assert [e.payload["tenantId"] for e in second] == [ORG]++[email protected]("endpoint", ["events", "notifications"])+async def test_microsofts_keys_out_of_reach_is_not_called_a_forgery(+ endpoint: str,+) -> None:+ installer = _installer(_Microsoft())+ authenticator = _Authenticator()+ authenticator.keys_unavailable = True+ installer._app.bot_authenticator = authenticator # type: ignore[assignment]+ installer._app.notification_authenticator = authenticator # type: ignore[assignment]+ body = (+ json.dumps(_activity()).encode()+ if endpoint == "events"+ else _notifications(_DATA, tokens=["t"])+ )++ with pytest.raises(WebhookVerificationUnavailable):+ await installer.verify_webhook(+ endpoint=endpoint, # type: ignore[arg-type]+ headers={"authorization": "Bearer t"},+ query={},+ body=body,+ )+++async def test_microsofts_keys_out_of_reach_at_approval_is_explained() -> None:+ microsoft = _Microsoft()+ installer = _installer(microsoft)++ async def keys_out_of_reach(id_token: str) -> dict[str, Any]:+ raise SigningKeysUnavailable("could not fetch signing keys")++ installer._app.verify_id_token = keys_out_of_reach # type: ignore[method-assign]++ with pytest.raises(MessagingInstallError, match="signing keys"):+ await installer.redeem(+ code="the-code", redirect_uri="https://switch.example/messaging/teams/cb"+ )+ assert microsoft.posted("/appCatalogs") == []+++async def test_a_forged_token_refuses_the_whole_batch() -> None:+ installer = _installer(_Microsoft())+ installer._app.notification_authenticator = _Authenticator(refuse=True) # type: ignore[assignment]++ with pytest.raises(WebhookAuthenticityError):+ await installer.verify_webhook(+ endpoint="notifications",+ headers={},+ query={},+ body=_notifications(_DATA, tokens=["forged"]),+ )+++async def test_vouched_notifications_pass() -> None:+ installer = _installer(_Microsoft())+ installer._app.notification_authenticator = _Authenticator(vouched=frozenset({ORG})) # type: ignore[assignment]++ await installer.verify_webhook(+ endpoint="notifications",+ headers={},+ query={},+ body=_notifications(_DATA, tokens=["t"]),+ )+++async def test_lifecycle_notifications_need_no_tokens() -> None:+ """They carry no data, and the bridge they reach checks its organisation's+ own clientState and that the subscription is its own."""+ installer = _installer(_Microsoft())+ lifecycle = {+ "subscriptionId": "s1",+ "tenantId": ORG,+ "lifecycleEvent": "reauthorizationRequired",+ "clientState": "x",+ }++ await installer.verify_webhook(+ endpoint="notifications",+ headers={},+ query={},+ body=_notifications(lifecycle, tokens=None),+ )+++def test_a_message_is_keyed_by_organisation_conversation_and_id() -> None:+ [event] = _installer(_Microsoft()).parse_webhook(+ endpoint="events", headers={}, query={}, body=json.dumps(_activity()).encode()+ )+ assert event.envelope_type == "activity"+ assert event.external_event_id == f"{ORG}|19:[email protected];messageid=m1|m1"+ assert not event.answers_inline+++def test_a_press_is_answered_inline_and_never_keyed() -> None:+ [event] = _installer(_Microsoft()).parse_webhook(+ endpoint="events",+ headers={},+ query={},+ body=json.dumps(_activity(type="invoke", name="adaptiveCard/action")).encode(),+ )+ assert event.answers_inline+ assert event.external_event_id is None+++async def test_a_batch_becomes_one_event_per_notification() -> None:+ other = {+ **_DATA,+ "tenantId": "org-2",+ "resource": "teams('t')/channels('c')/messages('n')",+ }+ installer = _installer(_Microsoft())+ installer._app.notification_authenticator = _Authenticator( # type: ignore[assignment]+ vouched=frozenset({ORG, "org-2"})+ )+ events = await _parsed(installer, _notifications(_DATA, other, tokens=["t"]))+ assert [e.envelope_type for e in events] == ["notification", "notification"]+ assert events[0].external_event_id == f"{ORG}|{_DATA['resource']}|created"+++def test_each_event_names_its_organisation() -> None:+ installer = _installer(_Microsoft())+ assert installer.workspace_of_event(_activity()) == ORG+ assert installer.workspace_of_event(_DATA) == ORG+ with pytest.raises(WebhookPayloadError):+ installer.workspace_of_event(+ _activity(channelData={"tenant": {"id": "a-different-org"}})+ )+++def test_microsoft_announces_no_organisation_wide_uninstall() -> None:+ assert _installer(_Microsoft()).revocation_of_event(_activity()) is None+++# ── Review gaps ──────────────────────────────────────────────────────────────+++def test_the_package_is_offered_for_a_manual_upload() -> None:+ installer = _installer(_Microsoft())+ assert installer.package is installer._package+++async def test_a_non_json_sign_in_response_is_explained() -> None:+ microsoft = _Microsoft()++ def not_json(request: httpx.Request) -> httpx.Response:+ if str(request.url).endswith("/organizations/oauth2/v2.0/token"):+ return httpx.Response(200, content=b"not json")+ return microsoft.handler(request)++ installer = _installer(microsoft)+ installer._app._http = httpx.AsyncClient(transport=httpx.MockTransport(not_json))++ with pytest.raises(MessagingInstallError, match="is not JSON"):+ await installer.redeem(code="c", redirect_uri="https://switch.example/cb")+++async def test_a_refused_sign_in_carries_microsofts_own_reason() -> None:+ microsoft = _Microsoft()++ def refused(request: httpx.Request) -> httpx.Response:+ if str(request.url).endswith("/organizations/oauth2/v2.0/token"):+ return httpx.Response(+ 400, json={"error": "invalid_grant", "error_description": "expired"}+ )+ return microsoft.handler(request)++ installer = _installer(microsoft)+ installer._app._http = httpx.AsyncClient(transport=httpx.MockTransport(refused))++ with pytest.raises(MessagingInstallError, match="Microsoft refused the sign-in"):+ await installer.redeem(code="c", redirect_uri="https://switch.example/cb")+++async def test_a_sign_in_response_with_no_id_token_is_explained() -> None:+ microsoft = _Microsoft()++ def no_id_token(request: httpx.Request) -> httpx.Response:+ if str(request.url).endswith("/organizations/oauth2/v2.0/token"):+ return httpx.Response(200, json={"access_token": "delegated"})+ return microsoft.handler(request)++ installer = _installer(microsoft)+ installer._app._http = httpx.AsyncClient(transport=httpx.MockTransport(no_id_token))++ with pytest.raises(MessagingInstallError, match="no id token"):+ await installer.redeem(code="c", redirect_uri="https://switch.example/cb")+++async def test_an_organisation_name_that_cannot_be_read_falls_back_to_its_id() -> None:+ microsoft = _Microsoft()++ def organisation_unreadable(request: httpx.Request) -> httpx.Response:+ if "/v1.0/organization" in str(request.url):+ return httpx.Response(500, json={"error": {"message": "down"}})+ return microsoft.handler(request)++ installer = _installer(microsoft)+ installer._app._http = httpx.AsyncClient(+ transport=httpx.MockTransport(organisation_unreadable)+ )++ grant = await installer.redeem(code="c", redirect_uri="https://switch.example/cb")++ assert grant.workspace_name == ORG+++def test_connection_config_is_a_shared_bridge_for_the_approved_organisation() -> None:+ installer = _installer(_Microsoft())+ grant = InstallGrant(+ external_workspace_id=ORG,+ workspace_name="Contoso",+ bot_token=None,+ scopes="",+ platform_data={},+ )++ assert installer.connection_config(grant) == {+ "event_delivery": "shared",+ "tenant_id": ORG,+ }+++async def test_releasing_an_organisation_leaves_it_through_the_shared_app() -> None:+ installer = _installer(_Microsoft())+ left: list[str] = []++ async def _withdraw(organisation: str) -> None:+ left.append(organisation)++ installer._app.withdraw_from_org = _withdraw # type: ignore[method-assign]++ await installer.release(external_workspace_id=ORG)++ assert left == [ORG]+++async def test_revoke_is_not_supported_for_a_tokenless_install() -> None:+ installer = _installer(_Microsoft())+ with pytest.raises(NotImplementedError, match="no per-install token"):+ await installer.revoke(bot_token="irrelevant")+++def test_an_unrecognised_refusal_is_reported_in_microsofts_own_words() -> None:+ installer = _installer(_Microsoft())+ assert (+ installer.describe_callback_error(+ error="server_error", description="something unexpected"+ )+ == "Microsoft reported: something unexpected."+ )+++async def test_a_notification_batch_whose_value_is_not_a_list_is_not_genuine() -> None:+ installer = _installer(_Microsoft())+ with pytest.raises(WebhookAuthenticityError, match="not a Graph notification"):+ await installer.verify_webhook(+ endpoint="notifications",+ headers={},+ query={},+ body=json.dumps({"value": "not-a-list"}).encode(),+ )+++def test_parsing_a_notification_batch_whose_value_is_not_a_list_is_refused() -> None:+ installer = _installer(_Microsoft())+ with pytest.raises(WebhookPayloadError, match="had no value"):+ installer.parse_webhook(+ endpoint="notifications",+ headers={},+ query={},+ body=json.dumps({"value": "not-a-list"}).encode(),+ )+++def test_a_non_object_item_in_a_notification_batch_is_skipped_not_raised() -> None:+ installer = _installer(_Microsoft())+ installer._vouched[teams_install._digest({"value": ["not-a-dict", _DATA]})] = (+ frozenset({ORG})+ )++ events = installer.parse_webhook(+ endpoint="notifications",+ headers={},+ query={},+ body=json.dumps({"value": ["not-a-dict", _DATA]}).encode(),+ )++ assert [e.payload for e in events] == [_DATA]+++def test_only_the_most_recently_vouched_batches_are_remembered() -> None:+ installer = _installer(_Microsoft())+ for i in range(300):+ installer._remember_vouched(f"digest-{i}".encode(), frozenset({ORG}))++ assert len(installer._vouched) == 256+ assert b"digest-0" not in installer._vouched+ assert b"digest-299" in installer._vouched+++async def test_a_webhook_body_that_is_valid_json_but_not_an_object_is_not_genuine() -> (+ None+):+ installer = _installer(_Microsoft())+ with pytest.raises(WebhookAuthenticityError, match="not a JSON object"):+ await installer.verify_webhook(+ endpoint="events", headers={}, query={}, body=b"[1, 2, 3]"+ )+++def test_a_graph_refusal_with_an_unreadable_body_falls_back_to_the_raw_text() -> None:+ request = httpx.Request("POST", "https://graph.microsoft.com/v1.0/x")+ response = httpx.Response(403, content=b"not json", request=request)+ error = httpx.HTTPStatusError("refused", request=request, response=response)++ assert "not a Teams administrator" in _graph_refusal(error)+ assert "not json" in _graph_refusal(error)+++def test_a_graph_refusal_that_is_not_a_permission_problem_names_the_status() -> None:+ request = httpx.Request("POST", "https://graph.microsoft.com/v1.0/x")+ response = httpx.Response(+ 500, json={"error": {"message": "internal error"}}, request=request+ )+ error = httpx.HTTPStatusError("refused", request=request, response=response)++ assert _graph_refusal(error) == "Microsoft refused (500): internal error"+++def test_a_graph_refusal_that_is_not_an_http_status_error_is_reported_as_is() -> None:+ assert _graph_refusal(ValueError("boom")) == "boom"diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.py b/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.pyindex 6e5b196e6..687e3ce00 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_post_replies.py@@ -38,7 +38,12 @@ class _Connector:self.replies: list[str] = []async def create_channel_thread(- self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ self,+ *,+ service_url: str,+ channel_id: str,+ tenant_id: str,+ activity: dict[str, Any],) -> tuple[str, str]:self.new_posts.append(channel_id)return f"{channel_id};messageid=new", "msg-new"diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.py b/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.pyindex 214137f1a..0231e64ca 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.py@@ -67,7 +67,12 @@ class _Connector:self.conversation: str | None = Noneasync def create_channel_thread(- self, *, service_url: str, channel_id: str, activity: dict[str, Any]+ self,+ *,+ service_url: str,+ channel_id: str,+ tenant_id: str,+ activity: dict[str, Any],) -> tuple[str, str]:if self.fail_send is not None:raise self.fail_senddiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_shared_app_config.py b/core/tests/switch_core/bridges/collaboration/test_teams_shared_app_config.pynew file mode 100644index 000000000..c33d6c61a--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_shared_app_config.py@@ -0,0 +1,98 @@+"""Building the one deployment-level Teams app from `SwitchConfig`.++`TEAMS_APP_*` settings are validated in `test_config_teams_app.py`; this is+what `TeamsSharedApp.from_config` builds from them once they have passed —+which of the three credential shapes it constructs, and that a retired+notification key is still held for decrypting what was encrypted under it.+"""++from __future__ import annotations++from pathlib import Path++from switch_core.bridges.collaboration.teams.auth import (+ ClientCertificate,+ ClientSecret,+ FederatedTokenFile,+)+from switch_core.bridges.collaboration.teams.shared_app import (+ TeamsSharedApp,+ _notification_certificate_id,+)+from tests.switch_core.test_config_teams_app import (+ _APP,+ _CREDENTIAL_CERT,+ _CREDENTIAL_KEY,+ _TENANT,+ _config,+ _keypair,+ _without,+)+++def test_a_secret_configuration_builds_a_secret_credential() -> None:+ app = TeamsSharedApp.from_config(_config(**_APP))++ assert app.app_id == _APP["teams_app_client_id"]+ assert isinstance(app.credential, ClientSecret)+ assert app.credential.secret == "secret"+++def test_a_certificate_configuration_builds_a_certificate_credential() -> None:+ config = _config(+ **_without(+ "teams_app_client_secret",+ teams_app_certificate=_CREDENTIAL_CERT,+ teams_app_certificate_private_key=_CREDENTIAL_KEY,+ )+ )++ app = TeamsSharedApp.from_config(config)++ assert isinstance(app.credential, ClientCertificate)+++def test_a_federated_token_file_configuration_builds_a_federated_credential(+ tmp_path: Path,+) -> None:+ token = tmp_path / "token"+ token.write_text("eyJ...")+ config = _config(+ **_without("teams_app_client_secret", teams_app_federated_token_file=str(token))+ )++ app = TeamsSharedApp.from_config(config)++ assert isinstance(app.credential, FederatedTokenFile)+ assert app.credential.path == str(token)+++def test_a_retired_key_decrypts_what_a_live_key_cannot() -> None:+ """Graph goes on delivering notifications encrypted under a key being+ retired until its subscription runs out, so `from_config` must keep it+ rather than dropping it the moment a new current key is configured."""+ _, previous_key = _keypair()+ config = _config(**_APP, teams_app_notification_previous_private_key=previous_key)++ app = TeamsSharedApp.from_config(config)++ retired_id = _notification_certificate_id(previous_key)+ current_id = _notification_certificate_id(+ _APP["teams_app_notification_private_key"]+ )+ assert app._keyring.certificate_id == current_id+ assert retired_id != current_id+ assert retired_id in app._keyring._keys+++def test_an_identity_is_built_for_the_organisation_asked_for_not_the_home_tenant() -> (+ None+):+ app = TeamsSharedApp.from_config(_config(**_APP))+ org_tenant = "99999999-0000-0000-0000-000000000009"++ identity = app.identity_for(org_tenant)++ assert identity.org_tenant_id == org_tenant+ assert identity.org_tenant_id != _TENANT+ assert identity.app_id == app.app_iddiff --git a/core/tests/switch_core/bridges/collaboration/test_teams_shared_app_org_lifecycle.py b/core/tests/switch_core/bridges/collaboration/test_teams_shared_app_org_lifecycle.pynew file mode 100644index 000000000..668cc94c6--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_shared_app_org_lifecycle.py@@ -0,0 +1,240 @@+"""Leaving an organisation that is no longer installed, and shutting the app down.++`TeamsSharedApp.withdraw_from_org` is called for an organisation whose bridge+is not running to undo it itself: delete every subscription this app's+notification URL owns there, and leave every team Switch was added to.+Neither half blocks the other — each is best effort — and the organisation's+token provider is forgotten whatever either found.+"""++from __future__ import annotations++import datetime+import functools+import logging++import httpx+import pytest+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import rsa+from cryptography.x509.oid import NameOID++from switch_core.bridges.collaboration.teams.auth import ClientSecret+from switch_core.bridges.collaboration.teams.crypto import load_certificate_der_b64+from switch_core.bridges.collaboration.teams.identity import (+ NotificationKey,+ NotificationKeyring,+)+from switch_core.bridges.collaboration.teams.shared_app import TeamsSharedApp++ORG = "aaaaaaaa-0000-0000-0000-000000000001"++[email protected]_cache(maxsize=1)+def _keypair() -> tuple[str, rsa.RSAPrivateKey]:+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-test")])+ now = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)+ certificate = (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now)+ .not_valid_after(now + datetime.timedelta(days=365))+ .sign(key, hashes.SHA256())+ )+ return certificate.public_bytes(serialization.Encoding.PEM).decode(), key+++def _app(handler: httpx.MockTransport | None = None) -> TeamsSharedApp:+ certificate, key = _keypair()+ http = (+ httpx.AsyncClient(transport=handler)+ if handler is not None+ else httpx.AsyncClient()+ )+ return TeamsSharedApp(+ app_id="switch-app",+ home_tenant_id="11111111-0000-0000-0000-000000000000",+ credential=ClientSecret("secret"),+ keyring=NotificationKeyring(+ current=NotificationKey(certificate_id="switch-cert", private_key=key),+ certificate_der_b64=load_certificate_der_b64(certificate),+ retired=(),+ ),+ messaging_public_url="https://switch.example",+ client_state_secret="jwt-secret",+ http=http,+ )+++def _token_response(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"access_token": "tok", "expires_in": 3600})+++async def test_withdrawing_forgets_the_org_even_when_listing_subscriptions_fails(+ caplog: pytest.LogCaptureFixture,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return _token_response(request)+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(500, json={"error": {"message": "down"}})+ if request.url.path == "/v1.0/teams":+ return httpx.Response(200, json={"value": []})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app(httpx.MockTransport(handler))+ app.org_tokens(ORG) # the provider that should be forgotten++ with caplog.at_level(logging.ERROR):+ await app.withdraw_from_org(ORG)++ assert ORG not in app._org_tokens+ messages = [r.message for r in caplog.records if r.levelno >= logging.ERROR]+ assert any("subscriptions" in m and ORG in m for m in messages)+++async def test_withdrawing_forgets_the_org_even_when_uninstalling_fails(+ caplog: pytest.LogCaptureFixture,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return _token_response(request)+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ if request.url.path == "/v1.0/teams":+ return httpx.Response(200, json={"value": [{"id": "team-1"}]})+ if request.url.path == "/v1.0/teams/team-1/installedApps":+ return httpx.Response(+ 200,+ json={+ "value": [+ {"id": "install-1", "teamsApp": {"id": "catalog-1"}},+ ]+ },+ )+ if request.url.path == "/v1.0/teams/team-1/installedApps/install-1":+ return httpx.Response(500, json={"error": {"message": "refused"}})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app(httpx.MockTransport(handler))+ app.org_tokens(ORG)++ with caplog.at_level(logging.ERROR):+ await app.withdraw_from_org(ORG)++ assert ORG not in app._org_tokens+ messages = [r.message for r in caplog.records if r.levelno >= logging.ERROR]+ assert any("the app in team team-1" in m and ORG in m for m in messages)+++async def test_withdrawing_cleanly_leaves_nothing_behind_to_log(+ caplog: pytest.LogCaptureFixture,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return _token_response(request)+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ if request.url.path == "/v1.0/teams":+ return httpx.Response(200, json={"value": []})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app(httpx.MockTransport(handler))+ app.org_tokens(ORG)++ with caplog.at_level(logging.ERROR):+ await app.withdraw_from_org(ORG)++ assert ORG not in app._org_tokens+ assert not [r for r in caplog.records if r.levelno >= logging.ERROR]+++async def test_aclose_closes_the_one_shared_client() -> None:+ app = _app()++ await app.aclose()++ with pytest.raises(RuntimeError):+ await app.http.get("https://graph.microsoft.com/v1.0/subscriptions")+++async def test_one_team_that_cannot_be_read_does_not_keep_the_app_in_the_rest(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """An archived or restricted team early in the listing used to end the+ loop, leaving the app in every team listed after it."""+ removed: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return _token_response(request)+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ if request.url.path == "/v1.0/teams":+ return httpx.Response(+ 200, json={"value": [{"id": "archived"}, {"id": "team-2"}]}+ )+ if request.url.path == "/v1.0/teams/archived/installedApps":+ return httpx.Response(403, json={"error": {"message": "archived"}})+ if request.url.path == "/v1.0/teams/team-2/installedApps":+ return httpx.Response(+ 200, json={"value": [{"id": "install-2", "teamsApp": {"id": "c"}}]}+ )+ if request.url.path == "/v1.0/teams/team-2/installedApps/install-2":+ removed.append("team-2")+ return httpx.Response(204)+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app(httpx.MockTransport(handler))++ with caplog.at_level(logging.ERROR):+ await app.withdraw_from_org(ORG)++ assert removed == ["team-2"]+ messages = [r.message for r in caplog.records if r.levelno >= logging.ERROR]+ assert any("the app in team archived" in m for m in messages)+++async def test_an_organisation_whose_teams_cannot_be_listed_is_still_forgotten(+ caplog: pytest.LogCaptureFixture,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return _token_response(request)+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ if request.url.path == "/v1.0/teams":+ return httpx.Response(403, json={"error": {"message": "no"}})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app(httpx.MockTransport(handler))+ app.org_tokens(ORG)++ with caplog.at_level(logging.ERROR):+ await app.withdraw_from_org(ORG)++ assert ORG not in app._org_tokens+ assert "listing the organisation's teams failed" in caplog.text+++async def test_a_team_listed_without_an_id_is_skipped() -> None:+ asked: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ return _token_response(request)+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ if request.url.path == "/v1.0/teams":+ return httpx.Response(200, json={"value": [{"displayName": "?"}]})+ asked.append(request.url.path)+ return httpx.Response(200, json={"value": []})++ await _app(httpx.MockTransport(handler)).withdraw_from_org(ORG)++ assert asked == []diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_shared_mode.py b/core/tests/switch_core/bridges/collaboration/test_teams_shared_mode.pynew file mode 100644index 000000000..5ef8785c5--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_teams_shared_mode.py@@ -0,0 +1,2148 @@+"""A Teams bridge on the distributed app: one organisation, the deployment's app.++The deployment's credential reaches every organisation that approved the app,+so most of what is tested here is the bridge refusing what is not its own+organisation's — activities, notifications, channels — and never sending the+deployment's token anywhere but Microsoft.+"""++from __future__ import annotations++import asyncio+import datetime+import functools+from typing import Any++import httpx+import jwt+import pytest+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import ec, rsa+from cryptography.x509.oid import NameOID+from pydantic import ValidationError++from switch_core.bridges.collaboration.adapter import (+ ChannelNotBindable,+ ConfigEditRefused,+)+from switch_core.bridges.collaboration.models import (+ BridgeOperationError,+ InboundMessage,+)+from switch_core.bridges.collaboration.teams import adapter as adapter_module+from switch_core.bridges.collaboration.teams import shared_app as shared_app_module+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)+from switch_core.bridges.collaboration.teams.auth import (+ ClientSecret,+ TokenRequestRefused,+)+from switch_core.bridges.collaboration.teams.crypto import load_certificate_der_b64+from switch_core.bridges.collaboration.teams.graph import AppInstallation, GraphError+from switch_core.bridges.collaboration.teams.identity import (+ REQUIRED_GRAPH_ROLES,+ NotificationKey,+ NotificationKeyring,+)+from switch_core.bridges.collaboration.teams.shared_app import (+ TeamsSharedApp,+ client_state_for,+)++ORG = "aaaaaaaa-0000-0000-0000-000000000001"+OTHER_ORG = "bbbbbbbb-0000-0000-0000-000000000002"+CHANNEL = "19:[email protected]"+SERVICE_URL = "https://smba.trafficmanager.net/amer/"++[email protected]_cache(maxsize=1)+def _keypair() -> tuple[str, rsa.RSAPrivateKey]:+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-test")])+ now = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)+ certificate = (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now)+ .not_valid_after(now + datetime.timedelta(days=365))+ .sign(key, hashes.SHA256())+ )+ return certificate.public_bytes(serialization.Encoding.PEM).decode(), key+++def _app() -> TeamsSharedApp:+ certificate, key = _keypair()+ return TeamsSharedApp(+ app_id="switch-app",+ home_tenant_id="11111111-0000-0000-0000-000000000000",+ credential=ClientSecret("secret"),+ keyring=NotificationKeyring(+ current=NotificationKey(certificate_id="switch-cert", private_key=key),+ certificate_der_b64=load_certificate_der_b64(certificate),+ retired=(),+ ),+ messaging_public_url="https://switch.example",+ client_state_secret="jwt-secret",+ http=httpx.AsyncClient(),+ )+++def _shared_config(**overrides: Any) -> TeamsConnectionConfig:+ return TeamsConnectionConfig.model_validate(+ {"event_delivery": "shared", "tenant_id": ORG, **overrides}+ )+++def _shared_adapter(**overrides: Any) -> TeamsAdapter:+ adapter = TeamsAdapter(config=_shared_config(**overrides))+ _app().attach_if_teams(adapter)+ return adapter+++# ── Config ───────────────────────────────────────────────────────────────────+++def test_a_shared_bridge_needs_only_its_organisation() -> None:+ config = _shared_config()+ assert config.tenant_id == ORG+ assert config.app_id is None and config.team_id is None+++ "foreign",+ [+ {"app_id": "x"},+ {"app_password": "x"},+ {"public_base_url": "https://x.example"},+ {"client_state": "x"},+ {"listen_port": 4000},+ ],+)+def test_a_shared_bridge_carrying_its_own_app_is_refused(+ foreign: dict[str, Any],+) -> None:+ with pytest.raises(ValidationError, match="distributed Teams app"):+ _shared_config(**foreign)+++def test_a_bring_your_own_bridge_still_needs_every_setting() -> None:+ with pytest.raises(ValidationError, match="app_password"):+ TeamsConnectionConfig.model_validate(+ {+ "app_id": "a",+ "tenant_id": "t",+ "team_id": "team",+ "public_base_url": "https://x.example",+ "client_state": "s",+ }+ )+++def test_the_registration_form_asks_for_the_same_fields_as_before() -> None:+ """The form is built from the schema's required list. The model now also+ describes a shared bridge, which holds none of those fields, so the list is+ declared rather than left to the field types."""+ schema = TeamsConnectionConfig.model_json_schema()+ assert schema["required"] == [+ "app_id",+ "app_password",+ "tenant_id",+ "team_id",+ "public_base_url",+ ]+ assert "event_delivery" not in schema["properties"]+++def test_a_shared_bridge_claims_no_port() -> None:+ """Every bring-your-own bridge claims port 3978; a second customer's+ install would otherwise be refused."""+ assert TeamsAdapter.exclusive_resource(_shared_config().model_dump()) is None+++async def test_registration_mints_nothing_for_a_shared_bridge() -> None:+ config = {"event_delivery": "shared", "tenant_id": ORG}+ assert await TeamsAdapter.prepare_config(config) == config+++async def test_a_shared_bridge_has_no_credentials_of_its_own_to_verify() -> None:+ """Whether the organisation approved the app is proved by the install, not+ by a secret this bridge never carries."""+ await TeamsAdapter.verify_credentials(+ {"event_delivery": "shared", "tenant_id": ORG}+ )+++def test_only_the_default_team_is_editable_on_a_shared_bridge() -> None:+ assert TeamsAdapter.editable_config_keys({"event_delivery": "shared"}) == (+ frozenset({"team_id"})+ )+ assert TeamsAdapter.editable_config_keys({"event_delivery": "own_listener"}) is None+++# ── The deployment's app ─────────────────────────────────────────────────────+++def test_each_organisation_gets_its_own_client_state() -> None:+ assert client_state_for("s", ORG) == client_state_for("s", ORG)+ assert client_state_for("s", ORG) != client_state_for("s", OTHER_ORG)+ assert client_state_for("s", ORG) != client_state_for("other-secret", ORG)+ assert len(client_state_for("s", ORG)) <= 128+++def test_the_identity_points_the_deployments_app_at_one_organisation() -> None:+ identity = _app().identity_for(ORG)+ assert identity.shared+ assert identity.org_tenant_id == ORG+ assert identity.app_id == "switch-app"+ assert identity.notification_url.startswith(+ "https://switch.example/messaging/teams/notifications?v="+ )+ assert identity.client_state == client_state_for("jwt-secret", ORG)+ assert identity.allowed_service_hosts == frozenset({"smba.trafficmanager.net"})+ assert identity.required_graph_roles == REQUIRED_GRAPH_ROLES+++def test_a_bring_your_own_bridge_is_never_attached() -> None:+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+ _app().attach_if_teams(adapter)+ assert adapter._shared_app is None+ with pytest.raises(ValueError):+ adapter.attach_shared_app(_app())+++async def test_a_shared_bridge_will_not_start_without_the_deployments_app() -> None:+ adapter = TeamsAdapter(config=_shared_config())++ async def _noop(*args: Any) -> None:+ return None++ with pytest.raises(RuntimeError, match="TEAMS_APP_"):+ await adapter.start(_noop, _noop, _noop, _noop, _noop)+++def _app_over(handler: httpx.MockTransport) -> TeamsSharedApp:+ certificate, key = _keypair()+ return TeamsSharedApp(+ app_id="switch-app",+ home_tenant_id="11111111-0000-0000-0000-000000000000",+ credential=ClientSecret("secret"),+ keyring=NotificationKeyring(+ current=NotificationKey(certificate_id="switch-cert", private_key=key),+ certificate_der_b64=load_certificate_der_b64(certificate),+ retired=(),+ ),+ messaging_public_url="https://switch.example",+ client_state_secret="jwt-secret",+ http=httpx.AsyncClient(transport=handler),+ )+++async def test_starting_a_shared_bridge_checks_approval_and_schedules_renewal() -> None:+ """The shared path of `start`: no listener of its own, tokens and a Graph+ client built from the deployment's app, and the renewal and repair loops+ running against it — proved by `stop` tearing down exactly those two tasks+ and leaving the app's own client open behind it."""++ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ token = jwt.encode({"roles": sorted(REQUIRED_GRAPH_ROLES)}, "k" * 32)+ return httpx.Response(200, json={"access_token": token, "expires_in": 3600})+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app_over(httpx.MockTransport(handler))+ adapter = TeamsAdapter(config=_shared_config())+ app.attach_if_teams(adapter)++ async def _noop(*args: Any) -> None:+ return None++ await adapter.start(_noop, _noop, _noop, _noop, _noop)++ assert adapter._owns_http is False+ assert adapter._http is app.http+ renewal_task, repair_task = adapter._renewal_task, adapter._repair_task+ assert renewal_task is not None and not renewal_task.done()+ assert repair_task is not None and not repair_task.done()++ await adapter.stop()++ assert renewal_task.cancelled()+ assert repair_task.cancelled()+ assert adapter._renewal_task is None+ assert adapter._repair_task is None+ assert adapter._http is None+ # The deployment's own client belongs to the app, not the bridge: stop()+ # must not have closed it.+ assert app.http.is_closed is False+ await app.aclose()+++async def test_start_does_not_wait_for_the_first_renewal_round() -> None:+ """Renewing many adopted subscriptions one by one, waiting out Graph's+ throttling, must not keep the bridge from connecting; the renewal loop's+ first round does it straight after."""++ def handler(request: httpx.Request) -> httpx.Response:+ if "oauth2/v2.0/token" in str(request.url):+ token = jwt.encode({"roles": sorted(REQUIRED_GRAPH_ROLES)}, "k" * 32)+ return httpx.Response(200, json={"access_token": token, "expires_in": 3600})+ if request.url.path == "/v1.0/subscriptions":+ return httpx.Response(200, json={"value": []})+ raise AssertionError(f"unexpected request: {request.method} {request.url}")++ app = _app_over(httpx.MockTransport(handler))+ adapter = TeamsAdapter(config=_shared_config())+ app.attach_if_teams(adapter)+ renewing = asyncio.Event()+ throttled = asyncio.Event()++ async def slow_renewal() -> None:+ renewing.set()+ await throttled.wait()++ adapter._renew_due_subscriptions = slow_renewal # type: ignore[method-assign]++ async def _noop(*args: Any) -> None:+ return None++ await asyncio.wait_for(adapter.start(_noop, _noop, _noop, _noop, _noop), 1)+ await asyncio.wait_for(renewing.wait(), 1)++ await adapter.stop()+ await app.aclose()+++# ── Inbound: only this organisation's ────────────────────────────────────────+++def _activity(tenant: str = ORG, **overrides: Any) -> dict[str, Any]:+ return {+ "type": "message",+ "id": "m1",+ "serviceUrl": SERVICE_URL,+ "text": "hello",+ "from": {"aadObjectId": "aad-1", "name": "Alice"},+ "conversation": {+ "id": f"{CHANNEL};messageid=m1",+ "conversationType": "channel",+ "tenantId": tenant,+ },+ "channelData": {"channel": {"id": CHANNEL}, "tenant": {"id": tenant}},+ **overrides,+ }+++def _capture(adapter: TeamsAdapter) -> list[InboundMessage]:+ seen: list[InboundMessage] = []++ async def on_message(message: InboundMessage) -> None:+ seen.append(message)++ adapter._on_message = on_message+ adapter._sender_handles["aad-1"] = "alice"+ adapter._channel_names[CHANNEL] = "general"+ return seen+++async def test_this_organisations_activity_is_delivered() -> None:+ adapter = _shared_adapter()+ seen = _capture(adapter)++ assert await adapter.receive_activity(_activity()) is None++ assert [m.content for m in seen] == ["hello"]+++async def test_another_organisations_activity_is_refused() -> None:+ adapter = _shared_adapter()+ seen = _capture(adapter)++ await adapter.receive_activity(_activity(tenant=OTHER_ORG))++ assert seen == []+++async def test_an_activity_naming_two_organisations_is_refused() -> None:+ adapter = _shared_adapter()+ seen = _capture(adapter)+ activity = _activity()+ activity["channelData"]["tenant"]["id"] = OTHER_ORG++ await adapter.receive_activity(activity)++ assert seen == []+++async def test_a_press_from_another_organisation_is_answered_with_a_refusal() -> None:+ """Left unanswered, the button spins and then reports a failure of its own."""+ adapter = _shared_adapter()++ answer = await adapter.receive_activity(+ _activity(tenant=OTHER_ORG, type="invoke", name="adaptiveCard/action")+ )++ assert answer is not None and answer["statusCode"] == 403+++async def test_a_service_url_that_is_not_microsofts_is_never_learned() -> None:+ """The bridge sends the deployment's token to whatever service URL it+ learns, so one that is not Microsoft's is refused before it is kept."""+ adapter = _shared_adapter()+ seen = _capture(adapter)++ await adapter.receive_activity(_activity(serviceUrl="https://evil.example/amer/"))++ assert seen == []+ assert adapter._default_service_url is None+++async def test_a_bring_your_own_bridge_takes_any_tenant_it_is_sent() -> None:+ """Its credential reaches only its own organisation, so there is nothing+ for it to refuse — and nothing changes for existing bridges."""+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+ seen = _capture(adapter)++ await adapter.receive_activity(_activity(tenant="whatever"))++ assert len(seen) == 1+++async def test_a_notification_for_a_subscription_the_bridge_did_not_make_is_refused() -> (+ None+):+ adapter = _shared_adapter()+ adapter._subscriptions[CHANNEL] = "SUB-MINE"++ class _Graph:+ renewed: list[str] = []++ async def renew_subscription(self, *, subscription_id: str, **_: Any) -> None:+ self.renewed.append(subscription_id)++ graph = _Graph()+ adapter._graph = graph # type: ignore[assignment]+ client_state = adapter._me.client_state++ await adapter.receive_notification(+ {+ "lifecycleEvent": "reauthorizationRequired",+ "subscriptionId": "SUB-SOMEONE-ELSES",+ "clientState": client_state,+ }+ )+ await adapter.receive_notification(+ {+ "lifecycleEvent": "reauthorizationRequired",+ "subscriptionId": "SUB-MINE",+ "clientState": client_state,+ }+ )++ assert graph.renewed == ["SUB-MINE"]+++async def test_another_organisations_client_state_is_refused() -> None:+ adapter = _shared_adapter()+ adapter._subscriptions[CHANNEL] = "SUB-MINE"++ class _Graph:+ renewed: list[str] = []++ async def renew_subscription(self, *, subscription_id: str, **_: Any) -> None:+ self.renewed.append(subscription_id)++ graph = _Graph()+ adapter._graph = graph # type: ignore[assignment]++ await adapter.receive_notification(+ {+ "lifecycleEvent": "reauthorizationRequired",+ "subscriptionId": "SUB-MINE",+ "clientState": client_state_for("jwt-secret", OTHER_ORG),+ }+ )++ assert graph.renewed == []+++# ── Binding a room to a channel by id ────────────────────────────────────────+++class _ChannelGraph:+ def __init__(self, *, fail: bool) -> None:+ self._fail = fail+ self.reads: list[tuple[str, str]] = []++ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:+ self.reads.append((team_id, channel_id))+ if self._fail:+ raise GraphError("get channel failed (404): NotFound", status=404)+ return {"id": channel_id}+++async def test_a_channel_in_this_organisation_can_be_bound() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _ChannelGraph(fail=False)+ adapter._graph = graph # type: ignore[assignment]++ await adapter.require_bindable_channel(CHANNEL)++ assert graph.reads == [("team-1", CHANNEL)]+++async def test_a_channel_graph_will_not_show_this_organisation_is_refused() -> None:+ adapter = _shared_adapter(team_id="team-1")+ adapter._graph = _ChannelGraph(fail=True) # type: ignore[assignment]++ with pytest.raises(ChannelNotBindable):+ await adapter.require_bindable_channel(CHANNEL)+++async def test_a_chat_cannot_be_bound_by_id() -> None:+ adapter = _shared_adapter(team_id="team-1")+ adapter._graph = _ChannelGraph(fail=False) # type: ignore[assignment]++ with pytest.raises(ChannelNotBindable, match="not a Teams channel"):+ await adapter.require_bindable_channel("19:[email protected]")+++async def test_a_channel_in_an_unknown_team_is_refused() -> None:+ adapter = _shared_adapter()+ adapter._graph = _ChannelGraph(fail=False) # type: ignore[assignment]++ with pytest.raises(ChannelNotBindable, match="which team"):+ await adapter.require_bindable_channel(CHANNEL)+++async def test_a_bring_your_own_bridge_has_nothing_to_refuse_when_binding() -> None:+ """Its own credential reaches only its own organisation, so there is no+ other organisation's channel it could bind by mistake."""+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )++ await adapter.require_bindable_channel(CHANNEL) # must not raise+++async def test_an_unstarted_shared_bridge_cannot_check_a_channel_binding() -> None:+ adapter = _shared_adapter(team_id="team-1")+ assert adapter._graph is None++ with pytest.raises(RuntimeError, match="not started"):+ await adapter.require_bindable_channel(CHANNEL)+++async def test_a_deeplink_for_a_channel_with_no_known_team_is_none() -> None:+ """Nothing to link to without a team id — a stopped bridge's dashboard+ shows no deeplink rather than a broken one."""+ adapter = _shared_adapter()++ assert await adapter.channel_deeplink(CHANNEL) is None+++async def test_adding_people_to_a_channel_with_no_known_team_fails_them_all() -> None:+ adapter = _shared_adapter()+ adapter._graph = _ChannelGraph(fail=False) # type: ignore[assignment]++ failed = await adapter.add_users_to_channel(CHANNEL, ["someone"], ["aad-1"])++ assert failed == ["aad-1"]+++async def test_creating_a_channel_needs_a_default_team() -> None:+ adapter = _shared_adapter()+ adapter._graph = _ChannelGraph(fail=False) # type: ignore[assignment]++ with pytest.raises(BridgeOperationError, match="default team"):+ await adapter.create_channel("room", "topic")+++async def test_the_type_of_a_channel_whose_team_is_not_yet_known_cannot_be_read() -> (+ None+):+ """Reading a channel needs its team, and nothing has learned this one's+ yet — no activity from it, and no default team to fall back to."""+ adapter = _shared_adapter()+ adapter._graph = _ChannelGraph(fail=False) # type: ignore[assignment]++ with pytest.raises(BridgeOperationError, match="which team"):+ await adapter.get_channel_type(CHANNEL)+++# ── Approval health ──────────────────────────────────────────────────────────+++class _Tokens:+ def __init__(+ self, *, roles: frozenset[str] | None = None, error: Exception | None = None+ ) -> None:+ self._roles = roles+ self._error = error++ async def graph_roles(self) -> frozenset[str]:+ if self._error is not None:+ raise self._error+ assert self._roles is not None+ return self._roles+++async def test_a_withdrawn_approval_is_something_to_act_on() -> None:+ adapter = _shared_adapter()+ adapter._tokens = _Tokens( # type: ignore[assignment]+ error=TokenRequestRefused("no app", error_codes=frozenset({700016}))+ )++ await adapter._check_approval()++ note = await adapter.attention()+ assert note is not None and "no longer approved" in note+++async def test_a_narrowed_approval_names_what_is_missing() -> None:+ adapter = _shared_adapter()+ adapter._tokens = _Tokens( # type: ignore[assignment]+ roles=REQUIRED_GRAPH_ROLES - {"Channel.Create"}+ )++ await adapter._check_approval()++ note = await adapter.attention()+ assert note is not None and "Channel.Create" in note+++async def test_an_intact_approval_clears_the_note() -> None:+ adapter = _shared_adapter()+ adapter._approval_problem = "stale"+ adapter._tokens = _Tokens(roles=REQUIRED_GRAPH_ROLES) # type: ignore[assignment]++ await adapter._check_approval()++ assert await adapter.attention() is None+++async def test_a_transient_failure_changes_nothing() -> None:+ """A blip in Microsoft's directory is not a withdrawn approval."""+ adapter = _shared_adapter()+ adapter._tokens = _Tokens( # type: ignore[assignment]+ error=TokenRequestRefused("busy", error_codes=frozenset({50196}))+ )++ await adapter._check_approval()++ assert await adapter.attention() is None+++async def test_microsoft_being_unreachable_is_not_an_approval_problem() -> None:+ """A connectivity failure says nothing about whether the organisation still+ approves the app, so it must not be mistaken for one."""+ adapter = _shared_adapter()+ adapter._tokens = _Tokens(error=httpx.ConnectError("no route to host")) # type: ignore[assignment]++ await adapter._check_approval()++ assert await adapter.attention() is None+++async def test_a_bring_your_own_bridge_has_no_approval_to_check() -> None:+ """Only a bridge on the distributed app can lose an organisation's+ approval; a bring-your-own bridge's identity asks for no Graph roles, so+ this returns before touching tokens it was never given."""+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )++ await adapter._check_approval()++ assert await adapter.attention() is None+++async def test_a_blocked_app_is_something_to_act_on() -> None:+ adapter = _shared_adapter()++ adapter._note_bot_disabled()++ note = await adapter.attention()+ assert note is not None and "blocked" in note+++# ── Subscriptions ────────────────────────────────────────────────────────────+++class _RenewGraph:+ def __init__(self, *, status: int | None = None) -> None:+ self._status = status+ self.renewed: list[str] = []++ async def renew_subscription(+ self, *, subscription_id: str, expiration_iso: str+ ) -> None:+ self.renewed.append(subscription_id)+ if self._status is not None:+ raise GraphError("renew failed", status=self._status)+++async def test_only_subscriptions_close_to_running_out_are_renewed() -> None:+ adapter = _shared_adapter()+ now = datetime.datetime.now(datetime.UTC)+ adapter._subscriptions = {+ "19:[email protected]": "SOON",+ "19:[email protected]": "LATER",+ }+ adapter._subscription_expiry = {+ "19:[email protected]": now + datetime.timedelta(minutes=5),+ "19:[email protected]": now + datetime.timedelta(minutes=50),+ }+ graph = _RenewGraph()+ adapter._graph = graph # type: ignore[assignment]++ await adapter._renew_due_subscriptions()++ assert graph.renewed == ["SOON"]+ assert adapter._subscription_expiry[+ "19:[email protected]"+ ] > now + datetime.timedelta(minutes=40)+++async def test_a_subscription_graph_no_longer_has_is_handed_to_the_repair_loop() -> (+ None+):+ adapter = _shared_adapter()+ adapter._subscriptions = {CHANNEL: "GONE"}+ adapter._graph = _RenewGraph(status=404) # type: ignore[assignment]++ await adapter._renew_due_subscriptions()++ assert CHANNEL not in adapter._subscriptions+ assert CHANNEL in adapter._capture_wanted+++async def test_a_failed_renewal_keeps_the_subscription_for_the_next_attempt() -> None:+ adapter = _shared_adapter()+ adapter._subscriptions = {CHANNEL: "SUB"}+ adapter._graph = _RenewGraph(status=503) # type: ignore[assignment]++ await adapter._renew_due_subscriptions()++ assert adapter._subscriptions == {CHANNEL: "SUB"}+++class _UnreachableRenewGraph:+ """Graph is not reachable at all — not even a Graph-shaped refusal."""++ async def renew_subscription(+ self, *, subscription_id: str, expiration_iso: str+ ) -> None:+ raise RuntimeError("connection reset")+++async def test_a_renewal_that_fails_outright_also_keeps_the_subscription() -> None:+ """Not every failure to renew comes back as a `GraphError` — anything else+ Graph's own client can raise is kept for the next attempt exactly the same+ way a refusal is."""+ adapter = _shared_adapter()+ adapter._subscriptions = {CHANNEL: "SUB"}+ adapter._graph = _UnreachableRenewGraph() # type: ignore[assignment]++ await adapter._renew_due_subscriptions()++ assert adapter._subscriptions == {CHANNEL: "SUB"}+++async def test_removing_the_app_from_a_team_stops_capture_there() -> None:+ adapter = _shared_adapter()+ adapter._team_of_channel = {CHANNEL: "team-1", "19:[email protected]": "team-2"}+ adapter._subscriptions = {CHANNEL: "SUB-1", "19:[email protected]": "SUB-2"}+ adapter._capture_wanted = {CHANNEL, "19:[email protected]"}++ class _Graph:+ deleted: list[str] = []++ async def delete_subscription(self, *, subscription_id: str) -> None:+ self.deleted.append(subscription_id)++ graph = _Graph()+ adapter._graph = graph # type: ignore[assignment]++ await adapter.receive_activity(+ {+ "type": "installationUpdate",+ "action": "remove",+ "serviceUrl": SERVICE_URL,+ "conversation": {+ "id": CHANNEL,+ "conversationType": "channel",+ "tenantId": ORG,+ },+ "channelData": {+ "team": {"aadGroupId": "team-1"},+ "channel": {"id": CHANNEL},+ "tenant": {"id": ORG},+ },+ }+ )++ assert graph.deleted == ["SUB-1"]+ assert adapter._capture_wanted == {"19:[email protected]"}+++async def test_an_upgrade_is_not_a_removal() -> None:+ adapter = _shared_adapter()+ adapter._team_of_channel = {CHANNEL: "team-1"}+ adapter._subscriptions = {CHANNEL: "SUB-1"}++ await adapter.receive_activity(+ {+ "type": "installationUpdate",+ "action": "remove-upgrade",+ "serviceUrl": SERVICE_URL,+ "conversation": {+ "id": CHANNEL,+ "conversationType": "channel",+ "tenantId": ORG,+ },+ "channelData": {"team": {"aadGroupId": "team-1"}, "tenant": {"id": ORG}},+ }+ )++ assert adapter._subscriptions == {CHANNEL: "SUB-1"}+++async def test_a_removal_naming_no_team_stops_capture_nowhere() -> None:+ """Graph always names the team on a real removal; this is the defensive+ branch for one that somehow does not, and it must not guess by falling+ back to whatever team this bridge defaults to."""+ adapter = _shared_adapter(team_id="team-1")+ adapter._team_of_channel = {CHANNEL: "team-1"}+ adapter._subscriptions = {CHANNEL: "SUB-1"}++ await adapter.receive_activity(+ {+ "type": "installationUpdate",+ "action": "remove",+ "serviceUrl": SERVICE_URL,+ "conversation": {+ "id": CHANNEL,+ "conversationType": "channel",+ "tenantId": ORG,+ },+ "channelData": {"tenant": {"id": ORG}},+ }+ )++ assert adapter._subscriptions == {CHANNEL: "SUB-1"}+++async def test_stopping_capture_with_no_live_subscription_is_a_no_op() -> None:+ adapter = _shared_adapter()+ adapter._capture_wanted = {CHANNEL}+ adapter._capture_failures = {CHANNEL: "some failure"}++ await adapter._stop_capture(CHANNEL)++ assert CHANNEL not in adapter._capture_wanted+ assert CHANNEL not in adapter._capture_failures+ assert CHANNEL not in adapter._subscriptions+++async def test_a_subscription_delete_that_fails_while_stopping_capture_is_only_logged() -> (+ None+):+ """The subscription runs out on its own within the hour; capture is+ already stopped either way, so a Graph failure here is not raised."""+ adapter = _shared_adapter()+ adapter._subscriptions = {CHANNEL: "SUB-1"}++ class _FailingDelete:+ async def delete_subscription(self, *, subscription_id: str) -> None:+ raise RuntimeError("Graph is down")++ adapter._graph = _FailingDelete() # type: ignore[assignment]++ await adapter._stop_capture(CHANNEL) # must not raise++ assert CHANNEL not in adapter._subscriptions+++# ── Removal ──────────────────────────────────────────────────────────────────+++class _WithdrawGraph:+ def __init__(+ self,+ *,+ listed: list[dict[str, Any]],+ installations: list[str],+ teams: tuple[str, ...] = ("team-1",),+ ) -> None:+ self._listed = listed+ self._installations = installations+ self._teams = teams+ self.deleted: list[str] = []+ self.uninstalled: list[tuple[str, str]] = []++ async def list_subscriptions(self) -> list[dict[str, Any]]:+ return self._listed++ async def list_teams(self) -> list[dict[str, Any]]:+ return [{"id": team_id} for team_id in self._teams]++ async def delete_subscription(self, *, subscription_id: str) -> None:+ self.deleted.append(subscription_id)++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ return [+ AppInstallation(installation_id=i, catalog_app_id="catalog-1")+ for i in self._installations+ ]++ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ self.uninstalled.append((team_id, installation_id))+++async def test_removing_a_shared_bridge_stops_listening_and_leaves_its_teams() -> None:+ adapter = _shared_adapter(team_id="team-default")+ url = adapter._me.notification_url+ adapter._subscriptions = {CHANNEL: "SUB-KNOWN"}+ adapter._team_of_channel = {CHANNEL: "team-1"}+ graph = _WithdrawGraph(+ listed=[+ {"id": "SUB-KNOWN", "notificationUrl": url},+ {"id": "SUB-UNADOPTED", "notificationUrl": url},+ {"id": "SUB-ELSEWHERE", "notificationUrl": "https://other.example/x"},+ ],+ installations=["INST-1"],+ teams=("team-1", "team-default", "team-never-seen"),+ )+ adapter._graph = graph # type: ignore[assignment]++ await adapter.withdraw()++ assert sorted(graph.deleted) == ["SUB-KNOWN", "SUB-UNADOPTED"]+ # Every team the app is in, including one whose join the bridge never saw.+ assert sorted(graph.uninstalled) == [+ ("team-1", "INST-1"),+ ("team-default", "INST-1"),+ ("team-never-seen", "INST-1"),+ ]+ assert adapter._capture_wanted == set()+++async def test_removing_a_bring_your_own_bridge_leaves_the_operators_app_in_place() -> (+ None+):+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+ adapter._subscriptions = {CHANNEL: "SUB-1"}+ graph = _WithdrawGraph(listed=[], installations=["INST-1"])+ adapter._graph = graph # type: ignore[assignment]++ await adapter.withdraw()++ assert graph.deleted == ["SUB-1"]+ assert graph.uninstalled == []+++async def test_what_could_not_be_withdrawn_is_said() -> None:+ adapter = _shared_adapter()+ adapter._subscriptions = {CHANNEL: "SUB-1"}++ class _Failing(_WithdrawGraph):+ async def delete_subscription(self, *, subscription_id: str) -> None:+ raise GraphError("delete failed (503)", status=503)++ adapter._graph = _Failing(listed=[], installations=[]) # type: ignore[assignment]++ with pytest.raises(BridgeOperationError, match="SUB-1"):+ await adapter.withdraw()+++async def test_withdrawing_before_a_graph_client_ever_existed_is_a_no_op() -> None:+ """A bridge that never got past `start`'s early checks has nothing on the+ platform to let go of."""+ adapter = _shared_adapter()+ assert adapter._graph is None++ await adapter.withdraw() # must not raise+++async def test_a_withdrawal_that_cannot_even_list_subscriptions_still_says_so() -> None:+ adapter = _shared_adapter()++ class _Unreachable(_WithdrawGraph):+ async def list_subscriptions(self) -> list[dict[str, Any]]:+ raise GraphError("list failed (503)", status=503)++ adapter._graph = _Unreachable(listed=[], installations=[]) # type: ignore[assignment]++ with pytest.raises(BridgeOperationError, match="listing subscriptions failed"):+ await adapter.withdraw()+++async def test_a_team_the_app_cannot_be_removed_from_is_named_in_what_is_left_behind() -> (+ None+):+ adapter = _shared_adapter(team_id="team-1")++ class _CannotUninstall(_WithdrawGraph):+ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ raise GraphError("uninstall failed (403)", status=403)++ adapter._graph = _CannotUninstall( # type: ignore[assignment]+ listed=[], installations=["INST-1"]+ )++ with pytest.raises(BridgeOperationError, match="the app in team team-1"):+ await adapter.withdraw()+++# ── From the deployment's public route ───────────────────────────────────────+++async def test_an_activity_from_the_public_route_is_delivered() -> None:+ adapter = _shared_adapter()+ seen = _capture(adapter)++ answer = await adapter.dispatch_event(envelope_type="activity", payload=_activity())++ assert answer is None+ assert [m.content for m in seen] == ["hello"]+++async def test_a_press_from_the_public_route_is_answered() -> None:+ adapter = _shared_adapter()++ answer = await adapter.dispatch_event(+ envelope_type="activity",+ payload=_activity(tenant=OTHER_ORG, type="invoke", name="adaptiveCard/action"),+ )++ assert answer is not None and answer["statusCode"] == 403+++async def test_an_envelope_it_does_not_know_is_refused() -> None:+ adapter = _shared_adapter()+ with pytest.raises(ValueError):+ await adapter.dispatch_event(envelope_type="mystery", payload={})+++async def test_a_notification_from_the_public_route_answers_nothing() -> None:+ """Unlike an activity, which may carry an invoke's answer, a notification+ never does — Graph does not wait on a reply."""+ adapter = _shared_adapter()++ answer = await adapter.dispatch_event(+ envelope_type="notification",+ payload={"clientState": "not this organisation's", "subscriptionId": "x"},+ )++ assert answer is None+++# ── Which teams Switch is in ─────────────────────────────────────────────────+++class _PlacementGraph:+ def __init__(self) -> None:+ self.installed: dict[str, list[str]] = {"team-b": ["INST-B"]}+ self.added: list[tuple[str, str]] = []+ self.uninstalled: list[tuple[str, str]] = []+ self.deleted: list[str] = []++ async def list_teams(self) -> list[dict[str, Any]]:+ return [+ {"id": "team-b", "displayName": "beta"},+ {"id": "team-a", "displayName": "Alpha"},+ {"id": "team-unreadable", "displayName": "gamma (archived)"},+ ]++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ assert external_id == "switch-app"+ if team_id == "team-unreadable":+ raise GraphError("forbidden", status=403)+ return [+ AppInstallation(installation_id=i, catalog_app_id="catalog-b")+ for i in self.installed.get(team_id, [])+ ]++ async def install_app(self, *, team_id: str, catalog_app_id: str) -> None:+ self.added.append((team_id, catalog_app_id))++ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ self.uninstalled.append((team_id, installation_id))++ async def delete_subscription(self, *, subscription_id: str) -> None:+ self.deleted.append(subscription_id)+++async def test_the_organisations_teams_are_listed_with_where_switch_is() -> None:+ adapter = _shared_adapter()+ adapter._graph = _PlacementGraph() # type: ignore[assignment]++ placements = await adapter.list_team_placements()++ assert [(p.name, p.has_switch) for p in placements.teams] == [+ ("Alpha", False),+ ("beta", True),+ ("gamma (archived)", None),+ ]+ # An installation reports the app's id in the catalogue, which is how it+ # is learned after a Teams admin uploaded the app by hand.+ assert placements.catalog_app_id == "catalog-b"+ assert adapter.places_app_in_teams+++async def test_switch_is_added_to_a_team_by_its_id_in_the_catalogue() -> None:+ adapter = _shared_adapter()+ graph = _PlacementGraph()+ adapter._graph = graph # type: ignore[assignment]++ await adapter.add_to_team("team-a", catalog_app_id="catalog-1")++ assert graph.added == [("team-a", "catalog-1")]+++async def test_leaving_a_team_stops_capture_in_its_channels() -> None:+ adapter = _shared_adapter()+ graph = _PlacementGraph()+ adapter._graph = graph # type: ignore[assignment]+ adapter._team_of_channel = {CHANNEL: "team-b"}+ adapter._subscriptions = {CHANNEL: "SUB-B"}++ await adapter.remove_from_team("team-b")++ assert graph.uninstalled == [("team-b", "INST-B")]+ assert graph.deleted == ["SUB-B"]+++async def test_a_bring_your_own_bridge_does_not_place_itself() -> None:+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+ adapter._graph = _PlacementGraph() # type: ignore[assignment]++ assert not adapter.places_app_in_teams+ with pytest.raises(BridgeOperationError):+ await adapter.list_team_placements()+++async def test_an_unstarted_shared_bridge_cannot_be_asked_which_teams_it_is_in() -> (+ None+):+ """It is a bridge on the distributed app, so the request is the right one —+ just asked of a bridge that has no Graph client yet."""+ adapter = _shared_adapter()+ assert adapter._graph is None++ with pytest.raises(RuntimeError, match="not started"):+ await adapter.list_team_placements()+++def test_before_any_activity_a_shared_bridge_posts_through_microsofts_global_endpoint() -> (+ None+):+ adapter = _shared_adapter()+ assert adapter._service_url_for(CHANNEL) == "https://smba.trafficmanager.net/teams/"+++def test_a_bring_your_own_bridge_still_waits_to_learn_its_endpoint() -> None:+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+ with pytest.raises(RuntimeError, match="serviceUrl"):+ adapter._service_url_for(CHANNEL)+++async def test_a_chat_is_never_mapped_to_a_team() -> None:+ adapter = _shared_adapter(team_id="team-default")+ _capture(adapter)+ chat = "19:[email protected]"++ await adapter.receive_activity(+ _activity(+ conversation={"id": chat, "conversationType": "groupChat", "tenantId": ORG},+ channelData={"tenant": {"id": ORG}},+ )+ )++ assert chat not in adapter._team_of_channel+++async def test_removing_a_shared_bridge_lets_go_of_its_organisations_tokens() -> None:+ app = _app()+ adapter = TeamsAdapter(config=_shared_config())+ app.attach_if_teams(adapter)+ app.org_tokens(ORG)+ adapter._graph = _WithdrawGraph(listed=[], installations=[]) # type: ignore[assignment]++ await adapter.withdraw()++ assert ORG not in app._org_tokens+++# ── Review fixes ─────────────────────────────────────────────────────────────+++async def test_a_renewal_round_that_fails_does_not_end_renewal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The loop is what keeps every subscription alive; an error escaping it+ would end renewal silently and for good."""+ adapter = _shared_adapter()+ rounds: list[int] = []++ async def failing_check() -> None:+ rounds.append(1)+ raise OSError("the projected token file is being rotated")++ async def fast_sleep(seconds: float) -> None:+ if len(rounds) >= 3:+ raise asyncio.CancelledError++ adapter._check_approval = failing_check # type: ignore[method-assign]+ monkeypatch.setattr(+ "switch_core.bridges.collaboration.teams.adapter.asyncio.sleep", fast_sleep+ )++ with pytest.raises(asyncio.CancelledError):+ await adapter._renewal_loop()++ assert len(rounds) == 3+++async def test_a_successful_round_goes_on_to_renew_due_subscriptions(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = _shared_adapter()+ rounds: list[int] = []++ async def ok_check() -> None:+ return None++ async def renew() -> None:+ rounds.append(1)++ async def fast_sleep(seconds: float) -> None:+ if len(rounds) >= 2:+ raise asyncio.CancelledError++ adapter._check_approval = ok_check # type: ignore[method-assign]+ adapter._renew_due_subscriptions = renew # type: ignore[method-assign]+ monkeypatch.setattr(+ "switch_core.bridges.collaboration.teams.adapter.asyncio.sleep", fast_sleep+ )++ with pytest.raises(asyncio.CancelledError):+ await adapter._renewal_loop()++ assert len(rounds) == 2+++def test_an_unusable_encryption_key_only_turns_capture_off() -> None:+ """A bring-your-own bridge with a key Graph cannot use still posts and+ hears mentions; it just does not capture channel messages."""+ key = ec.generate_private_key(ec.SECP256R1())+ pem = key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode()+ certificate, _ = _keypair()+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ encryption_certificate_id="c",+ encryption_public_certificate=certificate,+ encryption_private_key=pem,+ )+ )+ assert adapter._me.keyring is None+++async def test_rotating_the_secret_remakes_subscriptions_made_under_the_old_one() -> (+ None+):+ """The clientState key rides on the notification URL, so a subscription+ made under an earlier key points somewhere else and is replaced at start+ rather than kept and failing every origin check."""+ adapter = _shared_adapter()+ current = adapter._me.notification_url+ stale = current.split("?")[0] + "?v=0123456789ab"++ class _Graph:+ deleted: list[str] = []++ async def list_subscriptions(self) -> list[dict[str, Any]]:+ return [+ {+ "id": "OLD-KEY",+ "resource": f"teams/t/channels/{CHANNEL}/messages",+ "notificationUrl": stale,+ },+ {+ "id": "CURRENT",+ "resource": "teams/t/channels/19:[email protected]/messages",+ "notificationUrl": current,+ },+ ]++ async def delete_subscription(self, *, subscription_id: str) -> None:+ self.deleted.append(subscription_id)++ graph = _Graph()+ adapter._graph = graph # type: ignore[assignment]++ await adapter._adopt_existing_subscriptions()++ assert graph.deleted == ["OLD-KEY"]+ assert adapter._subscriptions == {"19:[email protected]": "CURRENT"}+++def test_a_subscription_made_under_an_earlier_key_still_delivers_here() -> None:+ """For cleaning up: it is this deployment's, whichever key made it."""+ identity = _app().identity_for(ORG)+ base = identity.notification_url.split("?")[0]+ assert identity.delivers_here(base + "?v=0123456789ab")+ assert not identity.delivers_here(+ "https://elsewhere.example/messaging/teams/notifications"+ )+++async def test_an_organisation_whose_bridge_is_not_running_is_still_left() -> None:+ app = _app()+ url = app.identity_for(ORG).notification_url.split("?")[0] + "?v=old"+ deleted: list[str] = []+ uninstalled: list[tuple[str, str]] = []++ class _Graph:+ async def list_subscriptions(self) -> list[dict[str, Any]]:+ return [+ {"id": "S1", "notificationUrl": url},+ {"id": "S2", "notificationUrl": "https://elsewhere.example/x"},+ ]++ async def delete_subscription(self, *, subscription_id: str) -> None:+ deleted.append(subscription_id)++ async def list_teams(self) -> list[dict[str, Any]]:+ return [{"id": "team-1"}, {"id": "team-2"}]++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ if team_id == "team-1":+ return [AppInstallation(installation_id="I1", catalog_app_id="c")]+ return []++ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ uninstalled.append((team_id, installation_id))++ original = shared_app_module.GraphClient+ shared_app_module.GraphClient = lambda **_: _Graph() # type: ignore[assignment,misc]+ try:+ app.org_tokens(ORG)+ await app.withdraw_from_org(ORG)+ finally:+ shared_app_module.GraphClient = original # type: ignore[misc]++ assert deleted == ["S1"]+ assert uninstalled == [("team-1", "I1")]+ assert ORG not in app._org_tokens+++# ── Channel ids offered for binding ──────────────────────────────────────────+++ "channel_id",+ [+ "19:x/../../../teams/[email protected]",+ "19:[email protected]",+ "19:x#@thread.tacv2",+ "19:x%[email protected]",+ "19:x [email protected]",+ "19:x@[email protected]",+ "19:@thread.tacv2",+ ],+)+async def test_a_channel_id_that_could_reshape_the_check_is_refused(+ channel_id: str,+) -> None:+ """The id goes into the Graph call that proves the channel is this+ organisation's; one that moved that call elsewhere could pass it."""+ adapter = _shared_adapter(team_id="team-1")+ graph = _ChannelGraph(fail=False)+ adapter._graph = graph # type: ignore[assignment]++ with pytest.raises(ChannelNotBindable, match="not a Teams channel"):+ await adapter.require_bindable_channel(channel_id)++ assert graph.reads == []+++async def test_an_older_teams_channel_id_can_be_bound() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _ChannelGraph(fail=False)+ adapter._graph = graph # type: ignore[assignment]++ await adapter.require_bindable_channel("19:[email protected]")++ assert graph.reads == [("team-1", "19:[email protected]")]+++# ── Never a second subscription ──────────────────────────────────────────────+++class _SubscribingGraph:+ """Lists what it holds (or fails to), and makes subscriptions on request."""++ def __init__(self, *, list_failures: int, held: list[dict[str, Any]]) -> None:+ self.list_failures = list_failures+ self.held = held+ self.created: list[str] = []+ self.deleted: list[str] = []+ self.create_started = asyncio.Event()+ self.let_create_finish: asyncio.Event | None = None+ # The teams Switch is in, and a failure for asking about any of them.+ self.installed_in: set[str] = {"team-1"}+ self.check_failure: Exception | None = None+ self.listings = 0++ async def list_subscriptions(self) -> list[dict[str, Any]]:+ self.listings += 1+ if self.list_failures:+ self.list_failures -= 1+ raise GraphError("list subscriptions failed (503)", status=503)+ return list(self.held)++ async def create_subscription(self, **kwargs: Any) -> dict[str, Any]:+ self.create_started.set()+ if self.let_create_finish is not None:+ await self.let_create_finish.wait()+ sub_id = f"NEW-{len(self.created) + 1}"+ self.created.append(sub_id)+ self.held.append(+ {+ "id": sub_id,+ "resource": kwargs["resource"],+ "notificationUrl": kwargs["notification_url"],+ }+ )+ return {"id": sub_id}++ async def delete_subscription(self, *, subscription_id: str) -> None:+ self.deleted.append(subscription_id)+ self.held = [s for s in self.held if s["id"] != subscription_id]++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ if self.check_failure is not None:+ raise self.check_failure+ if team_id not in self.installed_in:+ return []+ return [+ AppInstallation(installation_id=f"INST-{team_id}", catalog_app_id="cat-1")+ ]++ async def install_app(self, *, team_id: str, catalog_app_id: str) -> None:+ self.installed_in.add(team_id)++ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ self.installed_in.discard(team_id)++ async def list_teams(self) -> list[dict[str, Any]]:+ return []+++async def test_capture_waits_until_the_existing_subscriptions_can_be_read() -> None:+ """A channel whose live subscription could not be seen at start would be+ given a second, and every message delivered twice."""+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=2, held=[])+ adapter._graph = graph # type: ignore[assignment]++ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)++ assert graph.created == []+ assert CHANNEL in adapter._capture_wanted+ assert CHANNEL in adapter._capture_failures+++async def test_a_subscription_seen_once_listing_works_is_adopted_not_remade() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(+ list_failures=1,+ held=[+ {+ "id": "LIVE",+ "resource": f"teams/team-1/channels/{CHANNEL}/messages",+ "notificationUrl": adapter._me.notification_url,+ }+ ],+ )+ adapter._graph = graph # type: ignore[assignment]++ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)++ assert graph.created == []+ assert adapter._subscriptions == {CHANNEL: "LIVE"}+++async def test_a_channel_with_none_is_subscribed_once_listing_works() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=1, held=[])+ adapter._graph = graph # type: ignore[assignment]++ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)++ assert graph.created == ["NEW-1"]+ assert adapter._subscriptions == {CHANNEL: "NEW-1"}+++async def test_nothing_is_subscribed_once_the_bridge_is_withdrawing() -> None:+ """A `subscriptionRemoved` arriving while the bridge is being removed must+ not make a subscription nothing will renew or delete."""+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]+ adapter._adopted = True+ adapter._subscriptions = {CHANNEL: "SUB-1"}++ await adapter.withdraw()+ await adapter._recreate_removed_subscription("SUB-1")+ adapter._subscriptions = {}+ await adapter._ensure_channel_subscription(CHANNEL)++ assert graph.created == []+++async def test_a_subscription_being_made_as_withdrawal_starts_is_deleted() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=0, held=[])+ graph.let_create_finish = asyncio.Event()+ adapter._graph = graph # type: ignore[assignment]+ adapter._adopted = True++ making = asyncio.create_task(adapter._ensure_channel_subscription(CHANNEL))+ await graph.create_started.wait()+ withdrawing = asyncio.create_task(adapter.withdraw())+ await asyncio.sleep(0)+ graph.let_create_finish.set()+ await making+ await withdrawing++ assert graph.created == ["NEW-1"]+ assert graph.deleted == ["NEW-1"]+++async def test_a_notification_before_the_subscriptions_could_be_read_reads_them() -> (+ None+):+ """Graph has been answered by the time a notification reaches the bridge,+ so refusing one whose subscription is unknown only because the listing+ failed at start would lose it."""+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(+ list_failures=1,+ held=[+ {+ "id": "LIVE",+ "resource": f"teams/team-1/channels/{CHANNEL}/messages",+ "notificationUrl": adapter._me.notification_url,+ }+ ],+ )+ renewed: list[str] = []++ async def renew_subscription(*, subscription_id: str, **_: Any) -> None:+ renewed.append(subscription_id)++ graph.renew_subscription = renew_subscription # type: ignore[attr-defined]+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ assert adapter._adopted is False++ await adapter.receive_notification(+ {+ "lifecycleEvent": "reauthorizationRequired",+ "subscriptionId": "LIVE",+ "clientState": adapter._me.client_state,+ }+ )++ assert renewed == ["LIVE"]+ assert adapter._subscriptions == {CHANNEL: "LIVE"}+++# ── Capture only where Switch is ─────────────────────────────────────────────+++async def test_a_channel_in_a_team_switch_is_not_in_is_not_captured() -> None:+ """Graph delivers a team's messages whether or not the app is in it."""+ adapter = _shared_adapter(team_id="team-2")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]++ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)++ assert graph.created == []+ assert CHANNEL not in adapter._capture_wanted+ assert CHANNEL in adapter._capture_parked+++async def test_removing_switch_from_a_team_still_holds_after_a_restart() -> None:+ graph = _SubscribingGraph(list_failures=0, held=[])+ before = _shared_adapter(team_id="team-1")+ before._graph = graph # type: ignore[assignment]+ await before._adopt_existing_subscriptions()+ await before._ensure_channel_subscription(CHANNEL)+ assert graph.created == ["NEW-1"]++ await before.remove_from_team("team-1")+ assert graph.deleted == ["NEW-1"]++ after = _shared_adapter(team_id="team-1")+ after._graph = graph # type: ignore[assignment]+ await after._adopt_existing_subscriptions()+ await after.ensure_channel_subscriptions([(CHANNEL, "channel_public")])++ assert graph.created == ["NEW-1"]+ assert after._subscriptions == {}+++async def test_a_subscription_left_in_a_team_switch_is_out_of_is_deleted() -> None:+ """One whose deletion failed when Switch left is adopted at the next start;+ it must not be renewed for ever."""+ adapter = _shared_adapter(team_id="team-2")+ graph = _SubscribingGraph(+ list_failures=0,+ held=[+ {+ "id": "LEFT",+ "resource": f"teams/team-2/channels/{CHANNEL}/messages",+ "notificationUrl": adapter._me.notification_url,+ }+ ],+ )+ adapter._graph = graph # type: ignore[assignment]++ await adapter._adopt_existing_subscriptions()+ await adapter.ensure_channel_subscriptions([(CHANNEL, "channel_public")])++ assert graph.deleted == ["LEFT"]+ assert adapter._subscriptions == {}+++async def test_adding_switch_to_the_team_captures_its_waiting_channels() -> None:+ adapter = _shared_adapter(team_id="team-2")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)+ assert graph.created == []++ await adapter.add_to_team("team-2", catalog_app_id="cat-1")++ assert graph.created == ["NEW-1"]+ assert CHANNEL not in adapter._capture_parked+++async def test_teams_saying_switch_was_added_captures_its_waiting_channels() -> None:+ adapter = _shared_adapter(team_id="team-2")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)+ graph.installed_in.add("team-2")++ await adapter._dispatch_installation_update(+ {"action": "add", "channelData": {"team": {"aadGroupId": "team-2"}}}+ )++ assert graph.created == ["NEW-1"]+++async def test_unknown_subscriptions_do_not_each_cost_a_listing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Graph failing, or someone holding the organisation's clientState,+ must not turn every notification into a reading of Graph."""+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=10, held=[])+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ unknown = {+ "lifecycleEvent": "reauthorizationRequired",+ "subscriptionId": "NOT-MINE",+ "clientState": adapter._me.client_state,+ }++ await adapter.receive_notification(unknown)+ await adapter.receive_notification(unknown)+ assert graph.listings == 2++ monkeypatch.setattr(adapter_module, "_ADOPT_ON_DEMAND_COOLDOWN_SECONDS", 0)+ await adapter.receive_notification(unknown)+ assert graph.listings == 3+++async def test_leaving_the_default_team_leaves_channels_known_to_be_elsewhere() -> None:+ """A channel whose team is known, from Teams or from the subscription+ Graph accepted, is not taken to be in the default team."""+ learned = "19:[email protected]"+ adopted = "19:[email protected]"+ adapter = _shared_adapter(team_id="team-1", channel_teams={learned: "team-2"})+ graph = _SubscribingGraph(+ list_failures=0,+ held=[+ {+ "id": "ADOPTED",+ "resource": f"teams/team-2/channels/{adopted}/messages",+ "notificationUrl": adapter._me.notification_url,+ }+ ],+ )+ graph.installed_in = {"team-1", "team-2"}+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ await adapter.ensure_channel_subscriptions(+ [+ (CHANNEL, "channel_public"),+ (learned, "channel_public"),+ (adopted, "channel_public"),+ ]+ )+ assert set(adapter._subscriptions) == {CHANNEL, learned, adopted}++ await adapter.remove_from_team("team-1")++ assert set(adapter._subscriptions) == {learned, adopted}+ assert set(adapter._capture_parked) == {CHANNEL}+++async def test_switch_added_back_where_the_bot_heard_nothing_is_noticed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = _shared_adapter(team_id="team-2")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)+ graph.installed_in.add("team-2")++ await adapter._recheck_teams()+ assert graph.created == []++ monkeypatch.setattr(adapter_module, "_TEAM_RECHECK_SECONDS", 0)+ await adapter._recheck_teams()+ assert graph.created == ["NEW-1"]+++async def test_switch_removed_where_the_bot_heard_nothing_is_noticed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)+ graph.installed_in.discard("team-1")+ monkeypatch.setattr(adapter_module, "_TEAM_RECHECK_SECONDS", 0)++ await adapter._recheck_teams()++ assert graph.deleted == ["NEW-1"]+ assert CHANNEL in adapter._capture_parked+++async def test_a_recheck_that_cannot_reach_graph_changes_nothing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=0, held=[])+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()+ await adapter._ensure_channel_subscription(CHANNEL)+ graph.check_failure = GraphError("busy", status=503)+ monkeypatch.setattr(adapter_module, "_TEAM_RECHECK_SECONDS", 0)++ await adapter._recheck_teams()++ assert graph.deleted == []+ assert adapter._subscriptions == {CHANNEL: "NEW-1"}+ assert adapter._team_has_switch["team-1"][0] is True+++async def test_a_team_that_cannot_be_checked_is_left_to_the_repair_loop() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _SubscribingGraph(list_failures=0, held=[])+ graph.check_failure = GraphError("busy", status=503)+ adapter._graph = graph # type: ignore[assignment]+ await adapter._adopt_existing_subscriptions()++ await adapter._ensure_channel_subscription(CHANNEL)+ assert graph.created == []+ assert CHANNEL in adapter._capture_wanted+ assert "could not check" in adapter._capture_failures[CHANNEL]++ graph.check_failure = None+ await adapter._ensure_channel_subscription(CHANNEL)+ assert graph.created == ["NEW-1"]+++# ── The default team ─────────────────────────────────────────────────────────+++class _DefaultTeamGraph:+ def __init__(self, *, installed_in: set[str], failure: Exception | None) -> None:+ self.installed_in = installed_in+ self.failure = failure+ self.asked: list[str] = []++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ self.asked.append(team_id)+ if self.failure is not None:+ raise self.failure+ if team_id in self.installed_in:+ return [AppInstallation(installation_id="I", catalog_app_id="c")]+ return []+++async def test_a_team_switch_is_in_can_be_the_default() -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _DefaultTeamGraph(installed_in={"team-2"}, failure=None)+ adapter._graph = graph # type: ignore[assignment]++ await adapter.check_config_edit({"tenant_id": ORG, "team_id": "team-2"})++ assert graph.asked == ["team-2"]+++async def test_a_team_switch_is_not_in_cannot_be_the_default() -> None:+ adapter = _shared_adapter(team_id="team-1")+ adapter._graph = _DefaultTeamGraph(installed_in=set(), failure=None) # type: ignore[assignment]++ with pytest.raises(ConfigEditRefused, match="Add it to the team first"):+ await adapter.check_config_edit({"tenant_id": ORG, "team_id": "team-2"})+++async def test_a_team_that_does_not_exist_cannot_be_the_default() -> None:+ adapter = _shared_adapter(team_id="team-1")+ adapter._graph = _DefaultTeamGraph( # type: ignore[assignment]+ installed_in=set(), failure=GraphError("not found (404)", status=404)+ )++ with pytest.raises(ConfigEditRefused, match="no team"):+ await adapter.check_config_edit({"tenant_id": ORG, "team_id": "nope"})+++ "failure",+ [+ GraphError("busy (503)", status=503),+ TokenRequestRefused("AADSTS700016", error_codes=frozenset({700016})),+ httpx.ConnectError("unreachable"),+ ],+)+async def test_a_default_team_microsoft_cannot_be_asked_about_is_not_accepted(+ failure: Exception,+) -> None:+ adapter = _shared_adapter(team_id="team-1")+ adapter._graph = _DefaultTeamGraph(installed_in=set(), failure=failure) # type: ignore[assignment]++ with pytest.raises(BridgeOperationError):+ await adapter.check_config_edit({"tenant_id": ORG, "team_id": "team-2"})++[email protected]("team_id", [None, "team-1"])+async def test_an_unchanged_or_cleared_default_is_not_checked(+ team_id: str | None,+) -> None:+ adapter = _shared_adapter(team_id="team-1")+ graph = _DefaultTeamGraph(installed_in=set(), failure=None)+ adapter._graph = graph # type: ignore[assignment]++ await adapter.check_config_edit({"tenant_id": ORG, "team_id": team_id})++ assert graph.asked == []+++async def test_a_bring_your_own_bridges_default_team_is_its_operators() -> None:+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id="t",+ team_id="team",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+ graph = _DefaultTeamGraph(installed_in=set(), failure=None)+ adapter._graph = graph # type: ignore[assignment]++ await adapter.check_config_edit({"team_id": "anything"})++ assert graph.asked == []+++async def test_two_catalogue_ids_for_the_app_are_logged(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter = _shared_adapter()++ class _TwoCopies(_PlacementGraph):+ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ return [+ AppInstallation(installation_id="I", catalog_app_id=f"cat-{team_id}")+ ]++ adapter._graph = _TwoCopies() # type: ignore[assignment]++ with caplog.at_level("WARNING"):+ placements = await adapter.list_team_placements()++ assert placements.catalog_app_id is not None+ assert "more than one catalogue id" in caplog.text+++# ── Final review fixes ───────────────────────────────────────────────────────+++async def test_a_channel_activity_without_its_team_does_not_move_the_channel() -> None:+ """Teams names a channel's team group on some activities only. A bridge on+ the distributed app is in many teams, so guessing the default would file+ another team's channel under it, and its capture would ask the wrong team."""+ adapter = _shared_adapter(team_id="team-default")+ _capture(adapter)+ adapter._team_of_channel = {CHANNEL: "team-x"}++ await adapter.receive_activity(+ _activity(channelData={"channel": {"id": CHANNEL}, "tenant": {"id": ORG}})+ )++ assert adapter._team_of_channel == {CHANNEL: "team-x"}+++async def test_a_channel_activity_naming_its_team_places_the_channel() -> None:+ adapter = _shared_adapter(team_id="team-default")+ _capture(adapter)++ await adapter.receive_activity(+ _activity(+ channelData={+ "channel": {"id": CHANNEL},+ "tenant": {"id": ORG},+ "team": {"id": "19:team-thread", "aadGroupId": "team-x"},+ }+ )+ )++ assert adapter._team_of_channel == {CHANNEL: "team-x"}+++def _own_bridge() -> TeamsAdapter:+ return TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="a",+ app_password="p",+ tenant_id=ORG,+ team_id="team-own",+ public_base_url="https://x.example",+ client_state="s",+ )+ )+++async def test_a_bring_your_own_bridge_places_an_unplaced_channel_in_its_team() -> None:+ adapter = _own_bridge()+ _capture(adapter)++ await adapter.receive_activity(+ _activity(channelData={"channel": {"id": CHANNEL}, "tenant": {"id": ORG}})+ )++ assert adapter._team_of_channel == {CHANNEL: "team-own"}+++async def test_a_bring_your_own_bridge_keeps_a_channel_it_already_placed() -> None:+ adapter = _own_bridge()+ _capture(adapter)+ adapter._team_of_channel = {CHANNEL: "team-elsewhere"}++ await adapter.receive_activity(+ _activity(channelData={"channel": {"id": CHANNEL}, "tenant": {"id": ORG}})+ )++ assert adapter._team_of_channel == {CHANNEL: "team-elsewhere"}+++async def test_an_unreadable_credential_file_is_not_an_approval_problem() -> None:+ """The federated token file can be unreadable for a moment while it is+ rotated; the check says it could not ask, and the bridge carries on."""+ adapter = _shared_adapter()+ adapter._tokens = _Tokens( # type: ignore[assignment]+ error=FileNotFoundError("/var/run/secrets/microsoft/teams-app/token")+ )++ await adapter._check_approval()++ assert await adapter.attention() is None+++async def test_a_team_whose_read_times_out_is_listed_as_unknown() -> None:+ adapter = _shared_adapter()++ class _Slow(_PlacementGraph):+ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ if team_id == "team-a":+ raise httpx.ReadTimeout("timed out")+ return await super().find_app_installations(+ team_id=team_id, external_id=external_id+ )++ adapter._graph = _Slow() # type: ignore[assignment]++ placements = await adapter.list_team_placements()++ by_id = {p.team_id: p.has_switch for p in placements.teams}+ assert by_id["team-a"] is None+ assert by_id["team-b"] is True+++async def test_a_refused_organisation_token_fails_the_listing_and_stops_the_reads() -> (+ None+):+ adapter = _shared_adapter()+ started: list[str] = []+ finished: list[str] = []++ class _Refused(_PlacementGraph):+ async def list_teams(self) -> list[dict[str, Any]]:+ return [{"id": f"team-{n}", "displayName": str(n)} for n in range(20)]++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ started.append(team_id)+ if team_id == "team-0":+ raise TokenRequestRefused(+ "AADSTS7000112: disabled", error_codes=frozenset({7000112})+ )+ await asyncio.sleep(0.5)+ finished.append(team_id)+ return []++ adapter._graph = _Refused() # type: ignore[assignment]++ with pytest.raises(TokenRequestRefused):+ await adapter.list_team_placements()++ await asyncio.sleep(0.6)+ assert finished == []+++async def test_one_subscription_that_cannot_be_deleted_does_not_keep_the_rest() -> None:+ adapter = _shared_adapter()+ url = adapter._me.notification_url++ class _OneStuck(_WithdrawGraph):+ async def delete_subscription(self, *, subscription_id: str) -> None:+ if subscription_id == "SUB-A":+ raise GraphError("delete failed (503)", status=503)+ await super().delete_subscription(subscription_id=subscription_id)++ graph = _OneStuck(+ listed=[+ {"id": "SUB-A", "notificationUrl": url},+ {"id": "SUB-B", "notificationUrl": url},+ ],+ installations=[],+ )+ adapter._graph = graph # type: ignore[assignment]++ with pytest.raises(BridgeOperationError, match="SUB-A"):+ await adapter.withdraw()++ assert graph.deleted == ["SUB-B"]diff --git a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.pyindex 6ed3b1a2d..d044c6858 100644--- a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py+++ b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py@@ -394,3 +394,37 @@ async def test_a_service_url_write_does_not_clobber_learned_channel_teams(assert bridge.connection_config["channel_teams"] == {"19:[email protected]": "team-1"}+++async def test_an_edit_merges_into_what_the_bridge_learned_since_it_was_read(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """An edit's session reads the bridge, waits on the platform, then writes;+ what the running bridge persisted in between must survive the write."""+ store = CollaborationBridgeStore()+ async with session_factory() as session:+ bridge_id = await _make_bridge(session)+ await session.commit()++ async with session_factory() as editing:+ held = await store.get(editing, bridge_id)+ assert held is not None+ assert "channel_teams" not in (held.connection_config or {})++ async with session_factory() as learning:+ await store.set_channel_team(+ learning, bridge_id, "19:[email protected]", "team-1"+ )+ await learning.commit()++ await store.merge_connection_config(editing, bridge_id, {"team_id": "team-9"})+ await editing.commit()++ async with session_factory() as session:+ bridge = await store.get(session, bridge_id)+ assert bridge is not None+ assert bridge.connection_config["team_id"] == "team-9"+ assert bridge.connection_config["channel_teams"] == {+ "19:[email protected]": "team-1"+ }diff --git a/core/tests/switch_core/db/stores/test_messaging_install_store.py b/core/tests/switch_core/db/stores/test_messaging_install_store.pyindex 1d37a378b..40671b86f 100644--- a/core/tests/switch_core/db/stores/test_messaging_install_store.py+++ b/core/tests/switch_core/db/stores/test_messaging_install_store.py@@ -19,6 +19,7 @@ from sqlalchemy.ext.asyncio import async_sessionmakerfrom switch_core.db.models import Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.messaging_install_store import (+ INSTALL_DISCONNECTED,MessagingInstallClaimedError,MessagingInstallStateError,MessagingInstallStore,@@ -226,6 +227,7 @@ class TestRecordingAnInstall:external_workspace_id=fixture.workspace,encrypted_bot_token="ciphertext",scopes="chat:write",+ platform_data={},user_id=fixture.user_id,)await session.commit()@@ -238,6 +240,7 @@ class TestRecordingAnInstall:external_workspace_id=fixture.workspace,encrypted_bot_token="ciphertext",scopes="chat:write",+ platform_data={},user_id=fixture.user_id,)@@ -254,6 +257,7 @@ class TestRecordingAnInstall:external_workspace_id=fixture.workspace,encrypted_bot_token="ciphertext",scopes="chat:write",+ platform_data={},user_id=fixture.user_id,)await session.commit()@@ -286,6 +290,7 @@ class TestRecordingAnInstall:external_workspace_id=fixture.workspace,encrypted_bot_token=None,scopes="bot applications.commands",+ platform_data={},user_id=fixture.user_id,)assert recorded.encrypted_bot_token is None@@ -297,3 +302,69 @@ class TestRecordingAnInstall:)assert mine is not Noneassert mine.encrypted_bot_token is None+++class TestRefreshingALiveInstall:+ """What a repeated approval of a still-serving install (CHOO-3017's+ "approving again") records."""++ async def test_scopes_are_replaced_and_platform_data_is_merged_over(+ self, rls_harness: RLSHarness+ ) -> None:+ fixture = await _two_tenants(rls_harness.owner)+ store = MessagingInstallStore()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ recorded = await store.record_install(+ session,+ platform="teams",+ external_workspace_id=fixture.workspace,+ encrypted_bot_token=None,+ scopes="a b",+ platform_data={"kept": "yes", "catalog_app_id": "old"},+ user_id=fixture.user_id,+ )+ install_id = recorded.id+ await session.commit()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ refreshed = await store.refresh(+ session,+ install_id=install_id,+ scopes="a b c",+ platform_data={"catalog_app_id": "new"},+ )++ assert refreshed.scopes == "a b c"+ assert refreshed.platform_data == {+ "kept": "yes",+ "catalog_app_id": "new",+ }++ async def test_an_install_that_has_ended_cannot_be_refreshed(+ self, rls_harness: RLSHarness+ ) -> None:+ """Approving again is for the install still serving the workspace — one+ that has ended needs a fresh install, not a patch to a dead row."""+ fixture = await _two_tenants(rls_harness.owner)+ store = MessagingInstallStore()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ recorded = await store.record_install(+ session,+ platform="teams",+ external_workspace_id=fixture.workspace,+ encrypted_bot_token=None,+ scopes="a",+ platform_data={},+ user_id=fixture.user_id,+ )+ install_id = recorded.id+ recorded.status = INSTALL_DISCONNECTED+ await session.commit()++ async with tenant_session(rls_harness.restricted, fixture.tenant_a) as session:+ with pytest.raises(MessagingInstallStateError, match="ended"):+ await store.refresh(+ session, install_id=install_id, scopes="a b", platform_data={}+ )diff --git a/core/tests/switch_core/gateway/test_app_route_mounting.py b/core/tests/switch_core/gateway/test_app_route_mounting.pynew file mode 100644index 000000000..5e173b092--- /dev/null+++ b/core/tests/switch_core/gateway/test_app_route_mounting.py@@ -0,0 +1,64 @@+"""The gateway app is the one place every router is wired together.++A router that is built and tested on its own (`teams_placements.router`, say)+still has to actually be mounted for a request to reach it. This is the one+place that checks the mounting itself rather than the handlers behind it.+"""++from __future__ import annotations++from unittest.mock import MagicMock++from switch_core.gateway.app import create_gateway_app+from tests.switch_core.test_config_teams_app import _config+++def _app() -> object:+ # A real config rather than a mock: the app reads whatever settings it+ # needs, and a mock answers every one with a truthy stand-in.+ config = _config()+ return create_gateway_app(+ agent_store=MagicMock(),+ room_store=MagicMock(),+ room_group_store=MagicMock(),+ room_service=MagicMock(),+ bridge_store=MagicMock(),+ client_lifecycle=MagicMock(),+ collab_lifecycle=MagicMock(),+ connector_lifecycle=MagicMock(),+ connector_store=MagicMock(),+ event_buffer=MagicMock(),+ session_factory=MagicMock(),+ user_store=MagicMock(),+ external_user_store=MagicMock(),+ api_key_store=MagicMock(),+ invitation_store=MagicMock(),+ join_domain_store=MagicMock(),+ template_store=MagicMock(),+ usage_store=MagicMock(),+ budget_store=MagicMock(),+ resource_service=MagicMock(),+ protocol=MagicMock(),+ install_service=None,+ invite_mailer=None,+ config=config,+ )+++def test_the_teams_placement_routes_are_mounted_under_gateway_collaborations() -> None:+ app = _app()+ paths = {route.path for route in app.routes} # type: ignore[attr-defined]++ assert "/collaborations/{bridge_id}/teams" in paths+ assert "/collaborations/{bridge_id}/teams/{team_id}" in paths+ assert "/collaborations/{bridge_id}/teams-package" in paths+++def test_it_shares_the_prefix_with_the_ordinary_collaborations_routes() -> None:+ """Both routers answer under the same `/collaborations` prefix a bridge id+ is already namespaced under, rather than a prefix of their own."""+ app = _app()+ paths = {route.path for route in app.routes} # type: ignore[attr-defined]++ assert "/collaborations/{bridge_id}" in paths # the ordinary update route+ assert "/collaborations/{bridge_id}/teams" in paths # the placement routediff --git a/core/tests/switch_core/gateway/test_collaborations_bridge_detail.py b/core/tests/switch_core/gateway/test_collaborations_bridge_detail.pynew file mode 100644index 000000000..3a02eb2c8--- /dev/null+++ b/core/tests/switch_core/gateway/test_collaborations_bridge_detail.py@@ -0,0 +1,45 @@+"""Reading a bridge's attention note from its live adapter.++`_attention` is asked for every bridge listed on the connections page; one+adapter whose `attention()` raises must not take the whole list down with it —+it is worth a warning in the log and a connection whose attention is simply+unknown, same as a stopped bridge's.+"""++from __future__ import annotations++import logging++import pytest++from switch_core.gateway.collaborations import _attention+++class _RaisingAdapter:+ async def attention(self) -> str | None:+ raise RuntimeError("Microsoft is unreachable")+++class _Lifecycle:+ def __init__(self, adapter: object | None) -> None:+ self._adapter = adapter++ def get_adapter(self, bridge_id: str) -> object | None:+ return self._adapter+++async def test_a_raising_adapter_is_logged_and_reported_as_unknown(+ caplog: pytest.LogCaptureFixture,+) -> None:+ with caplog.at_level(logging.WARNING):+ note = await _attention("bridge-1", _Lifecycle(_RaisingAdapter())) # type: ignore[arg-type]++ assert note is None+ assert any(+ "Failed to read the attention note for bridge bridge-1" in r.message+ for r in caplog.records+ )+++async def test_a_stopped_bridge_has_no_attention_note() -> None:+ assert await _attention("bridge-1", _Lifecycle(None)) is None # type: ignore[arg-type]diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.pyindex b95037ba8..afac26745 100644--- a/core/tests/switch_core/gateway/test_held_connections.py+++ b/core/tests/switch_core/gateway/test_held_connections.py@@ -138,6 +138,11 @@ class _Adapter:async def install_note(self) -> str | None:return None+ places_app_in_teams = False++ async def attention(self) -> str | None:+ return None+async def channel_deeplink(self, external_channel_id: str) -> str | None:self._calls.record("platform channel deeplink")return None@@ -171,6 +176,14 @@ class _CollabLifecycle:async def check_start_guards(self, **_: Any) -> None:self._calls.record("start guards")+ def editable_config_keys(+ self, bridge_type: str, connection_config: dict[str, object]+ ) -> frozenset[str] | None:+ return None++ async def check_config_edit(self, **_: Any) -> None:+ self._calls.record("platform edit check")+async def restart(self, bridge_id: str) -> None:self._calls.record("bridge restart")@@ -553,6 +566,7 @@ class TestBridgeRoutes:assert [what for what, _ in calls.held] == ["platform credential check","start guards",+ "platform edit check","bridge restart","platform directory search","platform directory search",diff --git a/core/tests/switch_core/gateway/test_shared_bridge_registration.py b/core/tests/switch_core/gateway/test_shared_bridge_registration.pyindex 82b2453a1..f14d7c8aa 100644--- a/core/tests/switch_core/gateway/test_shared_bridge_registration.py+++ b/core/tests/switch_core/gateway/test_shared_bridge_registration.py@@ -16,8 +16,13 @@ import pytestfrom fastapi import HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.collaboration.adapter import ConfigEditRefusedfrom switch_core.bridges.collaboration.lifecycle_service import BridgeClaimConflict-from switch_core.bridges.collaboration.models import BridgeStartRefused+from switch_core.bridges.collaboration.models import (+ BridgeNotRunning,+ BridgeOperationError,+ BridgeStartRefused,+)from switch_core.db.models import Client, CollaborationBridge, Userfrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStore@@ -30,11 +35,37 @@ _BRIDGE_STORE = CollaborationBridgeStore()class _Lifecycle:"""Records what reached it; refuses any start when told to."""- def __init__(self, *, refuse: bool = False, claimed: bool = False) -> None:+ def __init__(+ self,+ *,+ refuse: bool = False,+ claimed: bool = False,+ editable: frozenset[str] | None = None,+ edit_refusal: Exception | None = None,+ ) -> None:self.refuse = refuseself.claimed = claimed+ self.editable = editable+ self.edit_refusal = edit_refusal+ self.channel_creation = Falseself.registered: list[dict[str, object]] = []self.checked: list[dict[str, Any]] = []+ self.edits_checked: list[dict[str, Any]] = []+ self.restarted: list[str] = []++ def editable_config_keys(+ self, bridge_type: str, connection_config: dict[str, object]+ ) -> frozenset[str] | None:+ return self.editable++ async def restart(self, bridge_id: str) -> None:+ self.restarted.append(bridge_id)++ def get_adapter(self, bridge_id: str) -> None:+ return None++ def supports_directory_search(self, bridge_type: str) -> bool:+ return Falseasync def register(self, **kwargs: object) -> None:self.registered.append(kwargs)@@ -44,19 +75,29 @@ class _Lifecycle:raise BridgeClaimConflict("Discord server 999 is already claimed")def supports_channel_creation(self, bridge_type: str) -> bool:- return False+ return self.channel_creationasync def check_start_guards(self, **kwargs: Any) -> None:self.checked.append(kwargs)if self.refuse:raise BridgeStartRefused("not installed for this tenant")+ async def check_config_edit(self, **kwargs: Any) -> None:+ self.edits_checked.append(kwargs)+ if self.edit_refusal is not None:+ raise self.edit_refusal+def _admin() -> User:return User(id="admin", name="admin", email="[email protected]", role="admin")-async def _shared_bridge(session: AsyncSession) -> str:+async def _shared_bridge(+ session: AsyncSession,+ *,+ bridge_type: str = "discord",+ connection_config: dict[str, object] | None = None,+) -> str:client = Client(transport_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",display_name="bridge client",@@ -65,11 +106,12 @@ async def _shared_bridge(session: AsyncSession) -> str:session.add(client)await session.flush()bridge = CollaborationBridge(- type="discord",+ type=bridge_type,display_name="Acme",client_id=client.id,status="active",- connection_config={"guild_id": "111", "event_delivery": "shared"},+ connection_config=connection_config+ or {"guild_id": "111", "event_delivery": "shared"},)session.add(bridge)await session.flush()@@ -175,3 +217,196 @@ async def test_an_edit_cannot_claim_a_workspace_another_bridge_holds(assert refused.status_code == 400assert "already claimed" in str(refused.detail)assert (await _stored_config(session_factory, bridge_id))["guild_id"] == "111"+++_TEAMS_SHARED = {+ "event_delivery": "shared",+ "tenant_id": "org-1",+ "service_url": "https://smba.trafficmanager.net/amer/",+}+++async def test_settings_switch_manages_cannot_be_edited(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """A shared Teams bridge's learned service URL decides where the+ deployment's Bot Connector token is sent; edited, it would send it to+ whoever the editor chose."""+ async with session_factory() as session:+ bridge_id = await _shared_bridge(+ session, bridge_type="teams", connection_config=dict(_TEAMS_SHARED)+ )+ await session.commit()+ lifecycle = _Lifecycle(editable=frozenset({"team_id"}))++ refused = await _update(+ session_factory,+ bridge_id,+ lifecycle,+ {"service_url": "https://attacker.example/"},+ )++ assert refused.status_code == 422+ assert "service_url" in str(refused.detail)+ assert (await _stored_config(session_factory, bridge_id))["service_url"] == (+ _TEAMS_SHARED["service_url"]+ )+++async def test_an_editable_setting_and_unchanged_ones_go_through(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Sending back a setting unchanged, as a form that posts the whole config+ does, is not an edit to it."""+ async with session_factory() as session:+ bridge_id = await _shared_bridge(+ session, bridge_type="teams", connection_config=dict(_TEAMS_SHARED)+ )+ await session.commit()+ lifecycle = _Lifecycle(editable=frozenset({"team_id"}))++ async with session_factory() as session:+ await update_bridge(+ bridge_id=bridge_id,+ payload=BridgeUpdateRequest(+ connection_config={"team_id": "team-9", "tenant_id": "org-1"}+ ),+ session=session,+ bridge_store=_BRIDGE_STORE,+ room_store=RoomStore(),+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ user=_admin(),+ )++ assert (await _stored_config(session_factory, bridge_id))["team_id"] == "team-9"+ assert lifecycle.restarted == [bridge_id]+++async def test_the_running_bridge_is_asked_about_the_edit_as_it_would_be(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ bridge_id = await _shared_bridge(+ session, bridge_type="teams", connection_config=dict(_TEAMS_SHARED)+ )+ await session.commit()+ lifecycle = _Lifecycle(editable=frozenset({"team_id"}))++ async with session_factory() as session:+ await update_bridge(+ bridge_id=bridge_id,+ payload=BridgeUpdateRequest(connection_config={"team_id": "team-9"}),+ session=session,+ bridge_store=_BRIDGE_STORE,+ room_store=RoomStore(),+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ user=_admin(),+ )++ [checked] = lifecycle.edits_checked+ assert checked["bridge_id"] == bridge_id+ assert checked["current"] == _TEAMS_SHARED+ assert checked["connection_config"] == {**_TEAMS_SHARED, "team_id": "team-9"}+++ ("refusal", "status"),+ [+ (ConfigEditRefused("Switch is not in that team."), 422),+ (BridgeNotRunning("The connection is not running."), 503),+ (BridgeOperationError("Microsoft could not be asked."), 502),+ ],+)+async def test_an_edit_the_platform_refuses_is_not_stored(+ session_factory: async_sessionmaker[AsyncSession],+ refusal: Exception,+ status: int,+) -> None:+ """A default team Switch is not in would fail at the first new channel,+ long after the edit; refused here, nothing is stored or restarted."""+ async with session_factory() as session:+ bridge_id = await _shared_bridge(+ session, bridge_type="teams", connection_config=dict(_TEAMS_SHARED)+ )+ await session.commit()+ lifecycle = _Lifecycle(editable=frozenset({"team_id"}), edit_refusal=refusal)++ refused = await _update(+ session_factory, bridge_id, lifecycle, {"team_id": "team-9"}+ )++ assert refused.status_code == status+ assert str(refusal) in str(refused.detail)+ assert "team_id" not in await _stored_config(session_factory, bridge_id)+ assert lifecycle.restarted == []+++async def test_a_refused_edit_stores_none_of_the_rest_of_the_request(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Every check runs before any write, so a refused connection edit leaves+ the request's other changes unmade too — and no write holds the bridge's+ row locked while the platform is asked."""+ async with session_factory() as session:+ bridge_id = await _shared_bridge(+ session, bridge_type="teams", connection_config=dict(_TEAMS_SHARED)+ )+ await session.commit()+ lifecycle = _Lifecycle(+ editable=frozenset({"team_id"}),+ edit_refusal=ConfigEditRefused("Switch is not in that team."),+ )++ async with session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await update_bridge(+ bridge_id=bridge_id,+ payload=BridgeUpdateRequest(+ agent_greetings_enabled=False,+ connection_config={"team_id": "team-9"},+ ),+ session=session,+ bridge_store=_BRIDGE_STORE,+ room_store=RoomStore(),+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ user=_admin(),+ )++ assert refused.value.status_code == 422+ async with session_factory() as session:+ bridge = await _BRIDGE_STORE.get(session, bridge_id)+ assert bridge is not None+ assert bridge.agent_greetings_enabled is True+++async def test_choosing_a_default_team_turns_channel_creation_on(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """What the Teams panel sends: the default team and channel creation in+ one request, both stored once the team checks out."""+ async with session_factory() as session:+ bridge_id = await _shared_bridge(+ session, bridge_type="teams", connection_config=dict(_TEAMS_SHARED)+ )+ await session.commit()+ lifecycle = _Lifecycle(editable=frozenset({"team_id"}))+ lifecycle.channel_creation = True++ async with session_factory() as session:+ await update_bridge(+ bridge_id=bridge_id,+ payload=BridgeUpdateRequest(+ channel_creation_enabled=True, connection_config={"team_id": "team-9"}+ ),+ session=session,+ bridge_store=_BRIDGE_STORE,+ room_store=RoomStore(),+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ user=_admin(),+ )++ async with session_factory() as session:+ bridge = await _BRIDGE_STORE.get(session, bridge_id)+ assert bridge is not None+ assert bridge.channel_creation_enabled is True+ assert bridge.connection_config["team_id"] == "team-9"diff --git a/core/tests/switch_core/gateway/test_teams_placements.py b/core/tests/switch_core/gateway/test_teams_placements.pynew file mode 100644index 000000000..36414030d--- /dev/null+++ b/core/tests/switch_core/gateway/test_teams_placements.py@@ -0,0 +1,530 @@+"""Choosing which teams the distributed Teams app is in, from the dashboard."""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from fastapi import HTTPException+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.collaboration.install import MessagingInstallError+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)+from switch_core.bridges.collaboration.teams.app_package import (+ build_distributed_app_package,+)+from switch_core.bridges.collaboration.teams.auth import TokenRequestRefused+from switch_core.bridges.collaboration.teams.graph import AppInstallation+from switch_core.bridges.collaboration.teams.identity import TeamsIdentity+from switch_core.bridges.collaboration.teams.install import TeamsAppInstaller+from switch_core.db.models import Client, CollaborationBridge, MessagingInstall, User+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.messaging_install_store import MessagingInstallStore+from switch_core.gateway.auth import require_tenant_admin+from switch_core.gateway.teams_placements import (+ add_to_team,+ download_app_package,+ list_team_placements,+ remove_from_team,+ router,+)++ORG = "aaaaaaaa-0000-0000-0000-000000000001"+++class _Graph:+ def __init__(self, *, installed_in: dict[str, str] | None = None) -> None:+ self.added: list[tuple[str, str]] = []+ self.removed: list[tuple[str, str]] = []+ # team id -> the catalogue id its installation reports+ self.installed_in = installed_in or {}+ self.fail_with: Exception | None = None++ async def list_teams(self) -> list[dict[str, Any]]:+ if self.fail_with is not None:+ raise self.fail_with+ return [+ {"id": "team-1", "displayName": "Engineering"},+ {"id": "team-2", "displayName": "Sales"},+ ]++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ if team_id in self.installed_in:+ return [+ AppInstallation(+ installation_id=f"I-{team_id}",+ catalog_app_id=self.installed_in[team_id],+ )+ ]+ return []++ async def install_app(self, *, team_id: str, catalog_app_id: str) -> None:+ self.added.append((team_id, catalog_app_id))++ async def uninstall_app(self, *, team_id: str, installation_id: str) -> None:+ self.removed.append((team_id, installation_id))+++class _Lifecycle:+ def __init__(self, adapter: TeamsAdapter | None, *, connected: bool = True) -> None:+ self._adapter = adapter+ self._connected = connected+ self.restarted: list[str] = []+ self.restart_failure: Exception | None = None++ def get_adapter(self, bridge_id: str) -> TeamsAdapter | None:+ return self._adapter++ def is_connected(self, bridge_id: str) -> bool:+ return self._adapter is not None and self._connected++ async def restart(self, bridge_id: str) -> None:+ self.restarted.append(bridge_id)+ if self.restart_failure is not None:+ raise self.restart_failure+++class _InstallService:+ def __init__(self, installer: object | None) -> None:+ self._installer = installer++ def installer(self, platform: str) -> object:+ if self._installer is None:+ raise MessagingInstallError(f"no installer for {platform}")+ return self._installer+++def _shared_adapter(graph: _Graph) -> TeamsAdapter:+ adapter = TeamsAdapter(+ config=TeamsConnectionConfig.model_validate(+ {"event_delivery": "shared", "tenant_id": ORG, "team_id": "team-1"}+ )+ )+ adapter._identity = _identity()+ adapter._graph = graph # type: ignore[assignment]+ return adapter+++def _identity() -> TeamsIdentity:+ return TeamsIdentity(+ app_id="switch-app",+ org_tenant_id=ORG,+ shared=True,+ notification_url="https://switch.example/messaging/teams/notifications",+ client_state="x",+ keyring=None,+ allowed_service_hosts=frozenset({"smba.trafficmanager.net"}),+ required_graph_roles=frozenset(),+ )+++def _admin() -> User:+ return User(id="admin", name="admin", email="[email protected]", role="admin")+++async def _connection(+ session: AsyncSession, *, platform_data: dict[str, object]+) -> str:+ user = User(name="installer", email=f"{uuid.uuid4().hex}@example.test", role="user")+ session.add(user)+ 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="teams",+ display_name="Contoso",+ client_id=client.id,+ status="active",+ connection_config={"event_delivery": "shared", "tenant_id": ORG},+ )+ session.add(bridge)+ await session.flush()+ session.add(+ MessagingInstall(+ platform="teams",+ external_workspace_id=ORG,+ encrypted_bot_token=None,+ scopes="",+ status="active",+ installed_by_user_id=user.id,+ bridge_id=bridge.id,+ platform_data=platform_data,+ )+ )+ await session.flush()+ return bridge.id+++async def _call(+ route: Any, session: AsyncSession, lifecycle: _Lifecycle, **kwargs: Any+) -> Any:+ return await route(+ session=session,+ bridge_store=CollaborationBridgeStore(),+ install_store=MessagingInstallStore(),+ collab_lifecycle=lifecycle, # type: ignore[arg-type]+ _user=_admin(),+ **kwargs,+ )+++async def test_the_teams_are_listed_with_the_default_marked(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ graph = _Graph()+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})++ placements = await _call(+ list_team_placements,+ session,+ _Lifecycle(_shared_adapter(graph)),+ bridge_id=bridge_id,+ )++ assert [(t.name, t.has_switch, t.is_default) for t in placements.teams] == [+ ("Engineering", False, True),+ ("Sales", False, False),+ ]+ assert placements.in_catalog+ assert placements.catalog_problem is None+++async def test_switch_is_added_to_a_team_from_the_catalogue(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ graph = _Graph()+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})++ await _call(+ add_to_team,+ session,+ _Lifecycle(_shared_adapter(graph)),+ bridge_id=bridge_id,+ team_id="team-1",+ )++ assert graph.added == [("team-1", "c-1")]+++async def test_without_the_app_in_the_catalogue_it_says_what_to_do(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ graph = _Graph()+ async with session_factory() as session:+ bridge_id = await _connection(+ session,+ platform_data={+ "catalog_app_id": None,+ "publish_problem": "not a Teams admin",+ },+ )+ lifecycle = _Lifecycle(_shared_adapter(graph))++ placements = await _call(+ list_team_placements, session, lifecycle, bridge_id=bridge_id+ )+ with pytest.raises(HTTPException) as refused:+ await _call(+ add_to_team, session, lifecycle, bridge_id=bridge_id, team_id="team-1"+ )++ assert not placements.in_catalog+ assert placements.catalog_problem == "not a Teams admin"+ assert refused.value.status_code == 409+ assert graph.added == []+++async def test_a_bridge_with_no_install_is_not_found(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await _call(+ remove_from_team,+ session,+ _Lifecycle(None),+ bridge_id="no-such-bridge",+ team_id="team-1",+ )++ assert refused.value.status_code == 404+++async def test_an_app_uploaded_by_hand_is_learned_from_the_first_team_it_is_in(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Switch could not publish the app, a Teams admin uploaded it, and a team+ owner added it to one team from Teams: that installation reports the id,+ and from then on Switch adds it to the rest."""+ graph = _Graph(installed_in={"team-2": "uploaded-by-hand"})+ async with session_factory() as session:+ bridge_id = await _connection(+ session,+ platform_data={"publish_problem": "not a Teams admin"},+ )+ lifecycle = _Lifecycle(_shared_adapter(graph))++ await _call(+ add_to_team, session, lifecycle, bridge_id=bridge_id, team_id="team-1"+ )+ install = await MessagingInstallStore().get_for_bridge(+ session, bridge_id=bridge_id+ )+ placements = await _call(+ list_team_placements, session, lifecycle, bridge_id=bridge_id+ )++ assert graph.added == [("team-1", "uploaded-by-hand")]+ assert install is not None+ assert install.platform_data["catalog_app_id"] == "uploaded-by-hand"+ assert placements.in_catalog+ assert placements.catalog_problem is None+++async def test_an_organisation_that_withdrew_its_approval_is_told_so_not_a_500(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ graph = _Graph()+ graph.fail_with = TokenRequestRefused(+ "AADSTS700016: application not found", error_codes=frozenset({700016})+ )+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})++ with pytest.raises(HTTPException) as refused:+ await _call(+ list_team_placements,+ session,+ _Lifecycle(_shared_adapter(graph)),+ bridge_id=bridge_id,+ )++ assert refused.value.status_code == 502+ assert "AADSTS700016" in str(refused.value.detail)+++def _dependency_calls(dependant: Any) -> list[object]:+ calls = [dependant.call]+ for sub in dependant.dependencies:+ calls.extend(_dependency_calls(sub))+ return calls+++def test_every_route_requires_a_workspace_admin() -> None:+ """Listing an organisation's teams, changing which Switch is in, and the+ app package are all workspace administration, reads included. Derived from+ the router, so a route added without the gate fails here."""+ ungated = sorted(+ f"{sorted(route.methods)} {route.path}"+ for route in router.routes+ if require_tenant_admin not in _dependency_calls(route.dependant) # type: ignore[attr-defined]+ )+ assert router.routes+ assert not ungated, (+ f"Teams placement routes missing require_tenant_admin: {ungated}"+ )+++async def test_removing_switch_from_the_default_team_turns_channel_creation_off(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """New channels are made in the default team, and cannot be in a team the+ app has left; the default goes with it rather than failing at the next+ room."""+ graph = _Graph(installed_in={"team-1": "c-1"})+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})+ await CollaborationBridgeStore().merge_connection_config(+ session, bridge_id, {"team_id": "team-1"}+ )+ await CollaborationBridgeStore().set_channel_creation_enabled(+ session, bridge_id, True+ )+ await session.commit()+ lifecycle = _Lifecycle(_shared_adapter(graph))++ await _call(+ remove_from_team, session, lifecycle, bridge_id=bridge_id, team_id="team-1"+ )++ async with session_factory() as session:+ bridge = await CollaborationBridgeStore().get(session, bridge_id)+ assert graph.removed == [("team-1", "I-team-1")]+ assert bridge is not None+ assert bridge.connection_config["team_id"] is None+ assert bridge.channel_creation_enabled is False+ assert lifecycle.restarted == [bridge_id]+++async def test_a_connection_that_does_not_restart_after_leaving_says_what_happened(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ graph = _Graph(installed_in={"team-1": "c-1"})+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})+ await CollaborationBridgeStore().merge_connection_config(+ session, bridge_id, {"team_id": "team-1"}+ )+ await session.commit()+ lifecycle = _Lifecycle(_shared_adapter(graph))+ lifecycle.restart_failure = RuntimeError("start guard refused")++ with pytest.raises(HTTPException) as refused:+ await _call(+ remove_from_team,+ session,+ lifecycle,+ bridge_id=bridge_id,+ team_id="team-1",+ )++ assert refused.value.status_code == 503+ assert "Switch left the team" in str(refused.value.detail)+ assert "start guard refused" in str(refused.value.detail)+ assert graph.removed == [("team-1", "I-team-1")]+++async def test_removing_switch_from_another_team_leaves_the_default_alone(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ graph = _Graph(installed_in={"team-2": "c-1"})+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})+ await session.commit()+ lifecycle = _Lifecycle(_shared_adapter(graph))++ await _call(+ remove_from_team, session, lifecycle, bridge_id=bridge_id, team_id="team-2"+ )++ assert graph.removed == [("team-2", "I-team-2")]+ assert lifecycle.restarted == []+++async def test_a_stopped_connection_is_said_to_be_not_running(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})++ with pytest.raises(HTTPException) as refused:+ await _call(+ list_team_placements, session, _Lifecycle(None), bridge_id=bridge_id+ )++ assert refused.value.status_code == 503+++async def test_a_microsoft_refusal_while_adding_or_removing_is_a_502(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ class _Refusing(_Graph):+ async def install_app(self, *, team_id: str, catalog_app_id: str) -> None:+ raise TokenRequestRefused(+ "AADSTS7000112: application is disabled",+ error_codes=frozenset({7000112}),+ )++ async def find_app_installations(+ self, *, team_id: str, external_id: str+ ) -> list[AppInstallation]:+ raise TokenRequestRefused(+ "AADSTS7000112: application is disabled",+ error_codes=frozenset({7000112}),+ )++ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})+ lifecycle = _Lifecycle(_shared_adapter(_Refusing()))++ with pytest.raises(HTTPException) as adding:+ await _call(+ add_to_team, session, lifecycle, bridge_id=bridge_id, team_id="team-1"+ )+ with pytest.raises(HTTPException) as removing:+ await _call(+ remove_from_team,+ session,+ lifecycle,+ bridge_id=bridge_id,+ team_id="team-1",+ )++ assert adding.value.status_code == removing.value.status_code == 502+++async def test_the_app_package_is_downloaded_for_a_teams_admin(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ package = build_distributed_app_package(+ app_id="11111111-2222-3333-4444-555555555555",+ app_name="Agent Switch",+ messaging_public_url="https://switch.example",+ privacy_url="https://switch.example/privacy",+ terms_url="https://switch.example/terms",+ )+ installer = TeamsAppInstaller(app=object(), package=package) # type: ignore[arg-type]+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={})++ response = await _call(+ download_app_package,+ session,+ _Lifecycle(_shared_adapter(_Graph())),+ bridge_id=bridge_id,+ install_service=_InstallService(installer),+ )++ assert response.media_type == "application/zip"+ assert response.body == package.archive+ assert (+ f"switch-teams-{package.version}.zip" in response.headers["content-disposition"]+ )++[email protected]("install_service", [None, _InstallService(None)])+async def test_a_deployment_without_the_app_has_no_package(+ session_factory: async_sessionmaker[AsyncSession],+ install_service: _InstallService | None,+) -> None:+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={})++ with pytest.raises(HTTPException) as refused:+ await _call(+ download_app_package,+ session,+ _Lifecycle(_shared_adapter(_Graph())),+ bridge_id=bridge_id,+ install_service=install_service,+ )++ assert refused.value.status_code == 404+++async def test_a_connection_still_starting_is_said_to_be_not_running(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Making a team the default restarts the connection, and the panel reloads+ at once; a bridge registered but not yet started has no Graph client, and+ the answer is 'try again', not a fault."""+ async with session_factory() as session:+ bridge_id = await _connection(session, platform_data={"catalog_app_id": "c-1"})+ starting = _Lifecycle(_shared_adapter(_Graph()), connected=False)++ with pytest.raises(HTTPException) as refused:+ await _call(list_team_placements, session, starting, bridge_id=bridge_id)++ assert refused.value.status_code == 503diff --git a/core/tests/switch_core/test_config_teams_app.py b/core/tests/switch_core/test_config_teams_app.pynew file mode 100644index 000000000..61f33493a--- /dev/null+++ b/core/tests/switch_core/test_config_teams_app.py@@ -0,0 +1,236 @@+"""Half-configuring the distributed Teams app has to be a startup error.++The app's id, its home directory, one credential and the notification keypair+are useless apart: without the directory no Bot Connector token can be issued,+without a credential nothing can be, and without the keypair Graph has nothing+to encrypt captured messages to. A deployment that sets some of them looks+configured and breaks, so it does not start.+"""++from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import ec, rsa+from cryptography.x509.oid import NameOID++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ id_server_name="switch.local",+ agent_registration_token="token",+ secret_keys="test:" + "x" * 40,+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)++_TENANT = "11111111-2222-3333-4444-555555555555"+++def _keypair() -> tuple[str, str]:+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "test")])+ now = datetime.now(UTC)+ certificate = (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now - timedelta(days=1))+ .not_valid_after(now + timedelta(days=1))+ .sign(key, hashes.SHA256())+ )+ return (+ certificate.public_bytes(serialization.Encoding.PEM).decode(),+ key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode(),+ )+++_NOTIFICATION_CERT, _NOTIFICATION_KEY = _keypair()+_CREDENTIAL_CERT, _CREDENTIAL_KEY = _keypair()++_APP = dict(+ teams_app_client_id="aaaaaaaa-0000-0000-0000-000000000001",+ teams_app_tenant_id=_TENANT,+ teams_app_client_secret="secret",+ teams_app_notification_certificate=_NOTIFICATION_CERT,+ teams_app_notification_private_key=_NOTIFICATION_KEY,+ teams_app_privacy_url="https://switch.example/privacy",+ teams_app_terms_url="https://switch.example/terms",+ messaging_public_url="https://switch.example",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++def _without(*names: str, **overrides: object) -> dict[str, object]:+ return {**{k: v for k, v in _APP.items() if k not in names}, **overrides}+++def test_setting_none_of_them_is_the_ordinary_case() -> None:+ assert _config().teams_app_client_id is None+++def test_a_complete_secret_configuration_is_accepted() -> None:+ assert _config(**_APP).teams_app_client_secret == "secret"+++def test_a_certificate_credential_is_accepted() -> None:+ config = _config(+ **_without(+ "teams_app_client_secret",+ teams_app_certificate=_CREDENTIAL_CERT,+ teams_app_certificate_private_key=_CREDENTIAL_KEY,+ )+ )+ assert config.teams_app_certificate == _CREDENTIAL_CERT+++def test_a_federated_token_file_is_accepted(tmp_path: Path) -> None:+ token = tmp_path / "token"+ token.write_text("eyJ...")+ config = _config(+ **_without("teams_app_client_secret", teams_app_federated_token_file=str(token))+ )+ assert config.teams_app_federated_token_file == str(token)+++ "missing",+ [+ "teams_app_client_id",+ "teams_app_tenant_id",+ "teams_app_notification_certificate",+ "teams_app_notification_private_key",+ "teams_app_privacy_url",+ "teams_app_terms_url",+ ],+)+def test_a_missing_required_setting_raises(missing: str) -> None:+ with pytest.raises(ValueError, match="Partial distributed Teams app config"):+ _config(**_without(missing))+++def test_no_credential_raises() -> None:+ with pytest.raises(ValueError, match="exactly one credential.*Got none"):+ _config(**_without("teams_app_client_secret"))+++def test_two_credentials_raise() -> None:+ """Which one would be used is a guess, and the unused one is a secret+ deployed for nothing."""+ with pytest.raises(ValueError, match="exactly one credential"):+ _config(+ **_APP,+ teams_app_certificate=_CREDENTIAL_CERT,+ teams_app_certificate_private_key=_CREDENTIAL_KEY,+ )+++def test_a_certificate_without_its_key_raises() -> None:+ with pytest.raises(ValueError, match="must be set together"):+ _config(+ **_without(+ "teams_app_client_secret", teams_app_certificate=_CREDENTIAL_CERT+ )+ )++[email protected]("tenant", ["common", "organizations", "contoso.com"])+def test_a_tenant_that_is_not_a_directory_id_raises(tenant: str) -> None:+ """A SingleTenant bot's tokens come from its own directory and nowhere else."""+ with pytest.raises(ValueError, match="TEAMS_APP_TENANT_ID"):+ _config(**_without(teams_app_tenant_id=tenant))+++def test_a_notification_key_that_is_not_the_certificates_raises() -> None:+ """Graph would encrypt every captured message to a key Switch does not hold."""+ _, other_key = _keypair()+ with pytest.raises(ValueError, match="are not a pair"):+ _config(**_without(teams_app_notification_private_key=other_key))+++def test_a_credential_key_that_is_not_the_certificates_raises() -> None:+ _, other_key = _keypair()+ with pytest.raises(ValueError, match="are not a pair"):+ _config(+ **_without(+ "teams_app_client_secret",+ teams_app_certificate=_CREDENTIAL_CERT,+ teams_app_certificate_private_key=other_key,+ )+ )+++def test_a_non_rsa_notification_key_raises() -> None:+ """Graph wraps each notification's key with RSA-OAEP and nothing else."""+ key = ec.generate_private_key(ec.SECP256R1())+ pem = key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ ).decode()+ with pytest.raises(ValueError, match="must be an RSA key"):+ _config(**_without(teams_app_notification_previous_private_key=pem))+++def test_a_garbled_key_names_its_setting() -> None:+ with pytest.raises(ValueError, match="TEAMS_APP_NOTIFICATION_PRIVATE_KEY"):+ _config(**_without(teams_app_notification_private_key="not a key"))+++def test_a_garbled_certificate_names_its_setting() -> None:+ with pytest.raises(ValueError, match="TEAMS_APP_NOTIFICATION_CERTIFICATE"):+ _config(**_without(teams_app_notification_certificate="not a certificate"))+++def test_a_missing_federated_token_file_raises(tmp_path: Path) -> None:+ with pytest.raises(ValueError, match="is not a file"):+ _config(+ **_without(+ "teams_app_client_secret",+ teams_app_federated_token_file=str(tmp_path / "absent"),+ )+ )+++def test_an_app_with_no_public_origin_raises() -> None:+ with pytest.raises(ValueError, match="MESSAGING_PUBLIC_URL"):+ _config(**_without("messaging_public_url"))+++def test_a_privacy_page_that_is_not_https_raises() -> None:+ with pytest.raises(ValueError, match="TEAMS_APP_PRIVACY_URL must be an https"):+ _config(**_without(teams_app_privacy_url="http://switch.example/privacy"))+++def test_the_app_is_called_agent_switch_unless_named() -> None:+ assert _config(**_APP).teams_app_name == "Agent Switch"+++def test_an_environment_can_name_its_app() -> None:+ config = _config(**_APP, teams_app_name="Agent Switch (dev)")+ assert config.teams_app_name == "Agent Switch (dev)"+++ "name",+ ["", " Agent Switch", "Agent Switch ", "A name far too long for a Teams app"],+)+def test_a_name_teams_would_refuse_is_refused_at_startup(name: str) -> None:+ with pytest.raises(ValueError, match="TEAMS_APP_NAME must be 1 to 30"):+ _config(**_APP, teams_app_name=name)diff --git a/core/tests/switch_core/test_main_teams_app.py b/core/tests/switch_core/test_main_teams_app.pynew file mode 100644index 000000000..26493ce78--- /dev/null+++ b/core/tests/switch_core/test_main_teams_app.py@@ -0,0 +1,133 @@+"""Turning the distributed Teams app on at startup, and off at shutdown."""++from __future__ import annotations++import io+import json+import zipfile+from collections.abc import Callable+from typing import Any++import pytest++from switch_core import main as main_module+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.install import MessagingInstallerRegistry+from switch_core.bridges.collaboration.teams.install import TeamsAppInstaller+from switch_core.bridges.collaboration.teams.shared_app import TeamsSharedApp+from switch_core.main import _distributed_teams_app, _shutdown+from tests.switch_core.test_config_teams_app import _APP, _config+++class _Lifecycle:+ def __init__(self, calls: list[str]) -> None:+ self.calls = calls+ self.starting_listeners: list[Callable[[PlatformAdapter], None]] = []++ def add_bridge_starting_listener(+ self, listener: Callable[[PlatformAdapter], None]+ ) -> None:+ self.starting_listeners.append(listener)++ async def stop_all(self) -> None:+ self.calls.append("bridges stopped")+++def test_a_deployment_without_the_app_offers_no_teams_install() -> None:+ installers = MessagingInstallerRegistry()+ lifecycle = _Lifecycle([])++ app = _distributed_teams_app(_config(), installers, lifecycle) # type: ignore[arg-type]++ assert app is None+ assert "teams" not in installers.platforms()+ assert lifecycle.starting_listeners == []+++async def test_a_configured_deployment_offers_the_install_and_hands_bridges_the_app() -> (+ None+):+ installers = MessagingInstallerRegistry()+ lifecycle = _Lifecycle([])++ app = _distributed_teams_app(_config(**_APP), installers, lifecycle) # type: ignore[arg-type]++ assert isinstance(app, TeamsSharedApp)+ installer = installers.get("teams")+ assert isinstance(installer, TeamsAppInstaller)+ assert installer.package.manifest_id == _APP["teams_app_client_id"]+ assert lifecycle.starting_listeners == [app.attach_if_teams]+ await app.aclose()+++async def test_the_apps_client_is_closed_only_after_the_bridges_stop(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Every bridge on the app borrows its HTTP client until it stops."""+ calls: list[str] = []++ class _Stoppable:+ def __init__(self, name: str) -> None:+ self._name = name++ async def stop_all(self) -> None:+ calls.append(f"{self._name} stopped")++ async def close(self) -> None:+ calls.append(f"{self._name} closed")++ class _TeamsApp:+ async def aclose(self) -> None:+ calls.append("teams app closed")++ class _Controllers:+ def begin_shutdown(self) -> None:+ calls.append("controllers told")++ class _Exited(Exception):+ pass++ def fake_exit(code: int) -> None:+ raise _Exited++ async def no_grace(seconds: float) -> None:+ return None++ monkeypatch.setattr(main_module.os, "_exit", fake_exit)+ monkeypatch.setattr(main_module.asyncio, "sleep", no_grace)+ server: Any = type("Server", (), {"should_exit": False})()++ with pytest.raises(_Exited):+ await _shutdown(+ server=server,+ controllers=_Controllers(), # type: ignore[arg-type]+ client_lifecycle=_Stoppable("clients"), # type: ignore[arg-type]+ collab_lifecycle=_Lifecycle(calls), # type: ignore[arg-type]+ connector_lifecycle=_Stoppable("connectors"), # type: ignore[arg-type]+ provisioning=_Stoppable("provisioning"), # type: ignore[arg-type]+ discord_gateway=None,+ discord_gateway_task=None,+ teams_app=_TeamsApp(), # type: ignore[arg-type]+ )++ assert calls.index("bridges stopped") < calls.index("teams app closed")+ assert server.should_exit is True+++async def test_the_package_carries_the_environments_app_name() -> None:+ installers = MessagingInstallerRegistry()++ app = _distributed_teams_app(+ _config(**_APP, teams_app_name="Agent Switch (dev)"),+ installers,+ _Lifecycle([]), # type: ignore[arg-type]+ )++ installer = installers.get("teams")+ assert isinstance(installer, TeamsAppInstaller)+ manifest = json.loads(+ zipfile.ZipFile(io.BytesIO(installer.package.archive)).read("manifest.json")+ )+ assert manifest["name"]["short"] == "Agent Switch (dev)"+ assert app is not None+ await app.aclose()diff --git a/core/uv.lock b/core/uv.lockindex 00b9f9be2..778b07b39 100644--- a/core/uv.lock+++ b/core/uv.lock@@ -2389,7 +2389,7 @@ requires-dist = [{ name = "mattermostdriver", specifier = ">=7.3.2" },{ name = "pydantic", specifier = ">=2,<3" },{ name = "pydantic-settings", specifier = ">=2.14.2,<3.0" },- { name = "pyjwt", specifier = ">=2.9,<3" },+ { name = "pyjwt", specifier = ">=2.14,<3" },{ name = "python-telegram-bot", specifier = ">=21,<22" },{ name = "pyyaml", specifier = ">=6,<7" },{ name = "slack-sdk", specifier = ">=3.41.0" },diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 3acfcd385..1d3ccb57c 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -236,6 +236,18 @@ services:DISCORD_APP_CLIENT_SECRET: ${DISCORD_APP_CLIENT_SECRET:-}DISCORD_APP_BOT_TOKEN: ${DISCORD_APP_BOT_TOKEN:-}DISCORD_APP_APPLICATION_ID: ${DISCORD_APP_APPLICATION_ID:-}+ TEAMS_APP_CLIENT_ID: ${TEAMS_APP_CLIENT_ID:-}+ TEAMS_APP_TENANT_ID: ${TEAMS_APP_TENANT_ID:-}+ TEAMS_APP_CLIENT_SECRET: ${TEAMS_APP_CLIENT_SECRET:-}+ TEAMS_APP_CERTIFICATE: ${TEAMS_APP_CERTIFICATE:-}+ TEAMS_APP_CERTIFICATE_PRIVATE_KEY: ${TEAMS_APP_CERTIFICATE_PRIVATE_KEY:-}+ TEAMS_APP_FEDERATED_TOKEN_FILE: ${TEAMS_APP_FEDERATED_TOKEN_FILE:-}+ TEAMS_APP_NOTIFICATION_CERTIFICATE: ${TEAMS_APP_NOTIFICATION_CERTIFICATE:-}+ TEAMS_APP_NOTIFICATION_PRIVATE_KEY: ${TEAMS_APP_NOTIFICATION_PRIVATE_KEY:-}+ TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY: ${TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY:-}+ TEAMS_APP_PRIVACY_URL: ${TEAMS_APP_PRIVACY_URL:-}+ TEAMS_APP_TERMS_URL: ${TEAMS_APP_TERMS_URL:-}+ TEAMS_APP_NAME: ${TEAMS_APP_NAME:-Agent Switch}# True/false flags, so bare keys for the reason given under LOG_FORMAT# below: `${VAR:-}` would hand them an empty string, which fails boot.DISCORD_APP_MESSAGE_CONTENT:diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex 5a9dd88ca..bbf76bacb 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -89,6 +89,20 @@ SLACK_APP_SIGNING_SECRET: {{ required "secrets.slackAppSigningSecret is requiredDISCORD_APP_CLIENT_SECRET: {{ required "secrets.discordAppClientSecret is required when switchCore.discordApp.enabled" .Values.secrets.discordAppClientSecret | b64enc | quote }}DISCORD_APP_BOT_TOKEN: {{ required "secrets.discordAppBotToken is required when switchCore.discordApp.enabled" .Values.secrets.discordAppBotToken | b64enc | quote }}{{- end }}+{{- if .Values.switchCore.teamsApp.enabled }}+{{- if eq .Values.switchCore.teamsApp.credential "secret" }}+TEAMS_APP_CLIENT_SECRET: {{ required "secrets.teamsAppClientSecret is required when switchCore.teamsApp.credential is secret" .Values.secrets.teamsAppClientSecret | b64enc | quote }}+{{- end }}+{{- if eq .Values.switchCore.teamsApp.credential "certificate" }}+TEAMS_APP_CERTIFICATE: {{ required "secrets.teamsAppCertificate is required when switchCore.teamsApp.credential is certificate" .Values.secrets.teamsAppCertificate | b64enc | quote }}+TEAMS_APP_CERTIFICATE_PRIVATE_KEY: {{ required "secrets.teamsAppCertificatePrivateKey is required when switchCore.teamsApp.credential is certificate" .Values.secrets.teamsAppCertificatePrivateKey | b64enc | quote }}+{{- end }}+TEAMS_APP_NOTIFICATION_CERTIFICATE: {{ required "secrets.teamsAppNotificationCertificate is required when switchCore.teamsApp.enabled" .Values.secrets.teamsAppNotificationCertificate | b64enc | quote }}+TEAMS_APP_NOTIFICATION_PRIVATE_KEY: {{ required "secrets.teamsAppNotificationPrivateKey is required when switchCore.teamsApp.enabled" .Values.secrets.teamsAppNotificationPrivateKey | b64enc | quote }}+{{- if .Values.secrets.teamsAppNotificationPreviousPrivateKey }}+TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY: {{ .Values.secrets.teamsAppNotificationPreviousPrivateKey | b64enc | quote }}+{{- end }}+{{- end }}{{- end }}{{/*@@ -813,9 +827,11 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}- name: GATEWAY_PUBLIC_URLvalue: {{ .Values.switchCore.gatewayPublicUrl | quote }}{{- end }}-{{- if .Values.switchCore.slackApp.enabled }}+{{- if or .Values.switchCore.slackApp.enabled .Values.switchCore.discordApp.enabled .Values.switchCore.teamsApp.enabled }}- name: MESSAGING_PUBLIC_URL- value: {{ required "switchCore.slackApp.messagingPublicUrl is required when switchCore.slackApp.enabled" .Values.switchCore.slackApp.messagingPublicUrl | quote }}+ value: {{ required "switchCore.messagingPublicUrl is required when a distributed messaging app is enabled" (include "switch.messagingPublicUrl" .) | quote }}+{{- end }}+{{- if .Values.switchCore.slackApp.enabled }}- name: SLACK_APP_CLIENT_IDvalue: {{ required "switchCore.slackApp.clientId is required when switchCore.slackApp.enabled" .Values.switchCore.slackApp.clientId | quote }}- name: SLACK_APP_CLIENT_SECRET@@ -830,10 +846,6 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}key: SLACK_APP_SIGNING_SECRET{{- end }}{{- if .Values.switchCore.discordApp.enabled }}-{{- if not .Values.switchCore.slackApp.enabled }}-- name: MESSAGING_PUBLIC_URL- value: {{ required "switchCore.discordApp.messagingPublicUrl is required when switchCore.discordApp.enabled" .Values.switchCore.discordApp.messagingPublicUrl | quote }}-{{- end }}- name: DISCORD_APP_CLIENT_IDvalue: {{ required "switchCore.discordApp.clientId is required when switchCore.discordApp.enabled" .Values.switchCore.discordApp.clientId | quote }}- name: DISCORD_APP_APPLICATION_ID@@ -857,6 +869,85 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}value: "true"{{- end }}{{- end }}+{{- if .Values.switchCore.teamsApp.enabled }}+- name: TEAMS_APP_CLIENT_ID+ value: {{ required "switchCore.teamsApp.clientId is required when switchCore.teamsApp.enabled" .Values.switchCore.teamsApp.clientId | quote }}+- name: TEAMS_APP_TENANT_ID+ value: {{ required "switchCore.teamsApp.tenantId is required when switchCore.teamsApp.enabled" .Values.switchCore.teamsApp.tenantId | quote }}+- name: TEAMS_APP_PRIVACY_URL+ value: {{ required "switchCore.teamsApp.privacyUrl is required when switchCore.teamsApp.enabled" .Values.switchCore.teamsApp.privacyUrl | quote }}+- name: TEAMS_APP_TERMS_URL+ value: {{ required "switchCore.teamsApp.termsUrl is required when switchCore.teamsApp.enabled" .Values.switchCore.teamsApp.termsUrl | quote }}+{{- with .Values.switchCore.teamsApp.name }}+- name: TEAMS_APP_NAME+ value: {{ . | quote }}+{{- end }}+{{- if eq .Values.switchCore.teamsApp.credential "secret" }}+- name: TEAMS_APP_CLIENT_SECRET+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TEAMS_APP_CLIENT_SECRET+{{- else if eq .Values.switchCore.teamsApp.credential "certificate" }}+- name: TEAMS_APP_CERTIFICATE+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TEAMS_APP_CERTIFICATE+- name: TEAMS_APP_CERTIFICATE_PRIVATE_KEY+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TEAMS_APP_CERTIFICATE_PRIVATE_KEY+{{- else if eq .Values.switchCore.teamsApp.credential "federated" }}+- name: TEAMS_APP_FEDERATED_TOKEN_FILE+ value: {{ include "switch.teamsAppTokenPath" . | quote }}+{{- else }}+{{- fail "switchCore.teamsApp.credential must be secret, certificate or federated" }}+{{- end }}+- name: TEAMS_APP_NOTIFICATION_CERTIFICATE+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TEAMS_APP_NOTIFICATION_CERTIFICATE+- name: TEAMS_APP_NOTIFICATION_PRIVATE_KEY+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TEAMS_APP_NOTIFICATION_PRIVATE_KEY+{{- if .Values.secrets.teamsAppNotificationPreviousPrivateKey }}+- name: TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY+ valueFrom:+ secretKeyRef:+ name: {{ include "switch.secretName" . }}+ key: TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY+{{- end }}+{{- end }}+{{- end }}++{{/*+The one public origin every distributed messaging app is reached on. Read+from switchCore.messagingPublicUrl, falling back to the per-app values earlier+releases took, so an existing Slack or Discord deployment keeps working.+*/}}+{{- define "switch.messagingPublicUrl" -}}+{{- coalesce .Values.switchCore.messagingPublicUrl .Values.switchCore.slackApp.messagingPublicUrl .Values.switchCore.discordApp.messagingPublicUrl | default "" -}}+{{- end }}++{{/*+Where the projected service-account token the distributed Teams app presents+to Microsoft (a federated credential, so no secret) is mounted.+*/}}+{{- define "switch.teamsAppTokenDir" -}}+/var/run/secrets/microsoft/teams-app+{{- end }}++{{- define "switch.teamsAppTokenPath" -}}+{{ include "switch.teamsAppTokenDir" . }}/token+{{- end }}++{{- define "switch.teamsAppFederated" -}}+{{- if and .Values.switchCore.teamsApp.enabled (eq .Values.switchCore.teamsApp.credential "federated") }}true{{- end }}{{- end }}{{/*diff --git a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml b/deploy/remote/helm/switch/templates/switch-core/deployment.yamlindex 1f16b0450..650281acd 100644--- a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/deployment.yaml@@ -107,7 +107,7 @@ spec:periodSeconds: 30resources:{{- toYaml .Values.switchCore.resources | nindent 12 }}- {{- if or (include "switch.dbCaBundleConfigMap" .) .Values.switchCore.githubConnectionsSecret .Values.switchCore.hostedControllerSecret }}+ {{- if or (include "switch.dbCaBundleConfigMap" .) .Values.switchCore.githubConnectionsSecret .Values.switchCore.hostedControllerSecret (include "switch.teamsAppFederated" .) }}volumeMounts:{{- if .Values.switchCore.hostedControllerSecret }}- name: hosted-controller@@ -122,8 +122,13 @@ spec:{{- if include "switch.dbCaBundleConfigMap" . }}{{- include "switch.dbCaBundleVolumeMount" . | nindent 12 }}{{- end }}+ {{- if include "switch.teamsAppFederated" . }}+ - name: teams-app-token+ mountPath: {{ include "switch.teamsAppTokenDir" . }}+ readOnly: true+ {{- end }}{{- end }}- {{- if or (include "switch.dbCaBundleConfigMap" .) .Values.switchCore.githubConnectionsSecret .Values.switchCore.hostedControllerSecret }}+ {{- if or (include "switch.dbCaBundleConfigMap" .) .Values.switchCore.githubConnectionsSecret .Values.switchCore.hostedControllerSecret (include "switch.teamsAppFederated" .) }}volumes:{{- if .Values.switchCore.hostedControllerSecret }}- name: hosted-controller@@ -140,4 +145,16 @@ spec:{{- if include "switch.dbCaBundleConfigMap" . }}{{- include "switch.dbCaBundleVolume" . | nindent 8 }}{{- end }}+ {{- if include "switch.teamsAppFederated" . }}+ # The token the distributed Teams app presents to Microsoft in place of+ # a secret. Its audience is the one Microsoft Entra expects of a+ # federated credential; the kubelet rotates it.+ - name: teams-app-token+ projected:+ sources:+ - serviceAccountToken:+ path: token+ audience: api://AzureADTokenExchange+ expirationSeconds: 3600+ {{- end }}{{- end }}diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 85e027875..f88ed9da2 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -151,6 +151,17 @@ secrets:# it lives here and is never stored against an install or revoked on disconnect.discordAppClientSecret: ""discordAppBotToken: ""+ # Distributed Teams app (when switchCore.teamsApp.enabled). One credential,+ # matching switchCore.teamsApp.credential: a client secret, or a certificate+ # and its private key; a federated credential needs neither. The+ # notification keypair (PEM) is what Graph encrypts captured messages to; the+ # previous private key is set only while rotating it.+ teamsAppClientSecret: ""+ teamsAppCertificate: ""+ teamsAppCertificatePrivateKey: ""+ teamsAppNotificationCertificate: ""+ teamsAppNotificationPrivateKey: ""+ teamsAppNotificationPreviousPrivateKey: ""# ── Switch Core (FastAPI) ─────────────────────────────────────────────────────switchCore:@@ -332,6 +343,12 @@ switchCore:# open anyone can own a workspace, so this keeps the relay from being used# to mail arbitrary addresses. Operators are exempt.emailsPerDayPerWorkspace: 50+ # Public origin every distributed messaging app (Slack, Discord, Teams) is+ # reached on — scheme + host, https, no path. Required when any of them is+ # enabled, and add /messaging to ingress.agentApiPaths as well. Earlier+ # releases took it per app (slackApp.messagingPublicUrl,+ # discordApp.messagingPublicUrl); those are still read when this is empty.+ messagingPublicUrl: ""# The distributed Slack app: the one a customer installs into their workspace# by clicking a button, as opposed to an app an operator registers themselves# and pastes a bot token for. Off unless you have registered such an app and@@ -374,6 +391,33 @@ switchCore:# mention-only operation; leave both false unless the app is verified.messageContent: falsemembers: false+ # The distributed Teams app (TEAMS_DISTRIBUTED_APP.md): one multi-tenant Entra+ # app backing a SingleTenant Azure Bot in your own directory, which a+ # customer's Microsoft admin approves for their organisation from Switch. Off+ # unless you have registered such an app for this environment — one app and+ # bot per environment, never shared. The bot's messaging endpoint and Graph's+ # notifications both arrive under /messaging at messagingPublicUrl.+ teamsApp:+ enabled: false+ # The app registration's Application (client) ID, and the id of the+ # directory it and the bot live in (never `common` or `organizations`).+ clientId: ""+ tenantId: ""+ # How the app proves who it is to Microsoft: secret+ # (secrets.teamsAppClientSecret), certificate+ # (secrets.teamsAppCertificate + secrets.teamsAppCertificatePrivateKey), or+ # federated — a projected service-account token the app registration+ # trusts as a federated credential, so no secret exists at all.+ credential: secret+ # Shown to the admin approving the app, and required in its package.+ privacyUrl: ""+ termsUrl: ""+ # The app's name in Teams, up to 30 characters; empty means "Agent+ # Switch". Name each non-production environment's app (for example+ # "Agent Switch (dev)"), so an organisation that approves more than one+ # can tell them apart. Set it before the first approval: Teams takes a+ # new name only with a newer app package.+ name: ""# Bearer-token resolution runs before every authenticated request and agents# beat continuously, so a successful resolution is memoised in process for# this many seconds. Only successes are cached — an unknown or revoked tokendiff --git a/docs/old/bridges/README.md b/docs/old/bridges/README.mdindex 065cfa026..63dd1e879 100644--- a/docs/old/bridges/README.md+++ b/docs/old/bridges/README.md@@ -24,6 +24,10 @@ supplies the credentials for. Slack additionally has a **distributed** app —one we register and a customer installs by clicking a button, receiving eventsover HTTPS rather than Socket Mode. It is a separate Slack app with differentrequirements: see [`SLACK_DISTRIBUTED_APP.md`](SLACK_DISTRIBUTED_APP.md).+Discord and Microsoft Teams have distributed apps too:+[`DISCORD_DISTRIBUTED_APP.md`](DISCORD_DISTRIBUTED_APP.md) and+[`TEAMS_DISTRIBUTED_APP.md`](TEAMS_DISTRIBUTED_APP.md), the second approved for+a whole organisation by its Microsoft admin.## The onboarding model (same for every bridge)diff --git a/docs/old/bridges/TEAMS_DISTRIBUTED_APP.md b/docs/old/bridges/TEAMS_DISTRIBUTED_APP.mdnew file mode 100644index 000000000..0112b4c53--- /dev/null+++ b/docs/old/bridges/TEAMS_DISTRIBUTED_APP.md@@ -0,0 +1,237 @@+# The distributed Teams app++`TEAMS_SETUP.md` describes the app **an operator registers for themselves**:+they create an Entra app and an Azure Bot in their own directory, grant it+permissions, upload an app package into their own Teams, and paste five values+into Switch. This page describes the other one — the app **we** register once+per environment, which a customer's Microsoft admin approves for their+organisation from Switch, and which never requires them to touch Azure.++They are two separate Microsoft apps and they will both exist. Nothing here+replaces the other page.++The install connects a Microsoft organisation (a directory, or **tenant** in+Microsoft's terms) to a Switch workspace that **already exists**. The flow+begins with an authenticated admin inside the workspace they are connecting,+so nothing in Microsoft's screens can bring a workspace into being.++## Why it cannot be the same app++The bring-your-own app runs entirely inside the customer's directory: its+credential reaches only that organisation, its bot listens on its own port,+and every activity it receives is its own. A distributed app has none of that:++- **Microsoft grants no credential per install.** Approving the app gives the+ one app we registered access to the organisation; Switch mints that+ organisation's tokens with the app's own credential when it needs them. So+ the credential is deployment config (`TEAMS_APP_*`), never stored against an+ install, and an install records no token — like Discord's.+- **One bot, one messaging endpoint.** An Azure Bot has exactly one messaging+ address, so every organisation's activities arrive at the same URL, and each+ is routed by the organisation it carries. Graph's change notifications do+ the same.+- **New "multi-tenant" Azure Bot resources cannot be created.** Microsoft+ stopped allowing them after 31 July 2025. The supported shape is a+ **SingleTenant** Azure Bot in our own directory, backed by an Entra app+ registered for **any organizational directory**. Bot Connector tokens for it+ are only ever issued in our own directory; Graph tokens are issued in each+ customer's.++## The two public URLs++Both arrive under the public `/messaging` prefix at `MESSAGING_PUBLIC_URL`+(scheme and host, https, no path):++| Where | Path |+| --- | --- |+| Azure Bot → Configuration → **Messaging endpoint** | `/messaging/teams/events` |+| Entra app → Authentication → **Redirect URI** (Web) | `/messaging/teams/oauth/callback` |++Graph's notification URL, `/messaging/teams/notifications`, is set by Switch+when it subscribes and needs no registration. Add `/messaging` to the ingress+path allowlist (`ingress.agentApiPaths` in the chart), or the URLs exist and+nothing routes to them. The bring-your-own path keeps its own listener on port+3978; the distributed app uses none.++## Registering the app (once per environment)++**One app and one bot per environment, never shared.** A bot has one messaging+address, and Switch deletes Graph subscriptions that point anywhere but its+own, so two environments on one app would take each other's traffic and wipe+each other's capture. They can all be registered in the same directory: a+SingleTenant bot's identity lives there, and the multi-tenant app behind it is+what customers approve. That directory can also approve a non-production+environment's app itself, to test against.++1. **Entra app registration.** Supported account types: **Accounts in any+ organizational directory**. Record the **Application (client) ID**+ (`TEAMS_APP_CLIENT_ID`) and **Directory (tenant) ID** (`TEAMS_APP_TENANT_ID`).+2. **Redirect URI** (platform Web): `https://<MESSAGING_PUBLIC_URL>/messaging/teams/oauth/callback`.+3. **Token configuration.** Emit **directory roles** in tokens — in the+ manifest, `"groupMembershipClaims": "DirectoryRole"` — so Switch can see+ that the person approving holds an admin role. Add the optional ID-token+ claim **`tenant_region_sub_scope`**, so a government-cloud organisation is+ refused at approval rather than half-installed.+4. **API permissions — Microsoft Graph, application:**++ | Permission | Why |+ | --- | --- |+ | `ChannelMessage.Read.All` | Every channel message, including private channels and other bots' posts |+ | `Channel.Create` | Create channels for new rooms |+ | `Channel.ReadBasic.All` | Channel names and layout; proving a channel is the organisation's |+ | `TeamMember.ReadWriteNonOwnerRole.All` | Add people to a team |+ | `ChannelMember.ReadWrite.All` | Add people to private channels |+ | `User.ReadBasic.All` | Find people in the organisation |+ | `Team.ReadBasic.All` | List the organisation's teams |+ | `TeamsAppInstallation.ReadWriteSelfForTeam.All` | Add Switch to, and remove it from, teams |++ **Delegated:** `openid`, `profile`, `User.Read` (the organisation's name) and+ `AppCatalog.ReadWrite.All` (putting the app in the organisation's Teams app+ list). Do **not** grant admin consent here — each customer's admin grants it+ for their own organisation.+5. **Credential — exactly one:**+ - **Federated (recommended):** a federated credential trusting the+ cluster's service-account issuer, subject+ `system:serviceaccount:<namespace>:<service account>`, audience+ `api://AzureADTokenExchange`. No secret exists. In the chart,+ `switchCore.teamsApp.credential: federated` mounts the projected token.+ - **Certificate:** upload the public certificate; give Switch the+ certificate and its key (`TEAMS_APP_CERTIFICATE`,+ `TEAMS_APP_CERTIFICATE_PRIVATE_KEY`).+ - **Client secret:** simplest, for local development; it expires.+6. **Azure Bot resource.** Type of app: **Single Tenant**, and **Use existing+ app registration** with the app above: the bot's Microsoft App ID *is* that+ app's client ID. Leaving "Create new" selected makes a second app, which has+ none of the setup above. Messaging endpoint as in the table. Under+ **Channels**, add **Microsoft Teams** — a new bot has it off.+7. **Notification keypair.** An RSA keypair Graph encrypts captured messages+ to, as PEM (`TEAMS_APP_NOTIFICATION_CERTIFICATE`,+ `TEAMS_APP_NOTIFICATION_PRIVATE_KEY`). Self-signed is fine; Graph uses it+ only to carry a key. For example:++ ```sh+ openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj "/CN=switch-teams" \+ -keyout notification.key -out notification.crt+ ```++ To rotate: set the new pair, move the old private key to+ `TEAMS_APP_NOTIFICATION_PREVIOUS_PRIVATE_KEY`, restart, and remove it once+ the subscriptions made against it have run out (an hour).+8. **Privacy and terms pages.** Every Teams app package names both, and the+ approving admin is shown them (`TEAMS_APP_PRIVACY_URL`,+ `TEAMS_APP_TERMS_URL`, https).+9. **Name (optional).** `TEAMS_APP_NAME`, up to 30 characters, is the app's+ name in Teams; unset, it is "Agent Switch". Give each non-production+ environment's app its own — "Agent Switch (dev)" — so an organisation that+ approves more than one, ours included, can tell them apart. Name the Entra+ app registration to match. Set it before the first approval: an+ organisation takes a new name only with a newer app package.+10. **Publisher verification** (Partner Center). Without it, Microsoft's+ approval screen shows the app as unverified, which makes IT teams more+ likely to refuse. A Teams Store listing also requires it.++All of these are required together; a partial configuration is refused at+startup. Setting `TEAMS_APP_CLIENT_ID` is what enables the button.++## What a customer's install produces++1. A workspace admin clicks **Add to Microsoft Teams** in Switch.+2. A Microsoft admin signs in and approves Switch for the organisation — one+ screen, with **Consent on behalf of your organization** ticked.+3. Switch records nothing until it has proved three things: the ID token+ Microsoft signed names the organisation and is issued by it; the person+ holds **Global Administrator** or **Privileged Role Administrator** there;+ and a token issued in that organisation carries every permission above.+ Personal accounts and government clouds are refused.+4. Switch puts the app into the organisation's Teams app list with the admin's+ delegated token, which it then throws away. If the admin may approve but is+ not a Teams administrator, the install still succeeds and the connection+ says the app is not in the list yet, with the package to download for a+ Teams admin to upload (Teams admin center → Teams apps → Manage apps →+ Upload new app). Once it has been added to any one team from Teams, Switch+ learns where it is in the list and can add it to the rest itself.+5. The connection's **Microsoft Teams** panel lists the organisation's teams.+ The workspace's admins add Switch to the teams they want and choose the+ default team new channels go in; choosing one turns channel creation on.+ Only a team Switch is in can be the default, and taking Switch out of the+ default team turns channel creation off until another is chosen. Switch+ captures messages only in teams it is in: taking it out of a team stops+ capture there, restarts included, until it is added back. Where Teams does+ not tell the bot that Switch was added or removed, Switch notices within+ about a quarter of an hour.+6. Channels Switch is in become rooms, as with the bring-your-own app.++One Microsoft organisation belongs to one Switch workspace. A second workspace+approving the same organisation is refused, without being told which holds it.+The same workspace approving again — for new permissions, a newer app, or after+withdrawing its approval — refreshes its install.++## A bridge reaches only its own organisation++The app's one credential reaches every approving organisation, so each bridge+is kept inside its own in four layers:++- **Start guard.** A shared bridge starts only for the workspace that holds the+ organisation's live install.+- **Locked settings.** Only the default team is editable on a shared bridge;+ the organisation and what Switch learned from Microsoft (the service URL, the+ channel-to-team map) are not.+- **Microsoft's hosts only.** The Bot Connector token is sent only to+ `smba.trafficmanager.net`, whatever a stored or learned address says.+- **Bind and send checks.** A room is bound to an existing channel only after+ Graph, asked with the organisation's own token, shows the channel; chats are+ never bound by id; activities and notifications from another organisation+ are refused; proactive posts name the organisation.++Inbound, every activity's Bot Framework token is checked as Microsoft's spec+requires — including its `serviceurl` claim and the signing key's endorsement+for `msteams`. Notifications carrying data must be vouched for by Graph's+validation tokens and may only name organisations those tokens vouch for; each+organisation's `clientState` is derived from `SECRET_KEYS`, so a value+learned for one forges nothing for another. An organisation that sets+**assignment required** on the Switch enterprise app stops Microsoft sending+validation tokens, and its captured messages are dropped until it is unset;+other organisations' messages in the same batch are unaffected.++Rotating `SECRET_KEYS` (a new current key) changes every organisation's+`clientState`. The notification URL carries a fingerprint of the key, so at the+next start every subscription made under the old key reads as stale and is+remade.++## When something goes wrong on Microsoft's side++Microsoft sends no word when an organisation withdraws its approval. Each+bridge checks every few minutes, with the token it is minting anyway: an app no+longer approved, permissions narrowed, or the app blocked by the+organisation's Teams admin shows on the connection as something to act on, with+**Approve again**. The install is not ended — a blip in Microsoft's directory+must not disconnect a customer and free their organisation for someone else.++Disconnecting from Switch stops capture in the organisation and takes Switch+out of every team it is in. Removing the app from the organisation entirely is+the customer's to do: their Teams admin removes **Agent Switch** in the Teams+admin center, and their Entra admin deletes the enterprise application.++## When setup goes wrong++What each mistake looks like, in the order an approval meets them:++| What you see | Cause | Fix |+| --- | --- | --- |+| Microsoft: `AADSTS500113` (no reply address) or `AADSTS50011` (reply address does not match) | The redirect URI is missing, or differs from the one Switch sends | Step 2: add it exactly, platform **Web** |+| Microsoft: `AADSTS650056` — misconfigured application | The app registration lists no Graph permissions | Step 4: add them |+| Microsoft: "Need admin approval" | The person signing in is not an admin | A Global or Privileged Role Administrator approves |+| Switch: "Microsoft did not say which roles the person signing in holds" | Directory roles are not emitted in tokens | Step 3 |+| Switch: "Workspace already connected" | The organisation belongs to another Switch workspace (perhaps another of yours) | Approve from the workspace that holds it, or disconnect it there first |+| Teams: "Invalid Bot", or the admin center cannot install the app | No Azure Bot on this app's client ID, or its Teams channel is off | Step 6 |+| The Teams panel says the app list already has an app under Switch's id that asks for per-team permissions | A package uploaded by hand under the same id | Delete it in Teams admin center, then approve again |++## Left out on purpose++- **Government clouds** (GCC, GCC High, DoD): refused at approval.+- **The Teams Store.** A listing would remove the catalogue step and let+ most package updates reach organisations without their admin; it needs+ Partner Center review and is public. Until then, an organisation takes a+ newer package when its admin approves again.+- **Per-team permissions.** The organisation-wide permissions already cover+ them, and asking again per team would only add a consent prompt.diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.tsindex 341011855..4a28e8b00 100644--- a/gateway/src/data/api.test.ts+++ b/gateway/src/data/api.test.ts@@ -1,5 +1,14 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { ApiError, errorText, fetchSession } from "./api";+import {+ ApiError,+ addBridgeToTeam,+ errorText,+ fetchSession,+ fetchTeamPlacements,+ fetchTeamsAppPackage,+ removeBridgeFromTeam,+ setDefaultTeamsTeam,+} from "./api";describe("errorText", () => {it("returns a string detail as is", () => {@@ -51,3 +60,142 @@ describe("fetchSession", () => {expect((err as ApiError).message).toBe("boom");});});++describe("fetchTeamPlacements", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("returns the organisation's teams", async () => {+ respond(200, {+ teams: [{ team_id: "t1", name: "Engineering", has_switch: true, is_default: true }],+ default_team_id: "t1",+ in_catalog: true,+ catalog_problem: null,+ });+ const result = await fetchTeamPlacements("b1");+ expect(result.teams).toHaveLength(1);+ expect(result.default_team_id).toBe("t1");+ });++ it("throws the server's own words on a connection that is not running", async () => {+ respond(409, { detail: "The Teams connection is not running; try again in a moment." });+ const err = await fetchTeamPlacements("b1").catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ApiError);+ expect((err as ApiError).status).toBe(409);+ expect((err as ApiError).message).toBe(+ "The Teams connection is not running; try again in a moment.",+ );+ });+});++describe("addBridgeToTeam / removeBridgeFromTeam", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("posts to the team's id and resolves on 204", async () => {+ const fetchMock = vi.fn(async () => new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);++ await addBridgeToTeam("b1", "t2");++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toContain("/collaborations/b1/teams/t2");+ expect(init.method).toBe("POST");+ });++ it("throws the catalogue problem when the app cannot be added yet", async () => {+ respond(409, {+ detail: "Switch is not in your organisation's Teams app list yet.",+ });+ const err = await addBridgeToTeam("b1", "t2").catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ApiError);+ expect((err as ApiError).message).toBe(+ "Switch is not in your organisation's Teams app list yet.",+ );+ });++ it("deletes to remove Switch from a team", async () => {+ const fetchMock = vi.fn(async () => new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);++ await removeBridgeFromTeam("b1", "t1");++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toContain("/collaborations/b1/teams/t1");+ expect(init.method).toBe("DELETE");+ });+});++describe("setDefaultTeamsTeam", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("PATCHes the connection's config and turns channel creation on", async () => {+ const bridge = {+ bridge_id: "b1",+ bridge_type: "teams",+ display_name: "Acme Corp",+ status: "active",+ agent_greetings_enabled: true,+ channel_creation_supported: true,+ channel_creation_enabled: true,+ room_count: 2,+ created_at: "2026-01-01",+ attention: null,+ team_placement_supported: true,+ };+ const fetchMock = vi.fn(+ async () => new Response(JSON.stringify(bridge), { status: 200 }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const result = await setDefaultTeamsTeam("b1", "t3");++ expect(result).toEqual(bridge);+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toContain("/collaborations/b1");+ expect(init.method).toBe("PATCH");+ expect(JSON.parse(String(init.body))).toEqual({+ connection_config: { team_id: "t3" },+ channel_creation_enabled: true,+ });+ });++ it("throws the server's reason when the team cannot be made the default", async () => {+ respond(422, {+ detail: "Switch is not in that team. Add it to the team first, then make it the default.",+ });+ const err = await setDefaultTeamsTeam("b1", "t3").catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ApiError);+ expect((err as ApiError).status).toBe(422);+ expect((err as ApiError).message).toBe(+ "Switch is not in that team. Add it to the team first, then make it the default.",+ );+ });+});++describe("fetchTeamsAppPackage", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("reads the filename off Content-Disposition", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(+ async () =>+ new Response(new Blob(["zip bytes"]), {+ status: 200,+ headers: {+ "Content-Disposition": 'attachment; filename="switch-teams-1.0.0.zip"',+ },+ }),+ ),+ );+ const result = await fetchTeamsAppPackage("b1");+ expect(result.filename).toBe("switch-teams-1.0.0.zip");+ expect(result.blob).toBeInstanceOf(Blob);+ });++ it("throws with the server's detail on failure", async () => {+ respond(404, { detail: "This deployment has no distributed Teams app." });+ await expect(fetchTeamsAppPackage("b1")).rejects.toThrow(+ "This deployment has no distributed Teams app.",+ );+ });+});diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 3f5de294b..6662f8e96 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -151,6 +151,15 @@ export interface BridgeDetail {install_links?: BridgeInstallLink[];// What those links do not cover — chats that have to be joined by hand.install_note?: string | null;+ // Something only the platform's side can fix, found while the bridge runs —+ // an approval withdrawn, the app blocked by the organisation's admin — in+ // plain words for a banner on the connection. Null while nothing is known+ // to be wrong, or the bridge is not running.+ attention: string | null;+ // Whether the workspace chooses, here, which of the platform's teams the+ // connection's app is in (the distributed Teams app). False while the+ // bridge is not running.+ team_placement_supported: boolean;}export interface ExternalUserSummary {@@ -278,6 +287,22 @@ async function jsonRequest<T>(return (await res.json()) as T;}+// For a mutation whose success response carries no body (204 No Content):+// `jsonRequest` would fail calling `.json()` on it, so this skips that parse+// on success and only reads a body back on failure, where FastAPI puts one.+async function noContentRequest(path: string, method: string): Promise<void> {+ const res = await fetch(`${BASE}${path}`, { method, credentials: "include" });+ if (!res.ok) {+ const payload = await res.json().catch(() => null);+ const detail = payload?.detail ?? null;+ throw new ApiError(+ res.status,+ detail,+ errorText(detail, `${res.status} ${res.statusText}`),+ );+ }+}+export async function fetchRooms(search?: string,includeArchived?: boolean,@@ -874,6 +899,10 @@ export async function deleteBridge(bridgeId: string): Promise<{ ok: boolean }> {export interface BridgeUpdateInput {agent_greetings_enabled?: boolean;channel_creation_enabled?: boolean;+ // Merged over the stored config, not substituted for it. Used to set the+ // distributed Teams app's default team — see `updateBridge`'s callers in+ // the Teams placements panel.+ connection_config?: Record<string, unknown>;}export async function updateBridge(@@ -887,6 +916,91 @@ export async function updateBridge(});}+/** Make a team the connection's default for new channels, which also turns+ * channel creation on. Throws `ApiError` with the server's reason — the team+ * is not one Switch is in, the connection is restarting, Microsoft could not+ * be asked — rather than returning null, so the dialog can say which. */+export async function setDefaultTeamsTeam(+ bridgeId: string,+ teamId: string,+): Promise<BridgeDetail> {+ return jsonRequest<BridgeDetail>(`/collaborations/${bridgeId}`, "PATCH", {+ connection_config: { team_id: teamId },+ channel_creation_enabled: true,+ });+}++// ── Teams placements ─────────────────────────────────────────────────────────+//+// Which of the organisation's teams the distributed Teams app is in. Chosen+// from the connection once a Microsoft admin has approved the app — see+// `BridgeDetail.team_placement_supported`. Every call here is refused (404)+// for a bridge that is not a running connection on that app.++export interface TeamPlacement {+ team_id: string;+ name: string;+ /** Null when the team's apps could not be read (archived, restricted). */+ has_switch: boolean | null;+ is_default: boolean;+}++export interface TeamPlacements {+ teams: TeamPlacement[];+ default_team_id: string | null;+ // Whether the app is in the organisation's catalogue yet, which adding it+ // to a team needs. `catalog_problem` says why when it is not, and the+ // package can be downloaded for a Teams admin to upload by hand.+ in_catalog: boolean;+ catalog_problem: string | null;+}++// Throws, carrying the server's own words: a 404 means this connection is not+// on the distributed app, 503 that it is not running right now, and 502 that+// Microsoft refused the call — all of them are read by the panel rather than+// collapsed into a boolean.+export async function fetchTeamPlacements(bridgeId: string): Promise<TeamPlacements> {+ return jsonRequest<TeamPlacements>(`/collaborations/${bridgeId}/teams`, "GET");+}++export async function addBridgeToTeam(bridgeId: string, teamId: string): Promise<void> {+ return noContentRequest(+ `/collaborations/${bridgeId}/teams/${encodeURIComponent(teamId)}`,+ "POST",+ );+}++export async function removeBridgeFromTeam(+ bridgeId: string,+ teamId: string,+): Promise<void> {+ return noContentRequest(+ `/collaborations/${bridgeId}/teams/${encodeURIComponent(teamId)}`,+ "DELETE",+ );+}++export interface DownloadedFile {+ blob: Blob;+ filename: string;+}++// The app package for a Teams admin to upload by hand, when the app is not in+// the organisation's catalogue yet. Fetched (rather than a plain link) so the+// panel can keep the admin on the page and report a failure in place, the+// same way `exportRoomYaml` does for a text download.+export async function fetchTeamsAppPackage(bridgeId: string): Promise<DownloadedFile> {+ const res = await fetch(`${BASE}/collaborations/${bridgeId}/teams-package`, {+ credentials: "include",+ });+ if (!res.ok) {+ const payload = await res.json().catch(() => null);+ throw new Error(errorText(payload?.detail, `${res.status} ${res.statusText}`));+ }+ const match = res.headers.get("Content-Disposition")?.match(/filename="?([^"]+)"?/);+ return { blob: await res.blob(), filename: match?.[1] ?? "switch-teams-app.zip" };+}+// ── Installed apps ───────────────────────────────────────────────────────────//// The other way a connection comes into being: instead of an operatordiff --git a/gateway/src/pages/collaborations/AttentionBanner.test.tsx b/gateway/src/pages/collaborations/AttentionBanner.test.tsxnew file mode 100644index 000000000..7fb9c98b4--- /dev/null+++ b/gateway/src/pages/collaborations/AttentionBanner.test.tsx@@ -0,0 +1,57 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import AttentionBanner from "./AttentionBanner";++describe("AttentionBanner", () => {+ afterEach(() => cleanup());++ it("renders the connection name and the attention message", () => {+ render(+ <AttentionBanner+ displayName="Acme Corp"+ message="Microsoft says Switch is no longer approved in this organisation."+ canApproveAgain={false}+ approving={false}+ onApproveAgain={() => {}}+ />,+ );++ expect(screen.getByText("Acme Corp:")).toBeTruthy();+ expect(+ screen.getByText(+ /Microsoft says Switch is no longer approved in this organisation\./,+ ),+ ).toBeTruthy();+ });++ it("offers to approve again only when that is possible, and calls back on click", () => {+ const onApproveAgain = vi.fn();+ render(+ <AttentionBanner+ displayName="Acme Corp"+ message="Approval was withdrawn."+ canApproveAgain+ approving={false}+ onApproveAgain={onApproveAgain}+ />,+ );++ const button = screen.getByRole("button", { name: "Approve again" });+ fireEvent.click(button);+ expect(onApproveAgain).toHaveBeenCalledTimes(1);+ });++ it("has no action when re-approval is not possible", () => {+ render(+ <AttentionBanner+ displayName="Acme Corp"+ message="Approval was withdrawn."+ canApproveAgain={false}+ approving={false}+ onApproveAgain={() => {}}+ />,+ );++ expect(screen.queryByRole("button", { name: "Approve again" })).toBeNull();+ });+});diff --git a/gateway/src/pages/collaborations/AttentionBanner.tsx b/gateway/src/pages/collaborations/AttentionBanner.tsxnew file mode 100644index 000000000..f4efef18e--- /dev/null+++ b/gateway/src/pages/collaborations/AttentionBanner.tsx@@ -0,0 +1,46 @@+import { Alert, Button, CircularProgress } from "@mui/material";++interface Props {+ displayName: string;+ message: string;+ // Only a connection on this deployment's own app (the distributed Teams+ // app) can be re-approved from here — a registered app's credentials are+ // the operator's to fix, not a button Switch can click for them.+ canApproveAgain: boolean;+ approving: boolean;+ onApproveAgain: () => void;+}++/** Something only the platform's side can fix, found on a live connection —+ * an approval withdrawn, the app blocked by an organisation admin. Shown for+ * any bridge type: the message is the adapter's own words, and this component+ * knows nothing about any particular platform. */+export default function AttentionBanner({+ displayName,+ message,+ canApproveAgain,+ approving,+ onApproveAgain,+}: Props) {+ return (+ <Alert+ severity="warning"+ sx={{ mb: 1 }}+ action={+ canApproveAgain ? (+ <Button+ color="inherit"+ size="small"+ onClick={onApproveAgain}+ disabled={approving}+ startIcon={approving ? <CircularProgress size={14} /> : undefined}+ >+ Approve again+ </Button>+ ) : undefined+ }+ >+ <strong>{displayName}:</strong> {message}+ </Alert>+ );+}diff --git a/gateway/src/pages/collaborations/CollaborationsPage.test.tsx b/gateway/src/pages/collaborations/CollaborationsPage.test.tsxnew file mode 100644index 000000000..3bfa1fe4c--- /dev/null+++ b/gateway/src/pages/collaborations/CollaborationsPage.test.tsx@@ -0,0 +1,283 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { BridgeDetail } from "../../data/api";+import * as api from "../../data/api";+import { useAuth } from "../../data/AuthContext";+import * as hooks from "../../data/hooks";+import type { UseQueryResult } from "../../data/hooks";+import CollaborationsPage from "./CollaborationsPage";++vi.mock("../../data/AuthContext", () => ({+ useAuth: vi.fn(),+}));++vi.mock("../../data/hooks", () => ({+ useBridges: vi.fn(),+ useInstallablePlatforms: vi.fn(),+ useInstalledApps: vi.fn(),+ useBridgeTypes: vi.fn(),+}));++vi.mock("../../data/api", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../data/api")>();+ return {+ ...actual,+ beginAppInstall: vi.fn(),+ };+});++function authState(canAdminTenant: boolean) {+ return {+ session: null,+ user: null,+ loading: false,+ loadError: null,+ isOperator: false,+ canAdminTenant,+ refresh: vi.fn(async () => {}),+ login: vi.fn(async () => {}),+ logout: vi.fn(async () => {}),+ switchTo: vi.fn(async () => {}),+ };+}++function queryResult<T>(data: T | null): UseQueryResult<T> {+ return { data, loading: false, error: null, refetch: vi.fn() };+}++function bridge(overrides: Partial<BridgeDetail> = {}): BridgeDetail {+ return {+ bridge_id: "b1",+ bridge_type: "teams",+ display_name: "Acme Corp",+ status: "active",+ agent_greetings_enabled: true,+ channel_creation_supported: true,+ channel_creation_enabled: false,+ room_count: 2,+ created_at: "2026-01-01",+ attention: null,+ team_placement_supported: false,+ ...overrides,+ };+}++function setup({+ isAdmin = true,+ bridges = [bridge()],+ installablePlatforms = [] as string[],+}: {+ isAdmin?: boolean;+ bridges?: BridgeDetail[];+ installablePlatforms?: string[];+} = {}) {+ vi.mocked(useAuth).mockReturnValue(authState(isAdmin));+ vi.mocked(hooks.useBridges).mockReturnValue(queryResult(bridges));+ vi.mocked(hooks.useInstallablePlatforms).mockReturnValue(+ queryResult(installablePlatforms),+ );+ vi.mocked(hooks.useInstalledApps).mockReturnValue(queryResult([]));+ vi.mocked(hooks.useBridgeTypes).mockReturnValue(queryResult([]));+}++/** A safety net for any request a sub-dialog fires once opened (e.g. the+ * Teams placement panel's own load) — unmocked requests answer with empty,+ * valid-enough bodies so an unrelated fetch cannot crash the test. */+function stubFetch() {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (String(url).includes("/teams")) {+ return new Response(+ JSON.stringify({+ teams: [],+ default_team_id: null,+ in_catalog: true,+ catalog_problem: null,+ }),+ { status: 200 },+ );+ }+ return new Response(JSON.stringify({}), { status: 404 });+ }),+ );+}++describe("CollaborationsPage", () => {+ const originalLocation = window.location;++ beforeEach(() => {+ stubFetch();+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: { ...originalLocation, href: "" },+ });+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: originalLocation,+ });+ });++ it("offers the Teams button only on rows the platform supports, and opens the dialog", async () => {+ setup({+ bridges: [+ bridge({ bridge_id: "b1", display_name: "Supports Teams", team_placement_supported: true }),+ bridge({ bridge_id: "b2", display_name: "No Team Placement", team_placement_supported: false }),+ ],+ });+ render(<CollaborationsPage />);++ const teamsButtons = screen.getAllByRole("button", {+ name: "Choose which teams this app is in",+ });+ expect(teamsButtons).toHaveLength(1);++ fireEvent.click(teamsButtons[0]);+ expect(await screen.findByText("Microsoft Teams: Supports Teams")).toBeTruthy();+ });++ it("shows an attention banner for a row that needs it", () => {+ setup({+ bridges: [+ bridge({+ display_name: "Acme Corp",+ attention: "Microsoft says Switch is no longer approved in this organisation.",+ }),+ ],+ });+ render(<CollaborationsPage />);++ expect(screen.getByText("Acme Corp:")).toBeTruthy();+ expect(+ screen.getByText(+ /Microsoft says Switch is no longer approved in this organisation\./,+ ),+ ).toBeTruthy();+ });++ it("offers Approve again only when admin, team-placement-supported, and installable all hold", () => {+ const attention = "Approval was withdrawn.";+ setup({+ isAdmin: true,+ installablePlatforms: ["teams"],+ bridges: [+ bridge({ team_placement_supported: true, attention }),+ ],+ });+ render(<CollaborationsPage />);++ expect(screen.getByRole("button", { name: "Approve again" })).toBeTruthy();+ });++ it("hides Approve again for a non-admin", () => {+ const attention = "Approval was withdrawn.";+ setup({+ isAdmin: false,+ installablePlatforms: ["teams"],+ bridges: [bridge({ team_placement_supported: true, attention })],+ });+ render(<CollaborationsPage />);++ expect(screen.queryByRole("button", { name: "Approve again" })).toBeNull();+ });++ it("hides Approve again when the bridge doesn't support team placement", () => {+ const attention = "Approval was withdrawn.";+ setup({+ isAdmin: true,+ installablePlatforms: ["teams"],+ bridges: [bridge({ team_placement_supported: false, attention })],+ });+ render(<CollaborationsPage />);++ expect(screen.queryByRole("button", { name: "Approve again" })).toBeNull();+ });++ it("hides Approve again when this deployment has no installable app for the platform", () => {+ const attention = "Approval was withdrawn.";+ setup({+ isAdmin: true,+ installablePlatforms: [],+ bridges: [bridge({ team_placement_supported: true, attention })],+ });+ render(<CollaborationsPage />);++ expect(screen.queryByRole("button", { name: "Approve again" })).toBeNull();+ });++ it("starts the install flow and navigates there on Approve again", async () => {+ setup({+ isAdmin: true,+ installablePlatforms: ["teams"],+ bridges: [+ bridge({+ bridge_type: "teams",+ team_placement_supported: true,+ attention: "Approval was withdrawn.",+ }),+ ],+ });+ vi.mocked(api.beginAppInstall).mockResolvedValue(+ "https://login.microsoftonline.com/authorize?x=1",+ );+ render(<CollaborationsPage />);++ fireEvent.click(screen.getByRole("button", { name: "Approve again" }));++ await waitFor(() => expect(api.beginAppInstall).toHaveBeenCalledWith("teams"));+ await waitFor(() =>+ expect(window.location.href).toBe("https://login.microsoftonline.com/authorize?x=1"),+ );+ });++ it("shows a dismissible error when starting the install fails", async () => {+ setup({+ isAdmin: true,+ installablePlatforms: ["teams"],+ bridges: [+ bridge({+ bridge_type: "teams",+ team_placement_supported: true,+ attention: "Approval was withdrawn.",+ }),+ ],+ });+ vi.mocked(api.beginAppInstall).mockRejectedValue(+ new Error("Microsoft did not answer; try again shortly."),+ );+ render(<CollaborationsPage />);++ fireEvent.click(screen.getByRole("button", { name: "Approve again" }));++ expect(+ await screen.findByText("Microsoft did not answer; try again shortly."),+ ).toBeTruthy();++ const alert = screen.getByText("Microsoft did not answer; try again shortly.")+ .closest('[role="alert"]') as HTMLElement;+ fireEvent.click(+ alert.querySelector('button[aria-label="Close"]') as HTMLElement,+ );++ await waitFor(() =>+ expect(+ screen.queryByText("Microsoft did not answer; try again shortly."),+ ).toBeNull(),+ );+ });++ it("labels the type column with the platform's own name", () => {+ setup({ bridges: [bridge({ bridge_type: "teams" })] });+ render(<CollaborationsPage />);++ expect(screen.getByText("Microsoft Teams")).toBeTruthy();+ });+});diff --git a/gateway/src/pages/collaborations/CollaborationsPage.tsx b/gateway/src/pages/collaborations/CollaborationsPage.tsxindex cf2420ba5..c499546c0 100644--- a/gateway/src/pages/collaborations/CollaborationsPage.tsx+++ b/gateway/src/pages/collaborations/CollaborationsPage.tsx@@ -1,6 +1,7 @@import AddLinkOutlined from "@mui/icons-material/AddLinkOutlined";import AddOutlined from "@mui/icons-material/AddOutlined";import DeleteOutline from "@mui/icons-material/DeleteOutline";+import GroupsOutlined from "@mui/icons-material/GroupsOutlined";import {Alert,Box,@@ -21,13 +22,20 @@ import {import type { GridColDef } from "@mui/x-data-grid";import { useCallback, useMemo, useState } from "react";import DataTable from "../../components/DataTable";-import { type BridgeDetail, deleteBridge, updateBridge } from "../../data/api";+import {+ type BridgeDetail,+ beginAppInstall,+ deleteBridge,+ updateBridge,+} from "../../data/api";import { useAuth } from "../../data/AuthContext";-import { useBridges } from "../../data/hooks";-import { formatDate, titleCase } from "../../theme/hootFormat";+import { useBridges, useInstallablePlatforms } from "../../data/hooks";+import { formatDate, platformLabel, titleCase } from "../../theme/hootFormat";import AddToChatDialog from "./AddToChatDialog";+import AttentionBanner from "./AttentionBanner";import InstalledAppsSection from "./InstalledAppsSection";import RegisterMessagingAppDialog from "./RegisterMessagingAppDialog";+import TeamsPlacementDialog from "./TeamsPlacementDialog";type BridgeRow = BridgeDetail & { id: string };@@ -40,12 +48,16 @@ const STATUS_COLOR: Record<string, "success" | "error" | "default"> = {export default function CollaborationsPage() {const { canAdminTenant: isAdmin } = useAuth();const { data: bridges, loading, refetch } = useBridges();+ const { data: installablePlatforms } = useInstallablePlatforms();const [deleteTarget, setDeleteTarget] = useState<BridgeDetail | null>(null);const [deleting, setDeleting] = useState(false);const [deleteError, setDeleteError] = useState<string | null>(null);const [savingId, setSavingId] = useState<string | null>(null);const [registerOpen, setRegisterOpen] = useState(false);const [installTarget, setInstallTarget] = useState<BridgeDetail | null>(null);+ const [teamsTarget, setTeamsTarget] = useState<BridgeDetail | null>(null);+ const [approvingId, setApprovingId] = useState<string | null>(null);+ const [approveError, setApproveError] = useState<string | null>(null);const handleDelete = useCallback(async () => {if (!deleteTarget) return;@@ -85,6 +97,20 @@ export default function CollaborationsPage() {[refetch],);+ // Re-approval is the same install flow the "Add to..." button starts: the+ // same workspace approving again refreshes the existing install, it does+ // not create a second one.+ const handleApproveAgain = useCallback(async (bridgeId: string, platform: string) => {+ setApprovingId(bridgeId);+ setApproveError(null);+ try {+ window.location.href = await beginAppInstall(platform);+ } catch (e) {+ setApproveError(e instanceof Error ? e.message : "Failed to start the install");+ setApprovingId(null);+ }+ }, []);+const columns = useMemo<GridColDef<BridgeRow>[]>(() => [{@@ -98,7 +124,7 @@ export default function CollaborationsPage() {headerName: "Type",width: 130,renderCell: ({ value }) => (- <Chip label={titleCase(String(value))} size="small" />+ <Chip label={platformLabel(String(value))} size="small" />),},{@@ -167,12 +193,12 @@ export default function CollaborationsPage() {{field: "actions" as const,headerName: "",- width: 110,+ width: 140,sortable: false,filterable: false,// Right-aligned and bottom-anchored to the same edge on every- // row: rows carry one icon or two depending on whether the- // platform offers an install link, and without this the delete+ // row: a row carries between one and three icons depending on+ // what the platform offers, and without this the delete// buttons sit at different x positions down the column.align: "right" as const,renderCell: ({ row }: { row: BridgeRow }) => (@@ -183,6 +209,13 @@ export default function CollaborationsPage() {justifyContent="flex-end"height="100%">+ {row.team_placement_supported && (+ <Tooltip title="Choose which teams this app is in">+ <IconButton size="small" onClick={() => setTeamsTarget(row)}>+ <GroupsOutlined fontSize="small" />+ </IconButton>+ </Tooltip>+ )}{(row.install_links ?? []).length > 0 && (<Tooltip title="Add this app to a chat"><IconButton@@ -210,6 +243,11 @@ export default function CollaborationsPage() {[bridges],);+ const needsAttention = useMemo(+ () => rows.filter((b) => !!b.attention),+ [rows],+ );+return (<Box><Stack direction="row" alignItems="center" mb={2}>@@ -226,6 +264,27 @@ export default function CollaborationsPage() {)}</Stack>+ {approveError && (+ <Alert severity="error" sx={{ mb: 1 }} onClose={() => setApproveError(null)}>+ {approveError}+ </Alert>+ )}++ {needsAttention.map((b) => (+ <AttentionBanner+ key={b.bridge_id}+ displayName={b.display_name}+ message={b.attention ?? ""}+ canApproveAgain={+ isAdmin &&+ b.team_placement_supported &&+ (installablePlatforms ?? []).includes(b.bridge_type)+ }+ approving={approvingId === b.bridge_id}+ onApproveAgain={() => handleApproveAgain(b.bridge_id, b.bridge_type)}+ />+ ))}+{loading ? (<CircularProgress />) : (@@ -245,6 +304,12 @@ export default function CollaborationsPage() {onClose={() => setInstallTarget(null)}/>+ <TeamsPlacementDialog+ bridge={teamsTarget}+ onClose={() => setTeamsTarget(null)}+ onChanged={refetch}+ />+<Dialogopen={!!deleteTarget}onClose={() => {diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsxnew file mode 100644index 000000000..fded96e70--- /dev/null+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsx@@ -0,0 +1,49 @@+import { cleanup, render } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import type { InstalledApp } from "../../data/api";+import DisconnectAppDialog from "./DisconnectAppDialog";++const install: InstalledApp = {+ id: "i1",+ platform: "teams",+ external_workspace_id: "org-123",+ status: "active",+ scopes: "ChannelMessage.Send",+ bridge_id: "b1",+ installed_at: "2026-01-01",+ ended_at: null,+};++describe("DisconnectAppDialog", () => {+ afterEach(() => cleanup());++ it("names Microsoft Teams and the admin centers, and does not claim a token is revoked", () => {+ render(+ <DisconnectAppDialog+ install={install}+ onClose={() => {}}+ onDisconnected={() => {}}+ />,+ );++ // The dialog renders through a portal, so it lands outside `container`+ // and has to be read off `document.body` instead.+ const text = document.body.textContent ?? "";+ expect(text).toContain("Microsoft Teams organisation");+ expect(text).toContain("Teams admin center");+ expect(text).toContain("Microsoft Entra admin center");+ expect(text).not.toContain("access token is revoked");+ });++ it("uses the default, token-revoking copy for a platform with no entry of its own", () => {+ render(+ <DisconnectAppDialog+ install={{ ...install, platform: "slack" }}+ onClose={() => {}}+ onDisconnected={() => {}}+ />,+ );++ expect(document.body.textContent ?? "").toContain("access token is revoked");+ });+});diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.tsxindex e177ca0f0..4f54e8b23 100644--- a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx@@ -10,7 +10,7 @@ import {} from "@mui/material";import { useState } from "react";import { type InstalledApp, disconnectApp } from "../../data/api";-import { titleCase } from "../../theme/hootFormat";+import { platformLabel } from "../../theme/hootFormat";/*** Disconnecting is the only way an install-created connection can be removed,@@ -45,6 +45,19 @@ const PLATFORM_COPY: Record<string, { noun: string; effect: string }> = {"the server until you remove it in Discord — disconnecting here does " +"not remove it.",},+ // The distributed Teams app holds no per-workspace token to revoke: one+ // install serves the whole Microsoft organisation, so disconnecting only+ // stops Switch from using it, the same way Discord's bot stays in its+ // server until removed there.+ teams: {+ noun: "organisation",+ effect:+ "Switch stops listening there and is taken out of every team it was " ++ "in — rooms that used it become internal-only. This does not remove " ++ "the app itself: a Microsoft admin removes \"Agent Switch\" in the " ++ "Teams admin center, and the enterprise application in the Microsoft " ++ "Entra admin center, to take it out of the organisation entirely.",+ },};const DEFAULT_COPY = {noun: "workspace",@@ -93,7 +106,7 @@ export default function DisconnectAppDialog({<DialogTitle>Disconnect the app</DialogTitle><DialogContent><DialogContentText>- Disconnect Switch from the {titleCase(install?.platform ?? "")}{" "}+ Disconnect Switch from the {platformLabel(install?.platform ?? "")}{" "}{copy.noun} <b>{install?.external_workspace_id}</b>? {copy.effect}</DialogContentText><DialogContentText sx={{ mt: 2 }}>diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.test.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.test.tsxnew file mode 100644index 000000000..977f0e7e0--- /dev/null+++ b/gateway/src/pages/collaborations/InstalledAppsSection.test.tsx@@ -0,0 +1,59 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { InstalledApp } from "../../data/api";+import InstalledAppsSection from "./InstalledAppsSection";++const teamsInstall: InstalledApp = {+ id: "i1",+ platform: "teams",+ external_workspace_id: "org-123",+ status: "active",+ scopes: "ChannelMessage.Send",+ bridge_id: "b1",+ installed_at: "2026-01-01",+ ended_at: null,+};++function mockFetch(installs: InstalledApp[] = []) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (String(url).includes("/messaging-apps/installs")) {+ return new Response(JSON.stringify({ installs }), { status: 200 });+ }+ if (String(url).includes("/messaging-apps")) {+ return new Response(JSON.stringify({ platforms: ["teams"] }), { status: 200 });+ }+ return new Response("not found", { status: 404 });+ }),+ );+}++describe("InstalledAppsSection", () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("names the Microsoft Teams app rather than a bare title-cased 'Teams'", async () => {+ mockFetch();+ render(<InstalledAppsSection isAdmin onConnectionsChanged={() => {}} />);++ expect(+ await screen.findByRole("button", { name: "Add to Microsoft Teams" }),+ ).toBeTruthy();+ });++ it("shows the platform column's own name, not a bare title-cased key", async () => {+ mockFetch([teamsInstall]);+ render(<InstalledAppsSection isAdmin onConnectionsChanged={() => {}} />);++ expect(await screen.findByText("org-123")).toBeTruthy();+ // The row's platform chip renders Microsoft's own name, same as the+ // "Add to..." button above it, rather than a title-cased "Teams".+ expect(screen.getByText("Microsoft Teams")).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Add to Microsoft Teams" }),+ ).toBeTruthy();+ });+});diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.tsxindex 19caecdd3..2bb4f1be9 100644--- a/gateway/src/pages/collaborations/InstalledAppsSection.tsx+++ b/gateway/src/pages/collaborations/InstalledAppsSection.tsx@@ -15,7 +15,7 @@ import { useCallback, useMemo, useState } from "react";import DataTable from "../../components/DataTable";import { type InstalledApp, beginAppInstall } from "../../data/api";import { useInstallablePlatforms, useInstalledApps } from "../../data/hooks";-import { EM_DASH, MONO_SX, formatDate, titleCase } from "../../theme/hootFormat";+import { EM_DASH, MONO_SX, formatDate, platformLabel, titleCase } from "../../theme/hootFormat";import DisconnectAppDialog from "./DisconnectAppDialog";/**@@ -91,7 +91,7 @@ export default function InstalledAppsSection({headerName: "Platform",width: 130,renderCell: ({ value }) => (- <Chip label={titleCase(String(value))} size="small" />+ <Chip label={platformLabel(String(value))} size="small" />),},{@@ -194,7 +194,7 @@ export default function InstalledAppsSection({}onClick={() => handleInstall(platform)}>- Add to {titleCase(platform)}+ Add to {platformLabel(platform)}</Button>))}</Stack>diff --git a/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsx b/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsxnew file mode 100644index 000000000..2c436e015--- /dev/null+++ b/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsx@@ -0,0 +1,519 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { BridgeDetail } from "../../data/api";+import TeamsPlacementDialog from "./TeamsPlacementDialog";++const bridge: BridgeDetail = {+ bridge_id: "b1",+ bridge_type: "teams",+ display_name: "Acme Corp",+ status: "active",+ agent_greetings_enabled: true,+ channel_creation_supported: true,+ channel_creation_enabled: false,+ room_count: 2,+ created_at: "2026-01-01",+ attention: null,+ team_placement_supported: true,+};++function placements(+ overrides: Partial<{+ teams: {+ team_id: string;+ name: string;+ has_switch: boolean | null;+ is_default: boolean;+ }[];+ default_team_id: string | null;+ in_catalog: boolean;+ catalog_problem: string | null;+ }> = {},+) {+ return {+ teams: [+ { team_id: "t1", name: "Engineering", has_switch: true, is_default: true },+ { team_id: "t2", name: "Sales", has_switch: false, is_default: false },+ ],+ default_team_id: "t1",+ in_catalog: true,+ catalog_problem: null,+ ...overrides,+ };+}++function jsonResponse(status: number, body: unknown) {+ return new Response(JSON.stringify(body), { status });+}++function mockFetch(handler: (url: string, init?: RequestInit) => Response) {+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => handler(url, init));+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++describe("TeamsPlacementDialog", () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("lists the organisation's teams", async () => {+ mockFetch(() => jsonResponse(200, placements()));+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ expect(await screen.findByText("Engineering")).toBeTruthy();+ expect(screen.getByText("Sales")).toBeTruthy();+ });++ it("shows a team whose apps could not be read as unknown, and offers no switch", async () => {+ mockFetch(() =>+ jsonResponse(+ 200,+ placements({+ teams: [+ { team_id: "t9", name: "Archive", has_switch: null, is_default: false },+ ],+ default_team_id: null,+ }),+ ),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ expect(await screen.findByText("Switch could not read this team's apps.")).toBeTruthy();+ const [toggle] = screen.getAllByRole("switch") as HTMLInputElement[];+ expect(toggle.disabled).toBe(true);+ });++ it("adds Switch to a team the switch is flipped on for", async () => {+ const fetchMock = mockFetch((_url, init) =>+ init?.method === "POST"+ ? new Response(null, { status: 204 })+ : jsonResponse(200, placements()),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Sales");+ const switches = screen.getAllByRole("switch");+ fireEvent.click(switches[1]); // Sales has no Switch yet++ await waitFor(() => {+ const post = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");+ expect(post).toBeTruthy();+ expect(String(post?.[0])).toContain("/collaborations/b1/teams/t2");+ });+ });++ it("removes Switch from a team the switch is flipped off for", async () => {+ const fetchMock = mockFetch((_url, init) =>+ init?.method === "DELETE"+ ? new Response(null, { status: 204 })+ : jsonResponse(200, placements()),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Engineering");+ const switches = screen.getAllByRole("switch");+ fireEvent.click(switches[0]); // Engineering already has Switch++ await waitFor(() => {+ const del = fetchMock.mock.calls.find(([, init]) => init?.method === "DELETE");+ expect(del).toBeTruthy();+ expect(String(del?.[0])).toContain("/collaborations/b1/teams/t1");+ });+ });++ it("sends connection_config.team_id and turns channel creation on when a default is chosen", async () => {+ // Support has Switch but is not yet the default, so picking it actually+ // changes the radio group's value — clicking the already-default team's+ // own radio fires no change event, in a browser or in jsdom.+ const withThirdTeam = placements({+ teams: [+ { team_id: "t1", name: "Engineering", has_switch: true, is_default: true },+ { team_id: "t2", name: "Sales", has_switch: false, is_default: false },+ { team_id: "t3", name: "Support", has_switch: true, is_default: false },+ ],+ });+ const fetchMock = mockFetch((_url, init) =>+ init?.method === "PATCH"+ ? jsonResponse(200, { ...bridge, channel_creation_enabled: true })+ : jsonResponse(200, withThirdTeam),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Support");+ const radios = screen.getAllByRole("radio");+ // Sales (index 1) has no Switch, so it cannot be made default.+ expect((radios[1] as HTMLInputElement).disabled).toBe(true);+ fireEvent.click(radios[2]);++ await waitFor(() => {+ const patch = fetchMock.mock.calls.find(([, init]) => init?.method === "PATCH");+ expect(patch).toBeTruthy();+ const body = JSON.parse(String(patch?.[1]?.body));+ expect(body.channel_creation_enabled).toBe(true);+ expect(body.connection_config).toEqual({ team_id: "t3" });+ });+ });++ it("waits out the restart a new default team causes instead of reporting it", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const before = placements({+ teams: [+ { team_id: "t1", name: "Engineering", has_switch: true, is_default: true },+ { team_id: "t3", name: "Support", has_switch: true, is_default: false },+ ],+ });+ const after = placements({+ teams: [+ { team_id: "t1", name: "Engineering", has_switch: true, is_default: false },+ { team_id: "t3", name: "Support", has_switch: true, is_default: true },+ ],+ default_team_id: "t3",+ });+ let reads = 0;+ mockFetch((_url, init) => {+ if (init?.method === "PATCH") {+ return jsonResponse(200, { ...bridge, channel_creation_enabled: true });+ }+ reads += 1;+ if (reads === 1) return jsonResponse(200, before);+ if (reads === 2) {+ return jsonResponse(503, {+ detail: "The Teams connection is not running; try again in a moment.",+ });+ }+ return jsonResponse(200, after);+ });+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Support");+ fireEvent.click(screen.getAllByRole("radio")[1]);++ expect(+ await screen.findByText("The connection is restarting with your change…"),+ ).toBeTruthy();+ expect(screen.queryByText(/not running/)).toBeNull();+ await vi.advanceTimersByTimeAsync(1500);++ await waitFor(() => {+ expect((screen.getAllByRole("radio")[1] as HTMLInputElement).checked).toBe(true);+ });+ expect(reads).toBe(3);+ expect(screen.queryByRole("alert")).toBeNull();+ vi.useRealTimers();+ });++ it("reports a connection that does not come back", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ mockFetch(() =>+ jsonResponse(503, {+ detail: "The Teams connection is not running; try again in a moment.",+ }),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("The connection is restarting with your change…");+ await vi.advanceTimersByTimeAsync(1500 * 21);++ expect(+ await screen.findByText(+ "The Teams connection is not running; try again in a moment.",+ ),+ ).toBeTruthy();+ vi.useRealTimers();+ });++ it("stops waiting for a restart once the dialog is closed", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const fetchMock = mockFetch(() =>+ jsonResponse(503, { detail: "The Teams connection is not running." }),+ );+ const { rerender } = render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );+ await screen.findByText("The connection is restarting with your change…");+ rerender(<TeamsPlacementDialog bridge={null} onClose={() => {}} onChanged={() => {}} />);+ const callsWhenClosed = fetchMock.mock.calls.length;++ await vi.advanceTimersByTimeAsync(1500 * 5);++ expect(fetchMock.mock.calls.length).toBe(callsWhenClosed);+ vi.useRealTimers();+ });++ it("disables adding a team and offers the package download when not in the catalogue", async () => {+ mockFetch(() =>+ jsonResponse(+ 200,+ placements({+ in_catalog: false,+ catalog_problem: "Microsoft has not listed the app for this organisation yet.",+ }),+ ),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ const downloadButton = await screen.findByRole("button", {+ name: /Download app package/,+ });+ expect(downloadButton).toBeTruthy();+ // The warning renders the catalogue problem alongside the download+ // button's own label in one alert, so it is read off the page rather than+ // matched as an element of its own.+ expect(document.body.textContent ?? "").toContain(+ "Microsoft has not listed the app for this organisation yet.",+ );++ const switches = screen.getAllByRole("switch");+ // Sales has no Switch, and the app isn't in the catalogue yet, so adding+ // it is refused here rather than failing only after the click.+ expect((switches[1] as HTMLInputElement).disabled).toBe(true);+ });++ it("shows the server's error when the teams list fails to load", async () => {+ mockFetch(() =>+ jsonResponse(502, { detail: "Microsoft refused to list the teams." }),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ expect(await screen.findByText("Microsoft refused to list the teams.")).toBeTruthy();+ });++ it("labels each row's radio and switch for assistive tech", async () => {+ mockFetch(() => jsonResponse(200, placements()));+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Engineering");+ expect(+ screen.getByRole("radio", { name: "Make Engineering the default team" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("radio", { name: "Make Sales the default team" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("switch", { name: "Remove Switch from Engineering" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("switch", { name: "Add Switch to Sales" }),+ ).toBeTruthy();+ });++ it("closes and clears stale errors when Close is clicked", async () => {+ mockFetch(() => jsonResponse(200, placements()));+ const onClose = vi.fn();+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={onClose} onChanged={() => {}} />,+ );++ await screen.findByText("Engineering");+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("shows the server's reason when toggling a team fails", async () => {+ mockFetch((_url, init) =>+ init?.method === "DELETE"+ ? jsonResponse(503, {+ detail: "The Teams connection is not running; try again in a moment.",+ })+ : jsonResponse(200, placements()),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Engineering");+ const switches = screen.getAllByRole("switch");+ fireEvent.click(switches[0]); // Engineering already has Switch -> DELETE, which fails++ expect(+ await screen.findByText("The Teams connection is not running; try again in a moment."),+ ).toBeTruthy();+ });++ it("shows the server's reason when making a team the default fails", async () => {+ const withThirdTeam = placements({+ teams: [+ { team_id: "t1", name: "Engineering", has_switch: true, is_default: true },+ { team_id: "t2", name: "Sales", has_switch: false, is_default: false },+ { team_id: "t3", name: "Support", has_switch: true, is_default: false },+ ],+ });+ mockFetch((_url, init) =>+ init?.method === "PATCH"+ ? jsonResponse(422, {+ detail:+ "Switch is not in that team. Add it to the team first, then make it the default.",+ })+ : jsonResponse(200, withThirdTeam),+ );+ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Support");+ const radios = screen.getAllByRole("radio");+ fireEvent.click(radios[2]); // Support has Switch but is not yet default++ expect(+ await screen.findByText(+ "Switch is not in that team. Add it to the team first, then make it the default.",+ ),+ ).toBeTruthy();+ });++ describe("downloading the app package", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ delete (URL as { createObjectURL?: unknown }).createObjectURL;+ delete (URL as { revokeObjectURL?: unknown }).revokeObjectURL;+ });++ it("creates an object URL and clicks an anchor named after the server's filename", async () => {+ mockFetch((url) =>+ String(url).includes("/teams-package")+ ? new Response(new Blob(["zip-bytes"]), {+ status: 200,+ headers: {+ "Content-Disposition": 'attachment; filename="switch-teams-app.zip"',+ },+ })+ : jsonResponse(+ 200,+ placements({+ in_catalog: false,+ catalog_problem: "Switch is not in your organisation's Teams app list yet.",+ }),+ ),+ );++ URL.createObjectURL = vi.fn(() => "blob:http://localhost/mock-id");+ URL.revokeObjectURL = vi.fn();+ const captured: { anchor: HTMLAnchorElement | null } = { anchor: null };+ const clickSpy = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(function (this: HTMLAnchorElement) {+ captured.anchor = this;+ });++ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ const downloadButton = await screen.findByRole("button", {+ name: /Download app package/,+ });+ fireEvent.click(downloadButton);++ await waitFor(() => expect(clickSpy).toHaveBeenCalledTimes(1));+ expect(URL.createObjectURL).toHaveBeenCalledTimes(1);+ expect(captured.anchor?.download).toBe("switch-teams-app.zip");+ expect(captured.anchor?.href).toBe("blob:http://localhost/mock-id");+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:http://localhost/mock-id");+ });++ it("shows the server's reason when the download fails", async () => {+ mockFetch((url) =>+ String(url).includes("/teams-package")+ ? jsonResponse(502, {+ detail: "Microsoft did not answer; try again shortly.",+ })+ : jsonResponse(+ 200,+ placements({+ in_catalog: false,+ catalog_problem: "Switch is not in your organisation's Teams app list yet.",+ }),+ ),+ );++ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ const downloadButton = await screen.findByRole("button", {+ name: /Download app package/,+ });+ fireEvent.click(downloadButton);++ expect(+ await screen.findByText("Microsoft did not answer; try again shortly."),+ ).toBeTruthy();+ });+ });++ it("shows the freshest reload even when an earlier one answers late", async () => {+ const initial = placements();+ const stale = placements({+ teams: [{ team_id: "t1", name: "STALE-TEAM", has_switch: false, is_default: false }],+ default_team_id: null,+ });+ const fresh = placements({+ teams: [{ team_id: "t1", name: "FRESH-TEAM", has_switch: true, is_default: true }],+ default_team_id: "t1",+ });++ type PendingGet = { resolve: (res: Response) => void };+ const pendingGets: PendingGet[] = [];+ let getCount = 0;++ const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ if (method === "DELETE") return new Response(null, { status: 204 });+ if (method === "POST") return new Response(null, { status: 204 });+ getCount += 1;+ if (getCount === 1) return jsonResponse(200, initial);+ return new Promise<Response>((resolve) => {+ pendingGets[getCount] = { resolve };+ });+ });+ vi.stubGlobal("fetch", fetchMock);++ render(+ <TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,+ );++ await screen.findByText("Engineering");+ const switches = screen.getAllByRole("switch");++ // Both clicks land while the list is still showing: a resolved reload+ // (load()) flips the dialog into its loading state, which unmounts the+ // very switches a second click would need, so team B has to be toggled+ // before team A's DELETE has resolved rather than after.+ fireEvent.click(switches[0]); // Engineering (has Switch) -> DELETE+ fireEvent.click(switches[1]); // Sales (no Switch) -> POST+ await waitFor(() => expect(getCount).toBe(3));++ // The newer load (#3) answers first, with fresh data.+ pendingGets[3].resolve(jsonResponse(200, fresh));+ expect(await screen.findByText("FRESH-TEAM")).toBeTruthy();++ // The older load (#2) answers late, with stale data that must be ignored.+ pendingGets[2].resolve(jsonResponse(200, stale));+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(screen.getByText("FRESH-TEAM")).toBeTruthy();+ expect(screen.queryByText("STALE-TEAM")).toBeNull();+ });+});diff --git a/gateway/src/pages/collaborations/TeamsPlacementDialog.tsx b/gateway/src/pages/collaborations/TeamsPlacementDialog.tsxnew file mode 100644index 000000000..265fbfc97--- /dev/null+++ b/gateway/src/pages/collaborations/TeamsPlacementDialog.tsx@@ -0,0 +1,360 @@+import DownloadOutlined from "@mui/icons-material/DownloadOutlined";+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Divider,+ Radio,+ RadioGroup,+ Stack,+ Switch,+ Tooltip,+ Typography,+} from "@mui/material";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ ApiError,+ type BridgeDetail,+ type TeamPlacement,+ addBridgeToTeam,+ fetchTeamPlacements,+ fetchTeamsAppPackage,+ removeBridgeFromTeam,+ setDefaultTeamsTeam,+} from "../../data/api";++// Choosing or clearing the default team restarts the connection, which answers+// 503 until it is running again: something to wait out, not a failure.+const RESTART_RETRY_MS = 1500;+const RESTART_RETRIES = 20;++interface Props {+ /** The bridge to manage teams for, or null when the dialog is closed. */+ bridge: BridgeDetail | null;+ onClose: () => void;+ // Choosing a default team turns channel creation on, so the bridges table+ // behind this dialog is stale once a change here succeeds.+ onChanged: () => void;+}++/** Which of the organisation's teams the distributed Teams app is in, and+ * which one new channels go in by default. Everything here comes from the+ * connection's own adapter; the dialog knows nothing about Microsoft Graph. */+export default function TeamsPlacementDialog({ bridge, onClose, onChanged }: Props) {+ const bridgeId = bridge?.bridge_id;++ const [teams, setTeams] = useState<TeamPlacement[]>([]);+ const [defaultTeamId, setDefaultTeamId] = useState<string | null>(null);+ const [inCatalog, setInCatalog] = useState(true);+ const [catalogProblem, setCatalogProblem] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const [restarting, setRestarting] = useState(false);+ const [loadError, setLoadError] = useState<string | null>(null);++ const [togglingTeamId, setTogglingTeamId] = useState<string | null>(null);+ const [settingDefaultId, setSettingDefaultId] = useState<string | null>(null);+ const [rowError, setRowError] = useState<{ teamId: string; message: string } | null>(+ null,+ );++ const [downloading, setDownloading] = useState(false);+ const [downloadError, setDownloadError] = useState<string | null>(null);++ // Each change reloads the list; only the latest load may write it, so an+ // earlier one answering late cannot put back what a later change undid.+ const latestLoad = useRef(0);+ const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ const stopLoading = useCallback(() => {+ latestLoad.current += 1;+ if (retryTimer.current !== null) clearTimeout(retryTimer.current);+ retryTimer.current = null;+ }, []);++ const load = useCallback(() => {+ if (!bridgeId) return;+ stopLoading();+ const thisLoad = latestLoad.current;+ setLoading(true);+ setRestarting(false);+ setLoadError(null);+ const attempt = (retriesLeft: number) => {+ fetchTeamPlacements(bridgeId)+ .then((result) => {+ if (thisLoad !== latestLoad.current) return;+ setTeams(result.teams);+ setDefaultTeamId(result.default_team_id);+ setInCatalog(result.in_catalog);+ setCatalogProblem(result.catalog_problem);+ setRestarting(false);+ setLoading(false);+ })+ .catch((e) => {+ if (thisLoad !== latestLoad.current) return;+ if (e instanceof ApiError && e.status === 503 && retriesLeft > 0) {+ setRestarting(true);+ retryTimer.current = setTimeout(+ () => attempt(retriesLeft - 1),+ RESTART_RETRY_MS,+ );+ return;+ }+ setRestarting(false);+ setLoadError(e instanceof Error ? e.message : "Failed to load teams");+ setLoading(false);+ });+ };+ attempt(RESTART_RETRIES);+ }, [bridgeId, stopLoading]);++ useEffect(() => {+ if (bridgeId) load();+ return stopLoading;+ }, [bridgeId, load, stopLoading]);++ const busy = togglingTeamId !== null || settingDefaultId !== null;++ const handleClose = () => {+ if (busy) return;+ setDownloadError(null);+ setRowError(null);+ onClose();+ };++ const handleToggle = useCallback(+ async (team: TeamPlacement) => {+ if (!bridgeId) return;+ setTogglingTeamId(team.team_id);+ setRowError(null);+ try {+ if (team.has_switch) {+ await removeBridgeFromTeam(bridgeId, team.team_id);+ } else {+ await addBridgeToTeam(bridgeId, team.team_id);+ }+ load();+ onChanged();+ } catch (e) {+ setRowError({+ teamId: team.team_id,+ message: e instanceof Error ? e.message : "Failed to update the team",+ });+ } finally {+ setTogglingTeamId(null);+ }+ },+ [bridgeId, load, onChanged],+ );++ const handleMakeDefault = useCallback(+ async (team: TeamPlacement) => {+ if (!bridgeId || !team.has_switch) return;+ setSettingDefaultId(team.team_id);+ setRowError(null);+ try {+ // Choosing a default team is also the decision to turn channel+ // creation on: installed bridges start with it off.+ await setDefaultTeamsTeam(bridgeId, team.team_id);+ load();+ onChanged();+ } catch (e) {+ setRowError({+ teamId: team.team_id,+ message: e instanceof Error ? e.message : "Failed to set the default team",+ });+ } finally {+ setSettingDefaultId(null);+ }+ },+ [bridgeId, load, onChanged],+ );++ const handleDownload = useCallback(async () => {+ if (!bridgeId) return;+ setDownloading(true);+ setDownloadError(null);+ try {+ const { blob, filename } = await fetchTeamsAppPackage(bridgeId);+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = filename;+ a.click();+ URL.revokeObjectURL(url);+ } catch (e) {+ setDownloadError(+ e instanceof Error ? e.message : "Failed to download the app package",+ );+ } finally {+ setDownloading(false);+ }+ }, [bridgeId]);++ return (+ <Dialog open={!!bridge} onClose={handleClose} maxWidth="sm" fullWidth>+ <DialogTitle>Microsoft Teams: {bridge?.display_name}</DialogTitle>+ <DialogContent>+ <Stack spacing={2} sx={{ mt: 0.5 }}>+ <Typography variant="body2" color="text.secondary">+ Choose which of your organisation's teams Switch is in, and which+ one new channels go in by default. Only a team Switch is in can be the+ default.+ </Typography>++ {loading && (+ <Stack alignItems="center" spacing={1.5} sx={{ py: 4 }}>+ <CircularProgress size={28} />+ {restarting && (+ <Typography variant="body2" color="text.secondary">+ The connection is restarting with your change…+ </Typography>+ )}+ </Stack>+ )}++ {!loading && loadError && <Alert severity="error">{loadError}</Alert>}++ {!loading && !loadError && (+ <>+ {!inCatalog && (+ <Alert+ severity="warning"+ action={+ <Button+ color="inherit"+ size="small"+ startIcon={+ downloading ? (+ <CircularProgress size={14} />+ ) : (+ <DownloadOutlined fontSize="small" />+ )+ }+ onClick={handleDownload}+ disabled={downloading}+ >+ Download app package+ </Button>+ }+ >+ {catalogProblem ??+ "Switch is not in your organisation's Teams app list yet."}{" "}+ A Teams admin uploads it by hand in the Teams admin center, under+ Teams apps, Manage apps, Upload new app. Once it is in any one team,+ added from Teams, Switch can add it to the rest from here.+ </Alert>+ )}+ {downloadError && <Alert severity="error">{downloadError}</Alert>}++ {teams.length === 0 ? (+ <Typography variant="body2" color="text.secondary">+ No teams found in your organisation.+ </Typography>+ ) : (+ <RadioGroup+ value={defaultTeamId ?? ""}+ onChange={(_e, value) => {+ const team = teams.find((t) => t.team_id === value);+ if (team) handleMakeDefault(team);+ }}+ >+ <Stack divider={<Divider />}>+ {teams.map((team) => (+ <Stack+ key={team.team_id}+ direction="row"+ alignItems="center"+ spacing={1}+ sx={{ py: 1 }}+ >+ <Tooltip+ title={+ team.has_switch+ ? "Make this the default team for new channels"+ : "Add Switch to this team before it can be the default"+ }+ >+ <span>+ <Radio+ size="small"+ value={team.team_id}+ disabled={!team.has_switch || busy}+ slotProps={{+ input: {+ "aria-label": `Make ${team.name} the default team`,+ },+ }}+ />+ </span>+ </Tooltip>++ <Stack sx={{ flex: 1 }}>+ <Typography variant="body2">{team.name}</Typography>+ {team.has_switch === null && (+ <Typography variant="caption" color="text.secondary">+ Switch could not read this team's apps.+ </Typography>+ )}+ {rowError?.teamId === team.team_id && (+ <Typography variant="caption" color="error">+ {rowError.message}+ </Typography>+ )}+ </Stack>++ {settingDefaultId === team.team_id && (+ <CircularProgress size={16} />+ )}++ <Tooltip+ title={+ team.has_switch === null+ ? "Switch could not read this team's apps"+ : !team.has_switch && !inCatalog+ ? "Switch is not in your organisation's Teams app list yet"+ : team.has_switch+ ? "Remove Switch from this team"+ : "Add Switch to this team"+ }+ >+ <span>+ <Switch+ size="small"+ checked={team.has_switch === true}+ disabled={+ team.has_switch === null ||+ togglingTeamId === team.team_id ||+ (!team.has_switch && !inCatalog)+ }+ onChange={() => handleToggle(team)}+ slotProps={{+ input: {+ "aria-label": team.has_switch+ ? `Remove Switch from ${team.name}`+ : `Add Switch to ${team.name}`,+ },+ }}+ />+ </span>+ </Tooltip>+ </Stack>+ ))}+ </Stack>+ </RadioGroup>+ )}+ </>+ )}+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={handleClose} disabled={busy}>+ Close+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/theme/hootFormat.test.ts b/gateway/src/theme/hootFormat.test.tsnew file mode 100644index 000000000..fe3bb55f2--- /dev/null+++ b/gateway/src/theme/hootFormat.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from "vitest";+import { platformLabel } from "./hootFormat";++describe("platformLabel", () => {+ it("names the Teams platform after Microsoft's own app, not a bare title case", () => {+ expect(platformLabel("teams")).toBe("Microsoft Teams");+ });++ it("falls back to title case for a platform with no name of its own to get wrong", () => {+ expect(platformLabel("slack")).toBe("Slack");+ expect(platformLabel("discord")).toBe("Discord");+ });+});diff --git a/gateway/src/theme/hootFormat.ts b/gateway/src/theme/hootFormat.tsindex 31a932cf5..0ebd1f357 100644--- a/gateway/src/theme/hootFormat.ts+++ b/gateway/src/theme/hootFormat.ts@@ -91,6 +91,17 @@ export function titleCase(value: string): string {.replace(/\b\w/g, (c) => c.toUpperCase());}+/** A messaging platform's own name for itself, where title-casing its key+ * gets it wrong — `teams` is Microsoft's own app, not a generic "Teams".+ * Falls back to title case for any platform with no name of its own to get+ * wrong. */+const PLATFORM_LABELS: Record<string, string> = {+ teams: "Microsoft Teams",+};++export const platformLabel = (value: string): string =>+ PLATFORM_LABELS[value] ?? titleCase(value);+/** Identifiers, hashes, IPs and code render in monospace — character-level* precision is the point. Spread onto an `sx`. */export const MONO_SX = {