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
Let the server administrator delete a user's account (#1000)
Abel Dantas6cd05a87c429
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4d41a9272..60c356f8a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -124,6 +124,11 @@ version of their own to them without also giving them a release of their own.still only needs write access to the room.#### Added+- **The server's administrator can delete someone's account.** The Users page+ has a Delete action (`DELETE /users/{id}`) that removes the account in every+ workspace, with the same refusals as deleting your own. Administrator+ accounts and your own account are refused, and every attempt is recorded in+ the server audit log with its outcome.- **The gateway says what the caller may change in a room.** Rooms, in thelist (`GET /rooms`) and in a room's detail, carry `can_write`,`can_manage` and `can_unlink`. Each room a reference, document or packagediff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.jsonindex d479907f5..eefc2fedf 100644--- a/console/tooling-e2e/surface/server-surface.json+++ b/console/tooling-e2e/surface/server-surface.json@@ -301,6 +301,11 @@"auth": "session","flags": []},+ {+ "route": "DELETE /gateway/users/{user_id}",+ "auth": "session",+ "flags": []+ },{"route": "DELETE /gateway/workspace/services/{service}","auth": "session",diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.pyindex 1033d1870..dc95cc741 100644--- a/core/switch_core/accounts/deletion.py+++ b/core/switch_core/accounts/deletion.py@@ -212,6 +212,20 @@ class AccountDeletionRefused(Exception):do first, in words for the person."""+class AccountDeletionIncomplete(Exception):+ """Deleting the account failed partway. Each workspace is left in its own+ transaction, so the ones in `completed` stay left; the account itself and+ every other workspace are as they were. The cause is chained."""++ def __init__(self, user_id: str, completed: list[Workspace]) -> None:+ super().__init__(+ f"Deleting the account of user {user_id} failed after leaving "+ f"{len(completed)} workspace(s)"+ )+ self.user_id = user_id+ self.completed = completed++@dataclass(frozen=True)class Workspace:id: str@@ -350,29 +364,44 @@ class AccountDeletion:)async def delete(- self, session: AsyncSession, user: User, workspaces: list[Workspace]+ self,+ session: AsyncSession,+ user: User,+ workspaces: list[Workspace],+ actor_id: str,) -> None:"""Delete the account. `session` is the caller's, and carries thedeletion of the rows that belong to no workspace; the caller has- checked `refusal` first, and `AccountDeletionRefused` is raised before- anything is changed if an organization's last `org_admin` check no- longer holds."""+ checked `refusal` first. `actor_id` is who asked: the person+ themselves, or the server's operator; each workspace's audit log names+ them.++ Raises `AccountDeletionRefused` before anything is changed if an+ organization's last `org_admin` check no longer holds, and+ `AccountDeletionIncomplete` when it fails partway."""user_id = user.idawait self._leave_organizations_as_admin(user, workspaces)- for workspace in workspaces:- await self._leave_workspace(user_id, workspace)- await self._hand_over_server_settings(session, user_id)- await session.execute(- delete(OidcIdentity).where(OidcIdentity.user_id == user_id)- )- await session.execute(- delete(CloudMachine).where(- CloudMachine.owner_id == user_id, CloudMachine.state == "deleted"+ completed: list[Workspace] = []+ try:+ for workspace in workspaces:+ await self._leave_workspace(user_id, workspace, actor_id)+ completed.append(workspace)+ await self._hand_over_server_settings(session, user_id)+ await session.execute(+ delete(OidcIdentity).where(OidcIdentity.user_id == user_id))+ await session.execute(+ delete(CloudMachine).where(+ CloudMachine.owner_id == user_id, CloudMachine.state == "deleted"+ )+ )+ await session.execute(delete(User).where(User.id == user_id))+ await session.commit()+ except Exception as error:+ raise AccountDeletionIncomplete(user_id, completed) from error+ logger.info(+ "Deleted the account of user %s at the request of %s", user_id, actor_id)- await session.execute(delete(User).where(User.id == user_id))- await session.commit()- logger.info("Deleted the account of user %s", user_id)async def _leave_organizations_as_admin(self, user: User, workspaces: list[Workspace]@@ -463,7 +492,9 @@ class AccountDeletion:.values(updated_by=admin_id))- async def _leave_workspace(self, user_id: str, workspace: Workspace) -> None:+ async def _leave_workspace(+ self, user_id: str, workspace: Workspace, actor_id: str+ ) -> None:tenant_id = workspace.idasync with tenant_session(self.session_factory, tenant_id) as session:agent_ids = [@@ -525,7 +556,7 @@ class AccountDeletion:await record_audit_event(session,tenant_id=tenant_id,- actor_user_id=user_id,+ actor_user_id=actor_id,action=AuditAction.ACCOUNT_DELETED,target_type="user",target_id=user_id,diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex a3d39c4ea..c38ba9057 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -113,6 +113,9 @@ class ServerAuditAction(StrEnum):CONNECTOR_APP_SAVED = "connector_app.saved"CONNECTOR_APP_IMPORTED = "connector_app.imported"CONNECTOR_APP_REMOVED = "connector_app.removed"+ USER_DELETED = "user.deleted"+ USER_DELETION_REFUSED = "user.deletion_refused"+ USER_DELETION_FAILED = "user.deletion_failed"# WorkOS refused where the directory mirror had got to in its events, and# the mirror started again from now, with a full check of every linked# organization.diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex ddbf1eb24..ef04a2c3f 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -11,6 +11,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.accounts.deletion import (AccountDeletion,+ AccountDeletionIncomplete,AccountDeletionRefused,Workspace,)@@ -20,6 +21,7 @@ from switch_core.chats.member_names import rename_member_clientsfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.connections.broker import ServiceBroker, get_service_broker+from switch_core.db.audit import ServerAuditAction, record_server_audit_eventfrom switch_core.db.models import TENANT_ZERO_ID, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore@@ -510,11 +512,49 @@ async def delete_my_account(raise HTTPException(status_code=400, detail="That email doesn't match this account.")- workspaces = [- Workspace(id=m.id, name=m.name, role=m.role)- for m in await list_tenant_memberships(session_factory, user_store, user.id)- ]- deletion = AccountDeletion(+ deletion = _account_deletion(+ request,+ session_factory,+ protocol,+ broker,+ resource_service,+ room_service,+ user_store,+ organization_store,+ agent_store,+ api_key_store,+ template_store,+ config,+ )+ workspaces = await _workspaces_to_delete(+ deletion, session_factory, user_store, user.id+ )+ reason = await deletion.refusal(session, user, workspaces)+ if reason is not None:+ raise HTTPException(status_code=409, detail=reason)+ try:+ await deletion.delete(session, user, workspaces, actor_id=user.id)+ except AccountDeletionRefused as refused:+ raise HTTPException(status_code=409, detail=str(refused)) from None+ response.delete_cookie("switch_auth", path="/")+ return {"ok": True}+++def _account_deletion(+ request: Request,+ session_factory: async_sessionmaker[AsyncSession],+ protocol: AgentCore,+ broker: ServiceBroker,+ resource_service: ResourceService,+ room_service: RoomService,+ user_store: UserStore,+ organization_store: OrganizationStore,+ agent_store: AgentStore,+ api_key_store: ApiKeyStore,+ template_store: TemplateStore,+ config: SwitchConfig,+) -> AccountDeletion:+ return AccountDeletion(session_factory=session_factory,protocol=protocol,# Set by the wiring when agent management runs (`switch_core.main`).@@ -530,16 +570,19 @@ 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)- try:- await deletion.delete(session, user, workspaces)- except AccountDeletionRefused as refused:- raise HTTPException(status_code=409, detail=str(refused)) from None- response.delete_cookie("switch_auth", path="/")- return {"ok": True}+++async def _workspaces_to_delete(+ deletion: AccountDeletion,+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user_id: str,+) -> list[Workspace]:+ memberships = [+ Workspace(id=m.id, name=m.name, role=m.role)+ for m in await list_tenant_memberships(session_factory, user_store, user_id)+ ]+ return await deletion.with_former_workspaces(user_id, memberships)@router.patch("/auth/me")@@ -646,3 +689,124 @@ async def create_user(role=user.role,created_at=str(user.created_at),)++[email protected]("/users/{user_id}")+async def delete_user(+ user_id: str,+ request: Request,+ session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ admin: Annotated[User, Depends(require_admin)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],+ resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ room_service: Annotated[RoomService, Depends(get_room_service)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> dict[str, bool]:+ """The deployment operator deletes someone's whole account.++ The same deletion, and the same refusals, as `DELETE /auth/me`: this only+ changes who asks. The operator's own account is refused, so that leaving+ the server is always the person's own act. Whether it went ahead, was+ refused or failed partway lands in the server's audit log, since an+ account spans every workspace and no one workspace's history is the place+ for it.++ `session` is bound to the operator's own workspace, like the other user+ routes, but carries only rows that belong to no workspace: the `users`+ row, its sign-in identities and the audit event. Each workspace the+ account is in is left in a `tenant_session` of its own.+ """+ if user_id == admin.id:+ detail = (+ "That's your own account. Delete it from your account settings instead."+ )+ await _record_refusal(session, admin.id, user_id, detail)+ raise HTTPException(status_code=409, detail=detail)+ target = await user_store.get(session, user_id)+ if target is None:+ await _record_refusal(session, admin.id, user_id, "User not found")+ raise HTTPException(status_code=404, detail="User not found")+ deletion = _account_deletion(+ request,+ session_factory,+ protocol,+ broker,+ resource_service,+ room_service,+ user_store,+ organization_store,+ agent_store,+ api_key_store,+ template_store,+ config,+ )+ workspaces = await _workspaces_to_delete(+ deletion, session_factory, user_store, target.id+ )+ reason = await deletion.refusal(session, target, workspaces)+ if reason is not None:+ await _record_refusal(session, admin.id, target.id, reason)+ raise HTTPException(status_code=409, detail=reason)+ await record_server_audit_event(+ session,+ actor_user_id=admin.id,+ action=ServerAuditAction.USER_DELETED,+ target_type="user",+ target_id=target.id,+ details={"outcome": "deleted", "workspaces": len(workspaces)},+ )+ # The event commits with the `users` row, so it never records a deletion+ # that did not finish. The ids outlive the rollback that expires the rows.+ operator_id, target_id = admin.id, target.id+ try:+ await deletion.delete(session, target, workspaces, actor_id=admin.id)+ except AccountDeletionRefused as refused:+ # An organization's last admin check failed under its lock, before+ # anything changed; the deletion event above goes with the rollback.+ await session.rollback()+ await _record_refusal(session, operator_id, target_id, str(refused))+ raise HTTPException(status_code=409, detail=str(refused)) from None+ except AccountDeletionIncomplete as error:+ # The workspaces already left stay left, so the attempt is recorded on+ # its own, in a transaction after the one that just rolled back.+ await session.rollback()+ await record_server_audit_event(+ session,+ actor_user_id=operator_id,+ action=ServerAuditAction.USER_DELETION_FAILED,+ target_type="user",+ target_id=target_id,+ details={+ "outcome": "failed",+ "workspaces": len(workspaces),+ "workspaces_completed": [w.id for w in error.completed],+ "error": type(error.__cause__).__name__,+ },+ )+ await session.commit()+ raise+ logger.info("Operator %s deleted the account of user %s", operator_id, target_id)+ return {"ok": True}+++async def _record_refusal(+ session: AsyncSession, operator_id: str, target_id: str, reason: str+) -> None:+ await record_server_audit_event(+ session,+ actor_user_id=operator_id,+ action=ServerAuditAction.USER_DELETION_REFUSED,+ target_type="user",+ target_id=target_id,+ details={"outcome": "refused", "reason": reason},+ )+ await session.commit()diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.pyindex 83310a2ec..c875aa45e 100644--- a/core/tests/switch_core/accounts/test_account_deletion.py+++ b/core/tests/switch_core/accounts/test_account_deletion.py@@ -287,7 +287,7 @@ async def test_an_org_admin_with_a_member_row_takes_no_admin_away(user = await session.get(User, user_id)assert user is not Noneassert await deletion.refusal(session, user, workspaces) is None- await deletion.delete(session, user, workspaces)+ await deletion.delete(session, user, workspaces, actor_id=user.id)async with session_factory() as session:assert await session.get(User, user_id) is None@@ -474,7 +474,7 @@ async def test_deleting_a_member_hands_over_and_clears_what_others_need(user = await session.get(User, ids["user"])assert user is not Noneassert await deletion.refusal(session, user, workspaces) is None- await deletion.delete(session, user, workspaces)+ await deletion.delete(session, user, workspaces, actor_id=user.id)assert protocol.deleted == [ids["agent"]]assert rooms.archived == [ids["chat"]]@@ -544,7 +544,7 @@ async def test_a_workspace_left_empty_stays_with_nothing_pointing_at_the_person(user = await session.get(User, user_id)assert user is not Noneassert await deletion.refusal(session, user, workspaces) is None- await deletion.delete(session, user, workspaces)+ await deletion.delete(session, user, workspaces, actor_id=user.id)async with session_factory() as session:assert await session.get(User, user_id) is None@@ -607,7 +607,7 @@ async def test_a_messaging_app_left_in_a_workspace_since_emptied_does_not_refuseworkspaces = 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)+ await deletion.delete(session, user, workspaces, actor_id=user.id)async with session_factory() as session:assert await session.get(User, removed_id) is None@@ -653,7 +653,7 @@ async def test_a_workspace_the_person_was_removed_from_is_cleared_too(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)+ await deletion.delete(session, user, workspaces, actor_id=user.id)async with session_factory() as session:assert await session.get(User, ids["removed"]) is None@@ -738,7 +738,7 @@ async def test_a_reference_type_in_use_passes_to_an_admin_else_the_oldest_refereasync with session_factory() as session:user = await session.get(User, leaving_id)assert user is not None- await deletion.delete(session, user, workspaces)+ await deletion.delete(session, user, workspaces, actor_id=user.id)async with tenant_session(session_factory, TENANT_ZERO_ID) as session:assert (diff --git a/core/tests/switch_core/gateway/test_admin_delete_user.py b/core/tests/switch_core/gateway/test_admin_delete_user.pynew file mode 100644index 000000000..ea0c2a16b--- /dev/null+++ b/core/tests/switch_core/gateway/test_admin_delete_user.py@@ -0,0 +1,272 @@+"""The deployment operator deleting someone's account (DELETE /users/{id}).++Against a real database: the route runs the same `AccountDeletion` as+`DELETE /auth/me`, whose difficulty is the schema. The services with side+effects outside the database are the fakes `test_account_deletion.py` uses.+"""++from __future__ import annotations++from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.accounts.deletion import AccountDeletionIncomplete+from switch_core.connections.broker import get_service_broker+from switch_core.db.models import (+ TENANT_ZERO_ID,+ AuditEvent,+ ServerAuditEvent,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.organization_store import OrganizationStore+from switch_core.db.stores.template_store import TemplateStore+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway import dependencies as gw_deps+from switch_core.gateway.auth import create_jwt+from switch_core.gateway.auth_routes import router+from tests.conftest import TEST_KEYRING+from tests.switch_core.accounts.test_account_deletion import (+ ADMIN_EMAIL,+ _Broker,+ _deletion,+ _SignInFlows,+)+from tests.switch_core.gateway.test_tenant_api_routes import _make_member+++def _app(+ session_factory: async_sessionmaker[AsyncSession], broker: _Broker | None = None+) -> FastAPI:+ deletion, _, _ = _deletion(session_factory)+ if broker is not None:+ deletion.broker = broker # type: ignore[assignment]++ async def _session_dep():+ async with session_factory() as session:+ yield session++ app = FastAPI()+ app.include_router(router)+ app.state.sign_in_flows = _SignInFlows()+ overrides = app.dependency_overrides+ overrides[gw_deps.get_session] = _session_dep+ overrides[gw_deps.get_system_session] = _session_dep+ overrides[gw_deps.get_session_factory] = lambda: session_factory+ overrides[gw_deps.get_user_store] = lambda: UserStore()+ overrides[gw_deps.get_organization_store] = lambda: OrganizationStore()+ overrides[gw_deps.get_agent_store] = lambda: AgentStore()+ overrides[gw_deps.get_api_key_store] = lambda: ApiKeyStore()+ overrides[gw_deps.get_template_store] = lambda: TemplateStore()+ overrides[gw_deps.get_protocol] = lambda: deletion.protocol+ overrides[gw_deps.get_resource_service] = lambda: deletion.resources+ overrides[gw_deps.get_room_service] = lambda: deletion.rooms+ overrides[get_service_broker] = lambda: deletion.broker+ overrides[gw_deps.get_config] = lambda: SimpleNamespace(+ keyring=TEST_KEYRING,+ gateway_cookie_secure=False,+ gateway_admin_email=ADMIN_EMAIL,+ gateway_tenant_choice_enabled=False,+ )+ return app+++def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:+ token = create_jwt(user_id, email, "user", TEST_KEYRING, TENANT_ZERO_ID)+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://test",+ cookies={"switch_auth": token},+ )+++async def _people(+ session_factory: async_sessionmaker[AsyncSession],+) -> tuple[str, str]:+ operator = await _make_member(+ session_factory,+ name="operator",+ tenant_id=TENANT_ZERO_ID,+ role="admin",+ email=ADMIN_EMAIL,+ user_role="admin",+ )+ member = await _make_member(+ session_factory, name="leaving", tenant_id=TENANT_ZERO_ID, role="member"+ )+ return operator, member+++async def _server_events(+ session_factory: async_sessionmaker[AsyncSession],+) -> list[ServerAuditEvent]:+ async with session_factory() as session:+ return list(+ (+ await session.scalars(+ select(ServerAuditEvent).order_by(ServerAuditEvent.occurred_at)+ )+ ).all()+ )+++async def test_the_operator_deletes_a_members_account_and_it_is_logged(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator, member = await _people(session_factory)+ async with _client(_app(session_factory), operator, ADMIN_EMAIL) as client:+ response = await client.delete(f"/users/{member}")+ assert response.status_code == 200, response.text+ async with session_factory() as session:+ assert await session.get(User, member) is None+ [event] = await _server_events(session_factory)+ assert event.action == "user.deleted"+ assert event.actor_user_id == operator+ assert event.target_id == member+ assert event.details is not None and event.details["outcome"] == "deleted"+++async def test_a_workspace_admin_who_is_not_the_operator_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ _, member = await _people(session_factory)+ workspace_admin = await _make_member(+ session_factory, name="ws-admin", tenant_id=TENANT_ZERO_ID, role="admin"+ )+ async with _client(+ _app(session_factory), workspace_admin, "[email protected]"+ ) as client:+ response = await client.delete(f"/users/{member}")+ assert response.status_code == 403, response.text+ async with session_factory() as session:+ assert await session.get(User, member) is not None+ assert await _server_events(session_factory) == []+++async def test_the_operators_own_account_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator, _ = await _people(session_factory)+ async with _client(_app(session_factory), operator, ADMIN_EMAIL) as client:+ response = await client.delete(f"/users/{operator}")+ assert response.status_code == 409, response.text+ assert "your own account" in response.json()["detail"]+ async with session_factory() as session:+ assert await session.get(User, operator) is not None+ [event] = await _server_events(session_factory)+ assert event.action == "user.deletion_refused"+ assert event.actor_user_id == operator+ assert event.target_id == operator+ assert event.details is not None and "your own account" in event.details["reason"]+++async def test_another_administrator_account_is_refused_and_logged(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator, _ = await _people(session_factory)+ other_admin = await _make_member(+ session_factory,+ name="second-admin",+ tenant_id=TENANT_ZERO_ID,+ role="member",+ user_role="admin",+ )+ async with _client(_app(session_factory), operator, ADMIN_EMAIL) as client:+ response = await client.delete(f"/users/{other_admin}")+ assert response.status_code == 409, response.text+ assert "administrator account" in response.json()["detail"]+ async with session_factory() as session:+ assert await session.get(User, other_admin) is not None+ [event] = await _server_events(session_factory)+ assert event.action == "user.deletion_refused"+ assert event.details is not None and event.details["outcome"] == "refused"+++async def test_an_unknown_user_is_not_found(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator, _ = await _people(session_factory)+ async with _client(_app(session_factory), operator, ADMIN_EMAIL) as client:+ response = await client.delete("/users/nobody")+ assert response.status_code == 404, response.text+ [event] = await _server_events(session_factory)+ assert event.action == "user.deletion_refused"+ assert event.actor_user_id == operator+ assert event.target_id == "nobody"+ assert event.details == {"outcome": "refused", "reason": "User not found"}+++async def test_each_workspace_records_the_operator_as_who_deleted_the_account(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator, member = await _people(session_factory)+ async with _client(_app(session_factory), operator, ADMIN_EMAIL) as client:+ response = await client.delete(f"/users/{member}")+ assert response.status_code == 200, response.text+ async with session_factory() as session:+ [event] = (+ await session.scalars(+ select(AuditEvent).where(AuditEvent.action == "account.deleted")+ )+ ).all()+ assert event.target_id == member+ assert event.actor_user_id == operator+++class _FailsOnSecondWorkspace(_Broker):+ def __init__(self) -> None:+ self.calls = 0++ async def remove_connections(self, _session: AsyncSession, _user_id: str) -> list:+ self.calls += 1+ if self.calls == 2:+ raise RuntimeError("the vendor is down")+ return []+++async def test_a_deletion_that_fails_partway_is_logged_with_what_it_finished(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The first workspace commits on its own before the second fails, so the+ attempt must land in the server log even though the success event rolls+ back with the `users` row."""+ operator, member = await _people(session_factory)+ async with session_factory() as session:+ session.add(Tenant(id="second", slug="second", name="Second"))+ await session.flush()+ session.add(TenantMember(tenant_id="second", user_id=member, role="member"))+ await session.commit()++ app = _app(session_factory, _FailsOnSecondWorkspace())+ async with _client(app, operator, ADMIN_EMAIL) as client:+ with pytest.raises(AccountDeletionIncomplete):+ await client.delete(f"/users/{member}")++ async with session_factory() as session:+ assert await session.get(User, member) is not None+ left = set(+ (+ await session.scalars(+ select(TenantMember.tenant_id).where(TenantMember.user_id == member)+ )+ ).all()+ )+ [still_in] = left+ [event] = await _server_events(session_factory)+ assert event.action == "user.deletion_failed"+ assert event.actor_user_id == operator+ assert event.target_id == member+ assert event.details is not None+ assert event.details["outcome"] == "failed"+ assert event.details["workspaces"] == 2+ [completed] = event.details["workspaces_completed"]+ assert completed != still_in+ assert {completed, still_in} == {TENANT_ZERO_ID, "second"}diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 2e07be5c1..8db0b20df 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1535,6 +1535,13 @@ export async function createUser(return jsonRequest<UserInfo>("/users", "POST", { name, email, password, role });}+// Deployment operator only. Deletes the whole account, as the person+// deleting it themselves would; the server refuses its own administrator+// account and the caller's own.+export async function deleteUser(userId: string): Promise<void> {+ await jsonRequest(`/users/${encodeURIComponent(userId)}`, "DELETE");+}+// ── Resources (References & Documents) ─────────────────────────────────────export interface ReferenceTypeInfo {diff --git a/gateway/src/pages/users/DeleteUserDialog.tsx b/gateway/src/pages/users/DeleteUserDialog.tsxnew file mode 100644index 000000000..7e91e2bbd--- /dev/null+++ b/gateway/src/pages/users/DeleteUserDialog.tsx@@ -0,0 +1,79 @@+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogContentText,+ DialogTitle,+} from "@mui/material";+import { useState } from "react";+import { type UserInfo, deleteUser } from "../../data/api";++interface Props {+ user: UserInfo | null;+ onClose: () => void;+ onDeleted: () => void;+}++export default function DeleteUserDialog({ user, onClose, onDeleted }: Props) {+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const handleClose = () => {+ if (submitting) return;+ setError(null);+ onClose();+ };++ const handleDelete = async () => {+ if (!user) return;+ setSubmitting(true);+ setError(null);+ try {+ await deleteUser(user.id);+ onDeleted();+ onClose();+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to delete the account");+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Dialog open={user !== null} onClose={handleClose} fullWidth maxWidth="xs">+ <DialogTitle>Delete account</DialogTitle>+ <DialogContent>+ <DialogContentText sx={{ mb: 2 }}>+ Delete the account of <b>{user?.name}</b> ({user?.email}) in every workspace?+ This cannot be undone.+ </DialogContentText>+ <Alert severity="warning">+ Their agents, packages, references, documents, templates and API keys are+ deleted. Rooms they created stay, with no owner.+ </Alert>+ {error && (+ <Alert severity="error" sx={{ mt: 2 }}>+ {error}+ </Alert>+ )}+ </DialogContent>+ <DialogActions>+ <Button onClick={handleClose} disabled={submitting}>+ Cancel+ </Button>+ <Button+ color="error"+ variant="contained"+ onClick={handleDelete}+ disabled={submitting}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Delete account+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/users/UsersPage.tsx b/gateway/src/pages/users/UsersPage.tsxindex 5c45b568d..17fff13be 100644--- a/gateway/src/pages/users/UsersPage.tsx+++ b/gateway/src/pages/users/UsersPage.tsx@@ -1,16 +1,31 @@import AddCircleOutline from "@mui/icons-material/AddCircleOutline";-import { Box, Button, Chip, CircularProgress, Stack, Typography } from "@mui/material";+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import {+ Box,+ Button,+ Chip,+ CircularProgress,+ IconButton,+ Stack,+ Tooltip,+ Typography,+} from "@mui/material";import type { GridColDef } from "@mui/x-data-grid";import { useMemo, useState } from "react";import DataTable from "../../components/DataTable";+import { useAuth } from "../../data/AuthContext";import type { UserInfo } from "../../data/api";import { useUsers } from "../../data/hooks";import { formatDate } from "../../theme/hootFormat";import CreateUserDialog from "./CreateUserDialog";+import DeleteUserDialog from "./DeleteUserDialog";export default function UsersPage() {const { data: users, loading, refetch } = useUsers();const [createOpen, setCreateOpen] = useState(false);+ const [deleting, setDeleting] = useState<UserInfo | null>(null);+ const { user: self } = useAuth();+ const selfId = self?.id;const columns = useMemo<GridColDef<UserInfo>[]>(() => [@@ -34,8 +49,28 @@ export default function UsersPage() {width: 140,valueFormatter: (value) => formatDate(value as string),},+ {+ field: "actions",+ headerName: "",+ width: 60,+ sortable: false,+ // The server refuses administrator accounts and your own, so neither+ // is offered. You delete your own account from your account settings.+ renderCell: ({ row }) =>+ row.role !== "admin" && row.id !== selfId ? (+ <Tooltip title="Delete account">+ <IconButton+ size="small"+ onClick={() => setDeleting(row)}+ aria-label={`Delete ${row.email}`}+ >+ <DeleteOutline fontSize="small" />+ </IconButton>+ </Tooltip>+ ) : null,+ },],- [],+ [selfId],);return (@@ -67,6 +102,11 @@ export default function UsersPage() {onClose={() => setCreateOpen(false)}onCreated={refetch}/>+ <DeleteUserDialog+ user={deleting}+ onClose={() => setDeleting(null)}+ onDeleted={refetch}+ /></Box>);}