Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(bridges): scope agent bridge-identity provisioning to the owning tenant (CHOO-2687)

Wojciech Wojtyniakc234dd1709ec
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 388020da6..4c1432412 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -93,7 +93,7 @@ from switch_core.events import (
ToolCallReport as MatrixToolCallReport,
)
from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPE
-from switch_core.tenant_context import tenant_scope
+from switch_core.tenant_context import current_tenant_id, tenant_scope
from switch_core.transport import (
TransportError,
)
@@ -697,7 +697,23 @@ class ProtocolService:
async def _create_bridge_identities(
self, agent_name: str, description: str
) -> None:
- for bridge_core in self.collab_lifecycle.all_bridges():
+ """Create `agent_name`'s platform identity on every running bridge of
+ the registering tenant — and only that tenant's bridges.
+
+ A bound tenant is a precondition, not an input to fall back from: both
+ registration paths bind one before this runs (an authenticated
+ request via middleware, or ``register_agent_with_token`` itself), so
+ nothing bound here is a bug upstream, and fanning out to every
+ tenant's bridges instead would repeat the cross-tenant identity leak
+ this method exists to avoid.
+ """
+ tenant_id = current_tenant_id()
+ if tenant_id is None:
+ raise RuntimeError(
+ "_create_bridge_identities requires a bound tenant; "
+ "register_agent must be called with one already bound"
+ )
+ for bridge_core in self.collab_lifecycle.bridges_for_tenant(tenant_id):
try:
await bridge_core.adapter.create_agent_identity(agent_name, description)
except Exception:
@@ -800,7 +816,24 @@ class ProtocolService:
await session.commit()
async def _remove_bridge_identities(self, agent_name: str) -> None:
- for bridge_core in self.collab_lifecycle.all_bridges():
+ """Remove `agent_name`'s platform identity from every running bridge of
+ the deleting tenant — and only that tenant's bridges.
+
+ Unscoped, this is worse than its `_create_bridge_identities` twin:
+ deleting an agent in one tenant would delete the platform bot, user
+ group, or role of a same-named agent belonging to another tenant. A
+ bound tenant is a precondition here too — every `delete_agent` caller
+ (the HTTP/gateway endpoints, and the server-connector removal path)
+ runs under a tenant already bound by the request — so nothing bound is
+ a bug upstream, not a reason to fall back to every bridge.
+ """
+ tenant_id = current_tenant_id()
+ if tenant_id is None:
+ raise RuntimeError(
+ "_remove_bridge_identities requires a bound tenant; "
+ "delete_agent must be called with one already bound"
+ )
+ for bridge_core in self.collab_lifecycle.bridges_for_tenant(tenant_id):
try:
await bridge_core.adapter.remove_agent_identity(agent_name)
except Exception:
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 1f63beb12..60c86db54 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -214,6 +214,10 @@ class BridgeCore:
def adapter(self) -> CollaborationAdapter:
return self._adapter
+ @property
+ def tenant_id(self) -> str:
+ return self._bridge_tenant_id
+
def _traced(
self, handler: Callable[[_InboundEventT], Awaitable[None]]
) -> Callable[[_InboundEventT], Awaitable[None]]:
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 77f72b271..3f4aea434 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -709,3 +709,16 @@ class CollaborationBridgeLifecycleService:
def all_bridges(self) -> list[BridgeCore]:
return list(self._bridges.values())
+
+ def bridges_for_tenant(self, tenant_id: str) -> list[BridgeCore]:
+ """Running bridges belonging to `tenant_id`, and none other.
+
+ For call sites that act on every bridge of one tenant — e.g. creating
+ an agent's platform identity — rather than every bridge on the
+ instance. `all_bridges()` returns the flat, cross-tenant dict; a
+ caller that fans out to it without filtering would act on other
+ tenants' bridges too.
+ """
+ return [
+ bridge for bridge in self._bridges.values() if bridge.tenant_id == tenant_id
+ ]
diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.py
index 3655ff8e3..81776ca32 100644
--- a/core/tests/integration/conftest.py
+++ b/core/tests/integration/conftest.py
@@ -122,6 +122,9 @@ class _NoBridges:
def all_bridges(self) -> list:
return []
+ def bridges_for_tenant(self, tenant_id: str) -> list:
+ return []
+
@dataclass
class StackInfo:
diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
index 9715ccbd2..154cb3848 100644
--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
@@ -62,6 +62,9 @@ class NoBridges:
def all_bridges(self) -> list[object]:
return []
+ def bridges_for_tenant(self, tenant_id: str) -> list[object]:
+ return []
+
def make_service(
session_factory: async_sessionmaker[AsyncSession],
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.py b/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.py
new file mode 100644
index 000000000..fbec7e45e
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.py
@@ -0,0 +1,161 @@
+"""Bridge-identity provisioning and teardown are confined to the tenant that
+owns the agent (CHOO-2687).
+
+Before this fix, both `_create_bridge_identities` and `_remove_bridge_identities`
+looped over every running bridge on the instance
+(`CollaborationBridgeLifecycleService.all_bridges()`), which is a flat,
+cross-tenant dict:
+
+- Registering an agent under tenant A called `create_agent_identity` on
+ tenant B's bridges too — creating a Mattermost bot, Slack user group, or
+ Discord role for tenant A's agent on a platform tenant B owns, leaking the
+ agent's name and description across the tenant boundary.
+- Deleting an agent under tenant A called `remove_agent_identity` on tenant
+ B's bridges too — and by name, so deleting an agent in tenant A would
+ delete the platform bot/group/role of a *same-named* agent belonging to
+ tenant B. Destructive, not just a leak.
+
+No query is involved in either (it's an in-memory iteration followed by
+outbound platform API calls), so row-level security cannot catch it.
+
+These tests pin the fix: only the owning tenant's bridges are asked to
+create or remove the identity.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.protocol.event_buffer import EventBuffer
+from switch_core.db.models import TENANT_ZERO_ID, Client, Tenant
+from tests.switch_core.bridges.agent.protocol.registration_harness import (
+ make_owner,
+ make_service,
+ register,
+)
+
+TENANT_B = "bridge-identity-tenant-b"
+
+
+class _FakeAdapter:
+ def __init__(self) -> None:
+ self.identities_created: list[tuple[str, str]] = []
+ self.identities_removed: list[str] = []
+
+ async def create_agent_identity(self, name: str, description: str) -> None:
+ self.identities_created.append((name, description))
+
+ async def remove_agent_identity(self, name: str) -> None:
+ self.identities_removed.append(name)
+
+
+class _FakeBridge:
+ def __init__(self, tenant_id: str) -> None:
+ self.tenant_id = tenant_id
+ self.adapter = _FakeAdapter()
+
+
+class _MultiTenantBridges:
+ """Stand-in for `CollaborationBridgeLifecycleService` carrying bridges from
+ more than one tenant, mirroring the real service's flat `_bridges` dict
+ and its per-tenant filtering."""
+
+ def __init__(self, bridges: list[_FakeBridge]) -> None:
+ self._bridges = bridges
+
+ def all_bridges(self) -> list[_FakeBridge]:
+ return list(self._bridges)
+
+ def bridges_for_tenant(self, tenant_id: str) -> list[_FakeBridge]:
+ return [b for b in self._bridges if b.tenant_id == tenant_id]
+
+
+async def _seed_tenant(session_factory: async_sessionmaker[AsyncSession]) -> None:
+ async with session_factory() as session:
+ session.add(Tenant(id=TENANT_B, slug=TENANT_B, name=TENANT_B))
+ await session.commit()
+
+
+class TestBridgeIdentityTenantScope:
+ async def test_other_tenants_bridge_is_not_given_the_new_agents_identity(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The `session_factory` fixture binds tenant zero as the ambient
+ # tenant for the whole test, so registering here is "tenant A".
+ await _seed_tenant(session_factory)
+
+ tenant_a_bridge = _FakeBridge(tenant_id=TENANT_ZERO_ID)
+ tenant_b_bridge = _FakeBridge(tenant_id=TENANT_B)
+
+ svc = make_service(session_factory)
+ svc.collab_lifecycle = _MultiTenantBridges( # type: ignore[attr-defined]
+ [tenant_a_bridge, tenant_b_bridge]
+ )
+
+ owner = await make_owner(session_factory)
+ await register(svc, "cross-tenant-bot", owner)
+
+ assert tenant_a_bridge.adapter.identities_created == [
+ ("cross-tenant-bot", "cross-tenant-bot desc")
+ ]
+ assert tenant_b_bridge.adapter.identities_created == []
+
+
+class _StoppableClientLifecycle:
+ """`registration_harness.FakeClientLifecycle`, plus the `stop`/`remove`
+ calls `delete_agent` makes that registration alone never reaches."""
+
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._session_factory = session_factory
+
+ async def create_client(self, *, client_type: str, display_name: str) -> Client:
+ async with self._session_factory() as session:
+ client = Client(
+ matrix_user_id=f"@{display_name}:test",
+ display_name=display_name,
+ type=client_type,
+ )
+ session.add(client)
+ await session.commit()
+ return client
+
+ def start_client(self, client: Client) -> None:
+ pass
+
+ async def stop(self, client_id: str) -> None:
+ return None
+
+ async def remove(self, client_id: str) -> None:
+ return None
+
+
+class TestBridgeIdentityRemovalTenantScope:
+ async def test_other_tenants_bridge_is_not_stripped_of_a_same_named_identity(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Tenant A deletes an agent named "shared-name"; tenant B happens to
+ # have its own, unrelated agent of the same name on its own bridge.
+ # Deleting tenant A's agent must not touch tenant B's bridge identity.
+ await _seed_tenant(session_factory)
+
+ tenant_a_bridge = _FakeBridge(tenant_id=TENANT_ZERO_ID)
+ tenant_b_bridge = _FakeBridge(tenant_id=TENANT_B)
+
+ svc = make_service(session_factory)
+ svc.collab_lifecycle = _MultiTenantBridges( # type: ignore[attr-defined]
+ [tenant_a_bridge, tenant_b_bridge]
+ )
+ svc.client_lifecycle = _StoppableClientLifecycle(session_factory) # type: ignore[attr-defined]
+ svc.event_buffer = EventBuffer() # type: ignore[attr-defined]
+
+ owner = await make_owner(session_factory)
+ agent_id = await register(svc, "shared-name", owner)
+ # The registration call above already exercised create_agent_identity;
+ # clear it so this test's assertions are about removal alone.
+ tenant_a_bridge.adapter.identities_created.clear()
+ tenant_b_bridge.adapter.identities_created.clear()
+
+ await svc.delete_agent(agent_id=agent_id)
+
+ assert tenant_a_bridge.adapter.identities_removed == ["shared-name"]
+ assert tenant_b_bridge.adapter.identities_removed == []
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py
index 5e039168c..c7af3b48b 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py
@@ -61,6 +61,9 @@ class _NoBridges:
def all_bridges(self) -> list[object]:
return []
+ def bridges_for_tenant(self, tenant_id: str) -> list[object]:
+ return []
+
def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:
svc = object.__new__(ProtocolService)
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
index c728f03b6..a31f5d8cd 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
@@ -58,6 +58,9 @@ class _NoBridges:
def all_bridges(self) -> list[object]:
return []
+ def bridges_for_tenant(self, tenant_id: str) -> list[object]:
+ return []
+
def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:
svc = object.__new__(ProtocolService)
diff --git a/core/tests/switch_core/bridges/agent/test_api_key_cache.py b/core/tests/switch_core/bridges/agent/test_api_key_cache.py
index da3dc4904..488f49680 100644
--- a/core/tests/switch_core/bridges/agent/test_api_key_cache.py
+++ b/core/tests/switch_core/bridges/agent/test_api_key_cache.py
@@ -83,6 +83,9 @@ class _NoBridges:
def all_bridges(self) -> list[object]:
return []
+ def bridges_for_tenant(self, tenant_id: str) -> list[object]:
+ return []
+
def _middleware(session_factory: Any, cache: ApiKeyCache) -> BearerAuthMiddleware:
async def _app(scope: Any, receive: Any, send: Any) -> None: