Skip to content

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

Let a workspace owner erase a person (CHOO-3047)

Petr Bauch90781602011b
diff --git a/CLAUDE.md b/CLAUDE.md
index b6efb7feb..b9cf6da00 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -224,7 +224,7 @@ Tests live in `core/tests/switch_core/` mirroring the module structure. Uses pyt
- `docs/design/data-retention.md` — what Switch deletes: the per-workspace
message-retention window, the orphaned-file sweep, the leftover records
pruned after a grace period, and a GDPR design note for what is not built
- (erasing a person, export, workspace deletion, audit-log horizon)
+ (export, workspace deletion, audit-log horizon) and how erasing a person works
- `docs/old/rds-migration.md` — moving a deployment's Postgres to RDS: the
proposal and the cutover runbook
diff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.py
index 2b0890658..993f90dca 100644
--- a/core/switch_core/bridges/collaboration/collaboration_core.py
+++ b/core/switch_core/bridges/collaboration/collaboration_core.py
@@ -2351,6 +2351,19 @@ class CollaborationCore:
)
return created
+ async def forget_human(self, external_user_id: str, transport_user_id: str) -> None:
+ """Drop what this bridge remembers about a person whose identity was erased.
+
+ Called once their rows are gone and their client is stopped. If they
+ write again they are provisioned afresh, as someone never seen before.
+ """
+ lock = self._human_actor_locks.setdefault(external_user_id, asyncio.Lock())
+ async with lock:
+ self._human_actors.pop(external_user_id, None)
+ self._names_known_good.discard(external_user_id)
+ self._human_user_ids.discard(transport_user_id)
+ self._human_actor_locks.pop(external_user_id, None)
+
async def _create_human_actor(
self, external_user_id: str, external_username: str
) -> str:
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 7a3cd3244..bfb9a9236 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -470,6 +470,16 @@ class CollaborationBridgeLifecycleService:
"""
return bridge_id in self._connected
+ async def forget_human(
+ self, bridge_id: str, external_user_id: str, transport_user_id: str
+ ) -> None:
+ """Tell a running bridge that one of its people was erased. A bridge
+ that is not running has nothing in memory, and loads from the database
+ when it starts."""
+ bridge = self._bridges.get(bridge_id)
+ if bridge is not None:
+ await bridge.forget_human(external_user_id, transport_user_id)
+
def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:
"""The live adapter for a running bridge, or None if it isn't running.
diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.py
index a9ea04679..f23306413 100644
--- a/core/switch_core/db/audit.py
+++ b/core/switch_core/db/audit.py
@@ -76,6 +76,8 @@ class AuditAction(StrEnum):
OWNERSHIP_TRANSFERRED = "ownership.transferred"
RETENTION_POLICY_SET = "retention_policy.set"
RETENTION_POLICY_CLEARED = "retention_policy.cleared"
+ PERSON_ERASURE_REQUESTED = "person_erasure.requested"
+ PERSON_ERASURE_COMPLETED = "person_erasure.completed"
class OrganizationAuditAction(StrEnum):
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index c16e98930..9db79f8ab 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -2748,6 +2748,8 @@ class Message(TenantScoped, Base):
"seq",
postgresql_where=text("event_type = 'com.switch.command'"),
),
+ # Erasing a person and counting what they sent both ask by sender.
+ Index("ix_messages_tenant_sender", "tenant_id", "sender_id"),
Index(
"ix_messages_thread_root",
"room_id",
@@ -4107,6 +4109,59 @@ class TenantRetentionPolicy(TenantScoped, Base):
)
+class PersonErasure(TenantScoped, Base):
+ """A workspace owner's request to erase one person from the workspace.
+
+ `external_user_ids` names the platform identities to erase: one row of
+ `external_users` per platform the person was seen on. Erasing them deletes
+ every message they sent, the files those carried, their identity records
+ and the client standing in for each, and their name on approval answers
+ (`retention/erasure.py`). Queued here and worked by a background loop, so
+ a person with years of history cannot time out the request that asked.
+
+ Nothing here names the person once they are erased: the ids are internal
+ and point at rows that no longer exist, and the counts are counts.
+ """
+
+ __tablename__ = "person_erasures"
+ __table_args__ = (
+ Index("ix_person_erasures_tenant_id", "tenant_id"),
+ CheckConstraint(
+ "state IN ('queued', 'running', 'done', 'failed')",
+ name="ck_person_erasures_state",
+ ),
+ )
+
+ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
+ external_user_ids: Mapped[list] = mapped_column(JSONB, nullable=False)
+ state: Mapped[str] = mapped_column(Text, nullable=False, default="queued")
+ requested_by_user_id: Mapped[str | None] = mapped_column(
+ Text, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
+ )
+ messages_deleted: Mapped[int] = mapped_column(
+ BigInteger, nullable=False, server_default=text("0")
+ )
+ files_deleted: Mapped[int] = mapped_column(
+ Integer, nullable=False, server_default=text("0")
+ )
+ identities_erased: Mapped[int] = mapped_column(
+ Integer, nullable=False, server_default=text("0")
+ )
+ error: Mapped[str | None] = mapped_column(Text, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ server_default=func.now(),
+ onupdate=func.now(),
+ nullable=False,
+ )
+ completed_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+
+
# ── Agent management ──────────────────────────────────────────────────────────
# `api_keys.type` values that hold a hash and nothing else. Nothing may decrypt
diff --git a/core/switch_core/db/stores/erasure_store.py b/core/switch_core/db/stores/erasure_store.py
new file mode 100644
index 000000000..6fe201c73
--- /dev/null
+++ b/core/switch_core/db/stores/erasure_store.py
@@ -0,0 +1,305 @@
+"""Erasing a person: who can be erased, the request queue, and the deletions
+that are not messages, for the bound tenant.
+
+A person in a room is a chat-platform identity: an `external_users` row on
+one bridge, standing behind a `clients` row that is the room participant.
+One person seen on two platforms is two identities. Message deletion itself
+is `MessageStore.delete_sent_by`, which keeps the room's numbering intact.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any, cast
+
+from sqlalchemy import (
+ ARRAY,
+ CursorResult,
+ Result,
+ Text,
+ delete,
+ func,
+ select,
+ text,
+ update,
+)
+from sqlalchemy import cast as cast_
+from sqlalchemy.dialects.postgresql import array
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import (
+ ApprovalRequest,
+ Client,
+ CollaborationBridge,
+ ExternalUser,
+ ExternalUserClaim,
+ Message,
+ PersonErasure,
+ User,
+ require_tenant_id,
+)
+
+#: What `answered_by` reads once the person who answered has been erased.
+ERASED_ANSWERER = "erased"
+
+ACTIVE_STATES = ("queued", "running")
+
+
+class ErasureAlreadyQueued(Exception):
+ """An identity named in a request already has an erasure queued or running."""
+
+
+class UnknownIdentity(Exception):
+ """An identity named in a request is not in this workspace."""
+
+
+@dataclass(frozen=True)
+class Claimant:
+ user_id: str
+ name: str
+
+
+@dataclass(frozen=True)
+class Person:
+ """One platform identity, and what erasing it would delete."""
+
+ external_user_id: str
+ username: str
+ bridge_id: str
+ platform: str
+ bridge_name: str
+ client_id: str
+ transport_user_id: str
+ message_count: int
+ claimed_by: list[Claimant]
+
+
+def _rowcount(result: Result[Any]) -> int:
+ return cast("CursorResult[Any]", result).rowcount
+
+
+class ErasureStore:
+ async def list_people(
+ self,
+ session: AsyncSession,
+ external_user_ids: Collection[str] | None = None,
+ ) -> list[Person]:
+ """Every platform identity in the bound tenant, or the ones named."""
+ tenant_id = require_tenant_id()
+ counts = (
+ select(Message.sender_id, func.count().label("n"))
+ .where(Message.tenant_id == tenant_id)
+ .group_by(Message.sender_id)
+ .subquery()
+ )
+ query = (
+ select(
+ ExternalUser.id,
+ ExternalUser.external_username,
+ ExternalUser.bridge_id,
+ CollaborationBridge.type,
+ CollaborationBridge.display_name,
+ Client.id,
+ Client.transport_user_id,
+ func.coalesce(counts.c.n, 0),
+ )
+ .join(
+ CollaborationBridge,
+ (CollaborationBridge.tenant_id == ExternalUser.tenant_id)
+ & (CollaborationBridge.id == ExternalUser.bridge_id),
+ )
+ .join(
+ Client,
+ (Client.tenant_id == ExternalUser.tenant_id)
+ & (Client.id == ExternalUser.client_id),
+ )
+ .outerjoin(counts, counts.c.sender_id == Client.transport_user_id)
+ .where(ExternalUser.tenant_id == tenant_id)
+ .order_by(func.lower(ExternalUser.external_username), ExternalUser.id)
+ )
+ if external_user_ids is not None:
+ query = query.where(ExternalUser.id.in_(list(external_user_ids)))
+ rows = (await session.execute(query)).all()
+
+ claims: dict[str, list[Claimant]] = {}
+ if rows:
+ claim_rows = await session.execute(
+ select(ExternalUserClaim.external_user_id, User.id, User.name)
+ .join(User, User.id == ExternalUserClaim.user_id)
+ .where(
+ ExternalUserClaim.tenant_id == tenant_id,
+ ExternalUserClaim.external_user_id.in_([r[0] for r in rows]),
+ )
+ .order_by(User.name)
+ )
+ for external_user_id, user_id, name in claim_rows.all():
+ claims.setdefault(external_user_id, []).append(Claimant(user_id, name))
+
+ return [
+ Person(
+ external_user_id=row[0],
+ username=row[1],
+ bridge_id=row[2],
+ platform=row[3],
+ bridge_name=row[4],
+ client_id=row[5],
+ transport_user_id=row[6],
+ message_count=int(row[7]),
+ claimed_by=claims.get(row[0], []),
+ )
+ for row in rows
+ ]
+
+ async def queue(
+ self,
+ session: AsyncSession,
+ *,
+ external_user_ids: list[str],
+ requested_by_user_id: str,
+ ) -> PersonErasure:
+ """Queue the erasure of these identities, or raise.
+
+ Locks the tenant's erasure queue for the transaction, so two owners
+ asking at once cannot both pass the "nothing already queued" check.
+ """
+ await session.execute(
+ text("SELECT pg_advisory_xact_lock(hashtext('person_erasures:' || :t))"),
+ {"t": require_tenant_id()},
+ )
+ known = {
+ p.external_user_id
+ for p in await self.list_people(session, external_user_ids)
+ }
+ unknown = set(external_user_ids) - known
+ if unknown:
+ raise UnknownIdentity(", ".join(sorted(unknown)))
+ overlapping = await session.scalar(
+ select(func.count())
+ .select_from(PersonErasure)
+ .where(
+ PersonErasure.tenant_id == require_tenant_id(),
+ PersonErasure.state.in_(ACTIVE_STATES),
+ PersonErasure.external_user_ids.op("?|")(
+ cast_(array(external_user_ids), ARRAY(Text))
+ ),
+ )
+ )
+ if overlapping:
+ raise ErasureAlreadyQueued()
+ erasure = PersonErasure(
+ external_user_ids=list(external_user_ids),
+ state="queued",
+ requested_by_user_id=requested_by_user_id,
+ )
+ session.add(erasure)
+ await session.flush()
+ await session.refresh(erasure)
+ return erasure
+
+ async def list_erasures(
+ self, session: AsyncSession, *, limit: int
+ ) -> list[PersonErasure]:
+ result = await session.execute(
+ select(PersonErasure)
+ .where(PersonErasure.tenant_id == require_tenant_id())
+ .order_by(PersonErasure.created_at.desc())
+ .limit(limit)
+ )
+ return list(result.scalars())
+
+ async def next_pending(self, session: AsyncSession) -> PersonErasure | None:
+ """The oldest request still to finish. A `running` one is resumed: the
+ work is safe to repeat, and one left running by a restart is otherwise
+ never finished."""
+ result = await session.execute(
+ select(PersonErasure)
+ .where(
+ PersonErasure.tenant_id == require_tenant_id(),
+ PersonErasure.state.in_(ACTIVE_STATES),
+ )
+ .order_by(PersonErasure.created_at)
+ .limit(1)
+ )
+ return result.scalar_one_or_none()
+
+ async def mark(
+ self,
+ session: AsyncSession,
+ erasure_id: str,
+ *,
+ state: str,
+ messages_deleted: int,
+ files_deleted: int,
+ identities_erased: int,
+ error: str | None,
+ ) -> None:
+ finished = state in ("done", "failed")
+ await session.execute(
+ update(PersonErasure)
+ .where(
+ PersonErasure.tenant_id == require_tenant_id(),
+ PersonErasure.id == erasure_id,
+ )
+ .values(
+ state=state,
+ messages_deleted=messages_deleted,
+ files_deleted=files_deleted,
+ identities_erased=identities_erased,
+ error=error,
+ completed_at=datetime.now(UTC) if finished else None,
+ )
+ )
+
+ async def scrub_approval_answers(
+ self, session: AsyncSession, transport_user_id: str
+ ) -> int:
+ """Replace this participant's name on every approval answer they gave."""
+ result = await session.execute(
+ update(ApprovalRequest)
+ .where(
+ ApprovalRequest.tenant_id == require_tenant_id(),
+ ApprovalRequest.answered_by == transport_user_id,
+ )
+ .values(answered_by=ERASED_ANSWERER)
+ )
+ return _rowcount(result)
+
+ async def delete_identity(
+ self, session: AsyncSession, external_user_id: str
+ ) -> None:
+ """Delete the identity row; its claims go with it by cascade. The
+ client behind it is the caller's to delete afterwards, since the
+ identity points at it."""
+ await session.execute(
+ delete(ExternalUser).where(
+ ExternalUser.tenant_id == require_tenant_id(),
+ ExternalUser.id == external_user_id,
+ )
+ )
+
+ async def delete_unreferenced_media(
+ self, session: AsyncSession, uris: Collection[str]
+ ) -> int:
+ """Delete the stored files among `uris` that no attachment refers to now.
+
+ Unlike the hourly sweep this has no grace period: these files are known
+ to have been attached to the erased person's messages, so none is an
+ upload still waiting for its message.
+ """
+ if not uris:
+ return 0
+ result = await session.execute(
+ text(
+ """
+ DELETE FROM media_blobs b
+ WHERE b.tenant_id = :t AND b.uri = ANY(:uris)
+ AND NOT EXISTS (
+ SELECT 1 FROM message_attachments a
+ WHERE a.tenant_id = b.tenant_id AND a.uri = b.uri)
+ """
+ ),
+ {"t": require_tenant_id(), "uris": list(uris)},
+ )
+ return _rowcount(result)
diff --git a/core/switch_core/db/stores/message_store.py b/core/switch_core/db/stores/message_store.py
index a15b576b6..9a261df99 100644
--- a/core/switch_core/db/stores/message_store.py
+++ b/core/switch_core/db/stores/message_store.py
@@ -214,21 +214,58 @@ class MessageStore:
"""Delete up to `limit` of the bound tenant's oldest messages sent before
`cutoff`, with their attachments. Returns their transport event ids.
+ See `_delete_where` for what else changes and what does not.
+ """
+ return await self._delete_where(session, Message.sent_at < cutoff, limit=limit)
+
+ async def delete_sent_by(
+ self, session: AsyncSession, *, transport_user_id: str, limit: int
+ ) -> list[str]:
+ """Delete up to `limit` of the messages one participant sent in the bound
+ tenant, with their attachments. Returns their transport event ids.
+
+ Matched on `sender_id`, the participant's transport id, rather than
+ `sender_client_id`: every row has the first, while the second is null
+ on reconstructed history and on rows older than the column. See
+ `_delete_where` for the rest.
+ """
+ return await self._delete_where(
+ session, Message.sender_id == transport_user_id, limit=limit
+ )
+
+ async def attachment_uris_sent_by(
+ self, session: AsyncSession, *, transport_user_id: str
+ ) -> set[str]:
+ """The files on every message one participant sent in the bound tenant."""
+ result = await session.execute(
+ select(MessageAttachment.uri)
+ .join(Message, Message.id == MessageAttachment.message_id)
+ .where(
+ Message.tenant_id == require_tenant_id(),
+ Message.sender_id == transport_user_id,
+ )
+ .distinct()
+ )
+ return set(result.scalars())
+
+ async def _delete_where(
+ self, session: AsyncSession, condition: ColumnElement[bool], *, limit: int
+ ) -> list[str]:
+ """Delete up to `limit` of the bound tenant's oldest messages matching
+ `condition`, with their attachments. Returns their transport event ids.
+
Each room's `seq_floor` is raised to the highest live position deleted
from it, in the same transaction, so `_next_seq` never reissues one.
The bytes behind the attachments are not touched: a blob may be quoted
- by a message that is kept, so `RetentionStore.delete_unreferenced_media` finds
- the ones nothing points at any more.
+ by a message that is kept, so `RetentionStore.delete_unreferenced_media`
+ finds the ones nothing points at any more.
"""
rows = (
await session.execute(
select(
Message.id, Message.room_id, Message.seq, Message.transport_event_id
)
- .where(
- Message.tenant_id == require_tenant_id(),
- Message.sent_at < cutoff,
- )
+ .where(Message.tenant_id == require_tenant_id(), condition)
.order_by(Message.sent_at)
.limit(limit)
)
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index d8d31b2bc..9383e2971 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -20,6 +20,7 @@ from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.budget_store import BudgetStore
from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.erasure_store import ErasureStore
from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.invitation_store import InvitationStore
from switch_core.db.stores.join_domain_store import JoinDomainStore
@@ -234,6 +235,10 @@ def get_retention_store() -> RetentionStore:
return RetentionStore()
+def get_erasure_store() -> ErasureStore:
+ return ErasureStore()
+
+
def get_template_store() -> TemplateStore:
return _state["template_store"] # type: ignore[no-any-return]
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 628f2f3a4..181716e05 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -2046,3 +2046,39 @@ class RetentionPreviewResponse(BaseModel):
message_retention_days: int
messages_to_delete: int
+
+
+# ── Erasing a person ────────────────────────────────────────────────────────
+
+
+class ClaimantDetail(BaseModel):
+ user_id: str
+ name: str
+
+
+class PersonDetail(BaseModel):
+ """One chat-platform identity seen in the workspace's rooms."""
+
+ external_user_id: str
+ username: str
+ platform: str
+ bridge_name: str
+ message_count: int
+ claimed_by: list[ClaimantDetail]
+
+
+class ErasureCreateRequest(BaseModel):
+ external_user_ids: list[str] = Field(min_length=1, max_length=50)
+
+
+class ErasureDetail(BaseModel):
+ id: str
+ state: Literal["queued", "running", "done", "failed"]
+ identities: int
+ identities_erased: int
+ messages_deleted: int
+ files_deleted: int
+ error: str | None
+ requested_by_user_id: str | None
+ created_at: datetime
+ completed_at: datetime | None
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 4faa17adc..63c3a7b0f 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -41,6 +41,7 @@ from switch_core.db.models import (
Invitation,
Organization,
OrganizationMember,
+ PersonErasure,
Tenant,
TenantJoinDomain,
TenantMember,
@@ -55,6 +56,11 @@ from switch_core.db.stores.budget_store import (
BudgetStanding,
BudgetStore,
)
+from switch_core.db.stores.erasure_store import (
+ ErasureAlreadyQueued,
+ ErasureStore,
+ UnknownIdentity,
+)
from switch_core.db.stores.invitation_store import (
InvitationNotUsableError,
InvitationStore,
@@ -92,6 +98,7 @@ from switch_core.gateway.dependencies import (
get_budget_store,
get_client_lifecycle,
get_config,
+ get_erasure_store,
get_invitation_store,
get_invite_mailer,
get_join_domain_store,
@@ -119,7 +126,10 @@ from switch_core.gateway.schemas import (
BudgetCreateRequest,
BudgetResponse,
BudgetUpdateRequest,
+ ClaimantDetail,
CurrentTenantResponse,
+ ErasureCreateRequest,
+ ErasureDetail,
InvitationAcceptRequest,
InvitationCreateRequest,
InvitationCreateResponse,
@@ -131,6 +141,7 @@ from switch_core.gateway.schemas import (
MemberDetail,
MemberUpdateRequest,
OperatorWorkspaceResponse,
+ PersonDetail,
RetentionPolicyRequest,
RetentionPolicyResponse,
RetentionPreviewResponse,
@@ -902,6 +913,124 @@ async def clear_retention_policy(
return _retention_response(None, None, None)
+def _erasure_detail(erasure: PersonErasure) -> ErasureDetail:
+ return ErasureDetail(
+ id=erasure.id,
+ state=erasure.state, # type: ignore[arg-type]
+ identities=len(erasure.external_user_ids),
+ identities_erased=erasure.identities_erased,
+ messages_deleted=erasure.messages_deleted,
+ files_deleted=erasure.files_deleted,
+ error=erasure.error,
+ requested_by_user_id=erasure.requested_by_user_id,
+ created_at=erasure.created_at,
+ completed_at=erasure.completed_at,
+ )
+
+async def _require_admin_membership(
+ session: AsyncSession, user_store: UserStore, tenant_id: str, user: User
+) -> None:
+ """Erasing a person cannot be undone, so, like deleting the workspace, it
+ takes the caller's own admin membership: not the deployment operator's
+ bypass, and not an organization admin acting as one."""
+ if await user_store.tenant_role(session, tenant_id, user.id) != "admin":
+ raise HTTPException(
+ status_code=403, detail="Only a workspace admin may erase people"
+ )
+
+
+
[email protected]("/tenants/{tenant_id}/people")
+async def list_people(
+ tenant_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ erasure_store: Annotated[ErasureStore, Depends(get_erasure_store)],
+ user: Annotated[User, Depends(require_tenant_admin)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+) -> list[PersonDetail]:
+ """Every chat-platform identity seen in the bound tenant's rooms, with how
+ many messages each sent and which members claim it. Admins only, by their
+ own admin membership: this is the list a person is erased from."""
+ _require_bound_tenant(tenant_id)
+ await _require_admin_membership(session, user_store, tenant_id, user)
+ return [
+ PersonDetail(
+ external_user_id=person.external_user_id,
+ username=person.username,
+ platform=person.platform,
+ bridge_name=person.bridge_name,
+ message_count=person.message_count,
+ claimed_by=[
+ ClaimantDetail(user_id=c.user_id, name=c.name)
+ for c in person.claimed_by
+ ],
+ )
+ for person in await erasure_store.list_people(session)
+ ]
+
+
[email protected]("/tenants/{tenant_id}/erasures")
+async def list_erasures(
+ tenant_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ erasure_store: Annotated[ErasureStore, Depends(get_erasure_store)],
+ user: Annotated[User, Depends(require_tenant_admin)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+) -> list[ErasureDetail]:
+ """The bound tenant's erasure requests, newest first. Admins only, by
+ their own admin membership."""
+ _require_bound_tenant(tenant_id)
+ await _require_admin_membership(session, user_store, tenant_id, user)
+ return [
+ _erasure_detail(e) for e in await erasure_store.list_erasures(session, limit=50)
+ ]
+
+
[email protected]("/tenants/{tenant_id}/erasures", status_code=202)
+async def create_erasure(
+ tenant_id: str,
+ body: ErasureCreateRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ erasure_store: Annotated[ErasureStore, Depends(get_erasure_store)],
+ user: Annotated[User, Depends(require_tenant_admin)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+) -> ErasureDetail:
+ """Queue the erasure of one person: every message the named identities
+ sent, their files, and the identities themselves. Admins only, by their
+ own admin membership.
+
+ Answered once queued; the work runs in the background within seconds and
+ `GET .../erasures` reports its progress. 404 names an identity that is not
+ in this workspace; 409 means one is already being erased.
+ """
+ _require_bound_tenant(tenant_id)
+ await _require_admin_membership(session, user_store, tenant_id, user)
+ ids = list(dict.fromkeys(body.external_user_ids))
+ try:
+ erasure = await erasure_store.queue(
+ session, external_user_ids=ids, requested_by_user_id=user.id
+ )
+ except UnknownIdentity as exc:
+ raise HTTPException(
+ status_code=404, detail="Person not found in this workspace"
+ ) from exc
+ except ErasureAlreadyQueued as exc:
+ raise HTTPException(
+ status_code=409, detail="This person is already being erased"
+ ) from exc
+ await record_audit_event(
+ session,
+ tenant_id=tenant_id,
+ actor_user_id=user.id,
+ action=AuditAction.PERSON_ERASURE_REQUESTED,
+ target_type="person_erasure",
+ target_id=erasure.id,
+ details={"external_user_ids": ids},
+ )
+ await session.commit()
+ return _erasure_detail(erasure)
+
+
@router.get("/tenants/{tenant_id}/invitations")
async def list_invitations(
tenant_id: str,
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 41de504fe..5160e59b1 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -212,6 +212,7 @@ from switch_core.provisioning import Provisioning
from switch_core.provisioning.postgres import PostgresProvisioning
from switch_core.room_changes import COALESCE_SECONDS, RoomChanges
from switch_core.retention.service import retention_loop
+from switch_core.retention.erasure import ErasureService, erasure_loop
from switch_core.room_service import RoomService
from switch_core.session_activity.listener import AgentSessionActivityListener
from switch_core.session_activity.maintenance import (
@@ -1523,6 +1524,12 @@ async def run(config: SwitchConfig, process_id: str) -> None:
else None
)
data_retention_task = asyncio.create_task(retention_loop(session_factory))
+ erasure_task = asyncio.create_task(
+ erasure_loop(
+ session_factory,
+ ErasureService(session_factory, client_lifecycle, collab_lifecycle),
+ )
+ )
# Only when telemetry is on: the chart tells a customer that off
# means nothing is collected, and the fan-out is not free.
snapshot_task = (
@@ -1545,6 +1552,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:
connection_sweep_task.cancel()
service_token_task.cancel()
data_retention_task.cancel()
+ erasure_task.cancel()
if snapshot_task is not None:
snapshot_task.cancel()
shared_connections_task.cancel()
diff --git a/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py b/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py
new file mode 100644
index 000000000..9d6d4289f
--- /dev/null
+++ b/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py
@@ -0,0 +1,105 @@
+"""person erasures: a queue of requests to erase one person from a workspace
+
+``person_erasures`` holds each request and its outcome; a background loop
+works through the queued ones. ``ix_messages_tenant_sender`` serves
+finding and counting a person's messages, which nothing indexed before.
+
+The row-level-security DDL is a verbatim copy of ``switch_core/db/rls_ddl.py``
+as it stood when this migration was written, copied rather than imported for
+the reason ``265ed188ad6f`` gives.
+
+Revision ID: e5c1b7a93d28
+Revises: d8a4e2c61f07
+Create Date: 2026-10-06 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import postgresql
+
+revision: str = "e5c1b7a93d28"
+down_revision: str | None = "d8a4e2c61f07"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"
+POLICY_NAME = "tenant_isolation"
+
+_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'
+_CREATE_POLICY = (
+ f'CREATE POLICY {POLICY_NAME} ON "person_erasures"\n'
+ f" FOR ALL\n"
+ f" USING ({_PREDICATE})\n"
+ f" WITH CHECK ({_PREDICATE})"
+)
+
+
+def upgrade() -> None:
+ op.create_index(
+ "ix_messages_tenant_sender",
+ "messages",
+ ["tenant_id", "sender_id"],
+ )
+ op.create_table(
+ "person_erasures",
+ sa.Column("tenant_id", sa.Text(), nullable=False),
+ sa.Column("id", sa.Text(), nullable=False),
+ sa.Column(
+ "external_user_ids", postgresql.JSONB(astext_type=sa.Text()), nullable=False
+ ),
+ sa.Column("state", sa.Text(), nullable=False),
+ sa.Column("requested_by_user_id", sa.Text(), nullable=True),
+ sa.Column(
+ "messages_deleted",
+ sa.BigInteger(),
+ server_default=sa.text("0"),
+ nullable=False,
+ ),
+ sa.Column(
+ "files_deleted", sa.Integer(), server_default=sa.text("0"), nullable=False
+ ),
+ sa.Column(
+ "identities_erased",
+ sa.Integer(),
+ server_default=sa.text("0"),
+ nullable=False,
+ ),
+ sa.Column("error", sa.Text(), nullable=True),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),
+ sa.ForeignKeyConstraint(
+ ["tenant_id"], ["tenants.id"], name="fk_person_erasures_tenant"
+ ),
+ sa.ForeignKeyConstraint(
+ ["requested_by_user_id"], ["users.id"], ondelete="SET NULL"
+ ),
+ sa.CheckConstraint(
+ "state IN ('queued', 'running', 'done', 'failed')",
+ name="ck_person_erasures_state",
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ )
+ op.create_index("ix_person_erasures_tenant_id", "person_erasures", ["tenant_id"])
+ op.execute('ALTER TABLE "person_erasures" ENABLE ROW LEVEL SECURITY')
+ op.execute(_CREATE_POLICY)
+
+
+def downgrade() -> None:
+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "person_erasures"')
+ op.drop_index("ix_person_erasures_tenant_id", table_name="person_erasures")
+ op.drop_table("person_erasures")
+ op.drop_index("ix_messages_tenant_sender", table_name="messages")
diff --git a/core/switch_core/retention/erasure.py b/core/switch_core/retention/erasure.py
new file mode 100644
index 000000000..f3518d918
--- /dev/null
+++ b/core/switch_core/retention/erasure.py
@@ -0,0 +1,225 @@
+"""Erasing a person from a workspace.
+
+A workspace owner queues a request naming one or more platform identities
+(`ErasureStore.queue`). `erasure_loop` works the queue: for each identity it
+
+1. deletes every message the identity sent, in every room, archived ones
+ included, in batches with their attachments and bridge post mappings;
+2. stops the client that stood in for them in rooms;
+3. in one transaction, deletes anything they sent meanwhile, replaces their
+ name on approval answers, and deletes their identity row (its claims go by
+ cascade), their room memberships and their client;
+4. tells the running bridge to forget them, so writing again provisions a
+ new identity;
+5. deletes the stored files that only their messages carried.
+
+Every step is safe to repeat, so a request interrupted by a restart is simply
+worked again. Kept: what other people wrote, including quotes and mentions of
+them; copies on the chat platforms; their Switch account and membership,
+which have their own actions. `docs/design/data-retention.md` covers why.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Protocol
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.audit import AuditAction, record_audit_event
+from switch_core.db.models import PersonErasure, require_tenant_id
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.erasure_store import ErasureStore, Person
+from switch_core.db.stores.message_store import MessageStore
+from switch_core.db.stores.retention_store import RetentionStore
+from switch_core.db.tenant_lookup import all_tenant_ids
+from switch_core.tenant_context import no_tenant, tenant_scope
+
+logger = logging.getLogger(__name__)
+
+ERASURE_INTERVAL_SECONDS = 5.0
+MESSAGE_BATCH = 1000
+
+
+class ClientControl(Protocol):
+ async def stop(self, client_id: str) -> None: ...
+
+ async def delete_record(self, session: AsyncSession, client_id: str) -> None: ...
+
+
+class BridgeMemory(Protocol):
+ async def forget_human(
+ self, bridge_id: str, external_user_id: str, transport_user_id: str
+ ) -> None: ...
+
+
+class ErasureService:
+ def __init__(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ clients: ClientControl,
+ bridges: BridgeMemory,
+ ) -> None:
+ self._sessions = session_factory
+ self._clients = clients
+ self._bridges = bridges
+ self._erasures = ErasureStore()
+ self._messages = MessageStore()
+ self._retention = RetentionStore()
+
+ async def work_once(self) -> PersonErasure | None:
+ """Work the bound tenant's oldest pending request to its end, if any."""
+ tenant_id = require_tenant_id()
+ async with tenant_session(self._sessions, tenant_id) as db:
+ erasure = await self._erasures.next_pending(db)
+ if erasure is None:
+ return None
+
+ messages = files = identities = 0
+ try:
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ await self._erasures.mark(
+ db,
+ erasure.id,
+ state="running",
+ messages_deleted=erasure.messages_deleted,
+ files_deleted=erasure.files_deleted,
+ identities_erased=erasure.identities_erased,
+ error=None,
+ )
+ messages, files, identities = (
+ erasure.messages_deleted,
+ erasure.files_deleted,
+ erasure.identities_erased,
+ )
+ async with tenant_session(self._sessions, tenant_id) as db:
+ people = await self._erasures.list_people(db, erasure.external_user_ids)
+ for person in people:
+ deleted, removed_files = await self._erase(tenant_id, person)
+ messages += deleted
+ files += removed_files
+ identities += 1
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ await self._erasures.mark(
+ db,
+ erasure.id,
+ state="running",
+ messages_deleted=messages,
+ files_deleted=files,
+ identities_erased=identities,
+ error=None,
+ )
+ except Exception as exc:
+ logger.exception(
+ "Erasure %s in tenant %s failed after %d message(s)",
+ erasure.id,
+ tenant_id,
+ messages,
+ )
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ await self._erasures.mark(
+ db,
+ erasure.id,
+ state="failed",
+ messages_deleted=messages,
+ files_deleted=files,
+ identities_erased=identities,
+ error=f"{type(exc).__name__}: {exc}",
+ )
+ raise
+
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ await self._erasures.mark(
+ db,
+ erasure.id,
+ state="done",
+ messages_deleted=messages,
+ files_deleted=files,
+ identities_erased=identities,
+ error=None,
+ )
+ await record_audit_event(
+ db,
+ tenant_id=tenant_id,
+ actor_user_id=erasure.requested_by_user_id,
+ action=AuditAction.PERSON_ERASURE_COMPLETED,
+ target_type="person_erasure",
+ target_id=erasure.id,
+ details={
+ "messages_deleted": messages,
+ "files_deleted": files,
+ "identities_erased": identities,
+ },
+ )
+ logger.info(
+ "Erasure %s in tenant %s done: %d identities, %d messages, %d files",
+ erasure.id,
+ tenant_id,
+ identities,
+ messages,
+ files,
+ )
+ return erasure
+
+ async def _erase(self, tenant_id: str, person: Person) -> tuple[int, int]:
+ async with tenant_session(self._sessions, tenant_id) as db:
+ uris = await self._messages.attachment_uris_sent_by(
+ db, transport_user_id=person.transport_user_id
+ )
+ deleted = 0
+ while True:
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ event_ids = await self._messages.delete_sent_by(
+ db, transport_user_id=person.transport_user_id, limit=MESSAGE_BATCH
+ )
+ await self._retention.delete_bridge_mappings(db, event_ids)
+ deleted += len(event_ids)
+ if len(event_ids) < MESSAGE_BATCH:
+ break
+
+ await self._clients.stop(person.client_id)
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ while True:
+ event_ids = await self._messages.delete_sent_by(
+ db, transport_user_id=person.transport_user_id, limit=MESSAGE_BATCH
+ )
+ await self._retention.delete_bridge_mappings(db, event_ids)
+ deleted += len(event_ids)
+ if len(event_ids) < MESSAGE_BATCH:
+ break
+ await self._erasures.scrub_approval_answers(db, person.transport_user_id)
+ await self._erasures.delete_identity(db, person.external_user_id)
+ await self._clients.delete_record(db, person.client_id)
+ await self._bridges.forget_human(
+ person.bridge_id, person.external_user_id, person.transport_user_id
+ )
+
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ files = await self._erasures.delete_unreferenced_media(db, uris)
+ return deleted, files
+
+
+async def erase_once(service: ErasureService, tenant_ids: list[str]) -> None:
+ for tenant_id in tenant_ids:
+ with tenant_scope(tenant_id):
+ try:
+ while await service.work_once() is not None:
+ pass
+ except Exception:
+ # Recorded on the request as failed; one tenant's failure must
+ # not stop the others' erasures.
+ logger.exception("Erasure upkeep failed for tenant %s", tenant_id)
+
+
+async def erasure_loop(
+ session_factory: async_sessionmaker[AsyncSession], service: ErasureService
+) -> None:
+ """Work every tenant's erasure queue every few seconds."""
+ with no_tenant():
+ while True:
+ try:
+ await erase_once(service, await all_tenant_ids(session_factory))
+ except Exception:
+ logger.exception("Erasure upkeep could not list tenants")
+ await asyncio.sleep(ERASURE_INTERVAL_SECONDS)
diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
index a7cddd492..5b51be78b 100644
--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
@@ -75,6 +75,10 @@ _ALLOWED_MODULES = {
# enumerate, then bind each tenant and work under its own policy, the same
# shape as session-activity upkeep.
"switch_core.retention.service",
+ # The erasure loop works every tenant's queue of person erasures:
+ # enumerate, then bind each tenant and work under its own policy, the
+ # same shape as session-activity upkeep.
+ "switch_core.retention.erasure",
# The runtime-state sweep reads every tenant's stale rows, one tenant at a
# time.
"switch_core.bridges.agent.protocol.agent_core",
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index d44ddba04..99638eced 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -43,6 +43,8 @@ from switch_core.db.models import (
ApiKey,
AuditEvent,
Client,
+ CollaborationBridge,
+ ExternalUser,
Invitation,
Message,
Organization,
@@ -60,6 +62,7 @@ from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.budget_store import BudgetStore
+from switch_core.db.stores.erasure_store import ErasureStore
from switch_core.db.stores.invitation_store import InvitationStore
from switch_core.db.stores.join_domain_store import JoinDomainStore
from switch_core.db.stores.message_store import MessageStore
@@ -178,6 +181,7 @@ def _app(
app.dependency_overrides[gw_deps.get_usage_store] = lambda: UsageStore()
app.dependency_overrides[gw_deps.get_budget_store] = lambda: BudgetStore()
app.dependency_overrides[gw_deps.get_retention_store] = lambda: RetentionStore()
+ app.dependency_overrides[gw_deps.get_erasure_store] = lambda: ErasureStore()
app.dependency_overrides[gw_deps.get_protocol] = lambda: _fake_protocol()
app.dependency_overrides[gw_deps.get_invite_mailer] = lambda: mailer
app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: (
@@ -2839,3 +2843,149 @@ class TestRetentionRoutes:
assert ninety.json() == {"message_retention_days": 90, "messages_to_delete": 1}
assert thirty.json() == {"message_retention_days": 30, "messages_to_delete": 2}
+
+
+class TestErasureRoutes:
+ async def _member(
+ self, session_factory: async_sessionmaker[AsyncSession], name: str, role: str
+ ) -> str:
+ user_id = await _make_member(
+ session_factory, name=name, tenant_id=TENANT_A, role=role
+ )
+ return _token(user_id, f"{name}@example.invalid", TENANT_A)
+
+ async def _person(
+ self, session_factory: async_sessionmaker[AsyncSession], username: str
+ ) -> str:
+ async with tenant_session(session_factory, TENANT_A) as session:
+ bridge_client = Client(
+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",
+ display_name="bridge",
+ type="bridge",
+ )
+ person_client = Client(
+ transport_user_id=f"@{username}-{uuid.uuid4().hex[:8]}:test",
+ display_name=username,
+ type="user",
+ )
+ session.add_all([bridge_client, person_client])
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="Acme Slack",
+ client_id=bridge_client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ person = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id=f"U-{username}",
+ external_username=username,
+ client_id=person_client.id,
+ )
+ session.add(person)
+ await session.commit()
+ return person.id
+
+ async def test_an_owner_lists_people_queues_an_erasure_and_sees_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ token = await self._member(session_factory, "erase-owner", "owner")
+ person_id = await self._person(session_factory, "ana")
+
+ async with _client(_app(session_factory), token) as client:
+ people = await client.get(f"/tenants/{TENANT_A}/people")
+ queued = await client.post(
+ f"/tenants/{TENANT_A}/erasures",
+ json={"external_user_ids": [person_id]},
+ )
+ again = await client.post(
+ f"/tenants/{TENANT_A}/erasures",
+ json={"external_user_ids": [person_id]},
+ )
+ listed = await client.get(f"/tenants/{TENANT_A}/erasures")
+
+ assert people.status_code == 200
+ assert [
+ (p["username"], p["platform"], p["message_count"]) for p in people.json()
+ ] == [("ana", "slack", 0)]
+ assert queued.status_code == 202
+ assert queued.json()["state"] == "queued"
+ assert queued.json()["identities"] == 1
+ assert again.status_code == 409
+ assert [e["id"] for e in listed.json()] == [queued.json()["id"]]
+ async with tenant_session(session_factory, TENANT_A) as session:
+ actions = (
+ await session.execute(
+ select(AuditEvent.action, AuditEvent.details).where(
+ AuditEvent.tenant_id == TENANT_A
+ )
+ )
+ ).all()
+ assert actions == [
+ ("person_erasure.requested", {"external_user_ids": [person_id]})
+ ]
+
+ async def test_an_admin_cannot_erase_or_list_people(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ token = await self._member(session_factory, "erase-admin", "admin")
+ person_id = await self._person(session_factory, "ana")
+
+ async with _client(_app(session_factory), token) as client:
+ people = await client.get(f"/tenants/{TENANT_A}/people")
+ queued = await client.post(
+ f"/tenants/{TENANT_A}/erasures",
+ json={"external_user_ids": [person_id]},
+ )
+
+ assert people.status_code == 403
+ assert queued.status_code == 403
+
+ async def test_a_person_from_another_workspace_is_not_found(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ await _make_tenant(session_factory, TENANT_B)
+ token = await self._member(session_factory, "erase-cross", "owner")
+ async with tenant_session(session_factory, TENANT_B) as session:
+ other_client = Client(
+ transport_user_id=f"@b-{uuid.uuid4().hex[:8]}:test",
+ display_name="b",
+ type="bridge",
+ )
+ person_client = Client(
+ transport_user_id=f"@p-{uuid.uuid4().hex[:8]}:test",
+ display_name="p",
+ type="user",
+ )
+ session.add_all([other_client, person_client])
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="B",
+ client_id=other_client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.flush()
+ person = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id="U-b",
+ external_username="b",
+ client_id=person_client.id,
+ )
+ session.add(person)
+ await session.commit()
+ other_person = person.id
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.post(
+ f"/tenants/{TENANT_A}/erasures",
+ json={"external_user_ids": [other_person]},
+ )
+
+ assert response.status_code == 404
diff --git a/core/tests/switch_core/retention/test_erasure.py b/core/tests/switch_core/retention/test_erasure.py
new file mode 100644
index 000000000..8909a4baf
--- /dev/null
+++ b/core/tests/switch_core/retention/test_erasure.py
@@ -0,0 +1,447 @@
+"""Erasing a person, against real Postgres.
+
+What matters here is what is gone and what is not: every message the person
+sent, in every room, with the files only they carried, their identity rows,
+claims, memberships and client, and their name on approval answers; while
+other people's messages, files those still quote, and other identities stay.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ Agent,
+ ApiKey,
+ ApprovalRequest,
+ AuditEvent,
+ Client,
+ ClientRoom,
+ CollaborationBridge,
+ ExternalUser,
+ ExternalUserClaim,
+ MediaBlob,
+ Message,
+ MessageAttachment,
+ PersonErasure,
+ Room,
+ User,
+)
+from switch_core.db.stores.client_store import ClientStore
+from switch_core.db.stores.erasure_store import (
+ ERASED_ANSWERER,
+ ErasureAlreadyQueued,
+ ErasureStore,
+ UnknownIdentity,
+)
+from switch_core.db.stores.message_store import MessageStore
+from switch_core.retention.erasure import ErasureService
+
+NOW = datetime(2026, 10, 6, 12, 0, tzinfo=UTC)
+
+
+class _Clients:
+ def __init__(self, fail_on_stop: bool = False) -> None:
+ self.stopped: list[str] = []
+ self._fail = fail_on_stop
+
+ async def stop(self, client_id: str) -> None:
+ if self._fail:
+ raise RuntimeError("client would not stop")
+ self.stopped.append(client_id)
+
+ async def delete_record(self, session: AsyncSession, client_id: str) -> None:
+ await ClientStore().delete(session, client_id)
+
+
+class _Bridges:
+ def __init__(self) -> None:
+ self.forgotten: list[tuple[str, str, str]] = []
+
+ async def forget_human(
+ self, bridge_id: str, external_user_id: str, transport_user_id: str
+ ) -> None:
+ self.forgotten.append((bridge_id, external_user_id, transport_user_id))
+
+
+async def _bridge(session: AsyncSession) -> CollaborationBridge:
+ client = Client(
+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",
+ display_name="bridge",
+ type="bridge",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack", display_name="Acme Slack", client_id=client.id, status="active"
+ )
+ session.add(bridge)
+ await session.flush()
+ return bridge
+
+
+async def _person(
+ session: AsyncSession, bridge: CollaborationBridge, username: str
+) -> ExternalUser:
+ client = Client(
+ transport_user_id=f"@switch-slack-{bridge.id}-{username}:test",
+ display_name=username,
+ type="user",
+ )
+ session.add(client)
+ await session.flush()
+ person = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id=f"U-{username}",
+ external_username=username,
+ client_id=client.id,
+ )
+ session.add(person)
+ await session.flush()
+ return person
+
+
+async def _room(session: AsyncSession, name: str, *, archived: bool = False) -> Room:
+ room = Room(
+ transport_room_id=f"!{name}-{uuid.uuid4().hex[:8]}:test",
+ name=name,
+ description=name,
+ archived_at=NOW if archived else None,
+ )
+ session.add(room)
+ await session.flush()
+ return room
+
+
+async def _say(
+ session: AsyncSession,
+ room: Room,
+ sender: Client,
+ event_id: str,
+ uri: str | None = None,
+) -> Message:
+ attachments = (
+ []
+ if uri is None
+ else [MessageAttachment(uri=uri, filename="f", mimetype="text/plain", size=1)]
+ )
+ return await MessageStore().create(
+ session,
+ Message(
+ room_id=room.id,
+ transport_event_id=event_id,
+ sender_id=sender.transport_user_id,
+ sender_client_id=sender.id,
+ event_type="m.room.message",
+ msgtype="m.text",
+ body=event_id,
+ content={"msgtype": "m.text", "body": event_id},
+ ),
+ attachments,
+ )
+
+
+async def _blob(session: AsyncSession, uri: str) -> None:
+ session.add(
+ MediaBlob(uri=uri, content_type="text/plain", filename="f", size=1, data=b"x")
+ )
+ await session.flush()
+
+
+async def _client_of(session: AsyncSession, person: ExternalUser) -> Client:
+ client = await session.get(Client, person.client_id)
+ assert client is not None
+ return client
+
+
+async def _agent(session: AsyncSession) -> Agent:
+ name = f"agent-{uuid.uuid4().hex[:6]}"
+ user = User(name=name, email=f"{name}@example.invalid", role="user")
+ session.add(user)
+ await session.flush()
+ api_key = ApiKey(
+ user_id=user.id,
+ key_hash=f"h-{name}",
+ encrypted_key="e",
+ label=name,
+ type="agent",
+ )
+ client = Client(transport_user_id=f"@{name}:test", display_name=name, type="agent")
+ session.add_all([api_key, client])
+ await session.flush()
+ agent = Agent(
+ name=name,
+ description=name,
+ agent_type="always_on",
+ connector_type="claude_code",
+ integration_profile={"connection_model": "always_on"},
+ client_id=client.id,
+ api_key_id=api_key.id,
+ )
+ session.add(agent)
+ await session.flush()
+ return agent
+
+
+async def _queue(
+ session_factory: async_sessionmaker[AsyncSession], external_user_ids: list[str]
+) -> str:
+ async with session_factory() as session:
+ owner = User(
+ name=f"owner-{uuid.uuid4().hex[:6]}",
+ email=f"{uuid.uuid4().hex[:6]}@example.invalid",
+ role="user",
+ )
+ session.add(owner)
+ await session.flush()
+ erasure = await ErasureStore().queue(
+ session, external_user_ids=external_user_ids, requested_by_user_id=owner.id
+ )
+ await session.commit()
+ return erasure.id
+
+
+class TestErasing:
+ async def test_everything_they_sent_goes_and_everything_else_stays(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge = await _bridge(session)
+ ana = await _person(session, bridge, "ana")
+ bo = await _person(session, bridge, "bo")
+ ana_client = await _client_of(session, ana)
+ bo_client = await _client_of(session, bo)
+ active = await _room(session, "active")
+ archived = await _room(session, "archived", archived=True)
+ session.add_all(
+ [
+ ClientRoom(client_id=ana_client.id, room_id=active.id),
+ ClientRoom(client_id=bo_client.id, room_id=active.id),
+ ]
+ )
+ claimant = User(name="ana-member", email="[email protected]", role="user")
+ session.add(claimant)
+ await session.flush()
+ session.add(ExternalUserClaim(external_user_id=ana.id, user_id=claimant.id))
+ for uri in ("switch-media://ana-only", "switch-media://shared"):
+ await _blob(session, uri)
+ await _say(session, active, ana_client, "$ana1", "switch-media://ana-only")
+ await _say(session, archived, ana_client, "$ana2", "switch-media://shared")
+ await _say(session, active, bo_client, "$bo1", "switch-media://shared")
+ last = await _say(session, active, ana_client, "$ana3")
+ agent = await _agent(session)
+ for request_id, answered_by in (
+ ("by-ana", ana_client.transport_user_id),
+ ("by-bo", bo_client.transport_user_id),
+ ):
+ session.add(
+ ApprovalRequest(
+ agent_id=agent.id,
+ session_id="s",
+ request_id=request_id,
+ turn_id="t",
+ kind="approval",
+ title="t",
+ options=[],
+ questions=[],
+ state="answered",
+ answered_by=answered_by,
+ )
+ )
+ await session.commit()
+ ana_id, ana_client_id, ana_tid = (
+ ana.id,
+ ana_client.id,
+ ana_client.transport_user_id,
+ )
+ bridge_id, active_id, last_seq = bridge.id, active.id, last.seq
+
+ erasure_id = await _queue(session_factory, [ana_id])
+ clients, bridges = _Clients(), _Bridges()
+ await ErasureService(session_factory, clients, bridges).work_once()
+
+ async with session_factory() as session:
+ events = set(
+ (await session.execute(select(Message.transport_event_id))).scalars()
+ )
+ blobs = set((await session.execute(select(MediaBlob.uri))).scalars())
+ identities = set(
+ (
+ await session.execute(select(ExternalUser.external_username))
+ ).scalars()
+ )
+ claims = await session.scalar(
+ select(func.count()).select_from(ExternalUserClaim)
+ )
+ memberships = set(
+ (await session.execute(select(ClientRoom.client_id))).scalars()
+ )
+ answers = dict(
+ (
+ await session.execute(
+ select(ApprovalRequest.request_id, ApprovalRequest.answered_by)
+ )
+ ).all()
+ )
+ erasure = await session.get(PersonErasure, erasure_id)
+ audit = (
+ await session.execute(
+ select(AuditEvent.action, AuditEvent.details).where(
+ AuditEvent.target_id == erasure_id
+ )
+ )
+ ).all()
+ fresh = await _say(
+ session, await session.get(Room, active_id), bo_client, "$bo2"
+ )
+ client_gone = await session.get(Client, ana_client_id) is None
+
+ assert events == {"$bo1"}
+ assert blobs == {"switch-media://shared"}
+ assert identities == {"bo"}
+ assert claims == 0
+ assert memberships == {bo_client.id}
+ assert client_gone
+ assert answers == {
+ "by-ana": ERASED_ANSWERER,
+ "by-bo": bo_client.transport_user_id,
+ }
+ assert clients.stopped == [ana_client_id]
+ assert bridges.forgotten == [(bridge_id, ana_id, ana_tid)]
+ assert fresh.seq == last_seq + 1
+ assert erasure is not None
+ assert (erasure.state, erasure.messages_deleted, erasure.files_deleted) == (
+ "done",
+ 3,
+ 1,
+ )
+ assert erasure.identities_erased == 1 and erasure.completed_at is not None
+ assert audit == [
+ (
+ "person_erasure.completed",
+ {"messages_deleted": 3, "files_deleted": 1, "identities_erased": 1},
+ )
+ ]
+
+ async def test_a_person_on_two_platforms_is_erased_from_both(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ slack, other = await _bridge(session), await _bridge(session)
+ on_slack = await _person(session, slack, "ana")
+ on_other = await _person(session, other, "ana")
+ room = await _room(session, "r")
+ await _say(session, room, await _client_of(session, on_slack), "$a")
+ await _say(session, room, await _client_of(session, on_other), "$b")
+ await session.commit()
+ ids = [on_slack.id, on_other.id]
+
+ erasure_id = await _queue(session_factory, ids)
+ await ErasureService(session_factory, _Clients(), _Bridges()).work_once()
+
+ async with session_factory() as session:
+ assert await session.scalar(select(func.count()).select_from(Message)) == 0
+ assert (
+ await session.scalar(select(func.count()).select_from(ExternalUser))
+ == 0
+ )
+ erasure = await session.get(PersonErasure, erasure_id)
+ assert erasure is not None
+ assert (erasure.identities_erased, erasure.messages_deleted) == (2, 2)
+
+ async def test_a_failure_is_recorded_on_the_request_and_not_retried(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ person = await _person(session, await _bridge(session), "ana")
+ await session.commit()
+ person_id = person.id
+ erasure_id = await _queue(session_factory, [person_id])
+ service = ErasureService(
+ session_factory, _Clients(fail_on_stop=True), _Bridges()
+ )
+
+ with pytest.raises(RuntimeError):
+ await service.work_once()
+
+ async with session_factory() as session:
+ erasure = await session.get(PersonErasure, erasure_id)
+ still_there = await session.get(ExternalUser, person_id)
+ assert erasure is not None
+ assert erasure.state == "failed"
+ assert erasure.error == "RuntimeError: client would not stop"
+ assert still_there is not None
+ assert await service.work_once() is None
+
+ async def test_a_request_left_running_by_a_restart_is_finished(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ person = await _person(session, await _bridge(session), "ana")
+ await session.commit()
+ person_id = person.id
+ erasure_id = await _queue(session_factory, [person_id])
+ async with session_factory() as session:
+ erasure = await session.get(PersonErasure, erasure_id)
+ assert erasure is not None
+ erasure.state = "running"
+ await session.commit()
+
+ await ErasureService(session_factory, _Clients(), _Bridges()).work_once()
+
+ async with session_factory() as session:
+ erasure = await session.get(PersonErasure, erasure_id)
+ assert erasure is not None and erasure.state == "done"
+
+
+class TestQueue:
+ async def test_people_are_listed_with_their_message_counts_and_claimants(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge = await _bridge(session)
+ ana = await _person(session, bridge, "ana")
+ await _person(session, bridge, "Bo")
+ room = await _room(session, "r")
+ for index in range(3):
+ await _say(session, room, await _client_of(session, ana), f"$a{index}")
+ member = User(name="Ana Member", email="[email protected]", role="user")
+ session.add(member)
+ await session.flush()
+ session.add(ExternalUserClaim(external_user_id=ana.id, user_id=member.id))
+ await session.commit()
+
+ people = await ErasureStore().list_people(session)
+
+ assert [(p.username, p.message_count) for p in people] == [
+ ("ana", 3),
+ ("Bo", 0),
+ ]
+ assert [c.name for c in people[0].claimed_by] == ["Ana Member"]
+ assert (people[0].platform, people[0].bridge_name) == ("slack", "Acme Slack")
+
+ async def test_an_identity_from_nowhere_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ with pytest.raises(UnknownIdentity):
+ await _queue(session_factory, ["not-a-person"])
+
+ async def test_an_identity_already_being_erased_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ bridge = await _bridge(session)
+ ana = await _person(session, bridge, "ana")
+ bo = await _person(session, bridge, "bo")
+ await session.commit()
+ ana_id, bo_id = ana.id, bo.id
+ await _queue(session_factory, [ana_id])
+
+ with pytest.raises(ErasureAlreadyQueued):
+ await _queue(session_factory, [bo_id, ana_id])
+ await _queue(session_factory, [bo_id])
diff --git a/docs/design/data-retention.md b/docs/design/data-retention.md
index 9366e3601..2861e0320 100644
--- a/docs/design/data-retention.md
+++ b/docs/design/data-retention.md
@@ -119,42 +119,79 @@ below, in the order it is likely to be needed.
| Session activity | `session_activity_items`, `approval_requests` | Who answered what. Prompt and tool text. Already pruned after 7 days (activity) or 30 days once settled (approvals). |
| Logs and backups | outside the database | Whatever the deployment's log and backup policy keeps |
-### Erase a person (not built)
-
-An owner action that removes one person's data from one workspace:
-
-1. Resolve the person to their identities in the workspace: their Switch user
- (if a member) and every `external_users` row claimed by them or named by the
- request.
-2. Delete every message whose sender is one of those identities, with its
- attachments, using the same machinery as retention:
- `MessageStore.delete_sent_before` generalised to a sender filter, keeping
- the `seq_floor` update. The hourly sweep then removes orphaned files.
-3. Delete the `external_users` rows and their claims. A person who later writes
- again from the same platform account is recorded afresh.
-4. Remove the membership, if any. Deleting the Switch account itself is a
- deployment-level action, because one account may belong to several
- workspaces.
-5. Record `person.erased` in the audit log, naming who was erased and who
- asked, but not what was deleted.
-
-Open questions:
-
-- **Quotes and mentions in other people's messages.** Erasing them would rewrite
- other people's records. The usual reading of Art. 17 does not require it, and
- this design leaves them alone.
-- **Agents' copies.** An agent may have the person's messages in its own
- transcript or memory, on a machine Switch does not control. The action can
- tell connected agents, but it cannot guarantee anything for them.
-- **Bridged platforms.** As with retention, the platform's copy is the
- customer's to erase in that platform.
+### Erase a person (built)
+
+A workspace owner can erase one person from the People list on the Workspace
+page, for example to answer an Art. 17 request. Admins cannot; the action
+cannot be undone.
+
+**Who a person is.** Everyone in a room is a chat-platform identity: an
+`external_users` row on one bridge, standing behind a `clients` row that is
+the room participant. Most have no Switch account. One person seen on two
+platforms is two identities. When a member has claimed identities, the
+confirmation dialog offers every identity that member claims, ticked by
+default.
+
+**The flow.**
+
+1. The owner picks the person and confirms by typing their name. The typed
+ name is not stored.
+2. `POST /tenants/{id}/erasures` queues a `person_erasures` row naming the
+ identities, and records `person_erasure.requested` (who asked, the internal
+ identity ids). It refuses an identity outside the workspace (404) or one
+ already being erased (409).
+3. A background loop (`retention/erasure.py`, every 5 s) works the queue. For
+ each identity it:
+ - deletes every message it sent, in every room including archived ones,
+ in batches with their attachments and bridge post mappings, keeping each
+ room's `seq_floor`;
+ - stops the client that stood in for the person;
+ - in one transaction, deletes anything sent meanwhile, replaces their name
+ on approval answers with `erased`, and deletes the identity row (claims
+ go by cascade), its room memberships and its client;
+ - tells the running bridge to forget the identity, so writing again
+ provisions a new one;
+ - deletes the stored files that only their messages carried. There is no
+ grace period, because these files are known to have been attached.
+4. The page polls `GET /tenants/{id}/erasures` for progress. On success the
+ request records counts and `person_erasure.completed`. On failure it is
+ marked `failed` with the error, not retried, and the owner can queue it
+ again. Every step is safe to repeat, so a request interrupted by a restart
+ is finished on the next pass.
+
+**The client row goes, it is not renamed.** Its transport id is built from the
+person's username, so keeping it would keep the name. With every message they
+sent deleted, nothing would show a placeholder anyway.
+
+**What stays, and why.**
+
+- **Quotes and mentions in other people's messages.** Erasing them would
+ rewrite other people's records. The usual reading of Art. 17 does not
+ require it.
+- **Their Switch account and membership.** Removing a member is its own
+ action, and deleting an account is deployment-level because one account may
+ belong to several workspaces.
+- **Copies on chat platforms.** The platform's copy is the customer's to
+ erase in that platform. The dialog says so.
+- **Agents' copies.** An agent may hold the person's messages in its own
+ transcript or memory, on a machine Switch does not control.
+- **Session activity lines** may quote what the person wrote. They are pruned
+ after 7 days.
+- **The bridge's in-memory mention map** keeps the platform's
+ username-to-id pair until the bridge restarts. The person is still on that
+ platform, so the pair is the platform's data, not Switch's record of them.
+
+**A known window.** A message the person sends after their client is stopped
+but before its rows are deleted fails to post (an error is logged). The
+window lasts one transaction.
### Data export (not built)
An owner or admin export of everything held about one person in the workspace,
as machine-readable JSON: account fields, platform identities, and messages
they sent, with attachments. The same identity resolution as erasure applies.
-This is a natural next step after erasure, since it needs the same lookup.
+This is the natural next step, since it needs the same identity lookup as
+erasure (`ErasureStore.list_people`).
### Deleting a workspace (not built)
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 1082a458a..f6655ddce 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1526,6 +1526,54 @@ export async function clearRetentionPolicy(tenantId: string): Promise<RetentionP
);
}
+// ── Erasing a person ───────────────────────────────────────────────────────
+
+export interface PersonClaimant {
+ user_id: string;
+ name: string;
+}
+
+export interface Person {
+ external_user_id: string;
+ username: string;
+ platform: string;
+ bridge_name: string;
+ message_count: number;
+ claimed_by: PersonClaimant[];
+}
+
+export type ErasureState = "queued" | "running" | "done" | "failed";
+
+export interface Erasure {
+ id: string;
+ state: ErasureState;
+ identities: number;
+ identities_erased: number;
+ messages_deleted: number;
+ files_deleted: number;
+ error: string | null;
+ requested_by_user_id: string | null;
+ created_at: string;
+ completed_at: string | null;
+}
+
+export async function fetchPeople(tenantId: string): Promise<Person[]> {
+ return jsonRequest<Person[]>(`/tenants/${encodeURIComponent(tenantId)}/people`, "GET");
+}
+
+export async function fetchErasures(tenantId: string): Promise<Erasure[]> {
+ return jsonRequest<Erasure[]>(`/tenants/${encodeURIComponent(tenantId)}/erasures`, "GET");
+}
+
+export async function eraseIdentities(
+ tenantId: string,
+ externalUserIds: string[],
+): Promise<Erasure> {
+ return jsonRequest<Erasure>(`/tenants/${encodeURIComponent(tenantId)}/erasures`, "POST", {
+ external_user_ids: externalUserIds,
+ });
+}
+
export async function fetchInvitations(tenantId: string): Promise<Invitation[]> {
return jsonRequest<Invitation[]>(
`/tenants/${encodeURIComponent(tenantId)}/invitations`,
diff --git a/gateway/src/pages/workspace/EraseDialog.test.tsx b/gateway/src/pages/workspace/EraseDialog.test.tsx
new file mode 100644
index 000000000..268b11f25
--- /dev/null
+++ b/gateway/src/pages/workspace/EraseDialog.test.tsx
@@ -0,0 +1,107 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Person } from "../../data/api";
+import EraseDialog, { relatedIdentities } from "./EraseDialog";
+import { describeErasure } from "./PeopleSection";
+
+function person(id: string, username: string, claimants: string[], messages = 0): Person {
+ return {
+ external_user_id: id,
+ username,
+ platform: "slack",
+ bridge_name: `Bridge ${id}`,
+ message_count: messages,
+ claimed_by: claimants.map((c) => ({ user_id: c, name: `Member ${c}` })),
+ };
+}
+
+const ana = person("a", "ana", ["m1"], 10);
+const anaElsewhere = person("b", "ana.b", ["m1"], 5);
+const bo = person("c", "bo", [], 3);
+
+describe("relatedIdentities", () => {
+ it("finds identities sharing a claimant, and none for an unclaimed person", () => {
+ expect(relatedIdentities(ana, [ana, anaElsewhere, bo])).toEqual([anaElsewhere]);
+ expect(relatedIdentities(bo, [ana, anaElsewhere, bo])).toEqual([]);
+ });
+});
+
+describe("describeErasure", () => {
+ it("reads as progress, then as an outcome", () => {
+ const base = {
+ id: "e",
+ identities: 1,
+ identities_erased: 0,
+ files_deleted: 0,
+ error: null,
+ requested_by_user_id: null,
+ created_at: "2026-10-06T00:00:00Z",
+ completed_at: null,
+ };
+ expect(describeErasure({ ...base, state: "running", messages_deleted: 1200 })).toBe(
+ "In progress: 1,200 messages deleted so far",
+ );
+ expect(
+ describeErasure({ ...base, state: "done", messages_deleted: 1, files_deleted: 2 }),
+ ).toBe("Erased: 1 message and 2 files deleted");
+ });
+});
+
+describe("EraseDialog", () => {
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("erases only once the name is typed, with the related identities included", async () => {
+ const fetchMock = vi.fn(
+ async () => new Response(JSON.stringify({ id: "e1", state: "queued" }), { status: 202 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const onQueued = vi.fn();
+ render(
+ <EraseDialog
+ tenantId="t1"
+ person={ana}
+ people={[ana, anaElsewhere, bo]}
+ onClose={() => {}}
+ onQueued={onQueued}
+ />,
+ );
+
+ expect(screen.getByText(/15 messages they sent/)).toBeTruthy();
+ const erase = screen.getByRole("button", { name: "Erase" });
+ expect(erase.hasAttribute("disabled")).toBe(true);
+ fireEvent.change(screen.getByLabelText("Type ana to confirm"), { target: { value: "Ana" } });
+ expect(erase.hasAttribute("disabled")).toBe(true);
+ fireEvent.change(screen.getByLabelText("Type ana to confirm"), { target: { value: "ana" } });
+ fireEvent.click(erase);
+
+ await waitFor(() => expect(onQueued).toHaveBeenCalled());
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(JSON.parse(String(init.body))).toEqual({ external_user_ids: ["a", "b"] });
+ });
+
+ it("leaves out a related identity that is unticked", async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({}), { status: 202 }));
+ vi.stubGlobal("fetch", fetchMock);
+ render(
+ <EraseDialog
+ tenantId="t1"
+ person={ana}
+ people={[ana, anaElsewhere]}
+ onClose={() => {}}
+ onQueued={() => {}}
+ />,
+ );
+
+ fireEvent.click(screen.getByLabelText(/ana.b on Bridge b/));
+ expect(screen.getByText(/10 messages they sent/)).toBeTruthy();
+ fireEvent.change(screen.getByLabelText("Type ana to confirm"), { target: { value: "ana" } });
+ fireEvent.click(screen.getByRole("button", { name: "Erase" }));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalled());
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(JSON.parse(String(init.body))).toEqual({ external_user_ids: ["a"] });
+ });
+});
diff --git a/gateway/src/pages/workspace/EraseDialog.tsx b/gateway/src/pages/workspace/EraseDialog.tsx
new file mode 100644
index 000000000..a44ab4997
--- /dev/null
+++ b/gateway/src/pages/workspace/EraseDialog.tsx
@@ -0,0 +1,146 @@
+import {
+ Alert,
+ Button,
+ Checkbox,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogContentText,
+ DialogTitle,
+ FormControlLabel,
+ Stack,
+ TextField,
+ Typography,
+} from "@mui/material";
+import { useEffect, useMemo, useState } from "react";
+import { type Person, eraseIdentities } from "../../data/api";
+
+/** The identities that are probably the same person as `person`: every one
+ * claimed by a member who also claims `person`. */
+export function relatedIdentities(person: Person, people: Person[]): Person[] {
+ const claimants = new Set(person.claimed_by.map((c) => c.user_id));
+ if (claimants.size === 0) return [];
+ return people.filter(
+ (other) =>
+ other.external_user_id !== person.external_user_id &&
+ other.claimed_by.some((c) => claimants.has(c.user_id)),
+ );
+}
+
+function plural(count: number, word: string): string {
+ return `${count.toLocaleString()} ${word}${count === 1 ? "" : "s"}`;
+}
+
+interface Props {
+ tenantId: string;
+ person: Person | null;
+ people: Person[];
+ onClose: () => void;
+ onQueued: () => void;
+}
+
+export default function EraseDialog({ tenantId, person, people, onClose, onQueued }: Props) {
+ const related = useMemo(
+ () => (person ? relatedIdentities(person, people) : []),
+ [person, people],
+ );
+ const [included, setIncluded] = useState<Set<string>>(new Set());
+ const [typed, setTyped] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ setIncluded(new Set(related.map((p) => p.external_user_id)));
+ setTyped("");
+ setError(null);
+ }, [person, related]);
+
+ if (!person) return null;
+
+ const chosen = [person, ...related.filter((p) => included.has(p.external_user_id))];
+ const messages = chosen.reduce((sum, p) => sum + p.message_count, 0);
+ const confirmed = typed === person.username;
+
+ const toggle = (id: string) =>
+ setIncluded((current) => {
+ const next = new Set(current);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+
+ const submit = async () => {
+ setSubmitting(true);
+ setError(null);
+ try {
+ await eraseIdentities(
+ tenantId,
+ chosen.map((p) => p.external_user_id),
+ );
+ onQueued();
+ onClose();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not start the erasure");
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog open onClose={onClose} maxWidth="sm" fullWidth>
+ <DialogTitle>Erase {person.username}?</DialogTitle>
+ <DialogContent>
+ <Stack spacing={2}>
+ <DialogContentText>
+ This permanently deletes {plural(messages, "message")} they sent in every room of
+ this workspace, archived rooms included, with their files and their identity. It
+ cannot be undone.
+ </DialogContentText>
+ <DialogContentText>
+ What other people wrote, including replies that quote them, is kept. Copies in{" "}
+ {person.bridge_name} and other chat apps are not deleted; remove those in the app.
+ Their Switch account and membership, if any, are not affected.
+ </DialogContentText>
+ {related.length > 0 && (
+ <Stack spacing={0.5}>
+ <Typography variant="subtitle2">
+ Also claimed by {person.claimed_by.map((c) => c.name).join(", ")}:
+ </Typography>
+ {related.map((other) => (
+ <FormControlLabel
+ key={other.external_user_id}
+ control={
+ <Checkbox
+ checked={included.has(other.external_user_id)}
+ onChange={() => toggle(other.external_user_id)}
+ />
+ }
+ label={`${other.username} on ${other.bridge_name} (${plural(other.message_count, "message")})`}
+ />
+ ))}
+ </Stack>
+ )}
+ <TextField
+ label={`Type ${person.username} to confirm`}
+ value={typed}
+ onChange={(event) => setTyped(event.target.value)}
+ autoComplete="off"
+ fullWidth
+ />
+ {error && <Alert severity="error">{error}</Alert>}
+ </Stack>
+ </DialogContent>
+ <DialogActions>
+ <Button onClick={onClose}>Cancel</Button>
+ <Button
+ color="error"
+ variant="contained"
+ disabled={!confirmed || submitting}
+ onClick={() => void submit()}
+ >
+ Erase
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
+}
diff --git a/gateway/src/pages/workspace/PeopleSection.tsx b/gateway/src/pages/workspace/PeopleSection.tsx
new file mode 100644
index 000000000..10f0e6274
--- /dev/null
+++ b/gateway/src/pages/workspace/PeopleSection.tsx
@@ -0,0 +1,164 @@
+import {
+ Alert,
+ Button,
+ Chip,
+ CircularProgress,
+ Stack,
+ TextField,
+ Typography,
+} from "@mui/material";
+import type { GridColDef } from "@mui/x-data-grid";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import DataTable from "../../components/DataTable";
+import { type Erasure, type Person, fetchErasures, fetchPeople } from "../../data/api";
+import { formatDate, titleCase } from "../../theme/hootFormat";
+import EraseDialog from "./EraseDialog";
+import { useLoad } from "./useLoad";
+
+type PersonRow = Person & { id: string };
+
+const POLL_MS = 3000;
+
+export function describeErasure(erasure: Erasure): string {
+ const messages = `${erasure.messages_deleted.toLocaleString()} ${erasure.messages_deleted === 1 ? "message" : "messages"}`;
+ const files = `${erasure.files_deleted.toLocaleString()} ${erasure.files_deleted === 1 ? "file" : "files"}`;
+ switch (erasure.state) {
+ case "queued":
+ return "Waiting to start";
+ case "running":
+ return `In progress: ${messages} deleted so far`;
+ case "done":
+ return `Erased: ${messages} and ${files} deleted`;
+ case "failed":
+ return `Failed after ${messages}: ${erasure.error ?? "unknown error"}`;
+ }
+}
+
+const STATE_COLORS = {
+ queued: "default",
+ running: "info",
+ done: "success",
+ failed: "error",
+} as const;
+
+export default function PeopleSection({ tenantId }: { tenantId: string }) {
+ const loadPeople = useCallback(() => fetchPeople(tenantId), [tenantId]);
+ const loadErasures = useCallback(() => fetchErasures(tenantId), [tenantId]);
+ const people = useLoad(loadPeople);
+ const erasures = useLoad(loadErasures);
+ const [search, setSearch] = useState("");
+ const [erasing, setErasing] = useState<Person | null>(null);
+
+ const active = (erasures.data ?? []).some(
+ (e) => e.state === "queued" || e.state === "running",
+ );
+ const { refetch: refetchErasures } = erasures;
+ const { refetch: refetchPeople } = people;
+ useEffect(() => {
+ if (!active) return;
+ const timer = window.setInterval(() => {
+ void refetchErasures();
+ void refetchPeople();
+ }, POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [active, refetchErasures, refetchPeople]);
+
+ const rows = useMemo<PersonRow[]>(() => {
+ const needle = search.trim().toLowerCase();
+ return (people.data ?? [])
+ .filter(
+ (p) =>
+ !needle ||
+ p.username.toLowerCase().includes(needle) ||
+ p.claimed_by.some((c) => c.name.toLowerCase().includes(needle)),
+ )
+ .map((p) => ({ ...p, id: p.external_user_id }));
+ }, [people.data, search]);
+
+ const columns = useMemo<GridColDef<PersonRow>[]>(
+ () => [
+ { field: "username", headerName: "Name", flex: 1, minWidth: 160 },
+ {
+ field: "bridge_name",
+ headerName: "Seen on",
+ flex: 1,
+ minWidth: 160,
+ valueGetter: (_value, row) => `${row.bridge_name} (${titleCase(row.platform)})`,
+ },
+ { field: "message_count", headerName: "Messages", width: 110, type: "number" },
+ {
+ field: "claimed_by",
+ headerName: "Claimed by",
+ flex: 1,
+ minWidth: 160,
+ sortable: false,
+ valueGetter: (_value, row) => row.claimed_by.map((c) => c.name).join(", "),
+ },
+ {
+ field: "actions",
+ headerName: "",
+ width: 100,
+ sortable: false,
+ renderCell: ({ row }) => (
+ <Button size="small" color="error" onClick={() => setErasing(row)}>
+ Erase
+ </Button>
+ ),
+ },
+ ],
+ [],
+ );
+
+ const queued = async () => {
+ await Promise.all([refetchErasures(), refetchPeople()]);
+ };
+
+ return (
+ <Stack spacing={1.5}>
+ <Typography variant="h6">People</Typography>
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
+ Everyone seen in this workspace&apos;s rooms through a connected chat app. Erasing
+ someone permanently deletes every message they sent and their files, for example to
+ answer a GDPR erasure request. Only owners can see this list.
+ </Typography>
+ {people.error && <Alert severity="error">{people.error}</Alert>}
+ {erasures.error && <Alert severity="error">{erasures.error}</Alert>}
+ {(erasures.data ?? []).slice(0, 5).map((erasure) => (
+ <Stack key={erasure.id} direction="row" spacing={1} alignItems="center">
+ <Chip
+ size="small"
+ label={titleCase(erasure.state)}
+ color={STATE_COLORS[erasure.state]}
+ />
+ <Typography variant="body2">
+ {describeErasure(erasure)} · requested {formatDate(erasure.created_at)}
+ </Typography>
+ </Stack>
+ ))}
+ <TextField
+ size="small"
+ label="Search people"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ sx={{ maxWidth: 320 }}
+ />
+ {people.loading ? (
+ <CircularProgress />
+ ) : (
+ <DataTable
+ rows={rows}
+ columns={columns}
+ height={Math.min(520, 108 + Math.max(1, rows.length) * 52)}
+ pageSize={25}
+ />
+ )}
+ <EraseDialog
+ tenantId={tenantId}
+ person={erasing}
+ people={people.data ?? []}
+ onClose={() => setErasing(null)}
+ onQueued={() => void queued()}
+ />
+ </Stack>
+ );
+}
diff --git a/gateway/src/pages/workspace/WorkspacePage.tsx b/gateway/src/pages/workspace/WorkspacePage.tsx
index dead67464..f40b6762a 100644
--- a/gateway/src/pages/workspace/WorkspacePage.tsx
+++ b/gateway/src/pages/workspace/WorkspacePage.tsx
@@ -3,6 +3,7 @@ import { useAuth } from "../../data/AuthContext";
import DeleteWorkspaceSection from "./DeleteWorkspaceSection";
import InvitationsSection from "./InvitationsSection";
import MembersSection from "./MembersSection";
+import PeopleSection from "./PeopleSection";
import RetentionSection from "./RetentionSection";
export default function WorkspacePage() {
@@ -36,6 +37,7 @@ export default function WorkspacePage() {
</Alert>
)}
{canAdminTenant && <RetentionSection tenantId={tenant.id} />}
+ {tenant.role === "admin" && <PeopleSection tenantId={tenant.id} />}
{/* An admin membership, not the operator's bypass: the server checks the same. */}
{tenant.role === "admin" && (
<DeleteWorkspaceSection tenantId={tenant.id} tenantName={tenant.name} />