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
fix(gateway): refuse to remove a member who owns agents here (CHOO-2722)
Wojciech Wojtyniakf5f073e59cb1
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 9609e5231..fbc36c2cd 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -418,21 +418,21 @@ async def remove_member(Removal also revokes what the member's own credentials in this tenant letthem do here, in the same transaction as the membership row going away —a bearer credential resolves its tenant from its own row and never- consults membership, so leaving the row behind would leave the person- with working, invisible access (`docs/old/multi-tenancy-phase2-tenants.md`,- §3). Concretely: every agent this user owns here is deleted outright —- there is no "disabled" flag on `Agent` to set instead, and an agent's own- bearer key (`agents.api_key_id`) is a `NOT NULL` column with no `ON- DELETE` action, so the key cannot be revoked while the agent still- references it. Deleting the agent first, through `AgentStore.delete`- rather than `ProtocolService.delete_agent`, frees that key to be deleted- with the rest of this user's keys right after — `delete_agent` spans- several sessions and commits of its own and reaches out to the live- Matrix client and collaboration bridges, none of which can be folded into- one transaction, so it is deliberately not used here. What this does not- do is tear down a live Matrix session such an agent already holds; its- next call to Switch fails at authentication instead, since the credential- behind it is gone.+ consults membership, so leaving it behind would leave the person with+ working, invisible access (`docs/old/multi-tenancy-phase2-tenants.md`,+ §3). Concretely, this deletes every personal API key the member holds+ here.++ It does **not** touch any agent the member owns — it refuses instead, 409,+ naming them. An agent is not that member's private property to lose along+ with their membership: it sits in rooms with other people, it may be the+ only copy of a working configuration, and its name is something other+ members already depend on. A personal key is trivially recoverable — mint+ another — but deleting an agent is not, and a member removal is routine+ enough, including by mistake, that it must not be the thing that makes an+ irreversible call about shared infrastructure. An admin who hits this+ reassigns or deletes those agents deliberately, with the agent in front of+ them, then removes the member."""_require_bound_tenant(tenant_id)membership = await session.get(TenantMember, (tenant_id, user_id))@@ -442,9 +442,16 @@ async def remove_member(if membership.role == "owner" and await user_store.count_owners(session) <= 1:raise HTTPException(status_code=409, detail="Cannot remove the last owner")- revoked_agent_ids = [a.id for a in await agent_store.get_by_owner(session, user_id)]- for agent_id in revoked_agent_ids:- await agent_store.delete(session, agent_id)+ owned_agents = await agent_store.get_by_owner(session, user_id)+ if owned_agents:+ names = ", ".join(sorted(agent.name for agent in owned_agents))+ raise HTTPException(+ status_code=409,+ detail=(+ "Cannot remove: this member owns agents in this tenant — "+ f"reassign or delete them first: {names}"+ ),+ )keys = await api_key_store.get_by_user(session, user_id)revoked_key_hashes = [key.key_hash for key in keys]@@ -454,8 +461,6 @@ async def remove_member(await session.delete(membership)await session.commit()- for agent_id in revoked_agent_ids:- protocol.api_key_cache.invalidate_agent(agent_id)for key_hash in revoked_key_hashes:protocol.api_key_cache.invalidate(key_hash)diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex 54f2a811b..7b646042e 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -166,14 +166,15 @@ async def _make_agent_with_key(*,tenant_id: str,owner_id: str,-) -> tuple[str, str]:+) -> tuple[str, str, str]:"""An agent owned by `owner_id`, plus the `agents`-type key backing it.- Returns `(agent_id, key_hash)`. The agent's own client and api_key rows- are constructed first — `agents.client_id` and `agents.api_key_id` are- both foreign keys, not free-form strings.+ Returns `(agent_id, agent_name, key_hash)`. The agent's own client and+ api_key rows are constructed first — `agents.client_id` and+ `agents.api_key_id` are both foreign keys, not free-form strings."""key_hash = uuid.uuid4().hex+ name = f"agent-{uuid.uuid4().hex[:8]}"async with session_factory() as session:client = Client(tenant_id=tenant_id,@@ -197,7 +198,7 @@ async def _make_agent_with_key(agent = Agent(tenant_id=tenant_id,- name=f"agent-{uuid.uuid4().hex[:8]}",+ name=name,description="test agent",agent_type="other",connector_type="claude-code",@@ -208,7 +209,7 @@ async def _make_agent_with_key()session.add(agent)await session.commit()- return agent.id, key_hash+ return agent.id, name, key_hashclass TestCreateTenant:@@ -675,9 +676,16 @@ class TestMemberRoutes:async with session_factory() as session:assert await ApiKeyStore().get_by_hash(session, key_hash) is None- async def test_removing_a_member_deletes_the_agents_they_own_here(+ async def test_a_member_who_owns_an_agent_here_cannot_be_removed(self, session_factory: async_sessionmaker[AsyncSession]) -> None:+ """An agent is not the member's private property to lose along with+ their membership — it sits in rooms with other people, and deleting it+ is not recoverable the way reminting a key is. Removal must refuse,+ naming the agent, and this must not be a partial write: not the+ membership, not the member's unrelated personal key, not the agent's+ own key may be touched when the route 409s.+ """await _make_tenant(session_factory, TENANT_A)owner_id = await _make_member(session_factory, name="agent-remover", tenant_id=TENANT_A, role="owner"@@ -685,18 +693,27 @@ class TestMemberRoutes:target_id = await _make_member(session_factory, name="agent-owner", tenant_id=TENANT_A, role="member")- agent_id, agent_key_hash = await _make_agent_with_key(+ agent_id, agent_name, agent_key_hash = await _make_agent_with_key(session_factory, tenant_id=TENANT_A, owner_id=target_id)+ personal_key_hash = await _make_api_key(+ session_factory, tenant_id=TENANT_A, user_id=target_id+ )token = _token(owner_id, "[email protected]", TENANT_A)async with _client(_app(session_factory), token) as client:response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")- assert response.status_code == 200, response.text++ assert response.status_code == 409, response.text+ assert agent_name in response.json()["detail"]async with session_factory() as session:- assert await AgentStore().get(session, agent_id) is None- assert await ApiKeyStore().get_by_hash(session, agent_key_hash) is None+ assert await session.get(TenantMember, (TENANT_A, target_id)) is not None+ assert await AgentStore().get(session, agent_id) is not None+ assert await ApiKeyStore().get_by_hash(session, agent_key_hash) is not None+ assert (+ await ApiKeyStore().get_by_hash(session, personal_key_hash) is not None+ )async def test_a_plain_member_cannot_remove_anyone(self, session_factory: async_sessionmaker[AsyncSession]