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
Refuse bot and webhook accounts when linking, and other link fixes (CHOO-3881) (#1336)
Christian McDermottf4b02c67b68a
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 afff26589..30f414d4d 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@@ -2491,15 +2491,21 @@ describe('older links an admin can require confirming', () => {await expect(fetchUnconfirmedLinks(SERVER, 'b1')).rejects.toMatchObject({ status: 403 });});- it('requires confirming them, and says how many moved', async () => {- fetchMock.mockResolvedValue(jsonResponse({ moved: 3 }) as never);+ it('requires confirming the links named, and says how many moved', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ moved: 1 }) as never);- await expect(requireLinkConfirmation(SERVER, 'b1')).resolves.toBe(3);- const [url, init] = fetchMock.mock.calls[0] as unknown as [string, { method: string }];+ await expect(+ requireLinkConfirmation(SERVER, 'b1', [{ id: 'eu-1', userId: 'u-1' }])+ ).resolves.toBe(1);+ const [url, init] = fetchMock.mock.calls[0] as unknown as [+ string,+ { method: string; body: string },+ ];expect(url).toBe('https://switch.example.com/gateway/collaborations/b1/identities/require-confirmation');expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({ links: [{ id: 'eu-1', user_id: 'u-1' }] });});});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 b78b2387e..4af95c1dd 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@@ -2433,19 +2433,25 @@ export async function fetchUnconfirmedLinks(}/**- * Stop trusting a messaging app's older links until each owner confirms theirs- * (`POST /collaborations/{id}/identities/require-confirmation`). Admin only.- * Each becomes a link waiting for its code and stops counting at once. Returns- * how many moved.+ * Stop trusting these older links on a messaging app until each owner confirms+ * theirs (`POST /collaborations/{id}/identities/require-confirmation`). Admin+ * only. Only the links named move — the ones the admin was shown, not any that+ * appeared since — and each becomes a link waiting for its code, counting for+ * nothing at once. Returns how many moved.*/export async function requireLinkConfirmation(server: SwitchServer,- bridgeId: string+ bridgeId: string,+ links: readonly Pick<UnconfirmedLink, 'id' | 'userId'>[]): Promise<number> {const res = await gatewayFetch(server,`/collaborations/${encodeURIComponent(bridgeId)}/identities/require-confirmation`,- { authenticated: true, method: 'POST' }+ {+ authenticated: true,+ method: 'POST',+ body: { links: links.map((link) => ({ id: link.id, user_id: link.userId })) },+ });return ((await res.json()) as { moved: number }).moved;}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.tsindex e7a68d013..c3d6745f6 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.test.ts@@ -292,10 +292,12 @@ describe('cancelLinkRequestOnServer', () => {});describe('requireLinkConfirmationOnServer', () => {+ const SHOWN = [{ id: 'eu-1', userId: 'u-1' }];+it('says how many links now wait for their code', async () => {fetchMock.mockResolvedValue(response(200, { moved: 2 }));- await expect(requireLinkConfirmationOnServer(SERVER, 'b1')).resolves.toEqual({+ await expect(requireLinkConfirmationOnServer(SERVER, 'b1', SHOWN)).resolves.toEqual({kind: 'required',moved: 2,});@@ -304,7 +306,7 @@ describe('requireLinkConfirmationOnServer', () => {it('passes on the server’s reason when the caller is not an admin', async () => {fetchMock.mockResolvedValue(response(403, { detail: 'Workspace admin access required' }));- await expect(requireLinkConfirmationOnServer(SERVER, 'b1')).resolves.toEqual({+ await expect(requireLinkConfirmationOnServer(SERVER, 'b1', SHOWN)).resolves.toEqual({kind: 'refused',message: 'Workspace admin access required',});@@ -313,7 +315,7 @@ describe('requireLinkConfirmationOnServer', () => {it('passes on the server’s reason when the app is gone', async () => {fetchMock.mockResolvedValue(response(404, { detail: 'Bridge not found' }));- await expect(requireLinkConfirmationOnServer(SERVER, 'b1')).resolves.toEqual({+ await expect(requireLinkConfirmationOnServer(SERVER, 'b1', SHOWN)).resolves.toEqual({kind: 'refused',message: 'Bridge not found',});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.tsindex c27c55f1f..9f3988100 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/identities.ts@@ -16,6 +16,7 @@ import type {IssueLinkCodeResult,RequireLinkConfirmationResult,SwitchServer,+ UnconfirmedLink,} from '@shared/core/switch-servers/switch-servers';/**@@ -182,10 +183,14 @@ export async function cancelLinkRequestOnServer(*/export async function requireLinkConfirmationOnServer(server: SwitchServer,- bridgeId: string+ bridgeId: string,+ links: readonly Pick<UnconfirmedLink, 'id' | 'userId'>[]): Promise<RequireLinkConfirmationResult> {try {- return { kind: 'required', moved: await requireLinkConfirmation(server, bridgeId) };+ return {+ kind: 'required',+ moved: await requireLinkConfirmation(server, bridgeId, links),+ };} catch (cause) {if (cause instanceof GatewayError) {if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };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 6e00b08b9..369d1d4d2 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@@ -352,9 +352,15 @@ describe('linking a messaging account', () => {requireLinkConfirmationOnServer.mockResolvedValue({ kind: 'required', moved: 2 });await expect(- workspacesController.requireLinkConfirmation({ workspaceId: 'ws', bridgeId: 'b1' })+ workspacesController.requireLinkConfirmation({+ workspaceId: 'ws',+ bridgeId: 'b1',+ links: [{ id: 'eu-1', userId: 'u-1' }],+ })).resolves.toEqual({ kind: 'required', moved: 2 });- expect(requireLinkConfirmationOnServer).toHaveBeenCalledWith(expect.anything(), 'b1');+ expect(requireLinkConfirmationOnServer).toHaveBeenCalledWith(expect.anything(), 'b1', [+ { id: 'eu-1', userId: 'u-1' },+ ]);});it('reports a refused claim as a failure', async () => {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 b4198d4d9..5fd5abe29 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@@ -1097,9 +1097,11 @@ export const workspacesController = createRPCController({requireLinkConfirmation: (params: {workspaceId: string;bridgeId: string;+ /** The links the admin was shown; only these move. */+ links: Pick<UnconfirmedLink, 'id' | 'userId'>[];}): Promise<RequireLinkConfirmationResult> =>withReachableWorkspaceSession(params.workspaceId, (server) =>- requireLinkConfirmationOnServer(server, params.bridgeId)+ requireLinkConfirmationOnServer(server, params.bridgeId, params.links)),/** Withdraw the signed-in user's confirmation waiting on a code. A link thatdiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsxindex fa53e435b..db3588769 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RequireLinkConfirmationModal.tsx@@ -53,7 +53,12 @@ export const RequireLinkConfirmationModal = observer(function RequireLinkConfirmsetRequiring(true);setError(null);try {- const result = await rpc.workspaces.requireLinkConfirmation({ workspaceId, bridgeId });+ // Exactly the people listed here, not whoever is unconfirmed by now.+ const result = await rpc.workspaces.requireLinkConfirmation({+ workspaceId,+ bridgeId,+ links: (links ?? []).map((link) => ({ id: link.id, userId: link.userId })),+ });if (result.kind !== 'required') {setError(linkRequestFailureText(result));setRequiring(false);diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsxindex 6aea7c20d..b75b2c10e 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/require-link-confirmation-modal.test.tsx@@ -112,9 +112,14 @@ describe('requiring confirmation for older links', () => {await act(async () => button(el, 'Require confirmation')!.click());await settle();+ // Exactly the links listed: the admin agreed to these people.expect(requireLinkConfirmation).toHaveBeenCalledWith({workspaceId: 'ws-1',bridgeId: 'b-acme',+ links: [+ { id: 'eu-1', userId: 'u1' },+ { id: 'eu-2', userId: 'u2' },+ ],});expect(toast).toHaveBeenCalledWith({ title: '2 links now need confirming' });expect(invalidate).toHaveBeenCalledWith({ queryKey: myIdentitiesQueryKey('ws-1') });diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex ee0bf1fdb..84d44fa67 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -43,7 +43,7 @@ from switch_core.db.models import ()from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import AgentRuntimeStateStore-from switch_core.db.stores.external_user_store import NoSuchLink+from switch_core.db.stores.external_user_store import CodeNotAccepted, NoSuchLinkfrom switch_core.db.stores.session_activity_store import (RETRYABLE_TURN_STATUSES,AgentSessionActivityStore,@@ -1462,51 +1462,57 @@ async def _cmd_link_account()return+ # Replies wait until the session has closed: a rejected code may have+ # locked the request it was checked against, and nobody should wait on+ # that while a reply is written.+ refusal: str | None = Noneasync with host.session_factory() as session:account = await _sender_account(host, session, event)if account is None:- await _reply(- host,- room,- event,+ refusal = ("⚠️ Only a chat account can confirm a link to itself, by posting "- "the code from that account.",- )- return- request = await host._external_user_store.redeem_link_code(- session, account, code, host._user_store- )- if request is None:- await _reply(- host,- room,- event,- "⚠️ That code doesn't match a link waiting for this account, or "- "it has expired. Get a new code in Switch Console, and post it "- "from the account you're linking.",+ "the code from that account.")- return- user_id = request.user_id- linked = await host._user_store.get(session, user_id)- bridge = await session.get(CollaborationBridge, account.bridge_id)- # Both are held by foreign keys from the rows just written.- if linked is None or bridge is None:- raise RuntimeError(- f"Confirmed a link for user {user_id} on bridge "- f"{account.bridge_id}, but could not read either back"- )- name, platform = linked.name, bridge.display_name- username = account.external_username- await record_audit_event(- session,- tenant_id=account.tenant_id,- actor_user_id=user_id,- action=AuditAction.BRIDGE_IDENTITY_CLAIMED,- target_type="external_user",- target_id=account.id,- details={"bridge_id": account.bridge_id, "user_id": user_id, "by": "code"},- )- await session.commit()+ else:+ try:+ request = await host._external_user_store.redeem_link_code(+ session, account, code, host._user_store+ )+ except CodeNotAccepted:+ refusal = (+ "⚠️ That code doesn't match a link waiting for this account, "+ "or it has expired. Get a new code in Switch Console, and post "+ "it from the account you're linking."+ )+ else:+ user_id = request.user_id+ linked = await host._user_store.get(session, user_id)+ bridge = await session.get(CollaborationBridge, account.bridge_id)+ # Both are held by foreign keys from the rows just written.+ if linked is None or bridge is None:+ raise RuntimeError(+ f"Confirmed a link for user {user_id} on bridge "+ f"{account.bridge_id}, but could not read either back"+ )+ name, platform = linked.name, bridge.display_name+ username = account.external_username+ await record_audit_event(+ session,+ tenant_id=account.tenant_id,+ actor_user_id=user_id,+ action=AuditAction.BRIDGE_IDENTITY_CLAIMED,+ target_type="external_user",+ target_id=account.id,+ details={+ "bridge_id": account.bridge_id,+ "user_id": user_id,+ "by": "code",+ },+ )+ await session.commit()+ if refusal is not None:+ await _reply(host, room, event, refusal)+ return# Names the Switch user, so whoever posted it sees who the account is now# recognised as, and how to take that back if it is not them. "The way you@@ -1533,113 +1539,92 @@ async def _cmd_unlink_account("""host = cast("CommandConsumer", client)wanted = _strip_quotes((event.args or "").strip())-async with host.session_factory() as session:- account = await _sender_account(host, session, event)- if account is None:- await _reply(- host,- room,- event,- "⚠️ Only a chat account can unlink itself, from that account.",- )- return- claims = (- await host._external_user_store.claims_for(session, [account.id])- ).get(account.id, [])- users = {- user.id: user- for user in await session.scalars(- select(User).where(User.id.in_([c.user_id for c in claims]))- )- }- linked = sorted(- (- (users[c.user_id].name, users[c.user_id].email, c)- for c in claims- if c.user_id in users- ),- key=lambda entry: entry[0].casefold(),+ reply = await _unlink_account(host, session, event, wanted)+ # After the session has closed, so no lock is held while the reply is+ # written.+ await _reply(host, room, event, reply)+++async def _unlink_account(+ host: CommandConsumer, session: AsyncSession, event: CommandEvent, wanted: str+) -> str:+ """`!unlink-account`'s work, returning what to reply."""+ account = await _sender_account(host, session, event)+ if account is None:+ return "⚠️ Only a chat account can unlink itself, from that account."+ claims = (await host._external_user_store.claims_for(session, [account.id])).get(+ account.id, []+ )+ users = {+ user.id: user+ for user in await host._user_store.get_many(+ session, [c.user_id for c in claims])- listing = "\n".join(- f"- **{name}**"- + (- ""- if claim.verified_at is not None- else " (made before links needed confirming)"- )- for name, _email, claim in linked+ }+ linked = sorted(+ (+ (users[c.user_id].name, users[c.user_id].email, c)+ for c in claims+ if c.user_id in users+ ),+ key=lambda entry: entry[0].casefold(),+ )+ listing = "\n".join(+ f"- **{name}**"+ + (+ ""+ if claim.verified_at is not None+ else " (made before links needed confirming)")+ for name, _email, claim in linked+ )- if not wanted:- await _reply(- host,- room,- event,- (- f"This account is linked to:\n{listing}\n\nRun "- "`!unlink-account NAME` to remove one."- )- if linked- else "This account isn't linked to any Switch user.",- )- return-- needle = wanted.casefold()- matches = [- claim- for name, email, claim in linked- if needle in (name.casefold(), email.casefold())- ]- if not matches:- await _reply(- host,- room,- event,- f"⚠️ This account isn't linked to a Switch user called "- f"**{wanted}**." + (f" It is linked to:\n{listing}" if linked else ""),- )- return- if len(matches) > 1:- await _reply(- host,- room,- event,- f"⚠️ More than one Switch user linked to this account goes by "- f"**{wanted}**. Run `!unlink-account` with their email instead.",- )- return- user_id = matches[0].user_id- name = users[user_id].name- try:- await host._external_user_store.release(session, account, user_id)- except NoSuchLink:- # Unlinked some other way while this ran: the outcome asked for.- await _reply(- host,- room,- event,- f"This account is no longer linked to Switch user **{name}**.",- )- return- await record_audit_event(- session,- tenant_id=account.tenant_id,- actor_user_id=None,- action=AuditAction.BRIDGE_IDENTITY_RELEASED,- target_type="external_user",- target_id=account.id,- details={- "bridge_id": account.bridge_id,- "user_id": user_id,- "by": "chat_account",- },+ if not wanted:+ if not linked:+ return "This account isn't linked to any Switch user."+ return (+ f"This account is linked to:\n{listing}\n\nRun "+ "`!unlink-account NAME` to remove one.")- await session.commit()- await _reply(- host, room, event, f"Unlinked this account from Switch user **{name}**."+ needle = wanted.casefold()+ matches = [+ claim+ for name, email, claim in linked+ if needle in (name.casefold(), email.casefold())+ ]+ if not matches:+ return f"⚠️ This account isn't linked to a Switch user called **{wanted}**." + (+ f" It is linked to:\n{listing}" if linked else ""+ )+ if len(matches) > 1:+ return (+ f"⚠️ More than one Switch user linked to this account goes by "+ f"**{wanted}**. Run `!unlink-account` with their email instead."+ )+ user_id = matches[0].user_id+ name = users[user_id].name+ try:+ await host._external_user_store.release(session, account, user_id)+ except NoSuchLink:+ # Unlinked some other way while this ran: the outcome asked for.+ return f"This account is no longer linked to Switch user **{name}**."+ await record_audit_event(+ session,+ tenant_id=account.tenant_id,+ actor_user_id=None,+ action=AuditAction.BRIDGE_IDENTITY_RELEASED,+ target_type="external_user",+ target_id=account.id,+ details={+ "bridge_id": account.bridge_id,+ "user_id": user_id,+ "by": "chat_account",+ },)+ await session.commit()+ return f"Unlinked this account from Switch user **{name}**."async def _cmd_rename_agent(diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex bf6df78d5..11b33f298 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -895,6 +895,18 @@ class PlatformAdapter(ABC):"""return None+ async def account_unlinkable_reason(self, external_user_id: str) -> str | None:+ """Why this account cannot be linked to anyone, asking the platform+ where the id alone cannot tell, or None if it can be.++ A bot or an integration's account is one whoever runs it posts as, so+ linking it would recognise all of them as one Switch user. Some+ platforms say so in the id (`unlinkable_account_reason`); others only+ when asked. Raise `LookupError` when the platform has no such account,+ and `RuntimeError` when it cannot be asked.+ """+ return self.unlinkable_account_reason(external_user_id)+async def account_id_for_session(self, token: str) -> str:"""The platform id of the account a session token belongs to.diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 4eff30fef..d7ef0ed4d 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -1112,6 +1112,25 @@ class DiscordAdapter(PlatformAdapter):option = COMMANDS_BY_NAME["invite-agent"].args_spec[0].namereturn f"`/invite-agent {option}:agent-name` — the Discord slash command"+ async def account_unlinkable_reason(self, external_user_id: str) -> str | None:+ # Other bots and webhooks are bridged like people (see `_on_message`),+ # and the id alone does not say which is which.+ client = self._require_client()+ try:+ user = await client.fetch_user(int(external_user_id))+ except (ValueError, discord.NotFound):+ return (+ "This isn't a Discord user's account. It may be a webhook, which "+ "anyone holding its URL posts as."+ )+ except discord.HTTPException as e:+ raise RuntimeError(+ f"Could not ask Discord about account {external_user_id}: {e}"+ ) from e+ if user.bot or user.system:+ return "This is a Discord bot's account, which whoever runs it posts as."+ return None+@classmethoddef link_code_instructions(cls, code: str, connection_config: Mapping[str, object]diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 660d0e63b..7a3cd3244 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -639,18 +639,6 @@ class CollaborationBridgeLifecycleService:)return adapter_cls.link_code_instructions(code, connection_config)- def unlinkable_account_reason(- self, bridge_type: str, external_user_id: str- ) -> str | None:- """Why this account cannot be linked to anyone. See- `PlatformAdapter.unlinkable_account_reason`."""- adapter_cls = self._adapter_registry.get(bridge_type)- if adapter_cls is None:- raise ValueError(- f"No adapter is registered for bridge type {bridge_type!r}"- )- return adapter_cls.unlinkable_account_reason(external_user_id)-def renders_custom_url_schemes(self, bridge_type: str) -> bool:"""Whether this platform makes a `switchdash://` link clickable.diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex ebdf00184..4ed8afcda 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -357,15 +357,6 @@ def _close_loop(loop: asyncio.AbstractEventLoop) -> None:_WEBHOOK_STAND_IN_PREFIX = "webhook:"-def _webhook_stand_in_name(props: dict[str, Any]) -> str:- """What a webhook's posts are shown as: the name it posts under, marked as- a webhook so nobody reading the room takes it for a person."""- name = str(- props.get("override_username") or props.get("webhook_display_name") or ""- )- return f"{name} (webhook)" if name.strip() else "webhook"--class MattermostAdapter(PlatformAdapter):display_name: ClassVar[str] = "Mattermost"channel_on_delete = "archived"@@ -2813,24 +2804,26 @@ class MattermostAdapter(PlatformAdapter):raise RuntimeError("Cannot handle posted event: adapter not started")ws_loop = asyncio.get_event_loop()+ try:+ user = await ws_loop.run_in_executor(+ None, self._admin_driver.users.get_user, user_id+ )+ username: str = user.get("username", user_id)+ except Exception:+ logger.exception("Failed to resolve Mattermost user %s", user_id)+ username = user_idprops = post.get("props") or {}if str(props.get("from_webhook", "")).lower() == "true":# An incoming webhook's post (or a custom slash command's reply)# carries the user id of whoever set the integration up, though# anyone holding its URL may have sent it. It is the integration# talking, not that person, so it goes under a stand-in of its own- # that no link and no owner rule can match (CHOO-3881).+ # that no link and no owner rule can match (CHOO-3881). One per+ # person, named after them, since every webhook they set up posts+ # under their id and the name a post gives itself is the sender's+ # to choose.user_id = f"{_WEBHOOK_STAND_IN_PREFIX}{user_id}"- username = _webhook_stand_in_name(props)- else:- try:- user = await ws_loop.run_in_executor(- None, self._admin_driver.users.get_user, user_id- )- username = user.get("username", user_id)- except Exception:- logger.exception("Failed to resolve Mattermost user %s", user_id)- username = user_id+ username = f"{username}'s webhook"channel_type = self._to_channel_type(mm_channel_type)stripped = message.strip()@@ -3035,6 +3028,29 @@ class MattermostAdapter(PlatformAdapter):)return None+ async def account_unlinkable_reason(self, external_user_id: str) -> str | None:+ reason = self.unlinkable_account_reason(external_user_id)+ if reason is not None:+ return reason+ driver = self._admin_driver+ if driver is None:+ raise RuntimeError(+ "The Mattermost bridge is not started, so it cannot be asked"+ )+ try:+ user = await asyncio.to_thread(driver.users.get_user, external_user_id)+ except ResourceNotFound as e:+ raise LookupError(+ f"No Mattermost account {external_user_id} exists on this server"+ ) from e+ except sync_requests.RequestException as e:+ raise RuntimeError(+ f"Could not ask Mattermost about account {external_user_id}: {e}"+ ) from e+ if user.get("is_bot"):+ return "This is a Mattermost bot's account, which whoever runs it posts as."+ return None+async def account_id_for_session(self, token: str) -> str:driver = self._create_driver(token=token)try:diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex fe764cf9a..d86f83553 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -462,9 +462,10 @@ def _slack_failure_reason(exc: SlackApiError) -> FailureReason:return "platform_error"-# The ids Slack gives an app's bot, under which `_handle_message` bridges its-# posts. A person's id starts with U or W.+# The ids Slack gives an app's bot, under which an app's posts with no user are+# bridged. A person's id starts with U or W, but so does a bot user's._SLACK_BOT_ID = re.compile(r"^B[A-Z0-9]+$")+_SLACK_BOT_ACCOUNT = "This is a Slack app's or bot's account, which isn't one person's."class SlackAdapter(PlatformAdapter):@@ -1827,9 +1828,34 @@ class SlackAdapter(PlatformAdapter):# An app's or a bot's posts are bridged under its `bot_id` (`B…`), and# whoever can post through the app (a webhook, a workflow) posts as it.if external_user_id == "USLACKBOT" or _SLACK_BOT_ID.match(external_user_id):- return "This is a Slack app's or bot's account, which isn't one person's."+ return _SLACK_BOT_ACCOUNTreturn None+ async def account_unlinkable_reason(self, external_user_id: str) -> str | None:+ # An app posting with its bot token is bridged under its bot user's+ # `U…` id, which looks like a person's; only Slack can say otherwise.+ reason = self.unlinkable_account_reason(external_user_id)+ if reason is not None:+ return reason+ if self._web_client is None:+ raise RuntimeError("The Slack bridge is not started, so it cannot be asked")+ try:+ result = await self._web_client.users_info(user=external_user_id)+ except SlackApiError as e:+ if e.response.get("error") == "user_not_found":+ raise LookupError(+ f"No Slack account {external_user_id} exists on this workspace"+ ) from e+ raise RuntimeError(+ f"Could not ask Slack about account {external_user_id}: {e}"+ ) from e+ except (aiohttp.ClientError, TimeoutError) as e:+ raise RuntimeError(+ f"Could not reach Slack to ask about account {external_user_id}: {e}"+ ) from e+ user = result["user"]+ return _SLACK_BOT_ACCOUNT if user.get("is_bot") else None+async def admin_message(self,channel_id: str,diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex 592f7ebac..73179b91d 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -50,7 +50,9 @@ class AuditAction(StrEnum):BRIDGE_UPDATED = "collaboration_bridge.updated"BRIDGE_DEFAULT_SET = "collaboration_bridge.default_set"BRIDGE_DELETED = "collaboration_bridge.deleted"- # A claim took effect: since CHOO-3881, when the account confirmed a link.+ # A claim took effect. Once links needed confirming from the account+ # (CHOO-3881), that is when the account confirmed one, not when someone+ # asked for it (`BRIDGE_IDENTITY_LINK_REQUESTED`).BRIDGE_IDENTITY_CLAIMED = "collaboration_bridge.identity_claimed"BRIDGE_IDENTITY_LINK_REQUESTED = "collaboration_bridge.identity_link_requested"BRIDGE_IDENTITY_LINK_CANCELLED = "collaboration_bridge.identity_link_cancelled"diff --git a/core/switch_core/db/stores/external_user_store.py b/core/switch_core/db/stores/external_user_store.pyindex e2632c500..23bef55b9 100644--- a/core/switch_core/db/stores/external_user_store.py+++ b/core/switch_core/db/stores/external_user_store.py@@ -3,7 +3,7 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import Any, cast-from sqlalchemy import CursorResult, delete, func, literal, select+from sqlalchemy import CursorResult, delete, func, literal, select, tuple_from sqlalchemy.dialects.postgresql import insert as pg_insertfrom sqlalchemy.ext.asyncio import AsyncSession@@ -27,6 +27,11 @@ class NoSuchLink(LookupError):"""There was no link, or no waiting one, between this account and user."""+class CodeNotAccepted(LookupError):+ """A link code confirms nothing: not a code, wrong or expired for this+ account, or for someone no longer in the workspace."""++@dataclass(frozen=True)class LinkRelease:"""What unlinking dropped: a claim that counted, a request that was@@ -261,40 +266,61 @@ class ExternalUserStore:return [(external, claim) for external, claim in result.tuples()]async def require_confirmation(- self, session: AsyncSession, bridge_id: str, requested_by_user_id: str+ self,+ session: AsyncSession,+ bridge_id: str,+ links: list[tuple[str, str]],+ requested_by_user_id: str,) -> list[tuple[str, str]]:- """Stop trusting this bridge's claims made before links needed+ """Stop trusting these claims on this bridge, each an+ `(external_user_id, user_id)` pair made before links neededconfirming, turning each into a request its owner confirms with a- code. Returns the `(external_user_id, user_id)` pairs moved.+ code. Returns the pairs moved.++ Only the pairs named: an admin agrees to demote the people they were+ shown, and a claim that appeared since is left alone. A pair that has+ been confirmed since, or is on another bridge, is skipped. A request+ already waiting (its owner started confirming) is kept, code and all.- A request already waiting (its owner started confirming) is kept, code- and all. The requests are written before the claims go, the order a- confirmation takes the two in, so the two cannot deadlock.+ The requests are written before the claims go, the order a+ confirmation takes the two in, so the two cannot deadlock; and a claim+ is only deleted where its request now exists, so none is lost between+ the two statements."""- on_bridge = select(ExternalUser.id).where(ExternalUser.bridge_id == bridge_id)- unconfirmed = select(- ExternalUserClaim.tenant_id,- ExternalUserClaim.external_user_id,- ExternalUserClaim.user_id,- literal(requested_by_user_id),- ).where(- ExternalUserClaim.external_user_id.in_(on_bridge),- ExternalUserClaim.verified_at.is_(None),+ if not links:+ return []+ named = tuple_(+ ExternalUserClaim.external_user_id, ExternalUserClaim.user_id+ ).in_(links)+ on_bridge = ExternalUserClaim.external_user_id.in_(+ select(ExternalUser.id).where(ExternalUser.bridge_id == bridge_id))+ unconfirmed = ExternalUserClaim.verified_at.is_(None)await session.execute(pg_insert(ExternalUserLinkRequest).from_select(["tenant_id", "external_user_id", "user_id", "requested_by_user_id"],- unconfirmed,+ select(+ ExternalUserClaim.tenant_id,+ ExternalUserClaim.external_user_id,+ ExternalUserClaim.user_id,+ literal(requested_by_user_id),+ ).where(named, on_bridge, unconfirmed),).on_conflict_do_nothing(index_elements=["external_user_id", "user_id"]))- moved = await session.execute(- delete(ExternalUserClaim)+ waiting = (+ select(ExternalUserLinkRequest.external_user_id).where(- ExternalUserClaim.external_user_id.in_(on_bridge),- ExternalUserClaim.verified_at.is_(None),+ ExternalUserLinkRequest.external_user_id+ == ExternalUserClaim.external_user_id,+ ExternalUserLinkRequest.user_id == ExternalUserClaim.user_id,)+ .exists()+ )+ moved = await session.execute(+ delete(ExternalUserClaim)+ .where(named, on_bridge, unconfirmed, waiting).returning(ExternalUserClaim.external_user_id, ExternalUserClaim.user_id))pairs = [(external_user_id, user_id) for external_user_id, user_id in moved]@@ -313,8 +339,9 @@ class ExternalUserStore:"""Start linking this account to a Switch user, pending the account'sconfirmation.- Asking again keeps the request that is already waiting, code and all,- and only records who asked most recently.+ Asking again keeps the request that is already waiting, code, who+ started it and all: the person shown as having started a link is the+ one who did."""await session.execute(pg_insert(ExternalUserLinkRequest)@@ -323,10 +350,7 @@ class ExternalUserStore:user_id=switch_user_id,requested_by_user_id=requested_by_user_id,)- .on_conflict_do_update(- index_elements=["external_user_id", "user_id"],- set_={"requested_by_user_id": requested_by_user_id},- )+ .on_conflict_do_nothing(index_elements=["external_user_id", "user_id"]))await session.flush()request = await session.get(@@ -440,14 +464,14 @@ class ExternalUserStore:external_user: ExternalUser,code: str,user_store: UserStore,- ) -> ExternalUserLinkRequest | None:+ ) -> ExternalUserLinkRequest:"""Confirm the link this code was issued for, if it was issued forthis account, has not expired, and is for someone who still stands inthe workspace.The request becomes a verified claim, upgrading an unverified one in- place. None when nothing matches, which the caller reports without- saying which part was wrong.+ place. Raises `CodeNotAccepted` when nothing matches, which the caller+ reports without saying which part was wrong.Standing is checked here as well as when the link was started, becausea request outlives a member's removal from the workspace and the claim@@ -458,7 +482,7 @@ class ExternalUserStore:"""normalised = normalise_link_code(code)if normalised is None:- return None+ raise CodeNotAccepted("That is not a link code")result = await session.execute(select(ExternalUserLinkRequest).where(@@ -471,14 +495,18 @@ class ExternalUserStore:)request = result.scalar_one_or_none()if request is None:- return None+ raise CodeNotAccepted(+ f"No unexpired code like that is waiting for account {external_user.id}"+ )if (await user_store.effective_tenant_role(session, request.tenant_id, request.user_id)is None):- return None+ raise CodeNotAccepted(+ f"User {request.user_id} no longer stands in the workspace"+ )await self.confirm_link_request(session, request)return requestdiff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 2619d0f44..441563c24 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -421,6 +421,16 @@ class UserStore:result = await session.execute(select(User))return list(result.scalars().all())+ async def get_many(+ self, session: AsyncSession, user_ids: Collection[str]+ ) -> list[User]:+ """The users with these ids, in one query; ids with no user are left+ out."""+ if not user_ids:+ return []+ result = await session.execute(select(User).where(User.id.in_(user_ids)))+ return list(result.scalars().all())+async def add_membership(self,session: AsyncSession,diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 6ef6a9ea4..c8b584707 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -76,6 +76,7 @@ from switch_core.gateway.schemas import (IdentityClaimant,LinkCode,LinkRequestSummary,+ RequireConfirmationRequest,RequireConfirmationResult,SlackOwnAppSetup,SlackTokensCheck,@@ -636,7 +637,7 @@ async def _user_names(wanted = {claim.user_id for found in claims.values() for claim in found}if not wanted:return {}- return {u.id: u.name for u in await user_store.get_all(session) if u.id in wanted}+ return {u.id: u.name for u in await user_store.get_many(session, wanted)}def _claimants(@@ -893,7 +894,9 @@ async def claim_bridge_identity(raise HTTPException(status_code=404, detail="Switch user not found")bridge_type, connection_config = bridge.type, bridge.connection_config or {}- _refuse_unlinkable(collab_lifecycle, bridge_type, payload.external_user_id)+ # Not held across asking the platform.+ await session.commit()+ await _refuse_unlinkable(collab_lifecycle, bridge_id, payload.external_user_id)external_user = await external_user_store.get_by_external_id(session, bridge_id, payload.external_user_id@@ -1047,18 +1050,37 @@ async def _identity_on_bridge(return external_user-def _refuse_unlinkable(+async def _unlinkable_reason(collab_lifecycle: CollaborationBridgeLifecycleService,- bridge_type: str,+ bridge_id: str,+ external_user_id: str,+) -> str | None:+ """Why the account cannot be linked, asking the platform. Call holding no+ connection: it may wait on the platform."""+ adapter = collab_lifecycle.get_adapter(bridge_id)+ if adapter is None:+ raise HTTPException(+ status_code=409,+ detail="Bridge is not running — cannot check this account",+ )+ try:+ return await adapter.account_unlinkable_reason(external_user_id)+ except LookupError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e+ except RuntimeError as e:+ raise HTTPException(status_code=502, detail=str(e)) from e+++async def _refuse_unlinkable(+ collab_lifecycle: CollaborationBridgeLifecycleService,+ bridge_id: str,external_user_id: str,) -> None:- unlinkable = collab_lifecycle.unlinkable_account_reason(- bridge_type, external_user_id- )- if unlinkable is not None:+ reason = await _unlinkable_reason(collab_lifecycle, bridge_id, external_user_id)+ if reason is not None:raise HTTPException(status_code=409,- detail=f"This account cannot be linked to anyone. {unlinkable}",+ detail=f"This account cannot be linked to anyone. {reason}",)@@ -1102,7 +1124,26 @@ async def issue_identity_link_code(external_user = await _identity_on_bridge(session, external_user_store, bridge_id, external_user_row_id)- _refuse_unlinkable(collab_lifecycle, bridge.type, external_user.external_user_id)+ bridge_type, connection_config = bridge.type, bridge.connection_config or {}+ external_account_id = external_user.external_user_id+ # Not held across asking the platform.+ await session.commit()+ unlinkable = await _unlinkable_reason(+ collab_lifecycle, bridge_id, external_account_id+ )+ if unlinkable is not None:+ # A link made before links needed confirming may point at such an+ # account. It cannot be confirmed, and must not go on counting.+ removed = await _drop_older_link(+ session, external_user_store, external_user, caller_id, bridge_id+ )+ raise HTTPException(+ status_code=409,+ detail=(+ f"This account cannot be linked to anyone. {unlinkable}"+ + (" Your earlier link to it has been removed." if removed else "")+ ),+ )# Locked first, so a code posted at this moment is either redeemed before# this reads the claim or waits for the new code to replace it.request = await external_user_store.lock_link_request(@@ -1136,13 +1177,43 @@ async def issue_identity_link_code(external_user_store,collab_lifecycle,request,- bridge_type=bridge.type,- connection_config=bridge.connection_config or {},+ bridge_type=bridge_type,+ connection_config=connection_config,)await session.commit()return code+async def _drop_older_link(+ session: AsyncSession,+ external_user_store: ExternalUserStore,+ external_user: ExternalUser,+ user_id: str,+ bridge_id: str,+) -> bool:+ """Remove `user_id`'s link to this account if it is one made before links+ needed confirming, and say whether there was one."""+ claim = await external_user_store.get_claim(session, external_user.id, user_id)+ if claim is None or claim.verified_at is not None:+ return False+ try:+ await external_user_store.release(session, external_user, user_id)+ except NoSuchLink:+ # Unlinked another way since it was read, which is the outcome wanted.+ return False+ await record_audit_event(+ session,+ tenant_id=external_user.tenant_id,+ actor_user_id=user_id,+ action=AuditAction.BRIDGE_IDENTITY_RELEASED,+ target_type="external_user",+ target_id=external_user.id,+ details={"bridge_id": bridge_id, "user_id": user_id, "by": "unlinkable"},+ )+ await session.commit()+ return True++@router.post("/{bridge_id}/identities/{external_user_row_id}/verify-session")async def verify_identity_with_session(bridge_id: str,@@ -1196,6 +1267,25 @@ async def verify_identity_with_session(status_code=403,detail="That session token belongs to a different account",)+ # A session proves who holds the account, not that one person does: a+ # bot's token is as good a proof as a person's, and its account is one+ # whoever runs it posts as. Such a link can never count, so it goes.+ unlinkable = await _unlinkable_reason(+ collab_lifecycle, bridge_id, external_user.external_user_id+ )+ if unlinkable is not None:+ try:+ await external_user_store.cancel_link_request(+ session, external_user, caller_id+ )+ except NoSuchLink:+ pass+ else:+ await session.commit()+ raise HTTPException(+ status_code=409,+ detail=f"This account cannot be linked to anyone. {unlinkable}",+ )request = await external_user_store.lock_link_request(session, external_user.id, caller_id@@ -1257,6 +1347,7 @@ async def list_unconfirmed_identity_links(@router.post("/{bridge_id}/identities/require-confirmation")async def require_identity_confirmation(bridge_id: str,+ payload: RequireConfirmationRequest,session: Annotated[AsyncSession, Depends(get_session)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],@@ -1268,14 +1359,19 @@ async def require_identity_confirmation(Each becomes a link waiting for its account, as if its owner had juststarted it, so it counts for nothing until then. Their owner-only agentsstop recognising them in the meantime, which is the point and what an- admin is told before running it. Links already confirmed, and other- bridges, are untouched; running it again moves nothing.+ admin is told before running it. Only the links named are moved: the+ ones the admin was shown, not any that appeared since. Links already+ confirmed, and other bridges, are untouched; running it again moves+ nothing."""bridge = await bridge_store.get(session, bridge_id)if bridge is None:raise HTTPException(status_code=404, detail="Bridge not found")moved = await external_user_store.require_confirmation(- session, bridge_id, requested_by_user_id=admin.id+ session,+ bridge_id,+ [(link.id, link.user_id) for link in payload.links],+ requested_by_user_id=admin.id,)await record_audit_event(session,diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 60aab4ba2..fac1d44ee 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -875,6 +875,19 @@ class UnconfirmedLink(BaseModel):user_name: str+class UnconfirmedLinkRef(BaseModel):+ # The `ExternalUser` row id and the Switch user, as `UnconfirmedLink` names+ # them.+ id: str+ user_id: str+++class RequireConfirmationRequest(BaseModel):+ """The older links an admin was shown and agrees to stop trusting."""++ links: list[UnconfirmedLinkRef]++class RequireConfirmationResult(BaseModel):# How many links stopped counting and now wait for their owners' codes.moved: intdiff --git a/core/switch_core/migrations/versions/22e1d92cfd4c_drop_links_to_shared_accounts.py b/core/switch_core/migrations/versions/22e1d92cfd4c_drop_links_to_shared_accounts.pynew file mode 100644index 000000000..4dd92ab7a--- /dev/null+++ b/core/switch_core/migrations/versions/22e1d92cfd4c_drop_links_to_shared_accounts.py@@ -0,0 +1,72 @@+"""drop older links to accounts many people post as++`3b81c0e5d9a7` made links wait for the account to confirm them and kept the+ones that already existed working, unverified. Some of those are on accounts+that from now on cannot be linked to anyone: Telegram's stand-ins for anonymous+group admins, for posts made as a channel and for its own service account, and+Slack's app and bot ids. Each recognises everyone posting as that account as+the claimant, and none could ever be confirmed, so this revision deletes them+rather than leave them counting. It deletes any link to one of them still+waiting for its code as well (an admin's "require confirmation" makes one of+an older link): none of those could be confirmed either, and a code issued+for one before this revision would otherwise go on working until it expired.++The ids are copied from the adapters as they stood (the Telegram and Slack+`unlinkable_account_reason`), not imported, so a later edit to an adapter+cannot change what this revision did. A bot that Slack files under a `U…` id,+like Discord's and Mattermost's bots, takes asking the platform; those older+links are left to the confirmation flow, which refuses them and removes the+link when their owner asks for a code. Nothing restores them on downgrade.++Expand only: it deletes rows, and a release from before it reads the table as+it always did.++Revision ID: 22e1d92cfd4c+Revises: 3b81c0e5d9a7+Create Date: 2026-11-02 18:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "22e1d92cfd4c"+down_revision: str | None = "3b81c0e5d9a7"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++# The accounts many people post as, by the id alone.+SHARED_ACCOUNTS = """+SELECT account.id+FROM external_users AS account+JOIN collaboration_bridges AS bridge ON bridge.id = account.bridge_id+WHERE (bridge.type = 'telegram'+ AND account.external_user_id IN ('1087968824', '136817688', '777000'))+ OR (bridge.type = 'slack'+ AND (account.external_user_id = 'USLACKBOT'+ OR account.external_user_id ~ '^B[A-Z0-9]+$'))+"""++# Requests first, the order a confirmation takes the two tables in.+PURGE_SHARED_ACCOUNT_REQUESTS = f"""+DELETE FROM external_user_link_requests+WHERE external_user_id IN ({SHARED_ACCOUNTS})+"""++PURGE_SHARED_ACCOUNT_CLAIMS = f"""+DELETE FROM external_user_claims+WHERE verified_at IS NULL+ AND external_user_id IN ({SHARED_ACCOUNTS})+"""+++def upgrade() -> None:+ op.execute(PURGE_SHARED_ACCOUNT_REQUESTS)+ op.execute(PURGE_SHARED_ACCOUNT_CLAIMS)+++def downgrade() -> None:+ # The links deleted were never confirmable; nothing to put back.+ passdiff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.pyindex 5ca154f55..64ac963ca 100644--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.py+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_webhook_posts.py@@ -96,7 +96,8 @@ def test_a_webhook_post_goes_under_a_stand_in_not_its_creator() -> None:[message] = receivedassert isinstance(message, InboundMessage)assert message.sender_id == f"webhook:{_CREATOR}"- assert message.sender_name == "ci (webhook)"+ # Named after the person who set it up, not the name the post claims.+ assert message.sender_name == "ada's webhook"def test_a_command_from_a_webhook_is_not_the_creators() -> None:@@ -108,7 +109,7 @@ def test_a_command_from_a_webhook_is_not_the_creators() -> None:assert isinstance(command, InboundCommand)assert command.command == "unlink-account"assert command.sender_id == f"webhook:{_CREATOR}"- assert command.sender_name == "webhook"+ assert command.sender_name == "ada's webhook"def test_the_stand_in_cannot_be_linked() -> None:diff --git a/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.py b/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.pyindex bedd4f20b..509bede3b 100644--- a/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.py+++ b/core/tests/switch_core/bridges/collaboration/test_unlinkable_accounts.py@@ -1,12 +1,31 @@"""Accounts several people post as cannot be linked to one Switch user-(CHOO-3881)."""+(CHOO-3881): some tell by their id, others only when the platform is asked."""from __future__ import annotations+import asyncio+from types import SimpleNamespace+from typing import Any++import aiohttp+import discordimport pytest+from mattermostdriver.exceptions import ResourceNotFound+from slack_sdk.errors import SlackApiErrorfrom switch_core.bridges.collaboration.adapter import PlatformAdapter-from switch_core.bridges.collaboration.slack.adapter import SlackAdapter+from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)from switch_core.bridges.collaboration.telegram.adapter import TelegramAdapter@@ -31,3 +50,131 @@ def test_a_slack_person_can_be_linked(account: str) -> None:def test_by_default_any_account_can_be_linked() -> None:assert PlatformAdapter.unlinkable_account_reason("anyone") is None+++# ── Asking the platform ─────────────────────────────────────────────────────+++class _SlackClient:+ def __init__(self, users: dict[str, dict[str, object]]) -> None:+ self._users = users++ async def users_info(self, *, user: str) -> dict[str, object]:+ if user == "U0DOWN":+ raise aiohttp.ClientConnectionError("connection reset")+ if user not in self._users:+ raise SlackApiError(+ "user_not_found", {"ok": False, "error": "user_not_found"}+ )+ return {"user": self._users[user]}+++def _slack(users: dict[str, dict[str, object]]) -> SlackAdapter:+ adapter = SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test", app_token="xapp-test", workspace_id="T123"+ )+ )+ adapter._web_client = _SlackClient(users) # type: ignore[assignment]+ return adapter+++def _run(coro: Any) -> Any:+ return asyncio.run(coro)+++def test_a_slack_bot_user_is_refused_though_its_id_looks_like_a_persons() -> None:+ # An app posting with its bot token is bridged under its bot user's U-id.+ adapter = _slack({"U0BOT": {"id": "U0BOT", "is_bot": True}})+ assert _run(adapter.account_unlinkable_reason("U0BOT")) is not None+++def test_a_slack_person_is_linkable_when_asked() -> None:+ adapter = _slack({"U0ADA": {"id": "U0ADA", "is_bot": False}})+ assert _run(adapter.account_unlinkable_reason("U0ADA")) is None+++def test_a_slack_account_slack_does_not_know_is_not_found() -> None:+ with pytest.raises(LookupError):+ _run(_slack({}).account_unlinkable_reason("U0TYPO"))+++def test_slack_out_of_reach_is_a_runtime_error() -> None:+ with pytest.raises(RuntimeError):+ _run(_slack({}).account_unlinkable_reason("U0DOWN"))+++def test_a_slack_bot_id_is_refused_without_asking() -> None:+ adapter = _slack({})+ assert _run(adapter.account_unlinkable_reason("B0123ABCD")) is not None+++class _MattermostUsers:+ def __init__(self, users: dict[str, dict[str, object]]) -> None:+ self._users = users++ def get_user(self, user_id: str) -> dict[str, object]:+ if user_id not in self._users:+ raise ResourceNotFound("Unable to find the user.")+ return self._users[user_id]+++def _mattermost(users: dict[str, dict[str, object]]) -> MattermostAdapter:+ adapter = MattermostAdapter(+ config=MattermostConnectionConfig(+ url="http://mm", admin_user="admin", admin_password="pw", team_name="t"+ )+ )+ adapter._admin_driver = type("_Driver", (), {"users": _MattermostUsers(users)})() # type: ignore[assignment]+ return adapter+++def test_a_mattermost_bot_is_refused() -> None:+ adapter = _mattermost({"bot1": {"id": "bot1", "is_bot": True}})+ assert _run(adapter.account_unlinkable_reason("bot1")) is not None+++def test_a_mattermost_account_the_server_does_not_know_is_not_found() -> None:+ with pytest.raises(LookupError):+ _run(_mattermost({}).account_unlinkable_reason("typo"))+++def test_a_mattermost_person_is_linkable_when_asked() -> None:+ adapter = _mattermost({"ada1": {"id": "ada1", "is_bot": False}})+ assert _run(adapter.account_unlinkable_reason("ada1")) is None+++class _DiscordClient:+ def __init__(self, users: dict[int, Any]) -> None:+ self._users = users++ async def fetch_user(self, user_id: int) -> Any:+ if user_id not in self._users:+ raise discord.NotFound(+ SimpleNamespace(status=404, reason="Not Found"), "Unknown User"+ )+ return self._users[user_id]+++def _discord(users: dict[int, Any]) -> DiscordAdapter:+ adapter = DiscordAdapter(+ config=DiscordConnectionConfig(bot_token="token", guild_id="1")+ )+ adapter._connection._client = _DiscordClient(users) # type: ignore[union-attr,assignment]+ return adapter+++def test_a_discord_bot_is_refused() -> None:+ adapter = _discord({42: SimpleNamespace(bot=True, system=False)})+ assert _run(adapter.account_unlinkable_reason("42")) is not None+++def test_a_discord_webhook_is_refused() -> None:+ # A webhook's posts carry the webhook's id, which no user has.+ adapter = _discord({})+ assert _run(adapter.account_unlinkable_reason("777")) is not None+++def test_a_discord_person_is_linkable_when_asked() -> None:+ adapter = _discord({42: SimpleNamespace(bot=False, system=False)})+ assert _run(adapter.account_unlinkable_reason("42")) is Nonediff --git a/core/tests/switch_core/db/stores/test_external_user_claims.py b/core/tests/switch_core/db/stores/test_external_user_claims.pyindex ad41d2927..2c0c29a07 100644--- a/core/tests/switch_core/db/stores/test_external_user_claims.py+++ b/core/tests/switch_core/db/stores/test_external_user_claims.py@@ -30,6 +30,7 @@ from switch_core.db.models import (User,)from switch_core.db.stores.external_user_store import (+ CodeNotAccepted,ExternalUserStore,LinkRelease,NoSuchLink,@@ -388,18 +389,13 @@ class TestLinkRequests:session, account, user_id, requested_by_user_id=user_id)code, _expires = await _STORE.issue_link_code(session, request)- assert (- await _STORE.redeem_link_code(session, account, code, UserStore())- is not None- )+ await _STORE.redeem_link_code(session, account, code, UserStore())await _STORE.release(session, account, user_id)await session.commit()async with session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session, account, code, UserStore())- is None- )assert await _STORE.claimant_ids(session, account.id) == []async def test_the_code_from_another_account_confirms_nothing(@@ -421,10 +417,8 @@ class TestLinkRequests:await session.commit()async with session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session, bystander, code, UserStore())- is None- )await session.commit()async with session_factory() as session:@@ -447,10 +441,8 @@ class TestLinkRequests:await session.commit()async with session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session, account, code, UserStore())- is None- )assert await _STORE.claimant_ids(session, account.id) == []async def test_a_new_code_replaces_the_old_one(@@ -468,14 +460,9 @@ class TestLinkRequests:await session.commit()async with session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session, account, old, UserStore())- is None- )- assert (- await _STORE.redeem_link_code(session, account, new, UserStore())- is not None- )+ await _STORE.redeem_link_code(session, account, new, UserStore())async def test_text_that_cannot_be_a_code_confirms_nothing(self, session_factory: async_sessionmaker[AsyncSession]@@ -492,10 +479,8 @@ class TestLinkRequests:async with session_factory() as session:for text in ("", "hello", "@ABCD-EFGH", "ABCD-EFGH-JKMN"):- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session, account, text, UserStore())- is None- )async def test_confirming_upgrades_an_unverified_claim(self, session_factory: async_sessionmaker[AsyncSession]@@ -515,10 +500,7 @@ class TestLinkRequests:await session.commit()async with session_factory() as session:- assert (- await _STORE.redeem_link_code(session, account, code, UserStore())- is not None- )+ await _STORE.redeem_link_code(session, account, code, UserStore())await session.commit()async with session_factory() as session:@@ -536,8 +518,8 @@ class TestLinkRequests:async def test_asking_again_keeps_the_waiting_code(self, session_factory: async_sessionmaker[AsyncSession]) -> None:- # A second "This is me" must not invalidate a code someone is already- # about to post; only asking for a new code does.+ # A second "This is me", or an admin's, must not invalidate a code+ # someone is already about to post; only asking for a new code does.async with session_factory() as session:bridge_id = await _make_bridge(session)account = await _make_external_user(session, bridge_id=bridge_id)@@ -550,14 +532,12 @@ class TestLinkRequests:again = await _STORE.request_link(session, account, user_id, requested_by_user_id=admin_id)- assert again.requested_by_user_id == admin_id+ # Whoever started it stays its starter.+ assert again.requested_by_user_id == user_idawait session.commit()async with session_factory() as session:- assert (- await _STORE.redeem_link_code(session, account, code, UserStore())- is not None- )+ await _STORE.redeem_link_code(session, account, code, UserStore())async def test_release_cancels_a_waiting_request(self, session_factory: async_sessionmaker[AsyncSession]@@ -581,10 +561,8 @@ class TestLinkRequests:async with session_factory() as session:with pytest.raises(NoSuchLink):await _STORE.release(session, account, user_id)- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session, account, code, UserStore())- is None- )async def test_deleting_the_switch_user_drops_their_requests(self, session_factory: async_sessionmaker[AsyncSession]diff --git a/core/tests/switch_core/gateway/test_claim_identity_membership.py b/core/tests/switch_core/gateway/test_claim_identity_membership.pyindex 0b49ed7f9..5fc2095be 100644--- a/core/tests/switch_core/gateway/test_claim_identity_membership.py+++ b/core/tests/switch_core/gateway/test_claim_identity_membership.py@@ -36,12 +36,13 @@ _EXTERNAL_USERS = ExternalUserStore()class _Lifecycle:- """The bridge-type questions a claim asks, for a platform with no- stand-in accounts."""+ """What a claim asks of a running bridge, for a platform where any account+ can be linked."""- def unlinkable_account_reason(- self, _bridge_type: str, _external_user_id: str- ) -> None:+ def get_adapter(self, _bridge_id: str) -> _Lifecycle:+ return self++ async def account_unlinkable_reason(self, _external_user_id: str) -> None:return Nonedef link_code_instructions(@@ -199,9 +200,7 @@ class _ProvisioningLifecycle:def get(self, _bridge_id: str) -> _ProvisioningLifecycle:return self- def unlinkable_account_reason(- self, _bridge_type: str, _external_user_id: str- ) -> None:+ async def account_unlinkable_reason(self, _external_user_id: str) -> None:return Nonedef link_code_instructions(diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.pyindex 5296a8a1b..e7e2fa805 100644--- a/core/tests/switch_core/gateway/test_held_connections.py+++ b/core/tests/switch_core/gateway/test_held_connections.py@@ -124,6 +124,10 @@ class _Adapter:def __init__(self, calls: _Calls) -> None:self._calls = calls+ async def account_unlinkable_reason(self, external_user_id: str) -> str | None:+ self._calls.record("platform account check")+ return None+async def search_directory_users(self, query: str) -> list[Any]:self._calls.record("platform directory search")return [@@ -594,6 +598,7 @@ class TestBridgeRoutes:"platform edit check","bridge restart","platform directory search",+ "platform account check","platform directory search","provision external user","bridge remove",diff --git a/core/tests/switch_core/gateway/test_identity_link_confirmation.py b/core/tests/switch_core/gateway/test_identity_link_confirmation.pyindex 50fc3d2e0..d2bab61b5 100644--- a/core/tests/switch_core/gateway/test_identity_link_confirmation.py+++ b/core/tests/switch_core/gateway/test_identity_link_confirmation.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport uuidfrom collections.abc import Awaitable, Callablefrom datetime import datetime+from types import SimpleNamespaceimport pytestfrom fastapi import HTTPException@@ -30,10 +31,15 @@ from switch_core.db.models import (User,)from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore-from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.external_user_store import (+ CodeNotAccepted,+ ExternalUserStore,+ NoSuchLink,+)from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth_routes import my_identities, my_pending_identitiesfrom switch_core.gateway.collaborations import (+ _drop_older_link,cancel_identity_link_request,claim_bridge_identity,issue_identity_link_code,@@ -44,11 +50,14 @@ from switch_core.gateway.collaborations import ()from switch_core.gateway.schemas import (ClaimIdentityRequest,+ RequireConfirmationRequest,+ UnconfirmedLinkRef,VerifyIdentitySessionRequest,)_STORE = ExternalUserStore()_STAND_IN = "stand-in"+_NOBODY = "U-nobody"class _Adapter:@@ -60,6 +69,11 @@ class _Adapter:self._session_owner = session_ownerself._meanwhile = meanwhile+ async def account_unlinkable_reason(self, external_user_id: str) -> str | None:+ if external_user_id == _NOBODY:+ raise LookupError("No such account")+ return "Many people post as it." if external_user_id == _STAND_IN else None+async def account_id_for_session(self, _token: str) -> str:if self._meanwhile is not None:await self._meanwhile()@@ -70,19 +84,14 @@ class _Adapter:class _Lifecycle:def __init__(self, adapter: _Adapter | None = None) -> None:- self._adapter = adapter-- def unlinkable_account_reason(- self, _bridge_type: str, external_user_id: str- ) -> str | None:- return "Many people post as it." if external_user_id == _STAND_IN else None+ self._adapter = adapter or _Adapter("U-ada")def link_code_instructions(self, bridge_type: str, _connection_config: object, code: str) -> str:return f"On {bridge_type}, post `!link-account {code}`."- def get_adapter(self, _bridge_id: str) -> _Adapter | None:+ def get_adapter(self, _bridge_id: str) -> _Adapter:return self._adapter@@ -252,6 +261,14 @@ class TestClaimWaitsForTheAccount:for c in again.claimed_by # type: ignore[attr-defined]] == [(world.ada.id, True)]+ async def test_an_account_the_platform_has_never_heard_of_is_a_404(+ self, world: _World+ ) -> None:+ with pytest.raises(HTTPException) as refused:+ await _claim(world, world.ada, external_user_id=_NOBODY)++ assert refused.value.status_code == 404+async def test_a_console_from_before_confirmation_is_told_to_update(self, world: _World) -> None:@@ -284,15 +301,13 @@ class TestIssuingACode:assert code.code != first.link_request.code.code # type: ignore[attr-defined]async with world.session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session,world.account,first.link_request.code.code, # type: ignore[attr-defined]UserStore(),)- is None- )assert await _STORE.redeem_link_code(session,world.account,@@ -365,15 +380,13 @@ class TestIssuingACode:await session.commit()async with world.session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session,world.account,summary.link_request.code.code, # type: ignore[attr-defined]UserStore(),)- is None- )assert await _claim_of(world, world.ada) is Noneasync def test_an_organization_admin_with_no_membership_can_confirm(@@ -406,6 +419,37 @@ class TestIssuingACode:await session.commit()assert await _claim_of(world, carol) is not None+ async def test_an_older_link_to_an_unlinkable_account_is_removed(+ self, world: _World+ ) -> None:+ # It could never be confirmed, and must not go on counting.+ async with world.session_factory() as session:+ stand_in = await _STORE.get_by_external_id(+ session, world.bridge_id, _STAND_IN+ )+ assert stand_in is not None+ session.add(+ ExternalUserClaim(external_user_id=stand_in.id, user_id=world.ada.id)+ )+ await session.commit()++ async with world.session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await issue_identity_link_code(+ world.bridge_id,+ stand_in.id,+ session,+ CollaborationBridgeStore(),+ _STORE,+ _Lifecycle(), # type: ignore[arg-type]+ world.ada,+ )++ assert refused.value.status_code == 409+ assert "Your earlier link to it has been removed." in refused.value.detail+ async with world.session_factory() as session:+ assert await _STORE.claimant_ids(session, stand_in.id) == []+async def test_a_confirmed_link_needs_no_code(self, world: _World) -> None:summary = await _claim(world, world.ada)async with world.session_factory() as session:@@ -482,6 +526,43 @@ class TestVerifyingWithASession:assert refused.value.status_code == 409assert await _claim_of(world, world.ada) is None+ async def test_a_bots_own_session_cannot_confirm_a_link_to_it(+ self, world: _World+ ) -> None:+ # A session proves who holds the account, not that one person does:+ # a bot's token would otherwise confirm a link to the bot.+ async with world.session_factory() as session:+ stand_in = await _STORE.get_by_external_id(+ session, world.bridge_id, _STAND_IN+ )+ assert stand_in is not None+ await _STORE.request_link(+ session, stand_in, world.ada.id, requested_by_user_id=world.bob.id+ )+ await session.commit()++ async with world.session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await verify_identity_with_session(+ world.bridge_id,+ stand_in.id,+ VerifyIdentitySessionRequest(token="bot-token"),+ session,+ _STORE,+ UserStore(),+ _Lifecycle(_Adapter(_STAND_IN)), # type: ignore[arg-type]+ world.ada,+ )++ assert refused.value.status_code == 409+ async with world.session_factory() as session:+ assert await _STORE.claimant_ids(session, stand_in.id) == []+ # It could never be confirmed, so it does not wait.+ assert (+ await _STORE.get_link_request(session, stand_in.id, world.ada.id)+ is None+ )+async def test_there_must_be_a_link_waiting(self, world: _World) -> None:with pytest.raises(HTTPException) as refused:await _verify(world, world.ada, _Adapter("U-ada"))@@ -510,15 +591,13 @@ class TestCancelling:await _STORE.get_link_request(session, world.account.id, world.ada.id)is None)- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session,world.account,summary.link_request.code.code, # type: ignore[attr-defined]UserStore(),)- is None- )async def test_cancelling_a_confirmation_keeps_an_older_link(self, world: _World@@ -546,15 +625,13 @@ class TestCancelling:claim = await _claim_of(world, world.ada)assert claim is not None and claim.verified_at is Noneasync with world.session_factory() as session:- assert (+ with pytest.raises(CodeNotAccepted):await _STORE.redeem_link_code(session,world.account,code.code, # type: ignore[attr-defined]UserStore(),)- is None- )async def test_cancelling_with_nothing_waiting_is_a_404(self, world: _World@@ -715,10 +792,20 @@ class TestRequiringConfirmationForOlderLinks:))- async def _require(self, world: _World) -> int:+ async def _require(+ self, world: _World, links: list[UnconfirmedLinkRef] | None = None+ ) -> int:+ """Run it as an admin would: on the links the list showed them,+ unless the test names others."""+ if links is None:+ links = [+ UnconfirmedLinkRef(id=link.id, user_id=link.user_id) # type: ignore[attr-defined]+ for link in await self._list(world)+ ]async with world.session_factory() as session:result = await require_identity_confirmation(world.bridge_id,+ RequireConfirmationRequest(links=links),session,CollaborationBridgeStore(),_STORE,@@ -797,11 +884,32 @@ class TestRequiringConfirmationForOlderLinks:UserStore(),)+ async def test_only_the_links_the_admin_was_shown_are_moved(+ self, world: _World+ ) -> None:+ # Someone else's older link that appeared after the admin looked is+ # left alone: they agreed to demote the people they were shown.+ await self._older_link(world, world.ada)+ shown = [+ UnconfirmedLinkRef(id=link.id, user_id=link.user_id) # type: ignore[attr-defined]+ for link in await self._list(world)+ ]+ await self._older_link(world, world.bob)++ assert await self._require(world, shown) == 1++ assert await _claim_of(world, world.ada) is None+ assert await _claim_of(world, world.bob) is not None+async def test_running_it_again_moves_nothing(self, world: _World) -> None:await self._older_link(world, world.ada)+ shown = [+ UnconfirmedLinkRef(id=link.id, user_id=link.user_id) # type: ignore[attr-defined]+ for link in await self._list(world)+ ]- assert await self._require(world) == 1- assert await self._require(world) == 0+ assert await self._require(world, shown) == 1+ assert await self._require(world, shown) == 0async def test_another_bridges_older_links_are_untouched(self, world: _World@@ -848,3 +956,26 @@ class TestRequiringConfirmationForOlderLinks:assert event is not Noneassert event.actor_user_id == world.bob.idassert event.details == {"moved": 1}+++class _ReleasedMeanwhile:+ """A store whose claim was unlinked between being read and released."""++ async def get_claim(self, *_args: object) -> object:+ return SimpleNamespace(verified_at=None)++ async def release(self, *_args: object) -> object:+ raise NoSuchLink("gone")+++async def test_an_older_link_unlinked_meanwhile_is_not_an_error() -> None:+ assert (+ await _drop_older_link(+ object(), # type: ignore[arg-type]+ _ReleasedMeanwhile(), # type: ignore[arg-type]+ SimpleNamespace(id="ext-1", tenant_id="t"), # type: ignore[arg-type]+ "u-1",+ "b-1",+ )+ is False+ )diff --git a/core/tests/switch_core/test_migration_drop_links_to_shared_accounts.py b/core/tests/switch_core/test_migration_drop_links_to_shared_accounts.pynew file mode 100644index 000000000..ea094d027--- /dev/null+++ b/core/tests/switch_core/test_migration_drop_links_to_shared_accounts.py@@ -0,0 +1,163 @@+"""Older links to accounts many people post as are dropped (CHOO-3881).++Links made before confirmation existed keep working, unverified. Not those on+Telegram's stand-ins or Slack's app and bot ids, which nobody could ever+confirm and which recognise everyone posting as them as the claimant:+`22e1d92cfd4c` deletes those, and only those.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from alembic.config import Config+from alembic.runtime.environment import EnvironmentContext+from alembic.script import ScriptDirectory+from sqlalchemy import Connection, text+from sqlalchemy.ext.asyncio import create_async_engine++from switch_core.db.models import TENANT_ZERO_ID++_CORE = Path(__file__).resolve().parents[2]+_MIGRATION_DB = "migration_drop_links_to_shared_accounts"++_MIGRATION_UNDER_TEST = "22e1d92cfd4c"+++def _script_directory(config: Config) -> ScriptDirectory:+ config.set_main_option("script_location", str(_CORE / "switch_core" / "migrations"))+ return ScriptDirectory.from_config(config)+++def _pre_migration_revision() -> str:+ config = Config(str(_CORE / "alembic.ini"))+ down = _script_directory(config).get_revision(_MIGRATION_UNDER_TEST).down_revision+ assert isinstance(down, str)+ return down+++def _migrate(revision: str) -> Any:+ def migrate(connection: Connection) -> None:+ config = Config(str(_CORE / "alembic.ini"))+ script = _script_directory(config)++ def do_migrate(current_revision: str, context: Any) -> Any:+ return script._upgrade_revs(revision, current_revision)++ with EnvironmentContext(config, script, fn=do_migrate) as environment:+ environment.configure(connection=connection)+ with environment.begin_transaction():+ environment.run_migrations()++ return migrate+++# (bridge type, the account's platform id, whether its claim should survive)+_ACCOUNTS = [+ ("telegram", "1087968824", False),+ ("telegram", "136817688", False),+ ("telegram", "777000", False),+ ("telegram", "424242", True),+ ("slack", "B0123ABCD", False),+ ("slack", "USLACKBOT", False),+ ("slack", "U0123ABCD", True),+ ("mattermost", "1087968824", True),+]+++async def test_only_links_to_shared_accounts_are_deleted(postgres_url: str) -> None:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_MIGRATION_DB}"'))+ await connection.execute(text(f'CREATE DATABASE "{_MIGRATION_DB}"'))+ base, _, _ = postgres_url.rpartition("/")+ engine = create_async_engine(f"{base}/{_MIGRATION_DB}")+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_migrate(_pre_migration_revision()))+ async with engine.begin() as connection:+ await connection.execute(+ text(+ "INSERT INTO users (id, name, email, role) VALUES "+ "('u1', 'ada', '[email protected]', 'user'), "+ "('u2', 'bob', '[email protected]', 'user')"+ )+ )+ for index, (bridge_type, external_id, _keep) in enumerate(_ACCOUNTS):+ params = {"t": TENANT_ZERO_ID, "i": str(index), "type": bridge_type}+ await connection.execute(+ text(+ "INSERT INTO clients (id, tenant_id, matrix_user_id, "+ "display_name, type) VALUES ('bc' || :i, :t, :mxid, "+ "'bridge', 'bridge')"+ ),+ {**params, "mxid": f"@bridge-{index}:test"},+ )+ await connection.execute(+ text(+ "INSERT INTO collaboration_bridges (id, tenant_id, type, "+ "display_name, client_id, status) VALUES ('b' || :i, :t, "+ ":type, 'bridge', 'bc' || :i, 'active')"+ ),+ params,+ )+ await connection.execute(+ text(+ "INSERT INTO clients (id, tenant_id, matrix_user_id, "+ "display_name, type) VALUES ('ec' || :i, :t, :mxid, "+ "'person', 'user')"+ ),+ {**params, "mxid": f"@person-{index}:test"},+ )+ await connection.execute(+ text(+ "INSERT INTO external_users (id, tenant_id, bridge_id, "+ "external_user_id, external_username, client_id) VALUES "+ "('e' || :i, :t, 'b' || :i, :ext, 'person', 'ec' || :i)"+ ),+ {**params, "ext": external_id},+ )+ await connection.execute(+ text(+ "INSERT INTO external_user_claims (tenant_id, "+ "external_user_id, user_id) VALUES (:t, 'e' || :i, 'u1')"+ ),+ params,+ )+ # And a link to it waiting for its code, as an admin's+ # "require confirmation" leaves one.+ await connection.execute(+ text(+ "INSERT INTO external_user_link_requests (tenant_id, "+ "external_user_id, user_id) VALUES (:t, 'e' || :i, 'u2')"+ ),+ params,+ )++ async with engine.begin() as connection:+ await connection.run_sync(_migrate(_MIGRATION_UNDER_TEST))++ async with engine.begin() as connection:+ claims = set(+ (+ await connection.execute(+ text("SELECT external_user_id FROM external_user_claims")+ )+ ).scalars()+ )+ requests = set(+ (+ await connection.execute(+ text("SELECT external_user_id FROM external_user_link_requests")+ )+ ).scalars()+ )+ kept = {f"e{index}" for index, (_t, _e, keep) in enumerate(_ACCOUNTS) if keep}+ assert claims == kept+ assert requests == kept+ finally:+ await engine.dispose()+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_MIGRATION_DB}"'))+ await admin.dispose()