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
Hand what a removed member owns to the admin removing them (#1555)
Abel Dantas93c132cf6836
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f043469b..75bb09475 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -346,6 +346,18 @@ version of their own to them without also giving them a release of their own.compares it only when someone signs in.#### Changed+- **Removing a member hands what they own to an admin.** Their rooms,+ packages, references, reference types, library documents and templates in+ that workspace stayed theirs, though they could no longer reach them, and+ were only cleared when their account was deleted. They now pass to the+ admin removing them, or, when the removal comes from the organization's+ directory or from an operator who is not a member, to the workspace's+ longest-standing other admin. The same happens in a workspace an+ organization admin reached only through that role, when they lose it. Each+ is audited as an ownership transfer. Chats, a room's own documents and a+ template whose name the admin already uses, in any workspace, stay as they+ were, and a member who owns agents still can't be removed+ until those are transferred or deleted.- **One role runs a workspace: owner merges into admin.** Every workspace`owner` becomes an `admin`, and every admin now manages every member, otheradmins included, as well as everything an owner could. A workspace alwaysdiff --git a/core/switch_core/accounts/transfer.py b/core/switch_core/accounts/transfer.pyindex b2532b0b1..10f1ff779 100644--- a/core/switch_core/accounts/transfer.py+++ b/core/switch_core/accounts/transfer.py@@ -42,6 +42,7 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal, cast, get_argsfrom sqlalchemy import select+from sqlalchemy.exc import IntegrityErrorfrom switch_core.authz import Principal, can_managefrom switch_core.db.audit import AuditAction, record_audit_event@@ -324,3 +325,90 @@ async def transfer_ownership(new_owner_id=new_owner_id,retired_key_hash=retired,)+++# What passes to an heir when its owner leaves the workspace, in the order+# handed over. Agents are not here: removing a member who owns one is refused+# until it is transferred or deleted with it in front of an admin.+_HANDED_OVER: tuple[tuple[str, type[Owned]], ...] = (+ ("room", Room),+ ("package", Package),+ ("reference", Reference),+ ("reference_type", ReferenceType),+ ("document", Document),+ ("template", Template),+)+++async def hand_over_everything(+ session: AsyncSession,+ *,+ tenant_id: str,+ previous_owner_id: str,+ heir_id: str,+ actor_id: str | None,+ reason: str,+) -> dict[str, int]:+ """Make `heir_id` the owner of what `previous_owner_id` owns in the+ workspace bound on `session`, each with its audit event, so nothing there+ is left owned by someone who can no longer reach it. Returns how many of+ each kind passed.++ What a transfer refuses stays with them: a chat, which is one person's+ conversation; a room's own document, which goes with its room; and a+ template whose name the heir already uses. The caller commits."""+ handed: dict[str, int] = {}+ for kind, model in _HANDED_OVER:+ rows: list[Owned] = list(+ await session.scalars(+ select(model)+ .where(+ model.tenant_id == tenant_id,+ model.owner_id == previous_owner_id,+ )+ .with_for_update()+ )+ )+ for row in rows:+ if isinstance(row, Room) and "chat_operation_id" in (row.metadata_ or {}):+ continue+ if isinstance(row, Document) and row.room_id is not None:+ continue+ if isinstance(row, Template):+ if not await _template_passes(session, row, heir_id):+ continue+ else:+ row.owner_id = heir_id+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=actor_id,+ action=AuditAction.OWNERSHIP_TRANSFERRED,+ target_type=kind,+ target_id=row.type if isinstance(row, ReferenceType) else row.id,+ details={+ "from": previous_owner_id,+ "to": heir_id,+ "reason": reason,+ "agent_key_reissued": False,+ },+ )+ handed[kind] = handed.get(kind, 0) + 1+ await session.flush()+ return handed+++async def _template_passes(+ session: AsyncSession, template: Template, heir_id: str+) -> bool:+ """Make `heir_id` the owner of `template` unless they already have a+ template by its name. Template names are unique per owner across every+ workspace, and this session sees only its own, so the clash is found by+ trying: in a savepoint, which a clash rolls back alone."""+ try:+ async with session.begin_nested():+ template.owner_id = heir_id+ await session.flush()+ except IntegrityError:+ return False+ return Truediff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex bf3bff72d..ee2ed06e9 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -1471,6 +1471,13 @@ async def remove_member(here, and every service connection they hold here (their grants go withthem), revoking what was issued on those once the removal has committed.+ What the member owns here (rooms, packages, references, reference types,+ library documents, templates) passes to the admin removing them, or to the+ workspace's longest-standing other admin when the remover is not a member+ of it (`organization_access.removal_heir`), so nothing is left owned by+ someone who can no longer reach it. Chats and a room's own documents stay+ as they are, as a transfer refuses them.+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 alongwith their membership: it sits in rooms with other people, it may be thediff --git a/core/switch_core/organization_access.py b/core/switch_core/organization_access.pyindex 526708104..fabd5ed61 100644--- a/core/switch_core/organization_access.py+++ b/core/switch_core/organization_access.py@@ -17,8 +17,10 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.accounts.transfer import hand_over_everythingfrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.connections.broker import ServiceBrokerfrom switch_core.connections.sign_in_flows import SignInFlows@@ -82,8 +84,11 @@ async def end_organization_admin_access("""In workspace `tenant_id`, bound on `session`, where `user_id` standsonly as their organization's `org_admin`: remove their keys, serviceconnections and sign-ins under way, recorded in its audit log with- `details`; `keep_agent_keys` as `revoke_workspace_access` has it. Raises- `ServiceError` when a connection is busy."""+ `details`; `keep_agent_keys` as `revoke_workspace_access` has it.++ What they own there passes to an heir, as `remove_membership` does it,+ since they can no longer reach it either. Raises `ServiceError` when a+ connection is busy."""revoked = await revoke_workspace_access(session,user_id,@@ -92,6 +97,13 @@ async def end_organization_admin_access(sign_in_flows=revocation.sign_in_flows,keep_agent_keys=keep_agent_keys,)+ heir, handed = await _hand_over_to_heir(+ session,+ tenant_id=tenant_id,+ user_id=user_id,+ actor_id=actor_id,+ reason="organization_admin_access_ended",+ )await record_audit_event(session,tenant_id=tenant_id,@@ -103,6 +115,8 @@ async def end_organization_admin_access(**details,"api_keys_deleted": len(revoked.key_hashes),"service_connections_deleted": len(revoked.removed_services),+ "handed_over_to": heir,+ "handed_over": handed,},)return revoked@@ -120,9 +134,13 @@ async def remove_membership("""Remove `membership` from its workspace, bound on `session`, with themember's keys, service connections and sign-ins under way there, recordedin its audit log with `details`; `keep_agent_keys` as- `revoke_workspace_access` has it. Agents they own are left as they are.- Raises `ServiceError` when a connection is busy, before anything is- removed."""+ `revoke_workspace_access` has it.++ What they own there passes to an heir (`removal_heir`), so the workspace+ is not left with rooms, packages and the like owned by someone who can no+ longer reach them. Agents they own are left as they are: the callers+ refuse, or record a conflict, while there are any. Raises `ServiceError`+ when a connection is busy, before anything is removed."""revoked = await revoke_workspace_access(session,membership.user_id,@@ -131,6 +149,13 @@ async def remove_membership(sign_in_flows=revocation.sign_in_flows,keep_agent_keys=keep_agent_keys,)+ heir, handed = await _hand_over_to_heir(+ session,+ tenant_id=membership.tenant_id,+ user_id=membership.user_id,+ actor_id=actor_id,+ reason="member_removed",+ )await record_audit_event(session,tenant_id=membership.tenant_id,@@ -143,12 +168,72 @@ async def remove_membership("role": membership.role,"api_keys_deleted": len(revoked.key_hashes),"service_connections_deleted": len(revoked.removed_services),+ "handed_over_to": heir,+ "handed_over": handed,},)await session.delete(membership)return revoked+async def _hand_over_to_heir(+ session: AsyncSession,+ *,+ tenant_id: str,+ user_id: str,+ actor_id: str | None,+ reason: str,+) -> tuple[str | None, dict[str, int]]:+ """Hand what `user_id` owns in `tenant_id` to their `removal_heir`, for+ `reason`. Returns the heir, or None when there is none and nothing moved,+ and how many of each kind passed."""+ heir = await removal_heir(session, tenant_id, user_id, actor_id)+ if heir is None:+ return None, {}+ handed = await hand_over_everything(+ session,+ tenant_id=tenant_id,+ previous_owner_id=user_id,+ heir_id=heir,+ actor_id=actor_id,+ reason=reason,+ )+ return heir, handed+++async def removal_heir(+ session: AsyncSession, tenant_id: str, user_id: str, actor_id: str | None+) -> str | None:+ """Who takes over what `user_id` owns in `tenant_id` when they lose access+ to it: the person removing them, when they are a member of the workspace+ themselves; otherwise, as for a removal the organization's directory made+ or the server's operator made from outside, the longest-standing other+ admin, then the lowest id. None when the workspace has no other admin, and+ what they own stays theirs.++ The heir's membership is locked until the caller commits, so a removal of+ the heir running at the same time waits for this one and then finds what+ was handed to them, rather than leaving it with someone already gone."""+ if actor_id is not None and actor_id != user_id:+ actor = await session.get(+ TenantMember, (tenant_id, actor_id), with_for_update=True+ )+ if actor is not None:+ return actor_id+ heir: str | None = await session.scalar(+ select(TenantMember.user_id)+ .where(+ TenantMember.tenant_id == tenant_id,+ TenantMember.user_id != user_id,+ TenantMember.role == "admin",+ )+ .order_by(TenantMember.created_at, TenantMember.user_id)+ .limit(1)+ .with_for_update()+ )+ return heir++async def end_access_through_organization(session_factory: async_sessionmaker[AsyncSession],revocation: AccessRevocation,diff --git a/core/tests/switch_core/accounts/test_removal_hand_over.py b/core/tests/switch_core/accounts/test_removal_hand_over.pynew file mode 100644index 000000000..bf327fe63--- /dev/null+++ b/core/tests/switch_core/accounts/test_removal_hand_over.py@@ -0,0 +1,264 @@+"""Removing a member hands what they own in the workspace to an heir+(`organization_access.remove_membership`), so nothing there is left owned by+someone who can no longer reach it: the admin removing them, or, for a+removal from outside the workspace, its longest-standing other admin."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ AuditEvent,+ Document,+ Package,+ Reference,+ ReferenceType,+ Room,+ Template,+ TenantMember,+)+from switch_core.db.session_scope import tenant_session+from switch_core.organization_access import removal_heir+from tests.switch_core.gateway.test_tenant_api_routes import (+ TENANT_A,+ TENANT_B,+ _app,+ _client,+ _make_member,+ _make_tenant,+ _token,+)+++def _library_document(owner_id: str, room_id: str | None = None) -> Document:+ return Document(+ owner_id=owner_id,+ room_id=room_id,+ read_visibility="public",+ write_visibility="private",+ name=f"doc-{uuid.uuid4().hex[:6]}",+ description="",+ instructions="",+ content="",+ )+++def _room(owner_id: str, metadata: dict[str, str] | None = None) -> Room:+ return Room(+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name=f"room-{uuid.uuid4().hex[:6]}",+ description="",+ owner_id=owner_id,+ created_by=owner_id,+ read_visibility="private",+ metadata_=metadata,+ )+++async def test_the_admin_removing_a_member_takes_over_what_they_own(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="remover", tenant_id=TENANT_A, role="admin"+ )+ member_id = await _make_member(+ session_factory, name="leaving", tenant_id=TENANT_A, role="member"+ )+ async with tenant_session(session_factory, TENANT_A) as session:+ package = Package(+ owner_id=member_id,+ name="kit",+ description="",+ instructions="",+ read_visibility="private",+ write_visibility="private",+ )+ reference = Reference(+ owner_id=member_id,+ read_visibility="private",+ write_visibility="private",+ type="url",+ name="link",+ description="",+ instructions="",+ value={"url": "https://example.test"},+ )+ room = _room(member_id)+ chat = _room(member_id, {"chat_operation_id": "op"})+ library = _library_document(member_id)+ template = Template(+ owner_id=member_id, name="plan", description="", kind="room", content="x"+ )+ clashing = Template(+ owner_id=member_id, name="same", description="", kind="room", content="y"+ )+ admins = Template(+ owner_id=admin_id, name="same", description="", kind="room", content="z"+ )+ clashing_elsewhere = Template(+ owner_id=member_id,+ name="elsewhere",+ description="",+ kind="room",+ content="w",+ )+ reference_type = ReferenceType(+ type="ticket",+ owner_id=member_id,+ read_visibility="public",+ write_visibility="private",+ display_name="Ticket",+ instructions="",+ value_hint="",+ )+ session.add_all(+ [+ package,+ reference,+ reference_type,+ room,+ chat,+ library,+ template,+ clashing,+ clashing_elsewhere,+ admins,+ ]+ )+ await session.flush()+ in_chat = _library_document(member_id, room_id=chat.id)+ session.add(in_chat)+ await session.commit()+ handed = {+ Package: package.id,+ Reference: reference.id,+ Room: room.id,+ Document: library.id,+ Template: template.id,+ }+ kept = {Room: chat.id, Document: in_chat.id, Template: clashing.id}+ kept_elsewhere = clashing_elsewhere.id+ # Template names are unique per owner across workspaces, and the removal's+ # session can't see this one in another workspace.+ await _make_tenant(session_factory, TENANT_B)+ async with tenant_session(session_factory, TENANT_B) as session:+ session.add(+ Template(+ owner_id=admin_id,+ name="elsewhere",+ description="",+ kind="room",+ content="v",+ )+ )+ await session.commit()++ token = _token(admin_id, "[email protected]", TENANT_A)+ async with _client(_app(session_factory), token) as client:+ response = await client.delete(f"/tenants/{TENANT_A}/members/{member_id}")+ assert response.status_code == 200, response.text++ async with tenant_session(session_factory, TENANT_A) as session:+ for model, row_id in handed.items():+ owner = await session.scalar(+ select(model.owner_id).where(model.id == row_id)+ )+ assert owner == admin_id, model.__name__+ for model, row_id in kept.items():+ owner = await session.scalar(+ select(model.owner_id).where(model.id == row_id)+ )+ assert owner == member_id, model.__name__+ assert (+ await session.scalar(+ select(Template.owner_id).where(Template.id == kept_elsewhere)+ )+ == member_id+ )+ assert (+ await session.scalar(+ select(ReferenceType.owner_id).where(ReferenceType.type == "ticket")+ )+ == admin_id+ )+ typed = await session.scalar(+ select(AuditEvent).where(+ AuditEvent.action == "ownership.transferred",+ AuditEvent.target_type == "reference_type",+ )+ )+ assert typed is not None and typed.target_id == "ticket"+ moved = await session.scalar(+ select(AuditEvent).where(AuditEvent.target_id == package.id)+ )+ assert moved is not None+ assert moved.action == "ownership.transferred"+ assert moved.actor_user_id == admin_id+ assert moved.details is not None+ assert moved.details["reason"] == "member_removed"+ removal = await session.scalar(+ select(AuditEvent).where(+ AuditEvent.action == "member.removed",+ AuditEvent.target_id == member_id,+ )+ )+ assert removal is not None and removal.details is not None+ assert removal.details["handed_over_to"] == admin_id+ assert removal.details["handed_over"] == {+ "room": 1,+ "package": 1,+ "reference": 1,+ "reference_type": 1,+ "document": 1,+ "template": 1,+ }+++async def test_from_outside_the_workspace_the_longest_standing_admin_takes_over(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The server's operator removing someone without being a member, or the+ organization's directory removing them, leaves no remover in the+ workspace to take over: its longest-standing other admin does."""+ await _make_tenant(session_factory, TENANT_A)+ joined = datetime(2026, 1, 1, tzinfo=UTC)+ later = await _make_member(+ session_factory, name="later-admin", tenant_id=TENANT_A, role="admin"+ )+ first = await _make_member(+ session_factory, name="first-admin", tenant_id=TENANT_A, role="admin"+ )+ leaving = await _make_member(+ session_factory, name="leaving", tenant_id=TENANT_A, role="admin"+ )+ outsider = "operator-without-a-membership"+ async with tenant_session(session_factory, TENANT_A) as session:+ for user_id, when in (+ (leaving, joined - timedelta(days=9)),+ (first, joined),+ (later, joined + timedelta(days=1)),+ ):+ row = await session.get(TenantMember, (TENANT_A, user_id))+ assert row is not None+ row.created_at = when # type: ignore[assignment]+ await session.commit()++ assert await removal_heir(session, TENANT_A, leaving, outsider) == first+ assert await removal_heir(session, TENANT_A, leaving, None) == first+ assert await removal_heir(session, TENANT_A, leaving, later) == later+++async def test_with_no_other_admin_what_they_own_stays_theirs(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ await _make_tenant(session_factory, TENANT_A)+ leaving = await _make_member(+ session_factory, name="leaving", tenant_id=TENANT_A, role="member"+ )+ async with tenant_session(session_factory, TENANT_A) as session:+ assert await removal_heir(session, TENANT_A, leaving, None) is Nonediff --git a/core/tests/switch_core/test_organization_mirror_apply.py b/core/tests/switch_core/test_organization_mirror_apply.pyindex ad08be93f..c944f05f0 100644--- a/core/tests/switch_core/test_organization_mirror_apply.py+++ b/core/tests/switch_core/test_organization_mirror_apply.py@@ -26,6 +26,7 @@ from switch_core.db.models import (Organization,OrganizationAuditEvent,OrganizationMember,+ Package,Tenant,TenantMember,User,@@ -305,6 +306,51 @@ class TestTakingAway:[(action, _)] = await _organization_events(owner, world.organization_id)assert action == OrganizationAuditAction.MEMBER_DEMOTED_FROM_DIRECTORY+ async def test_what_only_org_admin_reached_passes_to_an_admin_there(+ self, rls_harness: RLSHarness+ ) -> None:+ """Ending access that came only from being `org_admin` leaves what Ada+ owns in that workspace with someone who can still reach it, as a+ removal does."""+ owner = rls_harness.owner+ world = await _World.make(owner)+ cleo = _id("cleo")+ async with owner() as session:+ session.add(+ User(id=cleo, name=cleo, email=f"{cleo}@example.invalid", role="user")+ )+ await session.flush()+ session.add(+ TenantMember(tenant_id=world.reached, user_id=cleo, role="admin")+ )+ package = Package(+ tenant_id=world.reached,+ owner_id=world.ada,+ name="kit",+ description="",+ instructions="",+ read_visibility="private",+ write_visibility="private",+ )+ session.add(package)+ await session.commit()+ package_id = package.id++ await _apply(rls_harness, world, "member")++ async with owner() as session:+ moved = await session.get(Package, package_id)+ assert moved is not None and moved.owner_id == cleo+ ended = await session.scalar(+ select(AuditEvent).where(+ AuditEvent.tenant_id == world.reached,+ AuditEvent.action == AuditAction.ORGANIZATION_ADMIN_ACCESS_ENDED,+ )+ )+ assert ended is not None and ended.details is not None+ assert ended.details["handed_over_to"] == cleo+ assert ended.details["handed_over"] == {"package": 1}+async def test_nothing_is_applied_once_the_organization_follows_another(self, rls_harness: RLSHarness) -> None: