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): check the tenant before the work, not in the middle of it (CHOO-2687)

Petr Bauche714674a921a
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 4c1432412..cac0e1859 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -338,6 +338,9 @@ class ProtocolService:
Raises:
ValueError: name is invalid (lowercase alphanumeric, dots, hyphens,
or underscores — no spaces).
+ RuntimeError: no tenant is bound. Checked before anything is
+ written, because the agent's row and its bridge identities
+ both belong to a tenant and neither can be placed without one.
InvalidIconUrl: ``icon_url`` is malformed or points somewhere unsafe.
InvalidDisplayName: ``display_name`` is over-long or unsafe to render.
AgentExistsError: agent with this name exists and ``overwrite`` is
@@ -351,6 +354,13 @@ class ProtocolService:
"Use only lowercase letters, digits, dots, hyphens, and underscores."
)
+ tenant_id = current_tenant_id()
+ if tenant_id is None:
+ raise RuntimeError(
+ "register_agent requires a bound tenant; the agent's row and "
+ "its bridge identities both belong to one"
+ )
+
validated_icon_url = normalise_icon_url(icon_url)
validated_display_name = normalise_display_name(display_name)
@@ -430,7 +440,7 @@ class ProtocolService:
)
logger.info("Registered agent: %s (%s)", name, agent_id)
- await self._create_bridge_identities(name, description)
+ await self._create_bridge_identities(tenant_id, name, description)
return RegistrationResult(
agent_id=agent_id,
@@ -695,24 +705,17 @@ class ProtocolService:
return existing.id
async def _create_bridge_identities(
- self, agent_name: str, description: str
+ self, tenant_id: str, agent_name: str, description: str
) -> None:
- """Create `agent_name`'s platform identity on every running bridge of
- the registering tenant — and only that tenant's bridges.
+ """Create `agent_name`'s platform identity on the bridges of
+ `tenant_id` — 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.
+ The tenant is passed in rather than read from the ambient context so
+ that it is the caller's to establish: `register_agent` refuses without
+ one before it writes anything. 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)
@@ -815,24 +818,16 @@ class ProtocolService:
await self.agent_store.update(session, agent_id, icon_url=validated)
await session.commit()
- async def _remove_bridge_identities(self, agent_name: str) -> None:
- """Remove `agent_name`'s platform identity from every running bridge of
- the deleting tenant — and only that tenant's bridges.
+ async def _remove_bridge_identities(self, tenant_id: str, agent_name: str) -> None:
+ """Remove `agent_name`'s platform identity from the bridges of
+ `tenant_id` — 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.
+ group, or role of a same-named agent belonging to another tenant. As
+ there, the tenant is the caller's to establish — `delete_agent`
+ refuses without one before it stops anything.
"""
- 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)
@@ -852,12 +847,25 @@ class ProtocolService:
"""Delete an agent and clean up all associated state.
Provide exactly one of ``agent_id`` or ``agent_name``.
+
+ Raises:
+ ValueError: neither or both selectors were given, or no such agent.
+ RuntimeError: no tenant is bound. Checked before the agent is
+ stopped, so an unbound caller leaves it running rather than
+ half torn down.
"""
if (agent_id is None) == (agent_name is None):
raise ValueError(
"delete_agent requires exactly one of agent_id or agent_name"
)
+ tenant_id = current_tenant_id()
+ if tenant_id is None:
+ raise RuntimeError(
+ "delete_agent requires a bound tenant; the agent's row and its "
+ "bridge identities both belong to one"
+ )
+
async with self.session_factory() as session:
if agent_id is not None:
agent = await self.agent_store.get(session, agent_id)
@@ -874,7 +882,7 @@ class ProtocolService:
await self.client_lifecycle.stop(client_id)
self.event_buffer.remove(resolved_id)
- await self._remove_bridge_identities(resolved_name)
+ await self._remove_bridge_identities(tenant_id, resolved_name)
async with self.session_factory() as session:
await self.agent_store.delete(session, resolved_id)
diff --git a/core/switch_core/bridges/agent/server_connectors/core.py b/core/switch_core/bridges/agent/server_connectors/core.py
index 7746b1855..68c130e0a 100644
--- a/core/switch_core/bridges/agent/server_connectors/core.py
+++ b/core/switch_core/bridges/agent/server_connectors/core.py
@@ -124,9 +124,12 @@ class ConnectorCore:
logger.info("Stopped connector core %s", self._connector_id)
async def delete_agents(self) -> None:
+ # Removing the connector's agents is one unit of work for its row, so
+ # it binds that row's tenant here — as registration and each poll do.
for handle in self._agents.values():
try:
- await self._protocol.delete_agent(agent_id=handle.agent_id)
+ with tenant_scope(self._connector_tenant_id):
+ await self._protocol.delete_agent(agent_id=handle.agent_id)
except Exception:
logger.exception(
"Failed to delete agent %s during connector removal",
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 3f4aea434..0b9697df8 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -707,17 +707,12 @@ class CollaborationBridgeLifecycleService:
def get(self, bridge_id: str) -> BridgeCore | None:
return self._bridges.get(bridge_id)
- 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.
+ `_bridges` is a flat, instance-wide dict, so this is the only way to
+ act on a tenant's bridges — e.g. creating an agent's platform identity
+ — without reaching another tenant's.
"""
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 81776ca32..001c21e81 100644
--- a/core/tests/integration/conftest.py
+++ b/core/tests/integration/conftest.py
@@ -111,17 +111,14 @@ class _NoBridges:
"""Stand-in for CollaborationBridgeLifecycleService when no bridge is configured.
Room creation only calls `.get(bridge_id)` when a bridge_id is set (ours is
- None), and agent registration calls `.all_bridges()` for bridge-identity
- creation. Both paths are exercised here as no-ops — the feature under test
- involves no collaboration bridge.
+ None), and agent registration calls `.bridges_for_tenant()` for
+ bridge-identity creation. Both paths are exercised here as no-ops — the
+ feature under test involves no collaboration bridge.
"""
def get(self, _bridge_id: str) -> None:
return None
- def all_bridges(self) -> list:
- return []
-
def bridges_for_tenant(self, tenant_id: str) -> list:
return []
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 154cb3848..77e1cbe77 100644
--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
@@ -59,9 +59,6 @@ class FakeClientLifecycle:
class NoBridges:
- def all_bridges(self) -> list[object]:
- return []
-
def bridges_for_tenant(self, tenant_id: str) -> list[object]:
return []
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
index fbec7e45e..f1bb06cc6 100644
--- 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
@@ -2,9 +2,9 @@
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:
+looped over every running bridge on the instance —
+`CollaborationBridgeLifecycleService` holds them in one 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
@@ -19,15 +19,18 @@ 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.
+create or remove the identity, and neither `register_agent` nor
+`delete_agent` will touch anything at all without a tenant bound.
"""
from __future__ import annotations
+import pytest
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 switch_core.tenant_context import no_tenant
from tests.switch_core.bridges.agent.protocol.registration_harness import (
make_owner,
make_service,
@@ -63,9 +66,6 @@ class _MultiTenantBridges:
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]
@@ -100,6 +100,25 @@ class TestBridgeIdentityTenantScope:
]
assert tenant_b_bridge.adapter.identities_created == []
+ async def test_unbound_registration_is_refused_before_the_agent_is_created(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The tenant is a precondition of registering, not of the bridge fan-out
+ # at the end of it: raising once the row is committed would leave a
+ # registered agent whose caller never received its API key.
+ svc = make_service(session_factory)
+ svc.collab_lifecycle = _MultiTenantBridges([]) # type: ignore[attr-defined]
+
+ owner = await make_owner(session_factory)
+
+ with no_tenant():
+ with pytest.raises(RuntimeError, match="requires a bound tenant"):
+ await register(svc, "unbound-bot", owner)
+
+ assert svc.client_lifecycle.requested_display_names == [] # type: ignore[attr-defined]
+ async with session_factory() as session:
+ assert await svc.agent_store.get_by_name(session, "unbound-bot") is None
+
class _StoppableClientLifecycle:
"""`registration_harness.FakeClientLifecycle`, plus the `stop`/`remove`
@@ -107,6 +126,8 @@ class _StoppableClientLifecycle:
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
self._session_factory = session_factory
+ self.stopped: list[str] = []
+ self.removed: list[str] = []
async def create_client(self, *, client_type: str, display_name: str) -> Client:
async with self._session_factory() as session:
@@ -123,10 +144,10 @@ class _StoppableClientLifecycle:
pass
async def stop(self, client_id: str) -> None:
- return None
+ self.stopped.append(client_id)
async def remove(self, client_id: str) -> None:
- return None
+ self.removed.append(client_id)
class TestBridgeIdentityRemovalTenantScope:
@@ -159,3 +180,27 @@ class TestBridgeIdentityRemovalTenantScope:
assert tenant_a_bridge.adapter.identities_removed == ["shared-name"]
assert tenant_b_bridge.adapter.identities_removed == []
+
+ async def test_unbound_deletion_is_refused_before_the_agent_is_stopped(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Same precondition from the other end. Raising part-way through leaves
+ # the worst state of all: the client stopped but never removed, the
+ # event buffer cleared, and the agent's row still in the database.
+ svc = make_service(session_factory)
+ svc.collab_lifecycle = _MultiTenantBridges([]) # type: ignore[attr-defined]
+ lifecycle = _StoppableClientLifecycle(session_factory)
+ svc.client_lifecycle = lifecycle # type: ignore[attr-defined]
+ svc.event_buffer = EventBuffer() # type: ignore[attr-defined]
+
+ owner = await make_owner(session_factory)
+ agent_id = await register(svc, "still-here", owner)
+
+ with no_tenant():
+ with pytest.raises(RuntimeError, match="requires a bound tenant"):
+ await svc.delete_agent(agent_id=agent_id)
+
+ assert lifecycle.stopped == []
+ assert lifecycle.removed == []
+ async with session_factory() as session:
+ assert await svc.agent_store.get(session, agent_id) is not None
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 c7af3b48b..391181058 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
@@ -58,9 +58,6 @@ class _FakeClientLifecycle:
class _NoBridges:
- def all_bridges(self) -> list[object]:
- return []
-
def bridges_for_tenant(self, tenant_id: str) -> list[object]:
return []
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 a31f5d8cd..d25f710ee 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
@@ -55,9 +55,6 @@ class _FakeClientLifecycle:
class _NoBridges:
- def all_bridges(self) -> list[object]:
- return []
-
def bridges_for_tenant(self, tenant_id: str) -> list[object]:
return []
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 488f49680..ec815ef9e 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
@@ -80,9 +80,6 @@ class _FakeClientLifecycle:
class _NoBridges:
- def all_bridges(self) -> list[object]:
- return []
-
def bridges_for_tenant(self, tenant_id: str) -> list[object]:
return []