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 account deletion for people removed from a workspace (#999)
Abel Dantas7f6ce7b36b10
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef02cac8d..4d41a9272 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -759,6 +759,10 @@ version of their own to them without also giving them a release of their own.through. Slack apps that list `/run-cmd` in their manifest keep showing it,answering "Unknown command", until an admin deletes it; Discord and Telegramdrop it from their command lists by themselves (#730).+- **Deleting your account now also clears workspaces you were removed from.**+ Removing a member leaves what they own in that workspace, and deleting their+ account afterwards failed on it. Those rows are now deleted or handed over as+ they are in the workspaces you are still in.### [0.31.0] - 2026-10-20diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.pyindex 8d9ba045c..1033d1870 100644--- a/core/switch_core/accounts/deletion.py+++ b/core/switch_core/accounts/deletion.py@@ -23,6 +23,12 @@ ahead would strand something nobody else could reach:A workspace the person is alone in is left empty rather than deleted: theschema cannot delete a workspace yet.+A workspace the person has left, or been removed from, can still hold rows+that name them: removing a member deletes their keys and connections but not+what they own there. Those workspaces are found too (`with_former_workspaces`)+and cleared the same way, or the final `DELETE FROM users` would fail on a+foreign key after the other workspaces were already done.+`USER_REFERENCES` names every column that points at a user and how this moduledeals with it; a test holds it to the database, so a new column that points ata user cannot be added without saying what happens to it here.@@ -35,12 +41,13 @@ from contextlib import AsyncExitStackfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal, Protocol-from sqlalchemy import delete, func, or_, select, update+from sqlalchemy import Select, case, delete, exists, func, or_, select, updatefrom switch_core.authz import ORGANIZATION_ADMIN_ROLEfrom switch_core.bridges.resource.service import ReferenceTypeInUseErrorfrom switch_core.connections.broker import ServiceErrorfrom switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.base import Basefrom switch_core.db.models import (AgentController,AgentControllerEnrollmentCode,@@ -71,7 +78,9 @@ from switch_core.db.models import (User,WorkspaceServiceSetting,)+from switch_core.db.rls_ddl import GLOBAL_TABLESfrom switch_core.db.session_scope import organization_session, tenant_session+from switch_core.db.tenant_lookup import all_tenant_idsfrom switch_core.tenant_context import tenant_scopeif TYPE_CHECKING:@@ -147,6 +156,48 @@ USER_REFERENCES: dict[tuple[str, str], Handling] = {}+# The role recorded for a workspace the person is no longer a member of.+FORMER_MEMBER = "former member"+++def _holds_rows_in_workspace(tenant_id: str, user_id: str) -> Select[tuple[bool]]:+ """Whether any row this module deals with in `tenant_id` names `user_id`.++ The columns come from `USER_REFERENCES`, so a column added there is+ probed here too. Membership is left out: a former member has none. Names+ its tenant as well as relying on the policy, so a connection the policy+ does not apply to cannot find another workspace's rows."""+ probes = [+ exists().where(+ Base.metadata.tables[table].c.tenant_id == tenant_id,+ Base.metadata.tables[table].c[column] == user_id,+ )+ for (table, column), handling in USER_REFERENCES.items()+ if table not in GLOBAL_TABLES+ and table != "tenant_members"+ and handling not in ("database cascades", "database clears")+ ]+ return select(or_(*probes))+++def _reference_type_heir(slug: str, user_id: str) -> Select[tuple[str]]:+ """Who a reference type in use passes to: an admin of the workspace who+ has a reference of that type, else whoever owns the oldest such+ reference; ties go to the oldest reference, then the lowest id."""+ rank = case((TenantMember.role == "admin", 0), else_=1)+ return (+ select(Reference.owner_id)+ .outerjoin(+ TenantMember,+ (TenantMember.tenant_id == Reference.tenant_id)+ & (TenantMember.user_id == Reference.owner_id),+ )+ .where(Reference.type == slug, Reference.owner_id != user_id)+ .order_by(rank, Reference.created_at, Reference.id)+ .limit(1)+ )++class ControllerRevoker(Protocol):"""Revokes a machine, as removing it in Switch Console does. Agentmanagement's, handed over by the wiring: core does not import it."""@@ -184,6 +235,29 @@ class AccountDeletion:templates: TemplateStoreadmin_email: str+ async def with_former_workspaces(+ self, user_id: str, workspaces: list[Workspace]+ ) -> list[Workspace]:+ """`workspaces`, the person's memberships, plus every other workspace+ that still holds a row naming them, as `FORMER_MEMBER`."""+ member_of = {workspace.id for workspace in workspaces}+ former: list[Workspace] = []+ for tenant_id in sorted(await all_tenant_ids(self.session_factory)):+ if tenant_id in member_of:+ continue+ async with tenant_session(self.session_factory, tenant_id) as session:+ if not await session.scalar(+ _holds_rows_in_workspace(tenant_id, user_id)+ ):+ continue+ tenant = await session.get(Tenant, tenant_id)+ if tenant is None:+ raise RuntimeError(f"Workspace {tenant_id} vanished during lookup")+ former.append(+ Workspace(id=tenant_id, name=tenant.name, role=FORMER_MEMBER)+ )+ return [*workspaces, *former]+async def refusal(self, session: AsyncSession, user: User, workspaces: list[Workspace]) -> str | None:@@ -217,7 +291,11 @@ class AccountDeletion:if organization_refusal is not None:return organization_refusalmembers = await self.users.list_tenant_members(session)- alone = all(member.id == user.id for member, _ in members)+ # A former member is never alone in a workspace: what they left+ # there is handed over or cleared like anything else they left.+ alone = workspace.role != FORMER_MEMBER and all(+ member.id == user.id for member, _ in members+ )if (not aloneand await self.users.tenant_role(session, workspace.id, user.id)@@ -508,18 +586,15 @@ class AccountDeletion:async def _successor(self, session: AsyncSession, user_id: str) -> str | None:"""Who takes over what the workspace still needs from this person: an- admin, else nobody when no other admin is in it."""+ admin, else nobody when no other admin is in it. Among several, the+ longest-standing admin, then the lowest id, so the same workspace+ always picks the same person."""ranked = sorted(- (- (membership.role, member.id)- for member, membership in await self.users.list_tenant_members(session)- if member.id != user_id- ),- key=lambda entry: 0 if entry[0] == "admin" else 1,+ (membership.created_at, member.id)+ for member, membership in await self.users.list_tenant_members(session)+ if member.id != user_id and membership.role == "admin")- if not ranked or ranked[0][0] != "admin":- return None- return ranked[0][1]+ return ranked[0][1] if ranked else Noneasync def _revoke_controllers(self, tenant_id: str, user_id: str, controller_ids: list[str]@@ -573,9 +648,12 @@ class AccountDeletion:except ReferenceTypeInUseError:# Other people's references are of this type: it passes to one# of them rather than leaving their references with no type.- heir = await session.scalar(- select(Reference.owner_id).where(Reference.type == slug).limit(1)- )+ heir = await session.scalar(_reference_type_heir(slug, user_id))+ if heir is None:+ raise RuntimeError(+ f"Reference type {slug} is in use but has no other "+ "reference owner to pass to"+ )await session.execute(update(ReferenceType).where(ReferenceType.type == slug)diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex f55ba5abd..ddbf1eb24 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -530,6 +530,7 @@ async def delete_my_account(templates=template_store,admin_email=config.gateway_admin_email,)+ workspaces = await deletion.with_former_workspaces(user.id, workspaces)reason = await deletion.refusal(session, user, workspaces)if reason is not None:raise HTTPException(status_code=409, detail=reason)diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.pyindex 0bf79ee7e..83310a2ec 100644--- a/core/tests/switch_core/accounts/test_account_deletion.py+++ b/core/tests/switch_core/accounts/test_account_deletion.py@@ -37,6 +37,7 @@ from switch_core.db.models import (Organization,OrganizationMember,Reference,+ ReferenceType,Room,Template,Tenant,@@ -571,3 +572,228 @@ async def test_an_account_with_a_cloud_machine_is_refused(await session.commit()reason = await deletion.refusal(session, user, [])assert reason is not None and "cloud machine" in reason+++async def test_a_messaging_app_left_in_a_workspace_since_emptied_does_not_refuse(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Removed from a workspace everyone has since left, the person is not+ "alone" in it: the app they installed there goes with the rest, rather+ than refusing a deletion they could not act on."""+ deletion, _, _ = _deletion(session_factory)+ empty = f"empty-{uuid.uuid4().hex[:6]}"+ async with session_factory() as session:+ session.add(Tenant(id=empty, slug=empty, name="Empty"))+ await session.flush()+ removed = await _user(session, "removed")+ removed_id = removed.id+ await session.commit()+ async with tenant_session(session_factory, empty) as session:+ session.add(+ MessagingInstall(+ tenant_id=empty,+ platform="slack",+ external_workspace_id="T-empty",+ scopes="chat:write",+ status="active",+ installed_by_user_id=removed_id,+ )+ )+ await session.commit()++ async with session_factory() as session:+ user = await session.get(User, removed_id)+ assert user is not None+ workspaces = await deletion.with_former_workspaces(user.id, [])+ assert [(w.id, w.role) for w in workspaces] == [(empty, "former member")]+ assert await deletion.refusal(session, user, workspaces) is None+ await deletion.delete(session, user, workspaces)++ async with session_factory() as session:+ assert await session.get(User, removed_id) is None+++async def test_a_workspace_the_person_was_removed_from_is_cleared_too(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Removing a member leaves what they own in that workspace; deleting+ their account later finds it there and deletes it, rather than failing on+ the foreign keys it holds."""+ deletion, _, _ = _deletion(session_factory)+ left = f"left-{uuid.uuid4().hex[:6]}"+ async with session_factory() as session:+ session.add(Tenant(id=left, slug=left, name="Left"))+ await session.flush()+ admin = await _user(session, "admin")+ removed = await _user(session, "removed")+ ids = {"admin": admin.id, "removed": removed.id}+ await session.commit()+ async with tenant_session(session_factory, left) as session:+ await _member(session, left, admin, "admin")+ invitation = await _invitation(session, left, removed)+ reference = Reference(+ tenant_id=left,+ owner_id=removed.id,+ read_visibility="public",+ write_visibility="private",+ type="url",+ name="kept",+ description="",+ instructions="",+ value={"url": "https://example.test"},+ )+ session.add(reference)+ await session.commit()+ ids["invitation"] = invitation.id+ ids["reference"] = reference.id++ async with session_factory() as session:+ user = await session.get(User, ids["removed"])+ assert user is not None+ workspaces = await deletion.with_former_workspaces(user.id, [])+ assert [(w.id, w.role) for w in workspaces] == [(left, "former member")]+ assert await deletion.refusal(session, user, workspaces) is None+ await deletion.delete(session, user, workspaces)++ async with session_factory() as session:+ assert await session.get(User, ids["removed"]) is None+ async with tenant_session(session_factory, left) as session:+ assert await session.get(Reference, ids["reference"]) is None+ assert (+ await session.scalar(+ select(Invitation.created_by).where(Invitation.id == ids["invitation"])+ )+ ) == ids["admin"]+++async def test_a_workspace_holding_nothing_of_the_person_is_not_touched(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ deletion, _, _ = _deletion(session_factory)+ other = f"other-{uuid.uuid4().hex[:6]}"+ async with session_factory() as session:+ session.add(Tenant(id=other, slug=other, name="Other"))+ await session.flush()+ stranger = await _user(session, "stranger")+ await session.commit()+ workspaces = await deletion.with_former_workspaces(stranger.id, [])+ assert all(w.id != other for w in workspaces)+++def _reference_of(owner: User, slug: str, created_at: datetime) -> Reference:+ return Reference(+ owner_id=owner.id,+ read_visibility="public",+ write_visibility="private",+ type=slug,+ name=f"{owner.name}-{slug}",+ description="",+ instructions="",+ value={"value": "x"},+ created_at=created_at,+ )++[email protected]("admin_has_one", [True, False])+async def test_a_reference_type_in_use_passes_to_an_admin_else_the_oldest_reference(+ session_factory: async_sessionmaker[AsyncSession], admin_has_one: bool+) -> None:+ """An admin with a reference of the type inherits it before any member+ does; with none, the owner of the oldest reference of it does."""+ deletion, _, _ = _deletion(session_factory)+ slug = f"ticket-{uuid.uuid4().hex[:6]}"+ start = datetime(2026, 1, 1, tzinfo=UTC)+ async with session_factory() as session:+ other_admin = await _user(session, "other-admin")+ leaving = await _user(session, "leaving")+ early = await _user(session, "early")+ late = await _user(session, "late")+ admin = await _user(session, "admin-member")+ await _member(session, TENANT_ZERO_ID, other_admin, "admin")+ await _member(session, TENANT_ZERO_ID, leaving, "member")+ await _member(session, TENANT_ZERO_ID, early, "member")+ await _member(session, TENANT_ZERO_ID, late, "member")+ await _member(session, TENANT_ZERO_ID, admin, "admin")+ session.add(+ ReferenceType(+ tenant_id=TENANT_ZERO_ID,+ type=slug,+ owner_id=leaving.id,+ read_visibility="public",+ write_visibility="private",+ display_name="Ticket",+ instructions="",+ value_hint="",+ )+ )+ session.add(_reference_of(late, slug, start + timedelta(days=2)))+ session.add(_reference_of(early, slug, start + timedelta(days=1)))+ if admin_has_one:+ session.add(_reference_of(admin, slug, start + timedelta(days=3)))+ await session.commit()+ expected = admin.id if admin_has_one else early.id+ leaving_id = leaving.id++ workspaces = [Workspace(TENANT_ZERO_ID, "Default", "member")]+ async with session_factory() as session:+ user = await session.get(User, leaving_id)+ assert user is not None+ await deletion.delete(session, user, workspaces)++ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ assert (+ await session.scalar(+ select(ReferenceType.owner_id).where(ReferenceType.type == slug)+ )+ ) == expected+++async def test_the_successor_is_the_longest_standing_admin_then_the_lowest_id(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ deletion, _, _ = _deletion(session_factory)+ joined = datetime(2026, 1, 1, tzinfo=UTC)+ async with session_factory() as session:+ leaving = await _user(session, "leaving")+ session.add(+ TenantMember(+ tenant_id=TENANT_ZERO_ID,+ user_id=leaving.id,+ role="admin",+ created_at=joined - timedelta(days=9),+ )+ )+ member = await _user(session, "member-first")+ session.add(+ TenantMember(+ tenant_id=TENANT_ZERO_ID,+ user_id=member.id,+ role="member",+ created_at=joined - timedelta(days=5),+ )+ )+ tied = [await _user(session, f"admin-{n}") for n in range(3)]+ for admin in tied:+ session.add(+ TenantMember(+ tenant_id=TENANT_ZERO_ID,+ user_id=admin.id,+ role="admin",+ created_at=joined,+ )+ )+ later = await _user(session, "admin-later")+ session.add(+ TenantMember(+ tenant_id=TENANT_ZERO_ID,+ user_id=later.id,+ role="admin",+ created_at=joined + timedelta(days=1),+ )+ )+ await session.commit()+ expected = min(admin.id for admin in tied)+ leaving_id = leaving.id++ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ assert await deletion._successor(session, leaving_id) == expecteddiff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex 7a21d18ec..b66d3d7fa 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -112,6 +112,11 @@ _ALLOWED_MODULES = {# `tenants_of_cloud_machine`, and each one's row on the machine is then# read with that workspace bound."switch_core.db.stores.hosted_machine_store",+ # Deleting an account also clears the workspaces the person was removed+ # from, where nothing binds them any more: enumerate the tenants, then+ # look for their rows in each under its own policy, the same fan-out as+ # the boot work.+ "switch_core.accounts.deletion",# Enumerating tenants at boot, and starting one bridge by id from a# context bound to somebody else's tenant."switch_core.clients.client_lifecycle_service",